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