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