blob: cb38af65e268efcebb7c353a706a2e5bb12ae00c [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 Lattnera11136b2003-08-01 22:21:34 +000015#include "Support/Debug.h"
Chris Lattner302de592003-06-06 04:00:05 +000016#include "Support/Statistic.h"
John Criswell7a73b802003-06-30 21:59:07 +000017#include "Config/alloca.h"
Chris Lattner40ead952002-12-02 21:24:12 +000018
19namespace {
Chris Lattner302de592003-06-06 04:00:05 +000020 Statistic<>
21 NumEmitted("x86-emitter", "Number of machine instructions emitted");
22
Chris Lattner04b0b302003-06-01 23:23:50 +000023 class JITResolver {
24 MachineCodeEmitter &MCE;
25
26 // LazyCodeGenMap - Keep track of call sites for functions that are to be
27 // lazily resolved.
28 std::map<unsigned, Function*> LazyCodeGenMap;
29
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;
33 public:
34 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
35 unsigned getLazyResolver(Function *F);
36 unsigned addFunctionReference(unsigned Address, Function *F);
37
38 private:
39 unsigned emitStubForFunction(Function *F);
40 static void CompilationCallback();
41 unsigned resolveFunctionReference(unsigned RetAddr);
42 };
43
44 JITResolver *TheJITResolver;
45}
46
47
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.
52///
53unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
54 LazyCodeGenMap[Address] = F;
55 return (intptr_t)&JITResolver::CompilationCallback;
56}
57
58unsigned 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);
64}
65
66unsigned 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;
69
70//std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
71
72 unsigned Stub = emitStubForFunction(F);
73 LazyResolverMap.insert(I, std::make_pair(F, Stub));
74 return Stub;
75}
76
77void JITResolver::CompilationCallback() {
78 unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
Misha Brukmanbc80b222003-06-02 04:13:58 +000079 unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
Chris Lattner04b0b302003-06-01 23:23:50 +000080 assert(StackPtr[1] == RetAddr &&
81 "Could not find return address on the stack!");
Chris Lattner30d002b2003-06-06 18:25:33 +000082
83 // It's a stub if there is an interrupt marker after the call...
84 bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
Chris Lattner04b0b302003-06-01 23:23:50 +000085
Chris Lattner302de592003-06-06 04:00:05 +000086 // 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
89 // gross hack.
90 alloca(10+isStub);
91 // FIXME FIXME FIXME FIXME
92
Chris Lattner04b0b302003-06-01 23:23:50 +000093 // The call instruction should have pushed the return value onto the stack...
94 RetAddr -= 4; // Backtrack to the reference itself...
95
96#if 0
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");
101#endif
102
103 // Sanity check to make sure this really is a call instruction...
Chris Lattner30d002b2003-06-06 18:25:33 +0000104 assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000105
106 unsigned NewVal = TheJITResolver->resolveFunctionReference(RetAddr);
107
108 // Rewrite the call target... so that we don't fault every time we execute
109 // the call.
Chris Lattner30d002b2003-06-06 18:25:33 +0000110 *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;
Chris Lattner04b0b302003-06-01 23:23:50 +0000111
112 if (isStub) {
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.
Chris Lattner30d002b2003-06-06 18:25:33 +0000117 ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
Chris Lattner04b0b302003-06-01 23:23:50 +0000118 }
119
120 // Change the return address to reexecute the call instruction...
121 StackPtr[1] -= 5;
122}
123
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
128/// directly.
129///
130unsigned JITResolver::emitStubForFunction(Function *F) {
131 MCE.startFunctionStub(*F, 6);
132 MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
133
134 unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
135 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
136
137 MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
138 return (intptr_t)MCE.finishFunctionStub(*F);
139}
140
141
142
143namespace {
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000144 class Emitter : public MachineFunctionPass {
145 const X86InstrInfo *II;
Chris Lattner8f04b092002-12-02 21:56:18 +0000146 MachineCodeEmitter &MCE;
Chris Lattnerdee12632003-07-26 23:06:00 +0000147 std::map<const BasicBlock*, unsigned> BasicBlockAddrs;
148 std::vector<std::pair<const BasicBlock*, unsigned> > BBRefs;
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000149 public:
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000150 Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
Chris Lattner40ead952002-12-02 21:24:12 +0000151
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000152 bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner76041ce2002-12-02 21:44:34 +0000153
Chris Lattnerf0eb7be2002-12-15 21:13:40 +0000154 virtual const char *getPassName() const {
155 return "X86 Machine Code Emitter";
156 }
157
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000158 private:
Chris Lattner76041ce2002-12-02 21:44:34 +0000159 void emitBasicBlock(MachineBasicBlock &MBB);
160 void emitInstruction(MachineInstr &MI);
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000161
Chris Lattner04b0b302003-06-01 23:23:50 +0000162 void emitPCRelativeBlockAddress(BasicBlock *BB);
163 void emitMaybePCRelativeValue(unsigned Address, bool isPCRelative);
164 void emitGlobalAddressForCall(GlobalValue *GV);
165 void emitGlobalAddressForPtr(GlobalValue *GV);
166
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000167 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
168 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
169 void emitConstant(unsigned Val, unsigned Size);
170
171 void emitMemModRMByte(const MachineInstr &MI,
172 unsigned Op, unsigned RegOpcodeField);
173
Chris Lattner40ead952002-12-02 21:24:12 +0000174 };
175}
176
Chris Lattner40ead952002-12-02 21:24:12 +0000177/// 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
181/// not supported.
182///
183bool X86TargetMachine::addPassesToEmitMachineCode(PassManager &PM,
184 MachineCodeEmitter &MCE) {
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000185 PM.add(new Emitter(MCE));
Chris Lattner40ead952002-12-02 21:24:12 +0000186 return false;
187}
Chris Lattner76041ce2002-12-02 21:44:34 +0000188
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000189bool Emitter::runOnMachineFunction(MachineFunction &MF) {
190 II = &((X86TargetMachine&)MF.getTarget()).getInstrInfo();
Chris Lattner76041ce2002-12-02 21:44:34 +0000191
192 MCE.startFunction(MF);
Chris Lattnere831b6b2003-01-13 00:33:59 +0000193 MCE.emitConstantPool(MF.getConstantPool());
Chris Lattner76041ce2002-12-02 21:44:34 +0000194 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
195 emitBasicBlock(*I);
196 MCE.finishFunction(MF);
Chris Lattner04b0b302003-06-01 23:23:50 +0000197
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;
Chris Lattner30d002b2003-06-06 18:25:33 +0000202 *(unsigned*)(intptr_t)Ref = Location-Ref-4;
Chris Lattner04b0b302003-06-01 23:23:50 +0000203 }
204 BBRefs.clear();
205 BasicBlockAddrs.clear();
Chris Lattner76041ce2002-12-02 21:44:34 +0000206 return false;
207}
208
209void Emitter::emitBasicBlock(MachineBasicBlock &MBB) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000210 if (uint64_t Addr = MCE.getCurrentPCValue())
211 BasicBlockAddrs[MBB.getBasicBlock()] = Addr;
212
Chris Lattner76041ce2002-12-02 21:44:34 +0000213 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
214 emitInstruction(**I);
215}
216
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000217
Chris Lattner04b0b302003-06-01 23:23:50 +0000218/// 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).
222///
223void 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
227}
228
229/// emitMaybePCRelativeValue - Emit a 32-bit address which may be PC relative.
230///
231void Emitter::emitMaybePCRelativeValue(unsigned Address, bool isPCRelative) {
232 if (isPCRelative)
233 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
234 else
235 MCE.emitWord(Address);
236}
237
238/// emitGlobalAddressForCall - Emit the specified address to the code stream
239/// assuming this is part of a function call, which is PC relative.
240///
241void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
242 // Get the address from the backend...
243 unsigned Address = MCE.getGlobalValueAddress(GV);
244
245 // If the machine code emitter doesn't know what the address IS yet, we have
246 // to take special measures.
247 //
248 if (Address == 0) {
249 // FIXME: this is JIT specific!
250 if (TheJITResolver == 0)
251 TheJITResolver = new JITResolver(MCE);
252 Address = TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
253 (Function*)GV);
254 }
255 emitMaybePCRelativeValue(Address, true);
256}
257
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
260/// PC relative.
261///
262void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
263 // Get the address from the backend...
264 unsigned Address = MCE.getGlobalValueAddress(GV);
265
266 // If the machine code emitter doesn't know what the address IS yet, we have
267 // to take special measures.
268 //
269 if (Address == 0) {
270 // FIXME: this is JIT specific!
271 if (TheJITResolver == 0)
272 TheJITResolver = new JITResolver(MCE);
273 Address = TheJITResolver->getLazyResolver((Function*)GV);
274 }
275
276 emitMaybePCRelativeValue(Address, false);
277}
278
279
280
Chris Lattnerff3261a2003-06-03 15:31:23 +0000281/// N86 namespace - Native X86 Register numbers... used by X86 backend.
282///
283namespace N86 {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000284 enum {
285 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
286 };
287}
288
289
290// getX86RegNum - This function maps LLVM register identifiers to their X86
291// specific numbering, which is used in various places encoding instructions.
292//
293static unsigned getX86RegNum(unsigned RegNo) {
294 switch(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;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000303
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;
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000307 default:
308 assert(RegNo >= MRegisterInfo::FirstVirtualRegister &&
309 "Unknown physical register!");
310 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
311 return 0;
312 }
313}
314
315inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
316 unsigned RM) {
317 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
318 return RM | (RegOpcode << 3) | (Mod << 6);
319}
320
321void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
322 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
323}
324
325void 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));
328}
329
330void 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);
334 Val >>= 8;
335 }
336}
337
338static bool isDisp8(int Value) {
339 return Value == (signed char)Value;
340}
341
342void Emitter::emitMemModRMByte(const MachineInstr &MI,
343 unsigned Op, unsigned RegOpcodeField) {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000344 const MachineOperand &Disp = MI.getOperand(Op+3);
345 if (MI.getOperand(Op).isConstantPoolIndex()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000346 // Emit a direct address reference [disp32] where the displacement of the
347 // constant pool entry is controlled by the MCE.
Chris Lattnere831b6b2003-01-13 00:33:59 +0000348 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
349 unsigned Index = MI.getOperand(Op).getConstantPoolIndex();
Chris Lattner04b0b302003-06-01 23:23:50 +0000350 unsigned Address = MCE.getConstantPoolEntryAddress(Index);
351 MCE.emitWord(Address+Disp.getImmedValue());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000352 return;
353 }
354
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000355 const MachineOperand &BaseReg = MI.getOperand(Op);
356 const MachineOperand &Scale = MI.getOperand(Op+1);
357 const MachineOperand &IndexReg = MI.getOperand(Op+2);
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000358
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);
365 } else {
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);
374 } else {
375 // Emit the most general non-SIB encoding: [REG+disp32]
Chris Lattner20671842002-12-13 05:05:05 +0000376 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000377 emitConstant(Disp.getImmedValue(), 4);
378 }
379 }
380
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!");
383
384 bool ForceDisp32 = false;
Brian Gaeke95780cc2002-12-13 07:56:18 +0000385 bool ForceDisp8 = false;
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000386 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));
390 ForceDisp32 = true;
Brian Gaeke95780cc2002-12-13 07:56:18 +0000391 } else if (Disp.getImmedValue() == 0 && BaseReg.getReg() != X86::EBP) {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000392 // 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));
Brian Gaeke95780cc2002-12-13 07:56:18 +0000397 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000398 } else {
399 // Emit the normal disp32 encoding...
400 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
401 }
402
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()];
406
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);
412 } else {
413 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000414 unsigned IndexRegNo;
415 if (IndexReg.getReg())
416 IndexRegNo = getX86RegNum(IndexReg.getReg());
417 else
418 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000419 emitSIBByte(SS, IndexRegNo, BaseRegNo);
420 }
421
422 // Do we need to output a displacement?
Brian Gaeke95780cc2002-12-13 07:56:18 +0000423 if (Disp.getImmedValue() != 0 || ForceDisp32 || ForceDisp8) {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000424 if (!ForceDisp32 && isDisp8(Disp.getImmedValue()))
425 emitConstant(Disp.getImmedValue(), 1);
426 else
427 emitConstant(Disp.getImmedValue(), 4);
428 }
429 }
430}
431
Chris Lattner04b0b302003-06-01 23:23:50 +0000432static unsigned sizeOfPtr(const TargetInstrDescriptor &Desc) {
Chris Lattnera0f38c82002-12-13 03:51:55 +0000433 switch (Desc.TSFlags & X86II::ArgMask) {
434 case X86II::Arg8: return 1;
435 case X86II::Arg16: return 2;
436 case X86II::Arg32: return 4;
Chris Lattner5ada8df2002-12-25 05:09:21 +0000437 case X86II::ArgF32: return 4;
438 case X86II::ArgF64: return 8;
439 case X86II::ArgF80: return 10;
Chris Lattnera6a382c2002-12-13 03:50:13 +0000440 default: assert(0 && "Memory size not set!");
Chris Lattnerdf642e12002-12-20 04:12:48 +0000441 return 0;
Misha Brukman5000e432002-12-13 02:13:15 +0000442 }
443}
444
Chris Lattner76041ce2002-12-02 21:44:34 +0000445void Emitter::emitInstruction(MachineInstr &MI) {
Chris Lattner302de592003-06-06 04:00:05 +0000446 NumEmitted++; // Keep track of the # of mi's emitted
447
Chris Lattner76041ce2002-12-02 21:44:34 +0000448 unsigned Opcode = MI.getOpcode();
Chris Lattner3501fea2003-01-14 22:00:31 +0000449 const TargetInstrDescriptor &Desc = II->get(Opcode);
Chris Lattner76041ce2002-12-02 21:44:34 +0000450
451 // Emit instruction prefixes if neccesary
452 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
Chris Lattner5ada8df2002-12-25 05:09:21 +0000453
454 switch (Desc.TSFlags & X86II::Op0Mask) {
455 case X86II::TB:
456 MCE.emitByte(0x0F); // Two-byte opcode prefix
457 break;
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:
Chris Lattnere831b6b2003-01-13 00:33:59 +0000460 MCE.emitByte(0xD8+
461 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
462 >> X86II::Op0Shift));
Chris Lattner5ada8df2002-12-25 05:09:21 +0000463 break; // Two-byte opcode prefix
Chris Lattnere831b6b2003-01-13 00:33:59 +0000464 default: assert(0 && "Invalid prefix!");
465 case 0: break; // No prefix!
Chris Lattner5ada8df2002-12-25 05:09:21 +0000466 }
Chris Lattner76041ce2002-12-02 21:44:34 +0000467
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000468 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
Chris Lattner76041ce2002-12-02 21:44:34 +0000469 switch (Desc.TSFlags & X86II::FormMask) {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000470 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
Chris Lattner5ada8df2002-12-25 05:09:21 +0000471 case X86II::Pseudo:
Chris Lattnerc2489032003-05-07 19:21:28 +0000472 if (Opcode != X86::IMPLICIT_USE)
Chris Lattner9dedbcc2003-05-06 21:31:47 +0000473 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
Chris Lattner5ada8df2002-12-25 05:09:21 +0000474 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000475
Chris Lattner76041ce2002-12-02 21:44:34 +0000476 case X86II::RawFrm:
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000477 MCE.emitByte(BaseOpcode);
Chris Lattner8f04b092002-12-02 21:56:18 +0000478 if (MI.getNumOperands() == 1) {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000479 MachineOperand &MO = MI.getOperand(0);
480 if (MO.isPCRelativeDisp()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000481 // Conditional branch... FIXME: this should use an MBB destination!
482 emitPCRelativeBlockAddress(cast<BasicBlock>(MO.getVRegValue()));
Chris Lattnere831b6b2003-01-13 00:33:59 +0000483 } else if (MO.isGlobalAddress()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000484 assert(MO.isPCRelative() && "Call target is not PC Relative?");
485 emitGlobalAddressForCall(MO.getGlobal());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000486 } else if (MO.isExternalSymbol()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000487 unsigned Address = MCE.getGlobalValueAddress(MO.getSymbolName());
488 assert(Address && "Unknown external symbol!");
489 emitMaybePCRelativeValue(Address, MO.isPCRelative());
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000490 } else {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000491 assert(0 && "Unknown RawFrm operand!");
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000492 }
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000493 }
494 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000495
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!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000505 emitGlobalAddressForPtr(cast<GlobalValue>(V));
Chris Lattnere831b6b2003-01-13 00:33:59 +0000506 } else if (MO1.isGlobalAddress()) {
507 assert(Size == 4 && "Don't know how to emit non-pointer values!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000508 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
509 emitGlobalAddressForPtr(MO1.getGlobal());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000510 } else if (MO1.isExternalSymbol()) {
511 assert(Size == 4 && "Don't know how to emit non-pointer values!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000512
513 unsigned Address = MCE.getGlobalValueAddress(MO1.getSymbolName());
514 assert(Address && "Unknown external symbol!");
515 emitMaybePCRelativeValue(Address, MO1.isPCRelative());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000516 } else {
517 emitConstant(MO1.getImmedValue(), Size);
518 }
519 }
520 }
521 break;
522
523 case X86II::MRMDestReg: {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000524 MCE.emitByte(BaseOpcode);
Chris Lattnere831b6b2003-01-13 00:33:59 +0000525 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));
Chris Lattner9dedbcc2003-05-06 21:31:47 +0000529 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000530 }
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000531 case X86II::MRMDestMem:
532 MCE.emitByte(BaseOpcode);
533 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
534 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000535
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000536 case X86II::MRMSrcReg:
537 MCE.emitByte(BaseOpcode);
538 emitRegModRMByte(MI.getOperand(MI.getNumOperands()-1).getReg(),
539 getX86RegNum(MI.getOperand(0).getReg()));
540 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000541
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000542 case X86II::MRMSrcMem:
543 MCE.emitByte(BaseOpcode);
544 emitMemModRMByte(MI, MI.getNumOperands()-4,
545 getX86RegNum(MI.getOperand(0).getReg()));
546 break;
547
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);
555
Chris Lattnerd9096832002-12-15 08:01:39 +0000556 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
Misha Brukman5000e432002-12-13 02:13:15 +0000557 unsigned Size = sizeOfPtr(Desc);
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000558 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(), Size);
559 }
560 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000561
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);
568
569 if (MI.getNumOperands() == 5) {
570 unsigned Size = sizeOfPtr(Desc);
571 emitConstant(MI.getOperand(4).getImmedValue(), Size);
572 }
573 break;
Chris Lattner76041ce2002-12-02 21:44:34 +0000574 }
575}