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