Misc style fixes. NFC.
[oota-llvm.git] / lib / Target / X86 / Disassembler / X86Disassembler.cpp
1 //===-- X86Disassembler.cpp - Disassembler for x86 and x86_64 -------------===//
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 is part of the X86 Disassembler.
11 // It contains code to translate the data produced by the decoder into
12 //  MCInsts.
13 // Documentation for the disassembler can be found in X86Disassembler.h.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "X86Disassembler.h"
18 #include "X86DisassemblerDecoder.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDisassembler.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/MemoryObject.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/raw_ostream.h"
29
30 using namespace llvm;
31 using namespace llvm::X86Disassembler;
32
33 #define DEBUG_TYPE "x86-disassembler"
34
35 #define GET_REGINFO_ENUM
36 #include "X86GenRegisterInfo.inc"
37 #define GET_INSTRINFO_ENUM
38 #include "X86GenInstrInfo.inc"
39 #define GET_SUBTARGETINFO_ENUM
40 #include "X86GenSubtargetInfo.inc"
41
42 void llvm::X86Disassembler::Debug(const char *file, unsigned line,
43                                   const char *s) {
44   dbgs() << file << ":" << line << ": " << s;
45 }
46
47 const char *llvm::X86Disassembler::GetInstrName(unsigned Opcode,
48                                                 const void *mii) {
49   const MCInstrInfo *MII = static_cast<const MCInstrInfo *>(mii);
50   return MII->getName(Opcode);
51 }
52
53 #define debug(s) DEBUG(Debug(__FILE__, __LINE__, s));
54
55 namespace llvm {  
56   
57 // Fill-ins to make the compiler happy.  These constants are never actually
58 //   assigned; they are just filler to make an automatically-generated switch
59 //   statement work.
60 namespace X86 {
61   enum {
62     BX_SI = 500,
63     BX_DI = 501,
64     BP_SI = 502,
65     BP_DI = 503,
66     sib   = 504,
67     sib64 = 505
68   };
69 }
70
71 extern Target TheX86_32Target, TheX86_64Target;
72
73 }
74
75 static bool translateInstruction(MCInst &target,
76                                 InternalInstruction &source,
77                                 const MCDisassembler *Dis);
78
79 X86GenericDisassembler::X86GenericDisassembler(
80                                          const MCSubtargetInfo &STI,
81                                          MCContext &Ctx,
82                                          std::unique_ptr<const MCInstrInfo> MII)
83   : MCDisassembler(STI, Ctx), MII(std::move(MII)) {
84   switch (STI.getFeatureBits() &
85           (X86::Mode16Bit | X86::Mode32Bit | X86::Mode64Bit)) {
86   case X86::Mode16Bit:
87     fMode = MODE_16BIT;
88     break;
89   case X86::Mode32Bit:
90     fMode = MODE_32BIT;
91     break;
92   case X86::Mode64Bit:
93     fMode = MODE_64BIT;
94     break;
95   default:
96     llvm_unreachable("Invalid CPU mode");
97   }
98 }
99
100 /// A callback function that wraps the readByte method from MemoryObject.
101 ///
102 /// @param Arg      - The generic callback parameter.  In this case, this should
103 ///                   be a pointer to a MemoryObject.
104 /// @param Byte     - A pointer to the byte to be read.
105 /// @param Address  - The address to be read.
106 static int regionReader(const void *Arg, uint8_t *Byte, uint64_t Address) {
107   const MemoryObject *Region = static_cast<const MemoryObject *>(Arg);
108   return Region->readByte(Address, Byte);
109 }
110
111 /// logger - a callback function that wraps the operator<< method from
112 ///   raw_ostream.
113 ///
114 /// @param arg      - The generic callback parameter.  This should be a pointe
115 ///                   to a raw_ostream.
116 /// @param log      - A string to be logged.  logger() adds a newline.
117 static void logger(void* arg, const char* log) {
118   if (!arg)
119     return;
120   
121   raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
122   vStream << log << "\n";
123 }  
124   
125 //
126 // Public interface for the disassembler
127 //
128
129 MCDisassembler::DecodeStatus X86GenericDisassembler::getInstruction(
130     MCInst &Instr, uint64_t &Size, const MemoryObject &Region, uint64_t Address,
131     raw_ostream &VStream, raw_ostream &CStream) const {
132   CommentStream = &CStream;
133
134   InternalInstruction InternalInstr;
135
136   dlog_t LoggerFn = logger;
137   if (&VStream == &nulls())
138     LoggerFn = nullptr; // Disable logging completely if it's going to nulls().
139
140   int Ret = decodeInstruction(&InternalInstr, regionReader,
141                               (const void *)&Region, LoggerFn, (void *)&VStream,
142                               (const void *)MII.get(), Address, fMode);
143
144   if (Ret) {
145     Size = InternalInstr.readerCursor - Address;
146     return Fail;
147   } else {
148     Size = InternalInstr.length;
149     return (!translateInstruction(Instr, InternalInstr, this)) ? Success : Fail;
150   }
151 }
152
153 //
154 // Private code that translates from struct InternalInstructions to MCInsts.
155 //
156
157 /// translateRegister - Translates an internal register to the appropriate LLVM
158 ///   register, and appends it as an operand to an MCInst.
159 ///
160 /// @param mcInst     - The MCInst to append to.
161 /// @param reg        - The Reg to append.
162 static void translateRegister(MCInst &mcInst, Reg reg) {
163 #define ENTRY(x) X86::x,
164   uint8_t llvmRegnums[] = {
165     ALL_REGS
166     0
167   };
168 #undef ENTRY
169
170   uint8_t llvmRegnum = llvmRegnums[reg];
171   mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
172 }
173
174 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
175 /// immediate Value in the MCInst. 
176 ///
177 /// @param Value      - The immediate Value, has had any PC adjustment made by
178 ///                     the caller.
179 /// @param isBranch   - If the instruction is a branch instruction
180 /// @param Address    - The starting address of the instruction
181 /// @param Offset     - The byte offset to this immediate in the instruction
182 /// @param Width      - The byte width of this immediate in the instruction
183 ///
184 /// If the getOpInfo() function was set when setupForSymbolicDisassembly() was
185 /// called then that function is called to get any symbolic information for the
186 /// immediate in the instruction using the Address, Offset and Width.  If that
187 /// returns non-zero then the symbolic information it returns is used to create 
188 /// an MCExpr and that is added as an operand to the MCInst.  If getOpInfo()
189 /// returns zero and isBranch is true then a symbol look up for immediate Value
190 /// is done and if a symbol is found an MCExpr is created with that, else
191 /// an MCExpr with the immediate Value is created.  This function returns true
192 /// if it adds an operand to the MCInst and false otherwise.
193 static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
194                                      uint64_t Address, uint64_t Offset,
195                                      uint64_t Width, MCInst &MI, 
196                                      const MCDisassembler *Dis) {  
197   return Dis->tryAddingSymbolicOperand(MI, Value, Address, isBranch,
198                                        Offset, Width);
199 }
200
201 /// tryAddingPcLoadReferenceComment - trys to add a comment as to what is being
202 /// referenced by a load instruction with the base register that is the rip.
203 /// These can often be addresses in a literal pool.  The Address of the
204 /// instruction and its immediate Value are used to determine the address
205 /// being referenced in the literal pool entry.  The SymbolLookUp call back will
206 /// return a pointer to a literal 'C' string if the referenced address is an 
207 /// address into a section with 'C' string literals.
208 static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Value,
209                                             const void *Decoder) {
210   const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);
211   Dis->tryAddingPcLoadReferenceComment(Value, Address);
212 }
213
214 static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
215   0,        // SEG_OVERRIDE_NONE
216   X86::CS,
217   X86::SS,
218   X86::DS,
219   X86::ES,
220   X86::FS,
221   X86::GS
222 };
223
224 /// translateSrcIndex   - Appends a source index operand to an MCInst.
225 ///
226 /// @param mcInst       - The MCInst to append to.
227 /// @param insn         - The internal instruction.
228 static bool translateSrcIndex(MCInst &mcInst, InternalInstruction &insn) {
229   unsigned baseRegNo;
230
231   if (insn.mode == MODE_64BIT)
232     baseRegNo = insn.prefixPresent[0x67] ? X86::ESI : X86::RSI;
233   else if (insn.mode == MODE_32BIT)
234     baseRegNo = insn.prefixPresent[0x67] ? X86::SI : X86::ESI;
235   else {
236     assert(insn.mode == MODE_16BIT);
237     baseRegNo = insn.prefixPresent[0x67] ? X86::ESI : X86::SI;
238   }
239   MCOperand baseReg = MCOperand::CreateReg(baseRegNo);
240   mcInst.addOperand(baseReg);
241
242   MCOperand segmentReg;
243   segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
244   mcInst.addOperand(segmentReg);
245   return false;
246 }
247
248 /// translateDstIndex   - Appends a destination index operand to an MCInst.
249 ///
250 /// @param mcInst       - The MCInst to append to.
251 /// @param insn         - The internal instruction.
252
253 static bool translateDstIndex(MCInst &mcInst, InternalInstruction &insn) {
254   unsigned baseRegNo;
255
256   if (insn.mode == MODE_64BIT)
257     baseRegNo = insn.prefixPresent[0x67] ? X86::EDI : X86::RDI;
258   else if (insn.mode == MODE_32BIT)
259     baseRegNo = insn.prefixPresent[0x67] ? X86::DI : X86::EDI;
260   else {
261     assert(insn.mode == MODE_16BIT);
262     baseRegNo = insn.prefixPresent[0x67] ? X86::EDI : X86::DI;
263   }
264   MCOperand baseReg = MCOperand::CreateReg(baseRegNo);
265   mcInst.addOperand(baseReg);
266   return false;
267 }
268
269 /// translateImmediate  - Appends an immediate operand to an MCInst.
270 ///
271 /// @param mcInst       - The MCInst to append to.
272 /// @param immediate    - The immediate value to append.
273 /// @param operand      - The operand, as stored in the descriptor table.
274 /// @param insn         - The internal instruction.
275 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
276                                const OperandSpecifier &operand,
277                                InternalInstruction &insn,
278                                const MCDisassembler *Dis) {  
279   // Sign-extend the immediate if necessary.
280
281   OperandType type = (OperandType)operand.type;
282
283   bool isBranch = false;
284   uint64_t pcrel = 0;
285   if (type == TYPE_RELv) {
286     isBranch = true;
287     pcrel = insn.startLocation +
288             insn.immediateOffset + insn.immediateSize;
289     switch (insn.displacementSize) {
290     default:
291       break;
292     case 1:
293       if(immediate & 0x80)
294         immediate |= ~(0xffull);
295       break;
296     case 2:
297       if(immediate & 0x8000)
298         immediate |= ~(0xffffull);
299       break;
300     case 4:
301       if(immediate & 0x80000000)
302         immediate |= ~(0xffffffffull);
303       break;
304     case 8:
305       break;
306     }
307   }
308   // By default sign-extend all X86 immediates based on their encoding.
309   else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
310            type == TYPE_IMM64 || type == TYPE_IMMv) {
311     uint32_t Opcode = mcInst.getOpcode();
312     switch (operand.encoding) {
313     default:
314       break;
315     case ENCODING_IB:
316       // Special case those X86 instructions that use the imm8 as a set of
317       // bits, bit count, etc. and are not sign-extend.
318       if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
319           Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
320           Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
321           Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
322           Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
323           Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
324           Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
325           Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
326           Opcode != X86::VINSERTPSrr)
327         if(immediate & 0x80)
328           immediate |= ~(0xffull);
329       break;
330     case ENCODING_IW:
331       if(immediate & 0x8000)
332         immediate |= ~(0xffffull);
333       break;
334     case ENCODING_ID:
335       if(immediate & 0x80000000)
336         immediate |= ~(0xffffffffull);
337       break;
338     case ENCODING_IO:
339       break;
340     }
341   }
342
343   switch (type) {
344   case TYPE_XMM32:
345   case TYPE_XMM64:
346   case TYPE_XMM128:
347     mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
348     return;
349   case TYPE_XMM256:
350     mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
351     return;
352   case TYPE_XMM512:
353     mcInst.addOperand(MCOperand::CreateReg(X86::ZMM0 + (immediate >> 4)));
354     return;
355   case TYPE_REL8:
356     isBranch = true;
357     pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
358     if(immediate & 0x80)
359       immediate |= ~(0xffull);
360     break;
361   case TYPE_REL32:
362   case TYPE_REL64:
363     isBranch = true;
364     pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
365     if(immediate & 0x80000000)
366       immediate |= ~(0xffffffffull);
367     break;
368   default:
369     // operand is 64 bits wide.  Do nothing.
370     break;
371   }
372
373   if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
374                                insn.immediateOffset, insn.immediateSize,
375                                mcInst, Dis))
376     mcInst.addOperand(MCOperand::CreateImm(immediate));
377
378   if (type == TYPE_MOFFS8 || type == TYPE_MOFFS16 ||
379       type == TYPE_MOFFS32 || type == TYPE_MOFFS64) {
380     MCOperand segmentReg;
381     segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
382     mcInst.addOperand(segmentReg);
383   }
384 }
385
386 /// translateRMRegister - Translates a register stored in the R/M field of the
387 ///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
388 /// @param mcInst       - The MCInst to append to.
389 /// @param insn         - The internal instruction to extract the R/M field
390 ///                       from.
391 /// @return             - 0 on success; -1 otherwise
392 static bool translateRMRegister(MCInst &mcInst,
393                                 InternalInstruction &insn) {
394   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
395     debug("A R/M register operand may not have a SIB byte");
396     return true;
397   }
398   
399   switch (insn.eaBase) {
400   default:
401     debug("Unexpected EA base register");
402     return true;
403   case EA_BASE_NONE:
404     debug("EA_BASE_NONE for ModR/M base");
405     return true;
406 #define ENTRY(x) case EA_BASE_##x:
407   ALL_EA_BASES
408 #undef ENTRY
409     debug("A R/M register operand may not have a base; "
410           "the operand must be a register.");
411     return true;
412 #define ENTRY(x)                                                      \
413   case EA_REG_##x:                                                    \
414     mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
415   ALL_REGS
416 #undef ENTRY
417   }
418   
419   return false;
420 }
421
422 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
423 ///   fields of an internal instruction (and possibly its SIB byte) to a memory
424 ///   operand in LLVM's format, and appends it to an MCInst.
425 ///
426 /// @param mcInst       - The MCInst to append to.
427 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
428 ///                       from.
429 /// @return             - 0 on success; nonzero otherwise
430 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
431                               const MCDisassembler *Dis) {  
432   // Addresses in an MCInst are represented as five operands:
433   //   1. basereg       (register)  The R/M base, or (if there is a SIB) the 
434   //                                SIB base
435   //   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified 
436   //                                scale amount
437   //   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
438   //                                the index (which is multiplied by the 
439   //                                scale amount)
440   //   4. displacement  (immediate) 0, or the displacement if there is one
441   //   5. segmentreg    (register)  x86_registerNONE for now, but could be set
442   //                                if we have segment overrides
443   
444   MCOperand baseReg;
445   MCOperand scaleAmount;
446   MCOperand indexReg;
447   MCOperand displacement;
448   MCOperand segmentReg;
449   uint64_t pcrel = 0;
450   
451   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
452     if (insn.sibBase != SIB_BASE_NONE) {
453       switch (insn.sibBase) {
454       default:
455         debug("Unexpected sibBase");
456         return true;
457 #define ENTRY(x)                                          \
458       case SIB_BASE_##x:                                  \
459         baseReg = MCOperand::CreateReg(X86::x); break;
460       ALL_SIB_BASES
461 #undef ENTRY
462       }
463     } else {
464       baseReg = MCOperand::CreateReg(0);
465     }
466
467     // Check whether we are handling VSIB addressing mode for GATHER.
468     // If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and
469     // we should use SIB_INDEX_XMM4|YMM4 for VSIB.
470     // I don't see a way to get the correct IndexReg in readSIB:
471     //   We can tell whether it is VSIB or SIB after instruction ID is decoded,
472     //   but instruction ID may not be decoded yet when calling readSIB.
473     uint32_t Opcode = mcInst.getOpcode();
474     bool IndexIs128 = (Opcode == X86::VGATHERDPDrm ||
475                        Opcode == X86::VGATHERDPDYrm ||
476                        Opcode == X86::VGATHERQPDrm ||
477                        Opcode == X86::VGATHERDPSrm ||
478                        Opcode == X86::VGATHERQPSrm ||
479                        Opcode == X86::VPGATHERDQrm ||
480                        Opcode == X86::VPGATHERDQYrm ||
481                        Opcode == X86::VPGATHERQQrm ||
482                        Opcode == X86::VPGATHERDDrm ||
483                        Opcode == X86::VPGATHERQDrm);
484     bool IndexIs256 = (Opcode == X86::VGATHERQPDYrm ||
485                        Opcode == X86::VGATHERDPSYrm ||
486                        Opcode == X86::VGATHERQPSYrm ||
487                        Opcode == X86::VGATHERDPDZrm ||
488                        Opcode == X86::VPGATHERDQZrm ||
489                        Opcode == X86::VPGATHERQQYrm ||
490                        Opcode == X86::VPGATHERDDYrm ||
491                        Opcode == X86::VPGATHERQDYrm);
492     bool IndexIs512 = (Opcode == X86::VGATHERQPDZrm ||
493                        Opcode == X86::VGATHERDPSZrm ||
494                        Opcode == X86::VGATHERQPSZrm ||
495                        Opcode == X86::VPGATHERQQZrm ||
496                        Opcode == X86::VPGATHERDDZrm ||
497                        Opcode == X86::VPGATHERQDZrm);
498     if (IndexIs128 || IndexIs256 || IndexIs512) {
499       unsigned IndexOffset = insn.sibIndex -
500                          (insn.addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX);
501       SIBIndex IndexBase = IndexIs512 ? SIB_INDEX_ZMM0 :
502                            IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0;
503       insn.sibIndex = (SIBIndex)(IndexBase + 
504                            (insn.sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset));
505     }
506
507     if (insn.sibIndex != SIB_INDEX_NONE) {
508       switch (insn.sibIndex) {
509       default:
510         debug("Unexpected sibIndex");
511         return true;
512 #define ENTRY(x)                                          \
513       case SIB_INDEX_##x:                                 \
514         indexReg = MCOperand::CreateReg(X86::x); break;
515       EA_BASES_32BIT
516       EA_BASES_64BIT
517       REGS_XMM
518       REGS_YMM
519       REGS_ZMM
520 #undef ENTRY
521       }
522     } else {
523       indexReg = MCOperand::CreateReg(0);
524     }
525     
526     scaleAmount = MCOperand::CreateImm(insn.sibScale);
527   } else {
528     switch (insn.eaBase) {
529     case EA_BASE_NONE:
530       if (insn.eaDisplacement == EA_DISP_NONE) {
531         debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
532         return true;
533       }
534       if (insn.mode == MODE_64BIT){
535         pcrel = insn.startLocation +
536                 insn.displacementOffset + insn.displacementSize;
537         tryAddingPcLoadReferenceComment(insn.startLocation +
538                                         insn.displacementOffset,
539                                         insn.displacement + pcrel, Dis);
540         baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
541       }
542       else
543         baseReg = MCOperand::CreateReg(0);
544       
545       indexReg = MCOperand::CreateReg(0);
546       break;
547     case EA_BASE_BX_SI:
548       baseReg = MCOperand::CreateReg(X86::BX);
549       indexReg = MCOperand::CreateReg(X86::SI);
550       break;
551     case EA_BASE_BX_DI:
552       baseReg = MCOperand::CreateReg(X86::BX);
553       indexReg = MCOperand::CreateReg(X86::DI);
554       break;
555     case EA_BASE_BP_SI:
556       baseReg = MCOperand::CreateReg(X86::BP);
557       indexReg = MCOperand::CreateReg(X86::SI);
558       break;
559     case EA_BASE_BP_DI:
560       baseReg = MCOperand::CreateReg(X86::BP);
561       indexReg = MCOperand::CreateReg(X86::DI);
562       break;
563     default:
564       indexReg = MCOperand::CreateReg(0);
565       switch (insn.eaBase) {
566       default:
567         debug("Unexpected eaBase");
568         return true;
569         // Here, we will use the fill-ins defined above.  However,
570         //   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
571         //   sib and sib64 were handled in the top-level if, so they're only
572         //   placeholders to keep the compiler happy.
573 #define ENTRY(x)                                        \
574       case EA_BASE_##x:                                 \
575         baseReg = MCOperand::CreateReg(X86::x); break; 
576       ALL_EA_BASES
577 #undef ENTRY
578 #define ENTRY(x) case EA_REG_##x:
579       ALL_REGS
580 #undef ENTRY
581         debug("A R/M memory operand may not be a register; "
582               "the base field must be a base.");
583         return true;
584       }
585     }
586     
587     scaleAmount = MCOperand::CreateImm(1);
588   }
589   
590   displacement = MCOperand::CreateImm(insn.displacement);
591
592   segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
593   
594   mcInst.addOperand(baseReg);
595   mcInst.addOperand(scaleAmount);
596   mcInst.addOperand(indexReg);
597   if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
598                                insn.startLocation, insn.displacementOffset,
599                                insn.displacementSize, mcInst, Dis))
600     mcInst.addOperand(displacement);
601   mcInst.addOperand(segmentReg);
602   return false;
603 }
604
605 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
606 ///   byte of an instruction to LLVM form, and appends it to an MCInst.
607 ///
608 /// @param mcInst       - The MCInst to append to.
609 /// @param operand      - The operand, as stored in the descriptor table.
610 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
611 ///                       from.
612 /// @return             - 0 on success; nonzero otherwise
613 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
614                         InternalInstruction &insn, const MCDisassembler *Dis) {  
615   switch (operand.type) {
616   default:
617     debug("Unexpected type for a R/M operand");
618     return true;
619   case TYPE_R8:
620   case TYPE_R16:
621   case TYPE_R32:
622   case TYPE_R64:
623   case TYPE_Rv:
624   case TYPE_MM:
625   case TYPE_MM32:
626   case TYPE_MM64:
627   case TYPE_XMM:
628   case TYPE_XMM32:
629   case TYPE_XMM64:
630   case TYPE_XMM128:
631   case TYPE_XMM256:
632   case TYPE_XMM512:
633   case TYPE_VK1:
634   case TYPE_VK8:
635   case TYPE_VK16:
636   case TYPE_DEBUGREG:
637   case TYPE_CONTROLREG:
638     return translateRMRegister(mcInst, insn);
639   case TYPE_M:
640   case TYPE_M8:
641   case TYPE_M16:
642   case TYPE_M32:
643   case TYPE_M64:
644   case TYPE_M128:
645   case TYPE_M256:
646   case TYPE_M512:
647   case TYPE_Mv:
648   case TYPE_M32FP:
649   case TYPE_M64FP:
650   case TYPE_M80FP:
651   case TYPE_M16INT:
652   case TYPE_M32INT:
653   case TYPE_M64INT:
654   case TYPE_M1616:
655   case TYPE_M1632:
656   case TYPE_M1664:
657   case TYPE_LEA:
658     return translateRMMemory(mcInst, insn, Dis);
659   }
660 }
661   
662 /// translateFPRegister - Translates a stack position on the FPU stack to its
663 ///   LLVM form, and appends it to an MCInst.
664 ///
665 /// @param mcInst       - The MCInst to append to.
666 /// @param stackPos     - The stack position to translate.
667 static void translateFPRegister(MCInst &mcInst,
668                                 uint8_t stackPos) {
669   mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
670 }
671
672 /// translateMaskRegister - Translates a 3-bit mask register number to
673 ///   LLVM form, and appends it to an MCInst.
674 ///
675 /// @param mcInst       - The MCInst to append to.
676 /// @param maskRegNum   - Number of mask register from 0 to 7.
677 /// @return             - false on success; true otherwise.
678 static bool translateMaskRegister(MCInst &mcInst,
679                                 uint8_t maskRegNum) {
680   if (maskRegNum >= 8) {
681     debug("Invalid mask register number");
682     return true;
683   }
684
685   mcInst.addOperand(MCOperand::CreateReg(X86::K0 + maskRegNum));
686   return false;
687 }
688
689 /// translateOperand - Translates an operand stored in an internal instruction 
690 ///   to LLVM's format and appends it to an MCInst.
691 ///
692 /// @param mcInst       - The MCInst to append to.
693 /// @param operand      - The operand, as stored in the descriptor table.
694 /// @param insn         - The internal instruction.
695 /// @return             - false on success; true otherwise.
696 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
697                              InternalInstruction &insn,
698                              const MCDisassembler *Dis) {  
699   switch (operand.encoding) {
700   default:
701     debug("Unhandled operand encoding during translation");
702     return true;
703   case ENCODING_REG:
704     translateRegister(mcInst, insn.reg);
705     return false;
706   case ENCODING_WRITEMASK:
707     return translateMaskRegister(mcInst, insn.writemask);
708   CASE_ENCODING_RM:
709     return translateRM(mcInst, operand, insn, Dis);
710   case ENCODING_CB:
711   case ENCODING_CW:
712   case ENCODING_CD:
713   case ENCODING_CP:
714   case ENCODING_CO:
715   case ENCODING_CT:
716     debug("Translation of code offsets isn't supported.");
717     return true;
718   case ENCODING_IB:
719   case ENCODING_IW:
720   case ENCODING_ID:
721   case ENCODING_IO:
722   case ENCODING_Iv:
723   case ENCODING_Ia:
724     translateImmediate(mcInst,
725                        insn.immediates[insn.numImmediatesTranslated++],
726                        operand,
727                        insn,
728                        Dis);
729     return false;
730   case ENCODING_SI:
731     return translateSrcIndex(mcInst, insn);
732   case ENCODING_DI:
733     return translateDstIndex(mcInst, insn);
734   case ENCODING_RB:
735   case ENCODING_RW:
736   case ENCODING_RD:
737   case ENCODING_RO:
738   case ENCODING_Rv:
739     translateRegister(mcInst, insn.opcodeRegister);
740     return false;
741   case ENCODING_FP:
742     translateFPRegister(mcInst, insn.modRM & 7);
743     return false;
744   case ENCODING_VVVV:
745     translateRegister(mcInst, insn.vvvv);
746     return false;
747   case ENCODING_DUP:
748     return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
749                             insn, Dis);
750   }
751 }
752   
753 /// translateInstruction - Translates an internal instruction and all its
754 ///   operands to an MCInst.
755 ///
756 /// @param mcInst       - The MCInst to populate with the instruction's data.
757 /// @param insn         - The internal instruction.
758 /// @return             - false on success; true otherwise.
759 static bool translateInstruction(MCInst &mcInst,
760                                 InternalInstruction &insn,
761                                 const MCDisassembler *Dis) {  
762   if (!insn.spec) {
763     debug("Instruction has no specification");
764     return true;
765   }
766   
767   mcInst.setOpcode(insn.instructionID);
768   // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
769   // prefix bytes should be disassembled as xrelease and xacquire then set the
770   // opcode to those instead of the rep and repne opcodes.
771   if (insn.xAcquireRelease) {
772     if(mcInst.getOpcode() == X86::REP_PREFIX)
773       mcInst.setOpcode(X86::XRELEASE_PREFIX);
774     else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
775       mcInst.setOpcode(X86::XACQUIRE_PREFIX);
776   }
777   
778   insn.numImmediatesTranslated = 0;
779   
780   for (const auto &Op : insn.operands) {
781     if (Op.encoding != ENCODING_NONE) {
782       if (translateOperand(mcInst, Op, insn, Dis)) {
783         return true;
784       }
785     }
786   }
787   
788   return false;
789 }
790
791 static MCDisassembler *createX86Disassembler(const Target &T,
792                                              const MCSubtargetInfo &STI,
793                                              MCContext &Ctx) {
794   std::unique_ptr<const MCInstrInfo> MII(T.createMCInstrInfo());
795   return new X86Disassembler::X86GenericDisassembler(STI, Ctx, std::move(MII));
796 }
797
798 extern "C" void LLVMInitializeX86Disassembler() { 
799   // Register the disassembler.
800   TargetRegistry::RegisterMCDisassembler(TheX86_32Target, 
801                                          createX86Disassembler);
802   TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
803                                          createX86Disassembler);
804 }