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