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