Change X86 disassembly to print immediates values as signed by default. Special
[oota-llvm.git] / lib / Target / X86 / Disassembler / X86Disassembler.cpp
1 //===- X86Disassembler.cpp - Disassembler for x86 and x86_64 ----*- C++ -*-===//
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
20 #include "llvm/MC/EDInstInfo.h"
21 #include "llvm/MC/MCDisassembler.h"
22 #include "llvm/MC/MCDisassembler.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MemoryObject.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
28
29 #define GET_REGINFO_ENUM
30 #include "X86GenRegisterInfo.inc"
31 #define GET_INSTRINFO_ENUM
32 #include "X86GenInstrInfo.inc"
33 #include "X86GenEDInfo.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 #define debug(s) DEBUG(x86DisassemblerDebug(__FILE__, __LINE__, s));
45
46 namespace llvm {  
47   
48 // Fill-ins to make the compiler happy.  These constants are never actually
49 //   assigned; they are just filler to make an automatically-generated switch
50 //   statement work.
51 namespace X86 {
52   enum {
53     BX_SI = 500,
54     BX_DI = 501,
55     BP_SI = 502,
56     BP_DI = 503,
57     sib   = 504,
58     sib64 = 505
59   };
60 }
61
62 extern Target TheX86_32Target, TheX86_64Target;
63
64 }
65
66 static bool translateInstruction(MCInst &target,
67                                 InternalInstruction &source);
68
69 X86GenericDisassembler::X86GenericDisassembler(DisassemblerMode mode) :
70     MCDisassembler(),
71     fMode(mode) {
72 }
73
74 X86GenericDisassembler::~X86GenericDisassembler() {
75 }
76
77 EDInstInfo *X86GenericDisassembler::getEDInfo() const {
78   return instInfoX86;
79 }
80
81 /// regionReader - a callback function that wraps the readByte method from
82 ///   MemoryObject.
83 ///
84 /// @param arg      - The generic callback parameter.  In this case, this should
85 ///                   be a pointer to a MemoryObject.
86 /// @param byte     - A pointer to the byte to be read.
87 /// @param address  - The address to be read.
88 static int regionReader(void* arg, uint8_t* byte, uint64_t address) {
89   MemoryObject* region = static_cast<MemoryObject*>(arg);
90   return region->readByte(address, byte);
91 }
92
93 /// logger - a callback function that wraps the operator<< method from
94 ///   raw_ostream.
95 ///
96 /// @param arg      - The generic callback parameter.  This should be a pointe
97 ///                   to a raw_ostream.
98 /// @param log      - A string to be logged.  logger() adds a newline.
99 static void logger(void* arg, const char* log) {
100   if (!arg)
101     return;
102   
103   raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
104   vStream << log << "\n";
105 }  
106   
107 //
108 // Public interface for the disassembler
109 //
110
111 MCDisassembler::DecodeStatus
112 X86GenericDisassembler::getInstruction(MCInst &instr,
113                                        uint64_t &size,
114                                        const MemoryObject &region,
115                                        uint64_t address,
116                                        raw_ostream &vStream) const {
117   InternalInstruction internalInstr;
118   
119   int ret = decodeInstruction(&internalInstr,
120                               regionReader,
121                               (void*)&region,
122                               logger,
123                               (void*)&vStream,
124                               address,
125                               fMode);
126
127   if (ret) {
128     size = internalInstr.readerCursor - address;
129     return Fail;
130   }
131   else {
132     size = internalInstr.length;
133     return (!translateInstruction(instr, internalInstr)) ? Success : Fail;
134   }
135 }
136
137 //
138 // Private code that translates from struct InternalInstructions to MCInsts.
139 //
140
141 /// translateRegister - Translates an internal register to the appropriate LLVM
142 ///   register, and appends it as an operand to an MCInst.
143 ///
144 /// @param mcInst     - The MCInst to append to.
145 /// @param reg        - The Reg to append.
146 static void translateRegister(MCInst &mcInst, Reg reg) {
147 #define ENTRY(x) X86::x,
148   uint8_t llvmRegnums[] = {
149     ALL_REGS
150     0
151   };
152 #undef ENTRY
153
154   uint8_t llvmRegnum = llvmRegnums[reg];
155   mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
156 }
157
158 /// translateImmediate  - Appends an immediate operand to an MCInst.
159 ///
160 /// @param mcInst       - The MCInst to append to.
161 /// @param immediate    - The immediate value to append.
162 /// @param operand      - The operand, as stored in the descriptor table.
163 /// @param insn         - The internal instruction.
164 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
165                                const OperandSpecifier &operand,
166                                InternalInstruction &insn) {
167   // Sign-extend the immediate if necessary.
168
169   OperandType type = operand.type;
170
171   if (type == TYPE_RELv) {
172     switch (insn.displacementSize) {
173     default:
174       break;
175     case 1:
176       type = TYPE_MOFFS8;
177       break;
178     case 2:
179       type = TYPE_MOFFS16;
180       break;
181     case 4:
182       type = TYPE_MOFFS32;
183       break;
184     case 8:
185       type = TYPE_MOFFS64;
186       break;
187     }
188   }
189   // By default sign-extend all X86 immediates based on their encoding.
190   else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
191            type == TYPE_IMM64) {
192     uint32_t Opcode = mcInst.getOpcode();
193     switch (operand.encoding) {
194     default:
195       break;
196     case ENCODING_IB:
197       // Special case those X86 instructions that use the imm8 as a set of
198       // bits, bit count, etc. and are not sign-extend.
199       if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
200           Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
201           Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
202           Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
203           Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
204           Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
205           Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
206           Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
207           Opcode != X86::VINSERTPSrr)
208         type = TYPE_MOFFS8;
209       break;
210     case ENCODING_IW:
211       type = TYPE_MOFFS16;
212       break;
213     case ENCODING_ID:
214       type = TYPE_MOFFS32;
215       break;
216     case ENCODING_IO:
217       type = TYPE_MOFFS64;
218       break;
219     }
220   }
221
222   switch (type) {
223   case TYPE_MOFFS8:
224   case TYPE_REL8:
225     if(immediate & 0x80)
226       immediate |= ~(0xffull);
227     break;
228   case TYPE_MOFFS16:
229     if(immediate & 0x8000)
230       immediate |= ~(0xffffull);
231     break;
232   case TYPE_MOFFS32:
233   case TYPE_REL32:
234   case TYPE_REL64:
235     if(immediate & 0x80000000)
236       immediate |= ~(0xffffffffull);
237     break;
238   case TYPE_MOFFS64:
239   default:
240     // operand is 64 bits wide.  Do nothing.
241     break;
242   }
243     
244   mcInst.addOperand(MCOperand::CreateImm(immediate));
245 }
246
247 /// translateRMRegister - Translates a register stored in the R/M field of the
248 ///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
249 /// @param mcInst       - The MCInst to append to.
250 /// @param insn         - The internal instruction to extract the R/M field
251 ///                       from.
252 /// @return             - 0 on success; -1 otherwise
253 static bool translateRMRegister(MCInst &mcInst,
254                                 InternalInstruction &insn) {
255   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
256     debug("A R/M register operand may not have a SIB byte");
257     return true;
258   }
259   
260   switch (insn.eaBase) {
261   default:
262     debug("Unexpected EA base register");
263     return true;
264   case EA_BASE_NONE:
265     debug("EA_BASE_NONE for ModR/M base");
266     return true;
267 #define ENTRY(x) case EA_BASE_##x:
268   ALL_EA_BASES
269 #undef ENTRY
270     debug("A R/M register operand may not have a base; "
271           "the operand must be a register.");
272     return true;
273 #define ENTRY(x)                                                      \
274   case EA_REG_##x:                                                    \
275     mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
276   ALL_REGS
277 #undef ENTRY
278   }
279   
280   return false;
281 }
282
283 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
284 ///   fields of an internal instruction (and possibly its SIB byte) to a memory
285 ///   operand in LLVM's format, and appends it to an MCInst.
286 ///
287 /// @param mcInst       - The MCInst to append to.
288 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
289 ///                       from.
290 /// @return             - 0 on success; nonzero otherwise
291 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn) {
292   // Addresses in an MCInst are represented as five operands:
293   //   1. basereg       (register)  The R/M base, or (if there is a SIB) the 
294   //                                SIB base
295   //   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified 
296   //                                scale amount
297   //   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
298   //                                the index (which is multiplied by the 
299   //                                scale amount)
300   //   4. displacement  (immediate) 0, or the displacement if there is one
301   //   5. segmentreg    (register)  x86_registerNONE for now, but could be set
302   //                                if we have segment overrides
303   
304   MCOperand baseReg;
305   MCOperand scaleAmount;
306   MCOperand indexReg;
307   MCOperand displacement;
308   MCOperand segmentReg;
309   
310   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
311     if (insn.sibBase != SIB_BASE_NONE) {
312       switch (insn.sibBase) {
313       default:
314         debug("Unexpected sibBase");
315         return true;
316 #define ENTRY(x)                                          \
317       case SIB_BASE_##x:                                  \
318         baseReg = MCOperand::CreateReg(X86::x); break;
319       ALL_SIB_BASES
320 #undef ENTRY
321       }
322     } else {
323       baseReg = MCOperand::CreateReg(0);
324     }
325     
326     if (insn.sibIndex != SIB_INDEX_NONE) {
327       switch (insn.sibIndex) {
328       default:
329         debug("Unexpected sibIndex");
330         return true;
331 #define ENTRY(x)                                          \
332       case SIB_INDEX_##x:                                 \
333         indexReg = MCOperand::CreateReg(X86::x); break;
334       EA_BASES_32BIT
335       EA_BASES_64BIT
336 #undef ENTRY
337       }
338     } else {
339       indexReg = MCOperand::CreateReg(0);
340     }
341     
342     scaleAmount = MCOperand::CreateImm(insn.sibScale);
343   } else {
344     switch (insn.eaBase) {
345     case EA_BASE_NONE:
346       if (insn.eaDisplacement == EA_DISP_NONE) {
347         debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
348         return true;
349       }
350       if (insn.mode == MODE_64BIT)
351         baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
352       else
353         baseReg = MCOperand::CreateReg(0);
354       
355       indexReg = MCOperand::CreateReg(0);
356       break;
357     case EA_BASE_BX_SI:
358       baseReg = MCOperand::CreateReg(X86::BX);
359       indexReg = MCOperand::CreateReg(X86::SI);
360       break;
361     case EA_BASE_BX_DI:
362       baseReg = MCOperand::CreateReg(X86::BX);
363       indexReg = MCOperand::CreateReg(X86::DI);
364       break;
365     case EA_BASE_BP_SI:
366       baseReg = MCOperand::CreateReg(X86::BP);
367       indexReg = MCOperand::CreateReg(X86::SI);
368       break;
369     case EA_BASE_BP_DI:
370       baseReg = MCOperand::CreateReg(X86::BP);
371       indexReg = MCOperand::CreateReg(X86::DI);
372       break;
373     default:
374       indexReg = MCOperand::CreateReg(0);
375       switch (insn.eaBase) {
376       default:
377         debug("Unexpected eaBase");
378         return true;
379         // Here, we will use the fill-ins defined above.  However,
380         //   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
381         //   sib and sib64 were handled in the top-level if, so they're only
382         //   placeholders to keep the compiler happy.
383 #define ENTRY(x)                                        \
384       case EA_BASE_##x:                                 \
385         baseReg = MCOperand::CreateReg(X86::x); break; 
386       ALL_EA_BASES
387 #undef ENTRY
388 #define ENTRY(x) case EA_REG_##x:
389       ALL_REGS
390 #undef ENTRY
391         debug("A R/M memory operand may not be a register; "
392               "the base field must be a base.");
393         return true;
394       }
395     }
396     
397     scaleAmount = MCOperand::CreateImm(1);
398   }
399   
400   displacement = MCOperand::CreateImm(insn.displacement);
401   
402   static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
403     0,        // SEG_OVERRIDE_NONE
404     X86::CS,
405     X86::SS,
406     X86::DS,
407     X86::ES,
408     X86::FS,
409     X86::GS
410   };
411   
412   segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
413   
414   mcInst.addOperand(baseReg);
415   mcInst.addOperand(scaleAmount);
416   mcInst.addOperand(indexReg);
417   mcInst.addOperand(displacement);
418   mcInst.addOperand(segmentReg);
419   return false;
420 }
421
422 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
423 ///   byte of an instruction to LLVM form, and appends it to an MCInst.
424 ///
425 /// @param mcInst       - The MCInst to append to.
426 /// @param operand      - The operand, as stored in the descriptor table.
427 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
428 ///                       from.
429 /// @return             - 0 on success; nonzero otherwise
430 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
431                         InternalInstruction &insn) {
432   switch (operand.type) {
433   default:
434     debug("Unexpected type for a R/M operand");
435     return true;
436   case TYPE_R8:
437   case TYPE_R16:
438   case TYPE_R32:
439   case TYPE_R64:
440   case TYPE_Rv:
441   case TYPE_MM:
442   case TYPE_MM32:
443   case TYPE_MM64:
444   case TYPE_XMM:
445   case TYPE_XMM32:
446   case TYPE_XMM64:
447   case TYPE_XMM128:
448   case TYPE_XMM256:
449   case TYPE_DEBUGREG:
450   case TYPE_CONTROLREG:
451     return translateRMRegister(mcInst, insn);
452   case TYPE_M:
453   case TYPE_M8:
454   case TYPE_M16:
455   case TYPE_M32:
456   case TYPE_M64:
457   case TYPE_M128:
458   case TYPE_M256:
459   case TYPE_M512:
460   case TYPE_Mv:
461   case TYPE_M32FP:
462   case TYPE_M64FP:
463   case TYPE_M80FP:
464   case TYPE_M16INT:
465   case TYPE_M32INT:
466   case TYPE_M64INT:
467   case TYPE_M1616:
468   case TYPE_M1632:
469   case TYPE_M1664:
470   case TYPE_LEA:
471     return translateRMMemory(mcInst, insn);
472   }
473 }
474   
475 /// translateFPRegister - Translates a stack position on the FPU stack to its
476 ///   LLVM form, and appends it to an MCInst.
477 ///
478 /// @param mcInst       - The MCInst to append to.
479 /// @param stackPos     - The stack position to translate.
480 /// @return             - 0 on success; nonzero otherwise.
481 static bool translateFPRegister(MCInst &mcInst,
482                                uint8_t stackPos) {
483   if (stackPos >= 8) {
484     debug("Invalid FP stack position");
485     return true;
486   }
487   
488   mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
489
490   return false;
491 }
492
493 /// translateOperand - Translates an operand stored in an internal instruction 
494 ///   to LLVM's format and appends it to an MCInst.
495 ///
496 /// @param mcInst       - The MCInst to append to.
497 /// @param operand      - The operand, as stored in the descriptor table.
498 /// @param insn         - The internal instruction.
499 /// @return             - false on success; true otherwise.
500 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
501                              InternalInstruction &insn) {
502   switch (operand.encoding) {
503   default:
504     debug("Unhandled operand encoding during translation");
505     return true;
506   case ENCODING_REG:
507     translateRegister(mcInst, insn.reg);
508     return false;
509   case ENCODING_RM:
510     return translateRM(mcInst, operand, insn);
511   case ENCODING_CB:
512   case ENCODING_CW:
513   case ENCODING_CD:
514   case ENCODING_CP:
515   case ENCODING_CO:
516   case ENCODING_CT:
517     debug("Translation of code offsets isn't supported.");
518     return true;
519   case ENCODING_IB:
520   case ENCODING_IW:
521   case ENCODING_ID:
522   case ENCODING_IO:
523   case ENCODING_Iv:
524   case ENCODING_Ia:
525     translateImmediate(mcInst,
526                        insn.immediates[insn.numImmediatesTranslated++],
527                        operand,
528                        insn);
529     return false;
530   case ENCODING_RB:
531   case ENCODING_RW:
532   case ENCODING_RD:
533   case ENCODING_RO:
534     translateRegister(mcInst, insn.opcodeRegister);
535     return false;
536   case ENCODING_I:
537     return translateFPRegister(mcInst, insn.opcodeModifier);
538   case ENCODING_Rv:
539     translateRegister(mcInst, insn.opcodeRegister);
540     return false;
541   case ENCODING_VVVV:
542     translateRegister(mcInst, insn.vvvv);
543     return false;
544   case ENCODING_DUP:
545     return translateOperand(mcInst,
546                             insn.spec->operands[operand.type - TYPE_DUP0],
547                             insn);
548   }
549 }
550   
551 /// translateInstruction - Translates an internal instruction and all its
552 ///   operands to an MCInst.
553 ///
554 /// @param mcInst       - The MCInst to populate with the instruction's data.
555 /// @param insn         - The internal instruction.
556 /// @return             - false on success; true otherwise.
557 static bool translateInstruction(MCInst &mcInst,
558                                 InternalInstruction &insn) {  
559   if (!insn.spec) {
560     debug("Instruction has no specification");
561     return true;
562   }
563   
564   mcInst.setOpcode(insn.instructionID);
565   
566   int index;
567   
568   insn.numImmediatesTranslated = 0;
569   
570   for (index = 0; index < X86_MAX_OPERANDS; ++index) {
571     if (insn.spec->operands[index].encoding != ENCODING_NONE) {
572       if (translateOperand(mcInst, insn.spec->operands[index], insn)) {
573         return true;
574       }
575     }
576   }
577   
578   return false;
579 }
580
581 static MCDisassembler *createX86_32Disassembler(const Target &T) {
582   return new X86Disassembler::X86_32Disassembler;
583 }
584
585 static MCDisassembler *createX86_64Disassembler(const Target &T) {
586   return new X86Disassembler::X86_64Disassembler;
587 }
588
589 extern "C" void LLVMInitializeX86Disassembler() { 
590   // Register the disassembler.
591   TargetRegistry::RegisterMCDisassembler(TheX86_32Target, 
592                                          createX86_32Disassembler);
593   TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
594                                          createX86_64Disassembler);
595 }