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