Committing X86-64 support.
[oota-llvm.git] / lib / Target / X86 / X86CodeEmitter.cpp
1 //===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the pass that transforms the X86 machine instructions into
11 // relocatable machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86InstrInfo.h"
16 #include "X86Subtarget.h"
17 #include "X86TargetMachine.h"
18 #include "X86Relocations.h"
19 #include "X86.h"
20 #include "llvm/PassManager.h"
21 #include "llvm/CodeGen/MachineCodeEmitter.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/Function.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include <iostream>
30 using namespace llvm;
31
32 namespace {
33   Statistic<>
34   NumEmitted("x86-emitter", "Number of machine instructions emitted");
35 }
36
37 namespace {
38   class VISIBILITY_HIDDEN Emitter : public MachineFunctionPass {
39     const X86InstrInfo  *II;
40     const TargetData    *TD;
41     TargetMachine       &TM;
42     MachineCodeEmitter  &MCE;
43     bool Is64BitMode;
44   public:
45     explicit Emitter(TargetMachine &tm, MachineCodeEmitter &mce)
46       : II(0), TD(0), TM(tm), MCE(mce), Is64BitMode(false) {}
47     Emitter(TargetMachine &tm, MachineCodeEmitter &mce,
48             const X86InstrInfo &ii, const TargetData &td, bool is64)
49       : II(&ii), TD(&td), TM(tm), MCE(mce), Is64BitMode(is64) {}
50
51     bool runOnMachineFunction(MachineFunction &MF);
52
53     virtual const char *getPassName() const {
54       return "X86 Machine Code Emitter";
55     }
56
57     void emitInstruction(const MachineInstr &MI);
58
59   private:
60     void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
61     void emitPCRelativeValue(intptr_t Address);
62     void emitGlobalAddressForCall(GlobalValue *GV, bool DoesntNeedStub);
63     void emitGlobalAddressForPtr(GlobalValue *GV, bool isPCRelative,
64                                  int Disp = 0, unsigned PCAdj = 0);
65     void emitExternalSymbolAddress(const char *ES, bool isPCRelative);
66     void emitPCRelativeConstPoolAddress(unsigned CPI, int Disp = 0,
67                                         unsigned PCAdj = 0);
68     void emitPCRelativeJumpTableAddress(unsigned JTI, unsigned PCAdj = 0);
69
70     void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
71                                unsigned PCAdj = 0);
72
73     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
74     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
75     void emitConstant(uint64_t Val, unsigned Size);
76
77     void emitMemModRMByte(const MachineInstr &MI,
78                           unsigned Op, unsigned RegOpcodeField,
79                           unsigned PCAdj = 0);
80
81     unsigned getX86RegNum(unsigned RegNo);
82     bool isX86_64ExtendedReg(const MachineOperand &MO);
83     unsigned determineREX(const MachineInstr &MI);
84   };
85 }
86
87 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
88 /// to the specified MCE object.
89 FunctionPass *llvm::createX86CodeEmitterPass(X86TargetMachine &TM,
90                                              MachineCodeEmitter &MCE) {
91   return new Emitter(TM, MCE);
92 }
93
94 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
95   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
96           MF.getTarget().getRelocationModel() != Reloc::Static) &&
97          "JIT relocation model must be set to static or default!");
98   II = ((X86TargetMachine&)MF.getTarget()).getInstrInfo();
99   TD = ((X86TargetMachine&)MF.getTarget()).getTargetData();
100   Is64BitMode =
101     ((X86TargetMachine&)MF.getTarget()).getSubtarget<X86Subtarget>().is64Bit();
102
103   do {
104     MCE.startFunction(MF);
105     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
106          MBB != E; ++MBB) {
107       MCE.StartMachineBasicBlock(MBB);
108       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
109            I != E; ++I)
110         emitInstruction(*I);
111     }
112   } while (MCE.finishFunction(MF));
113
114   return false;
115 }
116
117 /// emitPCRelativeValue - Emit a PC relative address.
118 ///
119 void Emitter::emitPCRelativeValue(intptr_t Address) {
120   MCE.emitWordLE(Address-MCE.getCurrentPCValue()-4);
121 }
122
123 /// emitPCRelativeBlockAddress - This method keeps track of the information
124 /// necessary to resolve the address of this block later and emits a dummy
125 /// value.
126 ///
127 void Emitter::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
128   // Remember where this reference was and where it is to so we can
129   // deal with it later.
130   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
131                                              X86::reloc_pcrel_word, MBB));
132   MCE.emitWordLE(0);
133 }
134
135 /// emitGlobalAddressForCall - Emit the specified address to the code stream
136 /// assuming this is part of a function call, which is PC relative.
137 ///
138 void Emitter::emitGlobalAddressForCall(GlobalValue *GV, bool DoesntNeedStub) {
139   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
140                                       X86::reloc_pcrel_word, GV, 0,
141                                       DoesntNeedStub));
142   MCE.emitWordLE(0);
143 }
144
145 /// emitGlobalAddress - Emit the specified address to the code stream assuming
146 /// this is part of a "take the address of a global" instruction.
147 ///
148 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV, bool isPCRelative,
149                                       int Disp /* = 0 */,
150                                       unsigned PCAdj /* = 0 */) {
151   unsigned rt = isPCRelative ? X86::reloc_pcrel_word : X86::reloc_absolute_word;
152   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(), rt,
153                                              GV, PCAdj));
154   MCE.emitWordLE(Disp); // The relocated value will be added to the displacement
155 }
156
157 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
158 /// be emitted to the current location in the function, and allow it to be PC
159 /// relative.
160 void Emitter::emitExternalSymbolAddress(const char *ES, bool isPCRelative) {
161   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
162           isPCRelative ? X86::reloc_pcrel_word : X86::reloc_absolute_word, ES));
163   MCE.emitWordLE(0);
164 }
165
166 /// emitPCRelativeConstPoolAddress - Arrange for the address of an constant pool
167 /// to be emitted to the current location in the function, and allow it to be PC
168 /// relative.
169 void Emitter::emitPCRelativeConstPoolAddress(unsigned CPI, int Disp /* = 0 */,
170                                              unsigned PCAdj /* = 0 */) {
171   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
172                                             X86::reloc_pcrel_word, CPI, PCAdj));
173   MCE.emitWordLE(Disp); // The relocated value will be added to the displacement
174 }
175
176 /// emitPCRelativeJumpTableAddress - Arrange for the address of a jump table to
177 /// be emitted to the current location in the function, and allow it to be PC
178 /// relative.
179 void Emitter::emitPCRelativeJumpTableAddress(unsigned JTI,
180                                              unsigned PCAdj /* = 0 */) {
181   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
182                                             X86::reloc_pcrel_word, JTI, PCAdj));
183   MCE.emitWordLE(0); // The relocated value will be added to the displacement
184 }
185
186 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
187 ///
188 namespace N86 {
189   enum {
190     EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
191   };
192 }
193
194 // getX86RegNum - This function maps LLVM register identifiers to their X86
195 // specific numbering, which is used in various places encoding instructions.
196 //
197 unsigned Emitter::getX86RegNum(unsigned RegNo) {
198   switch(RegNo) {
199   case X86::RAX: case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
200   case X86::RCX: case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
201   case X86::RDX: case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
202   case X86::RBX: case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
203   case X86::RSP: case X86::ESP: case X86::SP: case X86::SPL: case X86::AH:
204     return N86::ESP;
205   case X86::RBP: case X86::EBP: case X86::BP: case X86::BPL: case X86::CH:
206     return N86::EBP;
207   case X86::RSI: case X86::ESI: case X86::SI: case X86::SIL: case X86::DH:
208     return N86::ESI;
209   case X86::RDI: case X86::EDI: case X86::DI: case X86::DIL: case X86::BH:
210     return N86::EDI;
211
212   case X86::R8:  case X86::R8D:  case X86::R8W:  case X86::R8B:
213     return N86::EAX;
214   case X86::R9:  case X86::R9D:  case X86::R9W:  case X86::R9B:
215     return N86::ECX;
216   case X86::R10: case X86::R10D: case X86::R10W: case X86::R10B:
217     return N86::EDX;
218   case X86::R11: case X86::R11D: case X86::R11W: case X86::R11B:
219     return N86::EBX;
220   case X86::R12: case X86::R12D: case X86::R12W: case X86::R12B:
221     return N86::ESP;
222   case X86::R13: case X86::R13D: case X86::R13W: case X86::R13B:
223     return N86::EBP;
224   case X86::R14: case X86::R14D: case X86::R14W: case X86::R14B:
225     return N86::ESI;
226   case X86::R15: case X86::R15D: case X86::R15W: case X86::R15B:
227     return N86::EDI;
228
229   case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
230   case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
231     return RegNo-X86::ST0;
232
233   case X86::XMM0:  case X86::XMM1:  case X86::XMM2:  case X86::XMM3:
234   case X86::XMM4:  case X86::XMM5:  case X86::XMM6:  case X86::XMM7:
235     return II->getRegisterInfo().getDwarfRegNum(RegNo) -
236            II->getRegisterInfo().getDwarfRegNum(X86::XMM0);
237   case X86::XMM8:  case X86::XMM9:  case X86::XMM10: case X86::XMM11:
238   case X86::XMM12: case X86::XMM13: case X86::XMM14: case X86::XMM15:
239     return II->getRegisterInfo().getDwarfRegNum(RegNo) -
240            II->getRegisterInfo().getDwarfRegNum(X86::XMM8);
241
242   default:
243     assert(MRegisterInfo::isVirtualRegister(RegNo) &&
244            "Unknown physical register!");
245     assert(0 && "Register allocator hasn't allocated reg correctly yet!");
246     return 0;
247   }
248 }
249
250 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
251                                       unsigned RM) {
252   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
253   return RM | (RegOpcode << 3) | (Mod << 6);
254 }
255
256 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
257   MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
258 }
259
260 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
261   // SIB byte is in the same format as the ModRMByte...
262   MCE.emitByte(ModRMByte(SS, Index, Base));
263 }
264
265 void Emitter::emitConstant(uint64_t Val, unsigned Size) {
266   // Output the constant in little endian byte order...
267   for (unsigned i = 0; i != Size; ++i) {
268     MCE.emitByte(Val & 255);
269     Val >>= 8;
270   }
271 }
272
273 /// isDisp8 - Return true if this signed displacement fits in a 8-bit 
274 /// sign-extended field. 
275 static bool isDisp8(int Value) {
276   return Value == (signed char)Value;
277 }
278
279 void Emitter::emitDisplacementField(const MachineOperand *RelocOp,
280                                     int DispVal, unsigned PCAdj) {
281   // If this is a simple integer displacement that doesn't require a relocation,
282   // emit it now.
283   if (!RelocOp) {
284     emitConstant(DispVal, 4);
285     return;
286   }
287   
288   // Otherwise, this is something that requires a relocation.  Emit it as such
289   // now.
290   if (RelocOp->isGlobalAddress()) {
291     // In 64-bit static small code model, we could potentially emit absolute.
292     // But it's probably not beneficial.
293     //  89 05 00 00 00 00       mov    %eax,0(%rip)  # PC-relative
294     //  89 04 25 00 00 00 00    mov    %eax,0x0      # Absolute
295     emitGlobalAddressForPtr(RelocOp->getGlobal(), Is64BitMode,
296                             RelocOp->getOffset(), PCAdj);
297   } else if (RelocOp->isConstantPoolIndex()) {
298     // Must be in 64-bit mode.
299     emitPCRelativeConstPoolAddress(RelocOp->getConstantPoolIndex(),
300                                    RelocOp->getOffset(), PCAdj);
301   } else if (RelocOp->isJumpTableIndex()) {
302     // Must be in 64-bit mode.
303     emitPCRelativeJumpTableAddress(RelocOp->getJumpTableIndex(), PCAdj);
304   } else {
305     assert(0 && "Unknown value to relocate!");
306   }
307 }
308
309 void Emitter::emitMemModRMByte(const MachineInstr &MI,
310                                unsigned Op, unsigned RegOpcodeField,
311                                unsigned PCAdj) {
312   const MachineOperand &Op3 = MI.getOperand(Op+3);
313   int DispVal = 0;
314   const MachineOperand *DispForReloc = 0;
315   
316   // Figure out what sort of displacement we have to handle here.
317   if (Op3.isGlobalAddress()) {
318     DispForReloc = &Op3;
319   } else if (Op3.isConstantPoolIndex()) {
320     if (Is64BitMode) {
321       DispForReloc = &Op3;
322     } else {
323       DispVal += MCE.getConstantPoolEntryAddress(Op3.getConstantPoolIndex());
324       DispVal += Op3.getOffset();
325     }
326   } else if (Op3.isJumpTableIndex()) {
327     if (Is64BitMode) {
328       DispForReloc = &Op3;
329     } else {
330       DispVal += MCE.getJumpTableEntryAddress(Op3.getJumpTableIndex());
331     }
332   } else {
333     DispVal = Op3.getImm();
334   }
335
336   const MachineOperand &Base     = MI.getOperand(Op);
337   const MachineOperand &Scale    = MI.getOperand(Op+1);
338   const MachineOperand &IndexReg = MI.getOperand(Op+2);
339
340   unsigned BaseReg = Base.getReg();
341
342   // Is a SIB byte needed?
343   if (IndexReg.getReg() == 0 &&
344       (BaseReg == 0 || getX86RegNum(BaseReg) != N86::ESP)) {
345     if (BaseReg == 0) {  // Just a displacement?
346       // Emit special case [disp32] encoding
347       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
348       
349       emitDisplacementField(DispForReloc, DispVal, PCAdj);
350     } else {
351       unsigned BaseRegNo = getX86RegNum(BaseReg);
352       if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
353         // Emit simple indirect register encoding... [EAX] f.e.
354         MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
355       } else if (!DispForReloc && isDisp8(DispVal)) {
356         // Emit the disp8 encoding... [REG+disp8]
357         MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
358         emitConstant(DispVal, 1);
359       } else {
360         // Emit the most general non-SIB encoding: [REG+disp32]
361         MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
362         emitDisplacementField(DispForReloc, DispVal, PCAdj);
363       }
364     }
365
366   } else {  // We need a SIB byte, so start by outputting the ModR/M byte first
367     assert(IndexReg.getReg() != X86::ESP &&
368            IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
369
370     bool ForceDisp32 = false;
371     bool ForceDisp8  = false;
372     if (BaseReg == 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));
376       ForceDisp32 = true;
377     } else if (DispForReloc) {
378       // Emit the normal disp32 encoding.
379       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
380       ForceDisp32 = true;
381     } else if (DispVal == 0 && getX86RegNum(BaseReg) != N86::EBP) {
382       // Emit no displacement ModR/M byte
383       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
384     } else if (isDisp8(DispVal)) {
385       // Emit the disp8 encoding...
386       MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
387       ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
388     } else {
389       // Emit the normal disp32 encoding...
390       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
391     }
392
393     // Calculate what the SS field value should be...
394     static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
395     unsigned SS = SSTable[Scale.getImm()];
396
397     if (BaseReg == 0) {
398       // Handle the SIB byte for the case where there is no base.  The
399       // displacement has already been output.
400       assert(IndexReg.getReg() && "Index register must be specified!");
401       emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
402     } else {
403       unsigned BaseRegNo = getX86RegNum(BaseReg);
404       unsigned IndexRegNo;
405       if (IndexReg.getReg())
406         IndexRegNo = getX86RegNum(IndexReg.getReg());
407       else
408         IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
409       emitSIBByte(SS, IndexRegNo, BaseRegNo);
410     }
411
412     // Do we need to output a displacement?
413     if (ForceDisp8) {
414       emitConstant(DispVal, 1);
415     } else if (DispVal != 0 || ForceDisp32) {
416       emitDisplacementField(DispForReloc, DispVal, PCAdj);
417     }
418   }
419 }
420
421 static unsigned sizeOfImm(const TargetInstrDescriptor &Desc) {
422   switch (Desc.TSFlags & X86II::ImmMask) {
423   case X86II::Imm8:   return 1;
424   case X86II::Imm16:  return 2;
425   case X86II::Imm32:  return 4;
426   case X86II::Imm64:  return 8;
427   default: assert(0 && "Immediate size not set!");
428     return 0;
429   }
430 }
431
432 /// isX86_64ExtendedReg - Is the MachineOperand a x86-64 extended register?
433 /// e.g. r8, xmm8, etc.
434 bool Emitter::isX86_64ExtendedReg(const MachineOperand &MO) {
435   if (!MO.isRegister()) return false;
436   unsigned RegNo = MO.getReg();
437   int DWNum = II->getRegisterInfo().getDwarfRegNum(RegNo);
438   if (DWNum >= II->getRegisterInfo().getDwarfRegNum(X86::R8) &&
439       DWNum <= II->getRegisterInfo().getDwarfRegNum(X86::R15))
440     return true;
441   if (DWNum >= II->getRegisterInfo().getDwarfRegNum(X86::XMM8) &&
442       DWNum <= II->getRegisterInfo().getDwarfRegNum(X86::XMM15))
443     return true;
444   return false;
445 }
446
447 inline static bool isX86_64TruncToByte(unsigned oc) {
448   return (oc == X86::TRUNC_64to8 || oc == X86::TRUNC_32to8 ||
449           oc == X86::TRUNC_16to8);
450 }
451
452
453 inline static bool isX86_64NonExtLowByteReg(unsigned reg) {
454   return (reg == X86::SPL || reg == X86::BPL ||
455           reg == X86::SIL || reg == X86::DIL);
456 }
457
458 /// determineREX - Determine if the MachineInstr has to be encoded with a X86-64
459 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
460 /// size, and 3) use of X86-64 extended registers.
461 unsigned Emitter::determineREX(const MachineInstr &MI) {
462   unsigned REX = 0;
463   unsigned Opcode = MI.getOpcode();
464   const TargetInstrDescriptor &Desc = II->get(Opcode);
465
466   // Pseudo instructions do not need REX prefix byte.
467   if ((Desc.TSFlags & X86II::FormMask) == X86II::Pseudo)
468     return 0;
469   if (Desc.TSFlags & X86II::REX_W)
470     REX |= 1 << 3;
471
472   if (MI.getNumOperands()) {
473     // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
474     bool isTrunc8 = isX86_64TruncToByte(Opcode);
475     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
476       const MachineOperand& MO = MI.getOperand(i);
477       if (MO.isRegister()) {
478         unsigned Reg = MO.getReg();
479         // Trunc to byte are actually movb. The real source operand is the low
480         // byte of the register.
481         if (isTrunc8 && i == 1)
482           Reg = getX86SubSuperRegister(Reg, MVT::i8);
483         if (isX86_64NonExtLowByteReg(Reg))
484           REX |= 0x40;
485       }
486     }
487
488     switch (Desc.TSFlags & X86II::FormMask) {
489     case X86II::MRMInitReg:
490       if (isX86_64ExtendedReg(MI.getOperand(0)))
491         REX |= (1 << 0) | (1 << 2);
492       break;
493     case X86II::MRMSrcReg: {
494       if (isX86_64ExtendedReg(MI.getOperand(0)))
495         REX |= 1 << 2;
496       for (unsigned i = 1, e = MI.getNumOperands(); i != e; ++i) {
497         const MachineOperand& MO = MI.getOperand(i);
498         if (isX86_64ExtendedReg(MO))
499           REX |= 1 << 0;
500       }
501       break;
502     }
503     case X86II::MRMSrcMem: {
504       if (isX86_64ExtendedReg(MI.getOperand(0)))
505         REX |= 1 << 2;
506       unsigned Bit = 0;
507       for (unsigned i = 1; i != 5; ++i) {
508         const MachineOperand& MO = MI.getOperand(i);
509         if (MO.isRegister()) {
510           if (isX86_64ExtendedReg(MO))
511             REX |= 1 << Bit;
512           Bit++;
513         }
514       }
515       break;
516     }
517     case X86II::MRM0m: case X86II::MRM1m:
518     case X86II::MRM2m: case X86II::MRM3m:
519     case X86II::MRM4m: case X86II::MRM5m:
520     case X86II::MRM6m: case X86II::MRM7m:
521     case X86II::MRMDestMem: {
522       if (MI.getNumOperands() >= 5 &&
523           isX86_64ExtendedReg(MI.getOperand(4)))
524         REX |= 1 << 2;
525       unsigned Bit = 0;
526       for (unsigned i = 0; i != 4; ++i) {
527         const MachineOperand& MO = MI.getOperand(i);
528         if (MO.isRegister()) {
529           if (isX86_64ExtendedReg(MO))
530             REX |= 1 << Bit;
531           Bit++;
532         }
533       }
534       break;
535     }
536     default: {
537       if (isX86_64ExtendedReg(MI.getOperand(0)))
538         REX |= 1 << 0;
539       for (unsigned i = 1, e = MI.getNumOperands(); i != e; ++i) {
540         const MachineOperand& MO = MI.getOperand(i);
541         if (isX86_64ExtendedReg(MO))
542           REX |= 1 << 2;
543       }
544       break;
545     }
546     }
547   }
548   return REX;
549 }
550
551 void Emitter::emitInstruction(const MachineInstr &MI) {
552   NumEmitted++;  // Keep track of the # of mi's emitted
553
554   unsigned Opcode = MI.getOpcode();
555   const TargetInstrDescriptor &Desc = II->get(Opcode);
556
557   // Emit the repeat opcode prefix as needed.
558   if ((Desc.TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
559
560   // Emit the operand size opcode prefix as needed.
561   if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);
562
563   // Emit the address size opcode prefix as needed.
564   if (Desc.TSFlags & X86II::AdSize) MCE.emitByte(0x67);
565
566   bool Need0FPrefix = false;
567   switch (Desc.TSFlags & X86II::Op0Mask) {
568   case X86II::TB:
569     Need0FPrefix = true;   // Two-byte opcode prefix
570     break;
571   case X86II::REP: break; // already handled.
572   case X86II::XS:   // F3 0F
573     MCE.emitByte(0xF3);
574     Need0FPrefix = true;
575     break;
576   case X86II::XD:   // F2 0F
577     MCE.emitByte(0xF2);
578     Need0FPrefix = true;
579     break;
580   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
581   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
582     MCE.emitByte(0xD8+
583                  (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
584                                    >> X86II::Op0Shift));
585     break; // Two-byte opcode prefix
586   default: assert(0 && "Invalid prefix!");
587   case 0: break;  // No prefix!
588   }
589
590   if (Is64BitMode) {
591     // REX prefix
592     unsigned REX = determineREX(MI);
593     if (REX)
594       MCE.emitByte(0x40 | REX);
595   }
596
597   // 0x0F escape code must be emitted just before the opcode.
598   if (Need0FPrefix)
599     MCE.emitByte(0x0F);
600
601   // If this is a two-address instruction, skip one of the register operands.
602   unsigned CurOp = 0;
603   CurOp += (Desc.Flags & M_2_ADDR_FLAG) != 0;
604   
605   unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
606   switch (Desc.TSFlags & X86II::FormMask) {
607   default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
608   case X86II::Pseudo:
609 #ifndef NDEBUG
610     switch (Opcode) {
611     default: 
612       assert(0 && "psuedo instructions should be removed before code emission");
613     case TargetInstrInfo::INLINEASM:
614       std::cerr << "JIT does not support inline asm!\n";
615       abort();
616     case X86::IMPLICIT_USE:
617     case X86::IMPLICIT_DEF:
618     case X86::IMPLICIT_DEF_GR8:
619     case X86::IMPLICIT_DEF_GR16:
620     case X86::IMPLICIT_DEF_GR32:
621     case X86::IMPLICIT_DEF_GR64:
622     case X86::IMPLICIT_DEF_FR32:
623     case X86::IMPLICIT_DEF_FR64:
624     case X86::IMPLICIT_DEF_VR64:
625     case X86::IMPLICIT_DEF_VR128:
626     case X86::FP_REG_KILL:
627       break;
628     }
629 #endif
630     CurOp = MI.getNumOperands();
631     break;
632
633   case X86II::RawFrm:
634     MCE.emitByte(BaseOpcode);
635     if (CurOp != MI.getNumOperands()) {
636       const MachineOperand &MO = MI.getOperand(CurOp++);
637       if (MO.isMachineBasicBlock()) {
638         emitPCRelativeBlockAddress(MO.getMachineBasicBlock());
639       } else if (MO.isGlobalAddress()) {
640         bool isTailCall = Opcode == X86::TAILJMPd ||
641                           Opcode == X86::TAILJMPr || Opcode == X86::TAILJMPm;
642         emitGlobalAddressForCall(MO.getGlobal(), !isTailCall);
643       } else if (MO.isExternalSymbol()) {
644         emitExternalSymbolAddress(MO.getSymbolName(), true);
645       } else if (MO.isImmediate()) {
646         emitConstant(MO.getImm(), sizeOfImm(Desc));
647       } else {
648         assert(0 && "Unknown RawFrm operand!");
649       }
650     }
651     break;
652
653   case X86II::AddRegFrm:
654     MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
655     
656     if (CurOp != MI.getNumOperands()) {
657       const MachineOperand &MO1 = MI.getOperand(CurOp++);
658       if (MO1.isGlobalAddress()) {
659         assert(sizeOfImm(Desc) == TD->getPointerSize() &&
660                "Don't know how to emit non-pointer values!");
661         emitGlobalAddressForPtr(MO1.getGlobal(), Is64BitMode, MO1.getOffset());
662       } else if (MO1.isExternalSymbol()) {
663         assert(sizeOfImm(Desc) == TD->getPointerSize() &&
664                "Don't know how to emit non-pointer values!");
665         emitExternalSymbolAddress(MO1.getSymbolName(), false);
666       } else if (MO1.isJumpTableIndex()) {
667         assert(sizeOfImm(Desc) == TD->getPointerSize() &&
668                "Don't know how to emit non-pointer values!");
669         emitConstant(MCE.getJumpTableEntryAddress(MO1.getJumpTableIndex()), 4);
670       } else {
671         emitConstant(MO1.getImm(), sizeOfImm(Desc));
672       }
673     }
674     break;
675
676   case X86II::MRMDestReg: {
677     MCE.emitByte(BaseOpcode);
678     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
679                      getX86RegNum(MI.getOperand(CurOp+1).getReg()));
680     CurOp += 2;
681     if (CurOp != MI.getNumOperands())
682       emitConstant(MI.getOperand(CurOp++).getImm(), sizeOfImm(Desc));
683     break;
684   }
685   case X86II::MRMDestMem: {
686     MCE.emitByte(BaseOpcode);
687     emitMemModRMByte(MI, CurOp, getX86RegNum(MI.getOperand(CurOp+4).getReg()));
688     CurOp += 5;
689     if (CurOp != MI.getNumOperands())
690       emitConstant(MI.getOperand(CurOp++).getImm(), sizeOfImm(Desc));
691     break;
692   }
693
694   case X86II::MRMSrcReg:
695     MCE.emitByte(BaseOpcode);
696     emitRegModRMByte(MI.getOperand(CurOp+1).getReg(),
697                      getX86RegNum(MI.getOperand(CurOp).getReg()));
698     CurOp += 2;
699     if (CurOp != MI.getNumOperands())
700       emitConstant(MI.getOperand(CurOp++).getImm(), sizeOfImm(Desc));
701     break;
702
703   case X86II::MRMSrcMem: {
704     unsigned PCAdj = (CurOp+5 != MI.getNumOperands()) ? sizeOfImm(Desc) : 0;
705
706     MCE.emitByte(BaseOpcode);
707     emitMemModRMByte(MI, CurOp+1, getX86RegNum(MI.getOperand(CurOp).getReg()),
708                      PCAdj);
709     CurOp += 5;
710     if (CurOp != MI.getNumOperands())
711       emitConstant(MI.getOperand(CurOp++).getImm(), sizeOfImm(Desc));
712     break;
713   }
714
715   case X86II::MRM0r: case X86II::MRM1r:
716   case X86II::MRM2r: case X86II::MRM3r:
717   case X86II::MRM4r: case X86II::MRM5r:
718   case X86II::MRM6r: case X86II::MRM7r:
719     MCE.emitByte(BaseOpcode);
720     emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
721                      (Desc.TSFlags & X86II::FormMask)-X86II::MRM0r);
722
723     if (CurOp != MI.getNumOperands() && MI.getOperand(CurOp).isImmediate())
724       emitConstant(MI.getOperand(CurOp++).getImm(), sizeOfImm(Desc));
725     break;
726
727   case X86II::MRM0m: case X86II::MRM1m:
728   case X86II::MRM2m: case X86II::MRM3m:
729   case X86II::MRM4m: case X86II::MRM5m:
730   case X86II::MRM6m: case X86II::MRM7m: {
731     unsigned PCAdj = (CurOp+4 != MI.getNumOperands()) ?
732       (MI.getOperand(CurOp+4).isImmediate() ? sizeOfImm(Desc) : 4) : 0;
733
734     MCE.emitByte(BaseOpcode);
735     emitMemModRMByte(MI, CurOp, (Desc.TSFlags & X86II::FormMask)-X86II::MRM0m,
736                      PCAdj);
737     CurOp += 4;
738
739     if (CurOp != MI.getNumOperands()) {
740       const MachineOperand &MO = MI.getOperand(CurOp++);
741       if (MO.isImmediate())
742         emitConstant(MO.getImm(), sizeOfImm(Desc));
743       else if (MO.isGlobalAddress())
744         emitGlobalAddressForPtr(MO.getGlobal(), Is64BitMode, MO.getOffset());
745       else if (MO.isJumpTableIndex())
746         emitConstant(MCE.getJumpTableEntryAddress(MO.getJumpTableIndex()), 4);
747       else
748         assert(0 && "Unknown operand!");
749     }
750     break;
751   }
752
753   case X86II::MRMInitReg:
754     MCE.emitByte(BaseOpcode);
755     // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
756     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
757                      getX86RegNum(MI.getOperand(CurOp).getReg()));
758     ++CurOp;
759     break;
760   }
761
762   assert((Desc.Flags & M_VARIABLE_OPS) != 0 ||
763          CurOp == MI.getNumOperands() && "Unknown encoding!");
764 }