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