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