Replace PROLOG_LABEL with a new CFI_INSTRUCTION.
[oota-llvm.git] / lib / Target / X86 / X86CodeEmitter.cpp
1 //===-- 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 "X86.h"
17 #include "X86InstrInfo.h"
18 #include "X86JITInfo.h"
19 #include "X86Relocations.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/JITCodeEmitter.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/MC/MCCodeEmitter.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/PassManager.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
37 using namespace llvm;
38
39 STATISTIC(NumEmitted, "Number of machine instructions emitted");
40
41 namespace {
42   template<class CodeEmitter>
43   class Emitter : public MachineFunctionPass {
44     const X86InstrInfo  *II;
45     const DataLayout    *TD;
46     X86TargetMachine    &TM;
47     CodeEmitter         &MCE;
48     MachineModuleInfo   *MMI;
49     intptr_t PICBaseOffset;
50     bool Is64BitMode;
51     bool IsPIC;
52   public:
53     static char ID;
54     explicit Emitter(X86TargetMachine &tm, CodeEmitter &mce)
55       : MachineFunctionPass(ID), II(0), TD(0), TM(tm),
56         MCE(mce), PICBaseOffset(0), Is64BitMode(false),
57         IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
58
59     bool runOnMachineFunction(MachineFunction &MF);
60
61     virtual const char *getPassName() const {
62       return "X86 Machine Code Emitter";
63     }
64
65     void emitOpcodePrefix(uint64_t TSFlags, int MemOperand,
66                           const MachineInstr &MI,
67                           const MCInstrDesc *Desc) const;
68
69     void emitVEXOpcodePrefix(uint64_t TSFlags, int MemOperand,
70                              const MachineInstr &MI,
71                              const MCInstrDesc *Desc) const;
72
73     void emitSegmentOverridePrefix(uint64_t TSFlags,
74                                    int MemOperand,
75                                    const MachineInstr &MI) const;
76
77     void emitInstruction(MachineInstr &MI, const MCInstrDesc *Desc);
78
79     void getAnalysisUsage(AnalysisUsage &AU) const {
80       AU.setPreservesAll();
81       AU.addRequired<MachineModuleInfo>();
82       MachineFunctionPass::getAnalysisUsage(AU);
83     }
84
85   private:
86     void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
87     void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
88                            intptr_t Disp = 0, intptr_t PCAdj = 0,
89                            bool Indirect = false);
90     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
91     void emitConstPoolAddress(unsigned CPI, unsigned Reloc, intptr_t Disp = 0,
92                               intptr_t PCAdj = 0);
93     void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
94                               intptr_t PCAdj = 0);
95
96     void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
97                                intptr_t Adj = 0, bool IsPCRel = true);
98
99     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
100     void emitRegModRMByte(unsigned RegOpcodeField);
101     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
102     void emitConstant(uint64_t Val, unsigned Size);
103
104     void emitMemModRMByte(const MachineInstr &MI,
105                           unsigned Op, unsigned RegOpcodeField,
106                           intptr_t PCAdj = 0);
107
108     unsigned getX86RegNum(unsigned RegNo) const {
109       const TargetRegisterInfo *TRI = TM.getRegisterInfo();
110       return TRI->getEncodingValue(RegNo) & 0x7;
111     }
112
113     unsigned char getVEXRegisterEncoding(const MachineInstr &MI,
114                                          unsigned OpNum) const;
115   };
116
117 template<class CodeEmitter>
118   char Emitter<CodeEmitter>::ID = 0;
119 } // end anonymous namespace.
120
121 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
122 /// to the specified JITCodeEmitter object.
123 FunctionPass *llvm::createX86JITCodeEmitterPass(X86TargetMachine &TM,
124                                                 JITCodeEmitter &JCE) {
125   return new Emitter<JITCodeEmitter>(TM, JCE);
126 }
127
128 template<class CodeEmitter>
129 bool Emitter<CodeEmitter>::runOnMachineFunction(MachineFunction &MF) {
130   MMI = &getAnalysis<MachineModuleInfo>();
131   MCE.setModuleInfo(MMI);
132
133   II = TM.getInstrInfo();
134   TD = TM.getDataLayout();
135   Is64BitMode = TM.getSubtarget<X86Subtarget>().is64Bit();
136   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
137
138   do {
139     DEBUG(dbgs() << "JITTing function '" << MF.getName() << "'\n");
140     MCE.startFunction(MF);
141     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
142          MBB != E; ++MBB) {
143       MCE.StartMachineBasicBlock(MBB);
144       for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
145            I != E; ++I) {
146         const MCInstrDesc &Desc = I->getDesc();
147         emitInstruction(*I, &Desc);
148         // MOVPC32r is basically a call plus a pop instruction.
149         if (Desc.getOpcode() == X86::MOVPC32r)
150           emitInstruction(*I, &II->get(X86::POP32r));
151         ++NumEmitted;  // Keep track of the # of mi's emitted
152       }
153     }
154   } while (MCE.finishFunction(MF));
155
156   return false;
157 }
158
159 /// determineREX - Determine if the MachineInstr has to be encoded with a X86-64
160 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
161 /// size, and 3) use of X86-64 extended registers.
162 static unsigned determineREX(const MachineInstr &MI) {
163   unsigned REX = 0;
164   const MCInstrDesc &Desc = MI.getDesc();
165
166   // Pseudo instructions do not need REX prefix byte.
167   if ((Desc.TSFlags & X86II::FormMask) == X86II::Pseudo)
168     return 0;
169   if (Desc.TSFlags & X86II::REX_W)
170     REX |= 1 << 3;
171
172   unsigned NumOps = Desc.getNumOperands();
173   if (NumOps) {
174     bool isTwoAddr = NumOps > 1 &&
175       Desc.getOperandConstraint(1, MCOI::TIED_TO) != -1;
176
177     // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
178     unsigned i = isTwoAddr ? 1 : 0;
179     for (unsigned e = NumOps; i != e; ++i) {
180       const MachineOperand& MO = MI.getOperand(i);
181       if (MO.isReg()) {
182         unsigned Reg = MO.getReg();
183         if (X86II::isX86_64NonExtLowByteReg(Reg))
184           REX |= 0x40;
185       }
186     }
187
188     switch (Desc.TSFlags & X86II::FormMask) {
189       case X86II::MRMSrcReg: {
190         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
191           REX |= 1 << 2;
192         i = isTwoAddr ? 2 : 1;
193         for (unsigned e = NumOps; i != e; ++i) {
194           const MachineOperand& MO = MI.getOperand(i);
195           if (X86InstrInfo::isX86_64ExtendedReg(MO))
196             REX |= 1 << 0;
197         }
198         break;
199       }
200       case X86II::MRMSrcMem: {
201         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
202           REX |= 1 << 2;
203         unsigned Bit = 0;
204         i = isTwoAddr ? 2 : 1;
205         for (; i != NumOps; ++i) {
206           const MachineOperand& MO = MI.getOperand(i);
207           if (MO.isReg()) {
208             if (X86InstrInfo::isX86_64ExtendedReg(MO))
209               REX |= 1 << Bit;
210             Bit++;
211           }
212         }
213         break;
214       }
215       case X86II::MRMXm:
216       case X86II::MRM0m: case X86II::MRM1m:
217       case X86II::MRM2m: case X86II::MRM3m:
218       case X86II::MRM4m: case X86II::MRM5m:
219       case X86II::MRM6m: case X86II::MRM7m:
220       case X86II::MRMDestMem: {
221         unsigned e = (isTwoAddr ? X86::AddrNumOperands+1 : X86::AddrNumOperands);
222         i = isTwoAddr ? 1 : 0;
223         if (NumOps > e && X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e)))
224           REX |= 1 << 2;
225         unsigned Bit = 0;
226         for (; i != e; ++i) {
227           const MachineOperand& MO = MI.getOperand(i);
228           if (MO.isReg()) {
229             if (X86InstrInfo::isX86_64ExtendedReg(MO))
230               REX |= 1 << Bit;
231             Bit++;
232           }
233         }
234         break;
235       }
236       default: {
237         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
238           REX |= 1 << 0;
239         i = isTwoAddr ? 2 : 1;
240         for (unsigned e = NumOps; i != e; ++i) {
241           const MachineOperand& MO = MI.getOperand(i);
242           if (X86InstrInfo::isX86_64ExtendedReg(MO))
243             REX |= 1 << 2;
244         }
245         break;
246       }
247     }
248   }
249   return REX;
250 }
251
252
253 /// emitPCRelativeBlockAddress - This method keeps track of the information
254 /// necessary to resolve the address of this block later and emits a dummy
255 /// value.
256 ///
257 template<class CodeEmitter>
258 void Emitter<CodeEmitter>::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
259   // Remember where this reference was and where it is to so we can
260   // deal with it later.
261   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
262                                              X86::reloc_pcrel_word, MBB));
263   MCE.emitWordLE(0);
264 }
265
266 /// emitGlobalAddress - Emit the specified address to the code stream assuming
267 /// this is part of a "take the address of a global" instruction.
268 ///
269 template<class CodeEmitter>
270 void Emitter<CodeEmitter>::emitGlobalAddress(const GlobalValue *GV,
271                                 unsigned Reloc,
272                                 intptr_t Disp /* = 0 */,
273                                 intptr_t PCAdj /* = 0 */,
274                                 bool Indirect /* = false */) {
275   intptr_t RelocCST = Disp;
276   if (Reloc == X86::reloc_picrel_word)
277     RelocCST = PICBaseOffset;
278   else if (Reloc == X86::reloc_pcrel_word)
279     RelocCST = PCAdj;
280   MachineRelocation MR = Indirect
281     ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
282                                            const_cast<GlobalValue *>(GV),
283                                            RelocCST, false)
284     : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
285                                const_cast<GlobalValue *>(GV), RelocCST, false);
286   MCE.addRelocation(MR);
287   // The relocated value will be added to the displacement
288   if (Reloc == X86::reloc_absolute_dword)
289     MCE.emitDWordLE(Disp);
290   else
291     MCE.emitWordLE((int32_t)Disp);
292 }
293
294 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
295 /// be emitted to the current location in the function, and allow it to be PC
296 /// relative.
297 template<class CodeEmitter>
298 void Emitter<CodeEmitter>::emitExternalSymbolAddress(const char *ES,
299                                                      unsigned Reloc) {
300   intptr_t RelocCST = (Reloc == X86::reloc_picrel_word) ? PICBaseOffset : 0;
301
302   // X86 never needs stubs because instruction selection will always pick
303   // an instruction sequence that is large enough to hold any address
304   // to a symbol.
305   // (see X86ISelLowering.cpp, near 2039: X86TargetLowering::LowerCall)
306   bool NeedStub = false;
307   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
308                                                  Reloc, ES, RelocCST,
309                                                  0, NeedStub));
310   if (Reloc == X86::reloc_absolute_dword)
311     MCE.emitDWordLE(0);
312   else
313     MCE.emitWordLE(0);
314 }
315
316 /// emitConstPoolAddress - Arrange for the address of an constant pool
317 /// to be emitted to the current location in the function, and allow it to be PC
318 /// relative.
319 template<class CodeEmitter>
320 void Emitter<CodeEmitter>::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
321                                    intptr_t Disp /* = 0 */,
322                                    intptr_t PCAdj /* = 0 */) {
323   intptr_t RelocCST = 0;
324   if (Reloc == X86::reloc_picrel_word)
325     RelocCST = PICBaseOffset;
326   else if (Reloc == X86::reloc_pcrel_word)
327     RelocCST = PCAdj;
328   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
329                                                     Reloc, CPI, RelocCST));
330   // The relocated value will be added to the displacement
331   if (Reloc == X86::reloc_absolute_dword)
332     MCE.emitDWordLE(Disp);
333   else
334     MCE.emitWordLE((int32_t)Disp);
335 }
336
337 /// emitJumpTableAddress - Arrange for the address of a jump table to
338 /// be emitted to the current location in the function, and allow it to be PC
339 /// relative.
340 template<class CodeEmitter>
341 void Emitter<CodeEmitter>::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
342                                    intptr_t PCAdj /* = 0 */) {
343   intptr_t RelocCST = 0;
344   if (Reloc == X86::reloc_picrel_word)
345     RelocCST = PICBaseOffset;
346   else if (Reloc == X86::reloc_pcrel_word)
347     RelocCST = PCAdj;
348   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
349                                                     Reloc, JTI, RelocCST));
350   // The relocated value will be added to the displacement
351   if (Reloc == X86::reloc_absolute_dword)
352     MCE.emitDWordLE(0);
353   else
354     MCE.emitWordLE(0);
355 }
356
357 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
358                                       unsigned RM) {
359   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
360   return RM | (RegOpcode << 3) | (Mod << 6);
361 }
362
363 template<class CodeEmitter>
364 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned ModRMReg,
365                                             unsigned RegOpcodeFld){
366   MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
367 }
368
369 template<class CodeEmitter>
370 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned RegOpcodeFld) {
371   MCE.emitByte(ModRMByte(3, RegOpcodeFld, 0));
372 }
373
374 template<class CodeEmitter>
375 void Emitter<CodeEmitter>::emitSIBByte(unsigned SS,
376                                        unsigned Index,
377                                        unsigned Base) {
378   // SIB byte is in the same format as the ModRMByte...
379   MCE.emitByte(ModRMByte(SS, Index, Base));
380 }
381
382 template<class CodeEmitter>
383 void Emitter<CodeEmitter>::emitConstant(uint64_t Val, unsigned Size) {
384   // Output the constant in little endian byte order...
385   for (unsigned i = 0; i != Size; ++i) {
386     MCE.emitByte(Val & 255);
387     Val >>= 8;
388   }
389 }
390
391 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
392 /// sign-extended field.
393 static bool isDisp8(int Value) {
394   return Value == (signed char)Value;
395 }
396
397 static bool gvNeedsNonLazyPtr(const MachineOperand &GVOp,
398                               const TargetMachine &TM) {
399   // For Darwin-64, simulate the linktime GOT by using the same non-lazy-pointer
400   // mechanism as 32-bit mode.
401   if (TM.getSubtarget<X86Subtarget>().is64Bit() &&
402       !TM.getSubtarget<X86Subtarget>().isTargetDarwin())
403     return false;
404
405   // Return true if this is a reference to a stub containing the address of the
406   // global, not the global itself.
407   return isGlobalStubReference(GVOp.getTargetFlags());
408 }
409
410 template<class CodeEmitter>
411 void Emitter<CodeEmitter>::emitDisplacementField(const MachineOperand *RelocOp,
412                                                  int DispVal,
413                                                  intptr_t Adj /* = 0 */,
414                                                  bool IsPCRel /* = true */) {
415   // If this is a simple integer displacement that doesn't require a relocation,
416   // emit it now.
417   if (!RelocOp) {
418     emitConstant(DispVal, 4);
419     return;
420   }
421
422   // Otherwise, this is something that requires a relocation.  Emit it as such
423   // now.
424   unsigned RelocType = Is64BitMode ?
425     (IsPCRel ? X86::reloc_pcrel_word : X86::reloc_absolute_word_sext)
426     : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
427   if (RelocOp->isGlobal()) {
428     // In 64-bit static small code model, we could potentially emit absolute.
429     // But it's probably not beneficial. If the MCE supports using RIP directly
430     // do it, otherwise fallback to absolute (this is determined by IsPCRel).
431     //  89 05 00 00 00 00     mov    %eax,0(%rip)  # PC-relative
432     //  89 04 25 00 00 00 00  mov    %eax,0x0      # Absolute
433     bool Indirect = gvNeedsNonLazyPtr(*RelocOp, TM);
434     emitGlobalAddress(RelocOp->getGlobal(), RelocType, RelocOp->getOffset(),
435                       Adj, Indirect);
436   } else if (RelocOp->isSymbol()) {
437     emitExternalSymbolAddress(RelocOp->getSymbolName(), RelocType);
438   } else if (RelocOp->isCPI()) {
439     emitConstPoolAddress(RelocOp->getIndex(), RelocType,
440                          RelocOp->getOffset(), Adj);
441   } else {
442     assert(RelocOp->isJTI() && "Unexpected machine operand!");
443     emitJumpTableAddress(RelocOp->getIndex(), RelocType, Adj);
444   }
445 }
446
447 template<class CodeEmitter>
448 void Emitter<CodeEmitter>::emitMemModRMByte(const MachineInstr &MI,
449                                             unsigned Op,unsigned RegOpcodeField,
450                                             intptr_t PCAdj) {
451   const MachineOperand &Op3 = MI.getOperand(Op+3);
452   int DispVal = 0;
453   const MachineOperand *DispForReloc = 0;
454
455   // Figure out what sort of displacement we have to handle here.
456   if (Op3.isGlobal()) {
457     DispForReloc = &Op3;
458   } else if (Op3.isSymbol()) {
459     DispForReloc = &Op3;
460   } else if (Op3.isCPI()) {
461     if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
462       DispForReloc = &Op3;
463     } else {
464       DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
465       DispVal += Op3.getOffset();
466     }
467   } else if (Op3.isJTI()) {
468     if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
469       DispForReloc = &Op3;
470     } else {
471       DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
472     }
473   } else {
474     DispVal = Op3.getImm();
475   }
476
477   const MachineOperand &Base     = MI.getOperand(Op);
478   const MachineOperand &Scale    = MI.getOperand(Op+1);
479   const MachineOperand &IndexReg = MI.getOperand(Op+2);
480
481   unsigned BaseReg = Base.getReg();
482
483   // Handle %rip relative addressing.
484   if (BaseReg == X86::RIP ||
485       (Is64BitMode && DispForReloc)) { // [disp32+RIP] in X86-64 mode
486     assert(IndexReg.getReg() == 0 && Is64BitMode &&
487            "Invalid rip-relative address");
488     MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
489     emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
490     return;
491   }
492
493   // Indicate that the displacement will use an pcrel or absolute reference
494   // by default. MCEs able to resolve addresses on-the-fly use pcrel by default
495   // while others, unless explicit asked to use RIP, use absolute references.
496   bool IsPCRel = MCE.earlyResolveAddresses() ? true : false;
497
498   // Is a SIB byte needed?
499   // If no BaseReg, issue a RIP relative instruction only if the MCE can
500   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
501   // 2-7) and absolute references.
502   unsigned BaseRegNo = -1U;
503   if (BaseReg != 0 && BaseReg != X86::RIP)
504     BaseRegNo = getX86RegNum(BaseReg);
505
506   if (// The SIB byte must be used if there is an index register.
507       IndexReg.getReg() == 0 &&
508       // The SIB byte must be used if the base is ESP/RSP/R12, all of which
509       // encode to an R/M value of 4, which indicates that a SIB byte is
510       // present.
511       BaseRegNo != N86::ESP &&
512       // If there is no base register and we're in 64-bit mode, we need a SIB
513       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
514       (!Is64BitMode || BaseReg != 0)) {
515     if (BaseReg == 0 ||          // [disp32]     in X86-32 mode
516         BaseReg == X86::RIP) {   // [disp32+RIP] in X86-64 mode
517       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
518       emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
519       return;
520     }
521
522     // If the base is not EBP/ESP and there is no displacement, use simple
523     // indirect register encoding, this handles addresses like [EAX].  The
524     // encoding for [EBP] with no displacement means [disp32] so we handle it
525     // by emitting a displacement of 0 below.
526     if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
527       MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
528       return;
529     }
530
531     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
532     if (!DispForReloc && isDisp8(DispVal)) {
533       MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
534       emitConstant(DispVal, 1);
535       return;
536     }
537
538     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
539     MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
540     emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
541     return;
542   }
543
544   // Otherwise we need a SIB byte, so start by outputting the ModR/M byte first.
545   assert(IndexReg.getReg() != X86::ESP &&
546          IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
547
548   bool ForceDisp32 = false;
549   bool ForceDisp8  = false;
550   if (BaseReg == 0) {
551     // If there is no base register, we emit the special case SIB byte with
552     // MOD=0, BASE=4, to JUST get the index, scale, and displacement.
553     MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
554     ForceDisp32 = true;
555   } else if (DispForReloc) {
556     // Emit the normal disp32 encoding.
557     MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
558     ForceDisp32 = true;
559   } else if (DispVal == 0 && BaseRegNo != N86::EBP) {
560     // Emit no displacement ModR/M byte
561     MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
562   } else if (isDisp8(DispVal)) {
563     // Emit the disp8 encoding...
564     MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
565     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
566   } else {
567     // Emit the normal disp32 encoding...
568     MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
569   }
570
571   // Calculate what the SS field value should be...
572   static const unsigned SSTable[] = { ~0U, 0, 1, ~0U, 2, ~0U, ~0U, ~0U, 3 };
573   unsigned SS = SSTable[Scale.getImm()];
574
575   if (BaseReg == 0) {
576     // Handle the SIB byte for the case where there is no base, see Intel
577     // Manual 2A, table 2-7. The displacement has already been output.
578     unsigned IndexRegNo;
579     if (IndexReg.getReg())
580       IndexRegNo = getX86RegNum(IndexReg.getReg());
581     else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
582       IndexRegNo = 4;
583     emitSIBByte(SS, IndexRegNo, 5);
584   } else {
585     unsigned BaseRegNo = getX86RegNum(BaseReg);
586     unsigned IndexRegNo;
587     if (IndexReg.getReg())
588       IndexRegNo = getX86RegNum(IndexReg.getReg());
589     else
590       IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
591     emitSIBByte(SS, IndexRegNo, BaseRegNo);
592   }
593
594   // Do we need to output a displacement?
595   if (ForceDisp8) {
596     emitConstant(DispVal, 1);
597   } else if (DispVal != 0 || ForceDisp32) {
598     emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
599   }
600 }
601
602 static const MCInstrDesc *UpdateOp(MachineInstr &MI, const X86InstrInfo *II,
603                                    unsigned Opcode) {
604   const MCInstrDesc *Desc = &II->get(Opcode);
605   MI.setDesc(*Desc);
606   return Desc;
607 }
608
609 /// Is16BitMemOperand - Return true if the specified instruction has
610 /// a 16-bit memory operand. Op specifies the operand # of the memoperand.
611 static bool Is16BitMemOperand(const MachineInstr &MI, unsigned Op) {
612   const MachineOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
613   const MachineOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
614
615   if ((BaseReg.getReg() != 0 &&
616        X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg.getReg())) ||
617       (IndexReg.getReg() != 0 &&
618        X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg.getReg())))
619     return true;
620   return false;
621 }
622
623 /// Is32BitMemOperand - Return true if the specified instruction has
624 /// a 32-bit memory operand. Op specifies the operand # of the memoperand.
625 static bool Is32BitMemOperand(const MachineInstr &MI, unsigned Op) {
626   const MachineOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
627   const MachineOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
628
629   if ((BaseReg.getReg() != 0 &&
630        X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg.getReg())) ||
631       (IndexReg.getReg() != 0 &&
632        X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg.getReg())))
633     return true;
634   return false;
635 }
636
637 /// Is64BitMemOperand - Return true if the specified instruction has
638 /// a 64-bit memory operand. Op specifies the operand # of the memoperand.
639 #ifndef NDEBUG
640 static bool Is64BitMemOperand(const MachineInstr &MI, unsigned Op) {
641   const MachineOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
642   const MachineOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
643
644   if ((BaseReg.getReg() != 0 &&
645        X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg.getReg())) ||
646       (IndexReg.getReg() != 0 &&
647        X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg.getReg())))
648     return true;
649   return false;
650 }
651 #endif
652
653 template<class CodeEmitter>
654 void Emitter<CodeEmitter>::emitOpcodePrefix(uint64_t TSFlags,
655                                             int MemOperand,
656                                             const MachineInstr &MI,
657                                             const MCInstrDesc *Desc) const {
658   // Emit the operand size opcode prefix as needed.
659   if (((TSFlags & X86II::OpSizeMask) >> X86II::OpSizeShift) == X86II::OpSize16)
660     MCE.emitByte(0x66);
661
662   switch (Desc->TSFlags & X86II::OpPrefixMask) {
663   case X86II::PD:   // 66
664     MCE.emitByte(0x66);
665     break;
666   case X86II::XS:   // F3
667     MCE.emitByte(0xF3);
668     break;
669   case X86II::XD:   // F2
670     MCE.emitByte(0xF2);
671     break;
672   }
673
674   // Handle REX prefix.
675   if (Is64BitMode) {
676     if (unsigned REX = determineREX(MI))
677       MCE.emitByte(0x40 | REX);
678   }
679
680   // 0x0F escape code must be emitted just before the opcode.
681   switch (Desc->TSFlags & X86II::OpMapMask) {
682   case X86II::TB:  // Two-byte opcode map
683   case X86II::T8:  // 0F 38
684   case X86II::TA:  // 0F 3A
685     MCE.emitByte(0x0F);
686     break;
687   }
688
689   switch (Desc->TSFlags & X86II::OpMapMask) {
690   case X86II::T8:    // 0F 38
691     MCE.emitByte(0x38);
692     break;
693   case X86II::TA:    // 0F 3A
694     MCE.emitByte(0x3A);
695     break;
696   }
697 }
698
699 // On regular x86, both XMM0-XMM7 and XMM8-XMM15 are encoded in the range
700 // 0-7 and the difference between the 2 groups is given by the REX prefix.
701 // In the VEX prefix, registers are seen sequencially from 0-15 and encoded
702 // in 1's complement form, example:
703 //
704 //  ModRM field => XMM9 => 1
705 //  VEX.VVVV    => XMM9 => ~9
706 //
707 // See table 4-35 of Intel AVX Programming Reference for details.
708 template<class CodeEmitter>
709 unsigned char
710 Emitter<CodeEmitter>::getVEXRegisterEncoding(const MachineInstr &MI,
711                                              unsigned OpNum) const {
712   unsigned SrcReg = MI.getOperand(OpNum).getReg();
713   unsigned SrcRegNum = getX86RegNum(MI.getOperand(OpNum).getReg());
714   if (X86II::isX86_64ExtendedReg(SrcReg))
715     SrcRegNum |= 8;
716
717   // The registers represented through VEX_VVVV should
718   // be encoded in 1's complement form.
719   return (~SrcRegNum) & 0xf;
720 }
721
722 /// EmitSegmentOverridePrefix - Emit segment override opcode prefix as needed
723 template<class CodeEmitter>
724 void Emitter<CodeEmitter>::emitSegmentOverridePrefix(uint64_t TSFlags,
725                                                  int MemOperand,
726                                                  const MachineInstr &MI) const {
727   if (MemOperand < 0)
728     return; // No memory operand
729
730   // Check for explicit segment override on memory operand.
731   switch (MI.getOperand(MemOperand+X86::AddrSegmentReg).getReg()) {
732   default: llvm_unreachable("Unknown segment register!");
733   case 0: break;
734   case X86::CS: MCE.emitByte(0x2E); break;
735   case X86::SS: MCE.emitByte(0x36); break;
736   case X86::DS: MCE.emitByte(0x3E); break;
737   case X86::ES: MCE.emitByte(0x26); break;
738   case X86::FS: MCE.emitByte(0x64); break;
739   case X86::GS: MCE.emitByte(0x65); break;
740   }
741 }
742
743 template<class CodeEmitter>
744 void Emitter<CodeEmitter>::emitVEXOpcodePrefix(uint64_t TSFlags,
745                                                int MemOperand,
746                                                const MachineInstr &MI,
747                                                const MCInstrDesc *Desc) const {
748   unsigned char Encoding = (TSFlags & X86II::EncodingMask) >>
749                            X86II::EncodingShift;
750   bool HasVEX_4V = (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
751   bool HasVEX_4VOp3 = (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
752   bool HasMemOp4 = (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
753
754   // VEX_R: opcode externsion equivalent to REX.R in
755   // 1's complement (inverted) form
756   //
757   //  1: Same as REX_R=0 (must be 1 in 32-bit mode)
758   //  0: Same as REX_R=1 (64 bit mode only)
759   //
760   unsigned char VEX_R = 0x1;
761
762   // VEX_X: equivalent to REX.X, only used when a
763   // register is used for index in SIB Byte.
764   //
765   //  1: Same as REX.X=0 (must be 1 in 32-bit mode)
766   //  0: Same as REX.X=1 (64-bit mode only)
767   unsigned char VEX_X = 0x1;
768
769   // VEX_B:
770   //
771   //  1: Same as REX_B=0 (ignored in 32-bit mode)
772   //  0: Same as REX_B=1 (64 bit mode only)
773   //
774   unsigned char VEX_B = 0x1;
775
776   // VEX_W: opcode specific (use like REX.W, or used for
777   // opcode extension, or ignored, depending on the opcode byte)
778   unsigned char VEX_W = 0;
779
780   // VEX_5M (VEX m-mmmmm field):
781   //
782   //  0b00000: Reserved for future use
783   //  0b00001: implied 0F leading opcode
784   //  0b00010: implied 0F 38 leading opcode bytes
785   //  0b00011: implied 0F 3A leading opcode bytes
786   //  0b00100-0b11111: Reserved for future use
787   //  0b01000: XOP map select - 08h instructions with imm byte
788   //  0b01001: XOP map select - 09h instructions with no imm byte
789   //  0b01010: XOP map select - 0Ah instructions with imm dword
790   unsigned char VEX_5M = 0;
791
792   // VEX_4V (VEX vvvv field): a register specifier
793   // (in 1's complement form) or 1111 if unused.
794   unsigned char VEX_4V = 0xf;
795
796   // VEX_L (Vector Length):
797   //
798   //  0: scalar or 128-bit vector
799   //  1: 256-bit vector
800   //
801   unsigned char VEX_L = 0;
802
803   // VEX_PP: opcode extension providing equivalent
804   // functionality of a SIMD prefix
805   //
806   //  0b00: None
807   //  0b01: 66
808   //  0b10: F3
809   //  0b11: F2
810   //
811   unsigned char VEX_PP = 0;
812
813   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_W)
814     VEX_W = 1;
815
816   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_L)
817     VEX_L = 1;
818
819   switch (TSFlags & X86II::OpPrefixMask) {
820   default: break; // VEX_PP already correct
821   case X86II::PD: VEX_PP = 0x1; break; // 66
822   case X86II::XS: VEX_PP = 0x2; break; // F3
823   case X86II::XD: VEX_PP = 0x3; break; // F2
824   }
825
826   switch (TSFlags & X86II::OpMapMask) {
827   default: llvm_unreachable("Invalid prefix!");
828   case X86II::TB:   VEX_5M = 0x1; break; // 0F
829   case X86II::T8:   VEX_5M = 0x2; break; // 0F 38
830   case X86II::TA:   VEX_5M = 0x3; break; // 0F 3A
831   case X86II::XOP8: VEX_5M = 0x8; break;
832   case X86II::XOP9: VEX_5M = 0x9; break;
833   case X86II::XOPA: VEX_5M = 0xA; break;
834   }
835
836   // Classify VEX_B, VEX_4V, VEX_R, VEX_X
837   unsigned NumOps = Desc->getNumOperands();
838   unsigned CurOp = 0;
839   if (NumOps > 1 && Desc->getOperandConstraint(1, MCOI::TIED_TO) == 0)
840     ++CurOp;
841   else if (NumOps > 3 && Desc->getOperandConstraint(2, MCOI::TIED_TO) == 0) {
842     assert(Desc->getOperandConstraint(NumOps - 1, MCOI::TIED_TO) == 1);
843     // Special case for GATHER with 2 TIED_TO operands
844     // Skip the first 2 operands: dst, mask_wb
845     CurOp += 2;
846   }
847
848   switch (TSFlags & X86II::FormMask) {
849     default: llvm_unreachable("Unexpected form in emitVEXOpcodePrefix!");
850     case X86II::RawFrm:
851       break;
852     case X86II::MRMDestMem: {
853       // MRMDestMem instructions forms:
854       //  MemAddr, src1(ModR/M)
855       //  MemAddr, src1(VEX_4V), src2(ModR/M)
856       //  MemAddr, src1(ModR/M), imm8
857       //
858       if (X86II::isX86_64ExtendedReg(MI.getOperand(X86::AddrBaseReg).getReg()))
859         VEX_B = 0x0;
860       if (X86II::isX86_64ExtendedReg(MI.getOperand(X86::AddrIndexReg).getReg()))
861         VEX_X = 0x0;
862
863       CurOp = X86::AddrNumOperands;
864       if (HasVEX_4V)
865         VEX_4V = getVEXRegisterEncoding(MI, CurOp++);
866
867       const MachineOperand &MO = MI.getOperand(CurOp);
868       if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
869         VEX_R = 0x0;
870       break;
871     }
872     case X86II::MRMSrcMem:
873       // MRMSrcMem instructions forms:
874       //  src1(ModR/M), MemAddr
875       //  src1(ModR/M), src2(VEX_4V), MemAddr
876       //  src1(ModR/M), MemAddr, imm8
877       //  src1(ModR/M), MemAddr, src2(VEX_I8IMM)
878       //
879       //  FMA4:
880       //  dst(ModR/M.reg), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
881       //  dst(ModR/M.reg), src1(VEX_4V), src2(VEX_I8IMM), src3(ModR/M),
882       if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
883         VEX_R = 0x0;
884       CurOp++;
885
886       if (HasVEX_4V) {
887         VEX_4V = getVEXRegisterEncoding(MI, CurOp);
888         CurOp++;
889       }
890
891       if (X86II::isX86_64ExtendedReg(
892                           MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
893         VEX_B = 0x0;
894       if (X86II::isX86_64ExtendedReg(
895                           MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
896         VEX_X = 0x0;
897
898       if (HasVEX_4VOp3)
899         VEX_4V = getVEXRegisterEncoding(MI, CurOp+X86::AddrNumOperands);
900       break;
901     case X86II::MRM0m: case X86II::MRM1m:
902     case X86II::MRM2m: case X86II::MRM3m:
903     case X86II::MRM4m: case X86II::MRM5m:
904     case X86II::MRM6m: case X86II::MRM7m: {
905       // MRM[0-9]m instructions forms:
906       //  MemAddr
907       //  src1(VEX_4V), MemAddr
908       if (HasVEX_4V)
909         VEX_4V = getVEXRegisterEncoding(MI, CurOp++);
910
911       if (X86II::isX86_64ExtendedReg(
912                           MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
913         VEX_B = 0x0;
914       if (X86II::isX86_64ExtendedReg(
915                           MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
916         VEX_X = 0x0;
917       break;
918     }
919     case X86II::MRMSrcReg:
920       // MRMSrcReg instructions forms:
921       //  dst(ModR/M), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
922       //  dst(ModR/M), src1(ModR/M)
923       //  dst(ModR/M), src1(ModR/M), imm8
924       //
925       if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
926         VEX_R = 0x0;
927       CurOp++;
928
929       if (HasVEX_4V)
930         VEX_4V = getVEXRegisterEncoding(MI, CurOp++);
931
932       if (HasMemOp4) // Skip second register source (encoded in I8IMM)
933         CurOp++;
934
935       if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
936         VEX_B = 0x0;
937       CurOp++;
938       if (HasVEX_4VOp3)
939         VEX_4V = getVEXRegisterEncoding(MI, CurOp);
940       break;
941     case X86II::MRMDestReg:
942       // MRMDestReg instructions forms:
943       //  dst(ModR/M), src(ModR/M)
944       //  dst(ModR/M), src(ModR/M), imm8
945       //  dst(ModR/M), src1(VEX_4V), src2(ModR/M)
946       if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
947         VEX_B = 0x0;
948       CurOp++;
949
950       if (HasVEX_4V)
951         VEX_4V = getVEXRegisterEncoding(MI, CurOp++);
952
953       if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
954         VEX_R = 0x0;
955       break;
956     case X86II::MRM0r: case X86II::MRM1r:
957     case X86II::MRM2r: case X86II::MRM3r:
958     case X86II::MRM4r: case X86II::MRM5r:
959     case X86II::MRM6r: case X86II::MRM7r:
960       // MRM0r-MRM7r instructions forms:
961       //  dst(VEX_4V), src(ModR/M), imm8
962       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
963       CurOp++;
964
965       if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
966         VEX_B = 0x0;
967       break;
968   }
969
970   // Emit segment override opcode prefix as needed.
971   emitSegmentOverridePrefix(TSFlags, MemOperand, MI);
972
973   // VEX opcode prefix can have 2 or 3 bytes
974   //
975   //  3 bytes:
976   //    +-----+ +--------------+ +-------------------+
977   //    | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
978   //    +-----+ +--------------+ +-------------------+
979   //  2 bytes:
980   //    +-----+ +-------------------+
981   //    | C5h | | R | vvvv | L | pp |
982   //    +-----+ +-------------------+
983   //
984   //  XOP uses a similar prefix:
985   //    +-----+ +--------------+ +-------------------+
986   //    | 8Fh | | RXB | m-mmmm | | W | vvvv | L | pp |
987   //    +-----+ +--------------+ +-------------------+
988   unsigned char LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
989
990   // Can this use the 2 byte VEX prefix?
991   if (Encoding == X86II::VEX && VEX_B && VEX_X && !VEX_W && (VEX_5M == 1)) {
992     MCE.emitByte(0xC5);
993     MCE.emitByte(LastByte | (VEX_R << 7));
994     return;
995   }
996
997   // 3 byte VEX prefix
998   MCE.emitByte(Encoding == X86II::XOP ? 0x8F : 0xC4);
999   MCE.emitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M);
1000   MCE.emitByte(LastByte | (VEX_W << 7));
1001 }
1002
1003 template<class CodeEmitter>
1004 void Emitter<CodeEmitter>::emitInstruction(MachineInstr &MI,
1005                                            const MCInstrDesc *Desc) {
1006   DEBUG(dbgs() << MI);
1007
1008   // If this is a pseudo instruction, lower it.
1009   switch (Desc->getOpcode()) {
1010   case X86::ADD16rr_DB:      Desc = UpdateOp(MI, II, X86::OR16rr); break;
1011   case X86::ADD32rr_DB:      Desc = UpdateOp(MI, II, X86::OR32rr); break;
1012   case X86::ADD64rr_DB:      Desc = UpdateOp(MI, II, X86::OR64rr); break;
1013   case X86::ADD16ri_DB:      Desc = UpdateOp(MI, II, X86::OR16ri); break;
1014   case X86::ADD32ri_DB:      Desc = UpdateOp(MI, II, X86::OR32ri); break;
1015   case X86::ADD64ri32_DB:    Desc = UpdateOp(MI, II, X86::OR64ri32); break;
1016   case X86::ADD16ri8_DB:     Desc = UpdateOp(MI, II, X86::OR16ri8); break;
1017   case X86::ADD32ri8_DB:     Desc = UpdateOp(MI, II, X86::OR32ri8); break;
1018   case X86::ADD64ri8_DB:     Desc = UpdateOp(MI, II, X86::OR64ri8); break;
1019   case X86::ACQUIRE_MOV8rm:  Desc = UpdateOp(MI, II, X86::MOV8rm); break;
1020   case X86::ACQUIRE_MOV16rm: Desc = UpdateOp(MI, II, X86::MOV16rm); break;
1021   case X86::ACQUIRE_MOV32rm: Desc = UpdateOp(MI, II, X86::MOV32rm); break;
1022   case X86::ACQUIRE_MOV64rm: Desc = UpdateOp(MI, II, X86::MOV64rm); break;
1023   case X86::RELEASE_MOV8mr:  Desc = UpdateOp(MI, II, X86::MOV8mr); break;
1024   case X86::RELEASE_MOV16mr: Desc = UpdateOp(MI, II, X86::MOV16mr); break;
1025   case X86::RELEASE_MOV32mr: Desc = UpdateOp(MI, II, X86::MOV32mr); break;
1026   case X86::RELEASE_MOV64mr: Desc = UpdateOp(MI, II, X86::MOV64mr); break;
1027   }
1028
1029
1030   MCE.processDebugLoc(MI.getDebugLoc(), true);
1031
1032   unsigned Opcode = Desc->Opcode;
1033
1034   // If this is a two-address instruction, skip one of the register operands.
1035   unsigned NumOps = Desc->getNumOperands();
1036   unsigned CurOp = 0;
1037   if (NumOps > 1 && Desc->getOperandConstraint(1, MCOI::TIED_TO) == 0)
1038     ++CurOp;
1039   else if (NumOps > 3 && Desc->getOperandConstraint(2, MCOI::TIED_TO) == 0) {
1040     assert(Desc->getOperandConstraint(NumOps - 1, MCOI::TIED_TO) == 1);
1041     // Special case for GATHER with 2 TIED_TO operands
1042     // Skip the first 2 operands: dst, mask_wb
1043     CurOp += 2;
1044   }
1045
1046   uint64_t TSFlags = Desc->TSFlags;
1047
1048   // Encoding type for this instruction.
1049   unsigned char Encoding = (TSFlags & X86II::EncodingMask) >>
1050                            X86II::EncodingShift;
1051
1052   // It uses the VEX.VVVV field?
1053   bool HasVEX_4V = (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
1054   bool HasVEX_4VOp3 = (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
1055   bool HasMemOp4 = (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
1056   const unsigned MemOp4_I8IMMOperand = 2;
1057
1058   // Determine where the memory operand starts, if present.
1059   int MemoryOperand = X86II::getMemoryOperandNo(TSFlags, Opcode);
1060   if (MemoryOperand != -1) MemoryOperand += CurOp;
1061
1062   // Emit the lock opcode prefix as needed.
1063   if (Desc->TSFlags & X86II::LOCK)
1064     MCE.emitByte(0xF0);
1065
1066   // Emit segment override opcode prefix as needed.
1067   emitSegmentOverridePrefix(TSFlags, MemoryOperand, MI);
1068
1069   // Emit the repeat opcode prefix as needed.
1070   if (Desc->TSFlags & X86II::REP)
1071     MCE.emitByte(0xF3);
1072
1073   // Emit the address size opcode prefix as needed.
1074   bool need_address_override;
1075   if (TSFlags & X86II::AdSize) {
1076     need_address_override = true;
1077   } else if (MemoryOperand < 0) {
1078     need_address_override = false;
1079   } else if (Is64BitMode) {
1080     assert(!Is16BitMemOperand(MI, MemoryOperand));
1081     need_address_override = Is32BitMemOperand(MI, MemoryOperand);
1082   } else {
1083     assert(!Is64BitMemOperand(MI, MemoryOperand));
1084     need_address_override = Is16BitMemOperand(MI, MemoryOperand);
1085   }
1086
1087   if (need_address_override)
1088     MCE.emitByte(0x67);
1089
1090   if (Encoding == 0)
1091     emitOpcodePrefix(TSFlags, MemoryOperand, MI, Desc);
1092   else
1093     emitVEXOpcodePrefix(TSFlags, MemoryOperand, MI, Desc);
1094
1095   unsigned char BaseOpcode = X86II::getBaseOpcodeFor(Desc->TSFlags);
1096   switch (TSFlags & X86II::FormMask) {
1097   default:
1098     llvm_unreachable("Unknown FormMask value in X86 MachineCodeEmitter!");
1099   case X86II::Pseudo:
1100     // Remember the current PC offset, this is the PIC relocation
1101     // base address.
1102     switch (Opcode) {
1103     default:
1104       llvm_unreachable("pseudo instructions should be removed before code"
1105                        " emission");
1106     // Do nothing for Int_MemBarrier - it's just a comment.  Add a debug
1107     // to make it slightly easier to see.
1108     case X86::Int_MemBarrier:
1109       DEBUG(dbgs() << "#MEMBARRIER\n");
1110       break;
1111
1112     case TargetOpcode::INLINEASM:
1113       // We allow inline assembler nodes with empty bodies - they can
1114       // implicitly define registers, which is ok for JIT.
1115       if (MI.getOperand(0).getSymbolName()[0])
1116         report_fatal_error("JIT does not support inline asm!");
1117       break;
1118     case TargetOpcode::CFI_INSTRUCTION:
1119       break;
1120     case TargetOpcode::GC_LABEL:
1121     case TargetOpcode::EH_LABEL:
1122       MCE.emitLabel(MI.getOperand(0).getMCSymbol());
1123       break;
1124
1125     case TargetOpcode::IMPLICIT_DEF:
1126     case TargetOpcode::KILL:
1127       break;
1128     case X86::MOVPC32r: {
1129       // This emits the "call" portion of this pseudo instruction.
1130       MCE.emitByte(BaseOpcode);
1131       emitConstant(0, X86II::getSizeOfImm(Desc->TSFlags));
1132       // Remember PIC base.
1133       PICBaseOffset = (intptr_t) MCE.getCurrentPCOffset();
1134       X86JITInfo *JTI = TM.getJITInfo();
1135       JTI->setPICBase(MCE.getCurrentPCValue());
1136       break;
1137     }
1138     }
1139     CurOp = NumOps;
1140     break;
1141   case X86II::RawFrm: {
1142     MCE.emitByte(BaseOpcode);
1143
1144     if (CurOp == NumOps)
1145       break;
1146
1147     const MachineOperand &MO = MI.getOperand(CurOp++);
1148
1149     DEBUG(dbgs() << "RawFrm CurOp " << CurOp << "\n");
1150     DEBUG(dbgs() << "isMBB " << MO.isMBB() << "\n");
1151     DEBUG(dbgs() << "isGlobal " << MO.isGlobal() << "\n");
1152     DEBUG(dbgs() << "isSymbol " << MO.isSymbol() << "\n");
1153     DEBUG(dbgs() << "isImm " << MO.isImm() << "\n");
1154
1155     if (MO.isMBB()) {
1156       emitPCRelativeBlockAddress(MO.getMBB());
1157       break;
1158     }
1159
1160     if (MO.isGlobal()) {
1161       emitGlobalAddress(MO.getGlobal(), X86::reloc_pcrel_word,
1162                         MO.getOffset(), 0);
1163       break;
1164     }
1165
1166     if (MO.isSymbol()) {
1167       emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
1168       break;
1169     }
1170
1171     // FIXME: Only used by hackish MCCodeEmitter, remove when dead.
1172     if (MO.isJTI()) {
1173       emitJumpTableAddress(MO.getIndex(), X86::reloc_pcrel_word);
1174       break;
1175     }
1176
1177     assert(MO.isImm() && "Unknown RawFrm operand!");
1178     if (Opcode == X86::CALLpcrel32 || Opcode == X86::CALL64pcrel32) {
1179       // Fix up immediate operand for pc relative calls.
1180       intptr_t Imm = (intptr_t)MO.getImm();
1181       Imm = Imm - MCE.getCurrentPCValue() - 4;
1182       emitConstant(Imm, X86II::getSizeOfImm(Desc->TSFlags));
1183     } else
1184       emitConstant(MO.getImm(), X86II::getSizeOfImm(Desc->TSFlags));
1185     break;
1186   }
1187
1188   case X86II::AddRegFrm: {
1189     MCE.emitByte(BaseOpcode +
1190                  getX86RegNum(MI.getOperand(CurOp++).getReg()));
1191
1192     if (CurOp == NumOps)
1193       break;
1194
1195     const MachineOperand &MO1 = MI.getOperand(CurOp++);
1196     unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
1197     if (MO1.isImm()) {
1198       emitConstant(MO1.getImm(), Size);
1199       break;
1200     }
1201
1202     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
1203       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
1204     if (Opcode == X86::MOV32ri64)
1205       rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
1206     // This should not occur on Darwin for relocatable objects.
1207     if (Opcode == X86::MOV64ri)
1208       rt = X86::reloc_absolute_dword;  // FIXME: add X86II flag?
1209     if (MO1.isGlobal()) {
1210       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
1211       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
1212                         Indirect);
1213     } else if (MO1.isSymbol())
1214       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
1215     else if (MO1.isCPI())
1216       emitConstPoolAddress(MO1.getIndex(), rt);
1217     else if (MO1.isJTI())
1218       emitJumpTableAddress(MO1.getIndex(), rt);
1219     break;
1220   }
1221
1222   case X86II::MRMDestReg: {
1223     MCE.emitByte(BaseOpcode);
1224
1225     unsigned SrcRegNum = CurOp+1;
1226     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1227       SrcRegNum++;
1228
1229     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
1230                      getX86RegNum(MI.getOperand(SrcRegNum).getReg()));
1231     CurOp = SrcRegNum + 1;
1232     break;
1233   }
1234   case X86II::MRMDestMem: {
1235     MCE.emitByte(BaseOpcode);
1236
1237     unsigned SrcRegNum = CurOp + X86::AddrNumOperands;
1238     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1239       SrcRegNum++;
1240     emitMemModRMByte(MI, CurOp,
1241                      getX86RegNum(MI.getOperand(SrcRegNum).getReg()));
1242     CurOp = SrcRegNum + 1;
1243     break;
1244   }
1245
1246   case X86II::MRMSrcReg: {
1247     MCE.emitByte(BaseOpcode);
1248
1249     unsigned SrcRegNum = CurOp+1;
1250     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1251       ++SrcRegNum;
1252
1253     if (HasMemOp4) // Skip 2nd src (which is encoded in I8IMM)
1254       ++SrcRegNum;
1255
1256     emitRegModRMByte(MI.getOperand(SrcRegNum).getReg(),
1257                      getX86RegNum(MI.getOperand(CurOp).getReg()));
1258     // 2 operands skipped with HasMemOp4, compensate accordingly
1259     CurOp = HasMemOp4 ? SrcRegNum : SrcRegNum + 1;
1260     if (HasVEX_4VOp3)
1261       ++CurOp;
1262     break;
1263   }
1264   case X86II::MRMSrcMem: {
1265     int AddrOperands = X86::AddrNumOperands;
1266     unsigned FirstMemOp = CurOp+1;
1267     if (HasVEX_4V) {
1268       ++AddrOperands;
1269       ++FirstMemOp;  // Skip the register source (which is encoded in VEX_VVVV).
1270     }
1271     if (HasMemOp4) // Skip second register source (encoded in I8IMM)
1272       ++FirstMemOp;
1273
1274     MCE.emitByte(BaseOpcode);
1275
1276     intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
1277       X86II::getSizeOfImm(Desc->TSFlags) : 0;
1278     emitMemModRMByte(MI, FirstMemOp,
1279                      getX86RegNum(MI.getOperand(CurOp).getReg()),PCAdj);
1280     CurOp += AddrOperands + 1;
1281     if (HasVEX_4VOp3)
1282       ++CurOp;
1283     break;
1284   }
1285
1286   case X86II::MRMXr:
1287   case X86II::MRM0r: case X86II::MRM1r:
1288   case X86II::MRM2r: case X86II::MRM3r:
1289   case X86II::MRM4r: case X86II::MRM5r:
1290   case X86II::MRM6r: case X86II::MRM7r: {
1291     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
1292       ++CurOp;
1293     MCE.emitByte(BaseOpcode);
1294     uint64_t Form = (Desc->TSFlags & X86II::FormMask);
1295     emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
1296                      (Form == X86II::MRMXr) ? 0 : Form-X86II::MRM0r);
1297
1298     if (CurOp == NumOps)
1299       break;
1300
1301     const MachineOperand &MO1 = MI.getOperand(CurOp++);
1302     unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
1303     if (MO1.isImm()) {
1304       emitConstant(MO1.getImm(), Size);
1305       break;
1306     }
1307
1308     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
1309       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
1310     if (Opcode == X86::MOV64ri32)
1311       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
1312     if (MO1.isGlobal()) {
1313       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
1314       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
1315                         Indirect);
1316     } else if (MO1.isSymbol())
1317       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
1318     else if (MO1.isCPI())
1319       emitConstPoolAddress(MO1.getIndex(), rt);
1320     else if (MO1.isJTI())
1321       emitJumpTableAddress(MO1.getIndex(), rt);
1322     break;
1323   }
1324
1325   case X86II::MRMXm:
1326   case X86II::MRM0m: case X86II::MRM1m:
1327   case X86II::MRM2m: case X86II::MRM3m:
1328   case X86II::MRM4m: case X86II::MRM5m:
1329   case X86II::MRM6m: case X86II::MRM7m: {
1330     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
1331       ++CurOp;
1332     intptr_t PCAdj = (CurOp + X86::AddrNumOperands != NumOps) ?
1333       (MI.getOperand(CurOp+X86::AddrNumOperands).isImm() ?
1334           X86II::getSizeOfImm(Desc->TSFlags) : 4) : 0;
1335
1336     MCE.emitByte(BaseOpcode);
1337     uint64_t Form = (Desc->TSFlags & X86II::FormMask);
1338     emitMemModRMByte(MI, CurOp, (Form==X86II::MRMXm) ? 0 : Form - X86II::MRM0m,
1339                      PCAdj);
1340     CurOp += X86::AddrNumOperands;
1341
1342     if (CurOp == NumOps)
1343       break;
1344
1345     const MachineOperand &MO = MI.getOperand(CurOp++);
1346     unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
1347     if (MO.isImm()) {
1348       emitConstant(MO.getImm(), Size);
1349       break;
1350     }
1351
1352     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
1353       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
1354     if (Opcode == X86::MOV64mi32)
1355       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
1356     if (MO.isGlobal()) {
1357       bool Indirect = gvNeedsNonLazyPtr(MO, TM);
1358       emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
1359                         Indirect);
1360     } else if (MO.isSymbol())
1361       emitExternalSymbolAddress(MO.getSymbolName(), rt);
1362     else if (MO.isCPI())
1363       emitConstPoolAddress(MO.getIndex(), rt);
1364     else if (MO.isJTI())
1365       emitJumpTableAddress(MO.getIndex(), rt);
1366     break;
1367   }
1368
1369   case X86II::MRM_C0: case X86II::MRM_C1: case X86II::MRM_C2:
1370   case X86II::MRM_C3: case X86II::MRM_C4: case X86II::MRM_C8:
1371   case X86II::MRM_C9: case X86II::MRM_CA: case X86II::MRM_CB:
1372   case X86II::MRM_D0: case X86II::MRM_D1: case X86II::MRM_D4:
1373   case X86II::MRM_D5: case X86II::MRM_D6: case X86II::MRM_D8:
1374   case X86II::MRM_D9: case X86II::MRM_DA: case X86II::MRM_DB:
1375   case X86II::MRM_DC: case X86II::MRM_DD: case X86II::MRM_DE:
1376   case X86II::MRM_DF: case X86II::MRM_E0: case X86II::MRM_E1:
1377   case X86II::MRM_E2: case X86II::MRM_E3: case X86II::MRM_E4:
1378   case X86II::MRM_E5: case X86II::MRM_E8: case X86II::MRM_E9:
1379   case X86II::MRM_EA: case X86II::MRM_EB: case X86II::MRM_EC:
1380   case X86II::MRM_ED: case X86II::MRM_EE: case X86II::MRM_F0:
1381   case X86II::MRM_F1: case X86II::MRM_F2: case X86II::MRM_F3:
1382   case X86II::MRM_F4: case X86II::MRM_F5: case X86II::MRM_F6:
1383   case X86II::MRM_F7: case X86II::MRM_F8: case X86II::MRM_F9:
1384   case X86II::MRM_FA: case X86II::MRM_FB: case X86II::MRM_FC:
1385   case X86II::MRM_FD: case X86II::MRM_FE: case X86II::MRM_FF:
1386     MCE.emitByte(BaseOpcode);
1387
1388     unsigned char MRM;
1389     switch (TSFlags & X86II::FormMask) {
1390     default: llvm_unreachable("Invalid Form");
1391     case X86II::MRM_C0: MRM = 0xC0; break;
1392     case X86II::MRM_C1: MRM = 0xC1; break;
1393     case X86II::MRM_C2: MRM = 0xC2; break;
1394     case X86II::MRM_C3: MRM = 0xC3; break;
1395     case X86II::MRM_C4: MRM = 0xC4; break;
1396     case X86II::MRM_C8: MRM = 0xC8; break;
1397     case X86II::MRM_C9: MRM = 0xC9; break;
1398     case X86II::MRM_CA: MRM = 0xCA; break;
1399     case X86II::MRM_CB: MRM = 0xCB; break;
1400     case X86II::MRM_D0: MRM = 0xD0; break;
1401     case X86II::MRM_D1: MRM = 0xD1; break;
1402     case X86II::MRM_D4: MRM = 0xD4; break;
1403     case X86II::MRM_D5: MRM = 0xD5; break;
1404     case X86II::MRM_D6: MRM = 0xD6; break;
1405     case X86II::MRM_D8: MRM = 0xD8; break;
1406     case X86II::MRM_D9: MRM = 0xD9; break;
1407     case X86II::MRM_DA: MRM = 0xDA; break;
1408     case X86II::MRM_DB: MRM = 0xDB; break;
1409     case X86II::MRM_DC: MRM = 0xDC; break;
1410     case X86II::MRM_DD: MRM = 0xDD; break;
1411     case X86II::MRM_DE: MRM = 0xDE; break;
1412     case X86II::MRM_DF: MRM = 0xDF; break;
1413     case X86II::MRM_E0: MRM = 0xE0; break;
1414     case X86II::MRM_E1: MRM = 0xE1; break;
1415     case X86II::MRM_E2: MRM = 0xE2; break;
1416     case X86II::MRM_E3: MRM = 0xE3; break;
1417     case X86II::MRM_E4: MRM = 0xE4; break;
1418     case X86II::MRM_E5: MRM = 0xE5; break;
1419     case X86II::MRM_E8: MRM = 0xE8; break;
1420     case X86II::MRM_E9: MRM = 0xE9; break;
1421     case X86II::MRM_EA: MRM = 0xEA; break;
1422     case X86II::MRM_EB: MRM = 0xEB; break;
1423     case X86II::MRM_EC: MRM = 0xEC; break;
1424     case X86II::MRM_ED: MRM = 0xED; break;
1425     case X86II::MRM_EE: MRM = 0xEE; break;
1426     case X86II::MRM_F0: MRM = 0xF0; break;
1427     case X86II::MRM_F1: MRM = 0xF1; break;
1428     case X86II::MRM_F2: MRM = 0xF2; break;
1429     case X86II::MRM_F3: MRM = 0xF3; break;
1430     case X86II::MRM_F4: MRM = 0xF4; break;
1431     case X86II::MRM_F5: MRM = 0xF5; break;
1432     case X86II::MRM_F6: MRM = 0xF6; break;
1433     case X86II::MRM_F7: MRM = 0xF7; break;
1434     case X86II::MRM_F8: MRM = 0xF8; break;
1435     case X86II::MRM_F9: MRM = 0xF9; break;
1436     case X86II::MRM_FA: MRM = 0xFA; break;
1437     case X86II::MRM_FB: MRM = 0xFB; break;
1438     case X86II::MRM_FC: MRM = 0xFC; break;
1439     case X86II::MRM_FD: MRM = 0xFD; break;
1440     case X86II::MRM_FE: MRM = 0xFE; break;
1441     case X86II::MRM_FF: MRM = 0xFF; break;
1442     }
1443     MCE.emitByte(MRM);
1444     break;
1445   }
1446
1447   while (CurOp != NumOps && NumOps - CurOp <= 2) {
1448     // The last source register of a 4 operand instruction in AVX is encoded
1449     // in bits[7:4] of a immediate byte.
1450     if ((TSFlags >> X86II::VEXShift) & X86II::VEX_I8IMM) {
1451       const MachineOperand &MO = MI.getOperand(HasMemOp4 ? MemOp4_I8IMMOperand
1452                                                          : CurOp);
1453       ++CurOp;
1454       unsigned RegNum = getX86RegNum(MO.getReg()) << 4;
1455       if (X86II::isX86_64ExtendedReg(MO.getReg()))
1456         RegNum |= 1 << 7;
1457       // If there is an additional 5th operand it must be an immediate, which
1458       // is encoded in bits[3:0]
1459       if (CurOp != NumOps) {
1460         const MachineOperand &MIMM = MI.getOperand(CurOp++);
1461         if (MIMM.isImm()) {
1462           unsigned Val = MIMM.getImm();
1463           assert(Val < 16 && "Immediate operand value out of range");
1464           RegNum |= Val;
1465         }
1466       }
1467       emitConstant(RegNum, 1);
1468     } else {
1469       emitConstant(MI.getOperand(CurOp++).getImm(),
1470                    X86II::getSizeOfImm(Desc->TSFlags));
1471     }
1472   }
1473
1474   if (!MI.isVariadic() && CurOp != NumOps) {
1475 #ifndef NDEBUG
1476     dbgs() << "Cannot encode all operands of: " << MI << "\n";
1477 #endif
1478     llvm_unreachable(0);
1479   }
1480
1481   MCE.processDebugLoc(MI.getDebugLoc(), false);
1482 }