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