[x86] Fix uninitialized variable warning in translate{Src,Dst}Index
[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 operand      - The operand, as stored in the descriptor table.
240 /// @param insn         - The internal instruction.
241 static bool translateSrcIndex(MCInst &mcInst, InternalInstruction &insn) {
242   unsigned baseRegNo;
243
244   if (insn.mode == MODE_64BIT)
245     baseRegNo = insn.prefixPresent[0x67] ? X86::ESI : X86::RSI;
246   else if (insn.mode == MODE_32BIT)
247     baseRegNo = insn.prefixPresent[0x67] ? X86::SI : X86::ESI;
248   else {
249     assert(insn.mode == MODE_16BIT);
250     baseRegNo = insn.prefixPresent[0x67] ? X86::ESI : X86::SI;
251   }
252   MCOperand baseReg = MCOperand::CreateReg(baseRegNo);
253   mcInst.addOperand(baseReg);
254
255   MCOperand segmentReg;
256   segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
257   mcInst.addOperand(segmentReg);
258   return false;
259 }
260
261 /// translateDstIndex   - Appends a destination index operand to an MCInst.
262 ///
263 /// @param mcInst       - The MCInst to append to.
264 /// @param operand      - The operand, as stored in the descriptor table.
265 /// @param insn         - The internal instruction.
266
267 static bool translateDstIndex(MCInst &mcInst, InternalInstruction &insn) {
268   unsigned baseRegNo;
269
270   if (insn.mode == MODE_64BIT)
271     baseRegNo = insn.prefixPresent[0x67] ? X86::EDI : X86::RDI;
272   else if (insn.mode == MODE_32BIT)
273     baseRegNo = insn.prefixPresent[0x67] ? X86::DI : X86::EDI;
274   else {
275     assert(insn.mode == MODE_16BIT);
276     baseRegNo = insn.prefixPresent[0x67] ? X86::EDI : X86::DI;
277   }
278   MCOperand baseReg = MCOperand::CreateReg(baseRegNo);
279   mcInst.addOperand(baseReg);
280   return false;
281 }
282
283 /// translateImmediate  - Appends an immediate operand to an MCInst.
284 ///
285 /// @param mcInst       - The MCInst to append to.
286 /// @param immediate    - The immediate value to append.
287 /// @param operand      - The operand, as stored in the descriptor table.
288 /// @param insn         - The internal instruction.
289 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
290                                const OperandSpecifier &operand,
291                                InternalInstruction &insn,
292                                const MCDisassembler *Dis) {  
293   // Sign-extend the immediate if necessary.
294
295   OperandType type = (OperandType)operand.type;
296
297   bool isBranch = false;
298   uint64_t pcrel = 0;
299   if (type == TYPE_RELv) {
300     isBranch = true;
301     pcrel = insn.startLocation +
302             insn.immediateOffset + insn.immediateSize;
303     switch (insn.displacementSize) {
304     default:
305       break;
306     case 1:
307       if(immediate & 0x80)
308         immediate |= ~(0xffull);
309       break;
310     case 2:
311       if(immediate & 0x8000)
312         immediate |= ~(0xffffull);
313       break;
314     case 4:
315       if(immediate & 0x80000000)
316         immediate |= ~(0xffffffffull);
317       break;
318     case 8:
319       break;
320     }
321   }
322   // By default sign-extend all X86 immediates based on their encoding.
323   else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
324            type == TYPE_IMM64) {
325     uint32_t Opcode = mcInst.getOpcode();
326     switch (operand.encoding) {
327     default:
328       break;
329     case ENCODING_IB:
330       // Special case those X86 instructions that use the imm8 as a set of
331       // bits, bit count, etc. and are not sign-extend.
332       if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
333           Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
334           Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
335           Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
336           Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
337           Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
338           Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
339           Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
340           Opcode != X86::VINSERTPSrr)
341         if(immediate & 0x80)
342           immediate |= ~(0xffull);
343       break;
344     case ENCODING_IW:
345       if(immediate & 0x8000)
346         immediate |= ~(0xffffull);
347       break;
348     case ENCODING_ID:
349       if(immediate & 0x80000000)
350         immediate |= ~(0xffffffffull);
351       break;
352     case ENCODING_IO:
353       break;
354     }
355   }
356
357   switch (type) {
358   case TYPE_XMM32:
359   case TYPE_XMM64:
360   case TYPE_XMM128:
361     mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
362     return;
363   case TYPE_XMM256:
364     mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
365     return;
366   case TYPE_XMM512:
367     mcInst.addOperand(MCOperand::CreateReg(X86::ZMM0 + (immediate >> 4)));
368     return;
369   case TYPE_REL8:
370     isBranch = true;
371     pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
372     if(immediate & 0x80)
373       immediate |= ~(0xffull);
374     break;
375   case TYPE_REL32:
376   case TYPE_REL64:
377     isBranch = true;
378     pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
379     if(immediate & 0x80000000)
380       immediate |= ~(0xffffffffull);
381     break;
382   default:
383     // operand is 64 bits wide.  Do nothing.
384     break;
385   }
386
387   if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
388                                insn.immediateOffset, insn.immediateSize,
389                                mcInst, Dis))
390     mcInst.addOperand(MCOperand::CreateImm(immediate));
391
392   if (type == TYPE_MOFFS8 || type == TYPE_MOFFS16 ||
393       type == TYPE_MOFFS32 || type == TYPE_MOFFS64) {
394     MCOperand segmentReg;
395     segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
396     mcInst.addOperand(segmentReg);
397   }
398 }
399
400 /// translateRMRegister - Translates a register stored in the R/M field of the
401 ///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
402 /// @param mcInst       - The MCInst to append to.
403 /// @param insn         - The internal instruction to extract the R/M field
404 ///                       from.
405 /// @return             - 0 on success; -1 otherwise
406 static bool translateRMRegister(MCInst &mcInst,
407                                 InternalInstruction &insn) {
408   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
409     debug("A R/M register operand may not have a SIB byte");
410     return true;
411   }
412   
413   switch (insn.eaBase) {
414   default:
415     debug("Unexpected EA base register");
416     return true;
417   case EA_BASE_NONE:
418     debug("EA_BASE_NONE for ModR/M base");
419     return true;
420 #define ENTRY(x) case EA_BASE_##x:
421   ALL_EA_BASES
422 #undef ENTRY
423     debug("A R/M register operand may not have a base; "
424           "the operand must be a register.");
425     return true;
426 #define ENTRY(x)                                                      \
427   case EA_REG_##x:                                                    \
428     mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
429   ALL_REGS
430 #undef ENTRY
431   }
432   
433   return false;
434 }
435
436 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
437 ///   fields of an internal instruction (and possibly its SIB byte) to a memory
438 ///   operand in LLVM's format, and appends it to an MCInst.
439 ///
440 /// @param mcInst       - The MCInst to append to.
441 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
442 ///                       from.
443 /// @return             - 0 on success; nonzero otherwise
444 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
445                               const MCDisassembler *Dis) {  
446   // Addresses in an MCInst are represented as five operands:
447   //   1. basereg       (register)  The R/M base, or (if there is a SIB) the 
448   //                                SIB base
449   //   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified 
450   //                                scale amount
451   //   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
452   //                                the index (which is multiplied by the 
453   //                                scale amount)
454   //   4. displacement  (immediate) 0, or the displacement if there is one
455   //   5. segmentreg    (register)  x86_registerNONE for now, but could be set
456   //                                if we have segment overrides
457   
458   MCOperand baseReg;
459   MCOperand scaleAmount;
460   MCOperand indexReg;
461   MCOperand displacement;
462   MCOperand segmentReg;
463   uint64_t pcrel = 0;
464   
465   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
466     if (insn.sibBase != SIB_BASE_NONE) {
467       switch (insn.sibBase) {
468       default:
469         debug("Unexpected sibBase");
470         return true;
471 #define ENTRY(x)                                          \
472       case SIB_BASE_##x:                                  \
473         baseReg = MCOperand::CreateReg(X86::x); break;
474       ALL_SIB_BASES
475 #undef ENTRY
476       }
477     } else {
478       baseReg = MCOperand::CreateReg(0);
479     }
480
481     // Check whether we are handling VSIB addressing mode for GATHER.
482     // If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and
483     // we should use SIB_INDEX_XMM4|YMM4 for VSIB.
484     // I don't see a way to get the correct IndexReg in readSIB:
485     //   We can tell whether it is VSIB or SIB after instruction ID is decoded,
486     //   but instruction ID may not be decoded yet when calling readSIB.
487     uint32_t Opcode = mcInst.getOpcode();
488     bool IndexIs128 = (Opcode == X86::VGATHERDPDrm ||
489                        Opcode == X86::VGATHERDPDYrm ||
490                        Opcode == X86::VGATHERQPDrm ||
491                        Opcode == X86::VGATHERDPSrm ||
492                        Opcode == X86::VGATHERQPSrm ||
493                        Opcode == X86::VPGATHERDQrm ||
494                        Opcode == X86::VPGATHERDQYrm ||
495                        Opcode == X86::VPGATHERQQrm ||
496                        Opcode == X86::VPGATHERDDrm ||
497                        Opcode == X86::VPGATHERQDrm);
498     bool IndexIs256 = (Opcode == X86::VGATHERQPDYrm ||
499                        Opcode == X86::VGATHERDPSYrm ||
500                        Opcode == X86::VGATHERQPSYrm ||
501                        Opcode == X86::VGATHERDPDZrm ||
502                        Opcode == X86::VPGATHERDQZrm ||
503                        Opcode == X86::VPGATHERQQYrm ||
504                        Opcode == X86::VPGATHERDDYrm ||
505                        Opcode == X86::VPGATHERQDYrm);
506     bool IndexIs512 = (Opcode == X86::VGATHERQPDZrm ||
507                        Opcode == X86::VGATHERDPSZrm ||
508                        Opcode == X86::VGATHERQPSZrm ||
509                        Opcode == X86::VPGATHERQQZrm ||
510                        Opcode == X86::VPGATHERDDZrm ||
511                        Opcode == X86::VPGATHERQDZrm);
512     if (IndexIs128 || IndexIs256 || IndexIs512) {
513       unsigned IndexOffset = insn.sibIndex -
514                          (insn.addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX);
515       SIBIndex IndexBase = IndexIs512 ? SIB_INDEX_ZMM0 :
516                            IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0;
517       insn.sibIndex = (SIBIndex)(IndexBase + 
518                            (insn.sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset));
519     }
520
521     if (insn.sibIndex != SIB_INDEX_NONE) {
522       switch (insn.sibIndex) {
523       default:
524         debug("Unexpected sibIndex");
525         return true;
526 #define ENTRY(x)                                          \
527       case SIB_INDEX_##x:                                 \
528         indexReg = MCOperand::CreateReg(X86::x); break;
529       EA_BASES_32BIT
530       EA_BASES_64BIT
531       REGS_XMM
532       REGS_YMM
533       REGS_ZMM
534 #undef ENTRY
535       }
536     } else {
537       indexReg = MCOperand::CreateReg(0);
538     }
539     
540     scaleAmount = MCOperand::CreateImm(insn.sibScale);
541   } else {
542     switch (insn.eaBase) {
543     case EA_BASE_NONE:
544       if (insn.eaDisplacement == EA_DISP_NONE) {
545         debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
546         return true;
547       }
548       if (insn.mode == MODE_64BIT){
549         pcrel = insn.startLocation +
550                 insn.displacementOffset + insn.displacementSize;
551         tryAddingPcLoadReferenceComment(insn.startLocation +
552                                         insn.displacementOffset,
553                                         insn.displacement + pcrel, Dis);
554         baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
555       }
556       else
557         baseReg = MCOperand::CreateReg(0);
558       
559       indexReg = MCOperand::CreateReg(0);
560       break;
561     case EA_BASE_BX_SI:
562       baseReg = MCOperand::CreateReg(X86::BX);
563       indexReg = MCOperand::CreateReg(X86::SI);
564       break;
565     case EA_BASE_BX_DI:
566       baseReg = MCOperand::CreateReg(X86::BX);
567       indexReg = MCOperand::CreateReg(X86::DI);
568       break;
569     case EA_BASE_BP_SI:
570       baseReg = MCOperand::CreateReg(X86::BP);
571       indexReg = MCOperand::CreateReg(X86::SI);
572       break;
573     case EA_BASE_BP_DI:
574       baseReg = MCOperand::CreateReg(X86::BP);
575       indexReg = MCOperand::CreateReg(X86::DI);
576       break;
577     default:
578       indexReg = MCOperand::CreateReg(0);
579       switch (insn.eaBase) {
580       default:
581         debug("Unexpected eaBase");
582         return true;
583         // Here, we will use the fill-ins defined above.  However,
584         //   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
585         //   sib and sib64 were handled in the top-level if, so they're only
586         //   placeholders to keep the compiler happy.
587 #define ENTRY(x)                                        \
588       case EA_BASE_##x:                                 \
589         baseReg = MCOperand::CreateReg(X86::x); break; 
590       ALL_EA_BASES
591 #undef ENTRY
592 #define ENTRY(x) case EA_REG_##x:
593       ALL_REGS
594 #undef ENTRY
595         debug("A R/M memory operand may not be a register; "
596               "the base field must be a base.");
597         return true;
598       }
599     }
600     
601     scaleAmount = MCOperand::CreateImm(1);
602   }
603   
604   displacement = MCOperand::CreateImm(insn.displacement);
605
606   segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
607   
608   mcInst.addOperand(baseReg);
609   mcInst.addOperand(scaleAmount);
610   mcInst.addOperand(indexReg);
611   if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
612                                insn.startLocation, insn.displacementOffset,
613                                insn.displacementSize, mcInst, Dis))
614     mcInst.addOperand(displacement);
615   mcInst.addOperand(segmentReg);
616   return false;
617 }
618
619 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
620 ///   byte of an instruction to LLVM form, and appends it to an MCInst.
621 ///
622 /// @param mcInst       - The MCInst to append to.
623 /// @param operand      - The operand, as stored in the descriptor table.
624 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
625 ///                       from.
626 /// @return             - 0 on success; nonzero otherwise
627 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
628                         InternalInstruction &insn, const MCDisassembler *Dis) {  
629   switch (operand.type) {
630   default:
631     debug("Unexpected type for a R/M operand");
632     return true;
633   case TYPE_R8:
634   case TYPE_R16:
635   case TYPE_R32:
636   case TYPE_R64:
637   case TYPE_Rv:
638   case TYPE_MM:
639   case TYPE_MM32:
640   case TYPE_MM64:
641   case TYPE_XMM:
642   case TYPE_XMM32:
643   case TYPE_XMM64:
644   case TYPE_XMM128:
645   case TYPE_XMM256:
646   case TYPE_XMM512:
647   case TYPE_VK1:
648   case TYPE_VK8:
649   case TYPE_VK16:
650   case TYPE_DEBUGREG:
651   case TYPE_CONTROLREG:
652     return translateRMRegister(mcInst, insn);
653   case TYPE_M:
654   case TYPE_M8:
655   case TYPE_M16:
656   case TYPE_M32:
657   case TYPE_M64:
658   case TYPE_M128:
659   case TYPE_M256:
660   case TYPE_M512:
661   case TYPE_Mv:
662   case TYPE_M32FP:
663   case TYPE_M64FP:
664   case TYPE_M80FP:
665   case TYPE_M16INT:
666   case TYPE_M32INT:
667   case TYPE_M64INT:
668   case TYPE_M1616:
669   case TYPE_M1632:
670   case TYPE_M1664:
671   case TYPE_LEA:
672     return translateRMMemory(mcInst, insn, Dis);
673   }
674 }
675   
676 /// translateFPRegister - Translates a stack position on the FPU stack to its
677 ///   LLVM form, and appends it to an MCInst.
678 ///
679 /// @param mcInst       - The MCInst to append to.
680 /// @param stackPos     - The stack position to translate.
681 static void translateFPRegister(MCInst &mcInst,
682                                 uint8_t stackPos) {
683   mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
684 }
685
686 /// translateMaskRegister - Translates a 3-bit mask register number to
687 ///   LLVM form, and appends it to an MCInst.
688 ///
689 /// @param mcInst       - The MCInst to append to.
690 /// @param maskRegNum   - Number of mask register from 0 to 7.
691 /// @return             - false on success; true otherwise.
692 static bool translateMaskRegister(MCInst &mcInst,
693                                 uint8_t maskRegNum) {
694   if (maskRegNum >= 8) {
695     debug("Invalid mask register number");
696     return true;
697   }
698
699   mcInst.addOperand(MCOperand::CreateReg(X86::K0 + maskRegNum));
700   return false;
701 }
702
703 /// translateOperand - Translates an operand stored in an internal instruction 
704 ///   to LLVM's format and appends it to an MCInst.
705 ///
706 /// @param mcInst       - The MCInst to append to.
707 /// @param operand      - The operand, as stored in the descriptor table.
708 /// @param insn         - The internal instruction.
709 /// @return             - false on success; true otherwise.
710 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
711                              InternalInstruction &insn,
712                              const MCDisassembler *Dis) {  
713   switch (operand.encoding) {
714   default:
715     debug("Unhandled operand encoding during translation");
716     return true;
717   case ENCODING_REG:
718     translateRegister(mcInst, insn.reg);
719     return false;
720   case ENCODING_WRITEMASK:
721     return translateMaskRegister(mcInst, insn.writemask);
722   case ENCODING_RM:
723     return translateRM(mcInst, operand, insn, Dis);
724   case ENCODING_CB:
725   case ENCODING_CW:
726   case ENCODING_CD:
727   case ENCODING_CP:
728   case ENCODING_CO:
729   case ENCODING_CT:
730     debug("Translation of code offsets isn't supported.");
731     return true;
732   case ENCODING_IB:
733   case ENCODING_IW:
734   case ENCODING_ID:
735   case ENCODING_IO:
736   case ENCODING_Iv:
737   case ENCODING_Ia:
738     translateImmediate(mcInst,
739                        insn.immediates[insn.numImmediatesTranslated++],
740                        operand,
741                        insn,
742                        Dis);
743     return false;
744   case ENCODING_SI:
745     return translateSrcIndex(mcInst, insn);
746   case ENCODING_DI:
747     return translateDstIndex(mcInst, insn);
748   case ENCODING_RB:
749   case ENCODING_RW:
750   case ENCODING_RD:
751   case ENCODING_RO:
752   case ENCODING_Rv:
753     translateRegister(mcInst, insn.opcodeRegister);
754     return false;
755   case ENCODING_FP:
756     translateFPRegister(mcInst, insn.modRM & 7);
757     return false;
758   case ENCODING_VVVV:
759     translateRegister(mcInst, insn.vvvv);
760     return false;
761   case ENCODING_DUP:
762     return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
763                             insn, Dis);
764   }
765 }
766   
767 /// translateInstruction - Translates an internal instruction and all its
768 ///   operands to an MCInst.
769 ///
770 /// @param mcInst       - The MCInst to populate with the instruction's data.
771 /// @param insn         - The internal instruction.
772 /// @return             - false on success; true otherwise.
773 static bool translateInstruction(MCInst &mcInst,
774                                 InternalInstruction &insn,
775                                 const MCDisassembler *Dis) {  
776   if (!insn.spec) {
777     debug("Instruction has no specification");
778     return true;
779   }
780   
781   mcInst.setOpcode(insn.instructionID);
782   // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
783   // prefix bytes should be disassembled as xrelease and xacquire then set the
784   // opcode to those instead of the rep and repne opcodes.
785   if (insn.xAcquireRelease) {
786     if(mcInst.getOpcode() == X86::REP_PREFIX)
787       mcInst.setOpcode(X86::XRELEASE_PREFIX);
788     else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
789       mcInst.setOpcode(X86::XACQUIRE_PREFIX);
790   }
791   
792   int index;
793   
794   insn.numImmediatesTranslated = 0;
795   
796   for (index = 0; index < X86_MAX_OPERANDS; ++index) {
797     if (insn.operands[index].encoding != ENCODING_NONE) {
798       if (translateOperand(mcInst, insn.operands[index], insn, Dis)) {
799         return true;
800       }
801     }
802   }
803   
804   return false;
805 }
806
807 static MCDisassembler *createX86Disassembler(const Target &T,
808                                              const MCSubtargetInfo &STI) {
809   return new X86Disassembler::X86GenericDisassembler(STI,
810                                                      T.createMCInstrInfo());
811 }
812
813 extern "C" void LLVMInitializeX86Disassembler() { 
814   // Register the disassembler.
815   TargetRegistry::RegisterMCDisassembler(TheX86_32Target, 
816                                          createX86Disassembler);
817   TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
818                                          createX86Disassembler);
819 }