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