1 //===-- X86Disassembler.cpp - Disassembler for x86 and x86_64 -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is part of the X86 Disassembler.
11 // It contains code to translate the data produced by the decoder into
13 // Documentation for the disassembler can be found in X86Disassembler.h.
15 //===----------------------------------------------------------------------===//
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"
30 #define GET_REGINFO_ENUM
31 #include "X86GenRegisterInfo.inc"
32 #define GET_INSTRINFO_ENUM
33 #include "X86GenInstrInfo.inc"
34 #define GET_SUBTARGETINFO_ENUM
35 #include "X86GenSubtargetInfo.inc"
38 using namespace llvm::X86Disassembler;
40 void x86DisassemblerDebug(const char *file,
43 dbgs() << file << ":" << line << ": " << s;
46 const char *x86DisassemblerGetInstrName(unsigned Opcode, const void *mii) {
47 const MCInstrInfo *MII = static_cast<const MCInstrInfo *>(mii);
48 return MII->getName(Opcode);
51 #define debug(s) DEBUG(x86DisassemblerDebug(__FILE__, __LINE__, s));
55 // Fill-ins to make the compiler happy. These constants are never actually
56 // assigned; they are just filler to make an automatically-generated switch
69 extern Target TheX86_32Target, TheX86_64Target;
73 static bool translateInstruction(MCInst &target,
74 InternalInstruction &source,
75 const MCDisassembler *Dis);
77 X86GenericDisassembler::X86GenericDisassembler(const MCSubtargetInfo &STI,
78 const MCInstrInfo *MII)
79 : MCDisassembler(STI), MII(MII) {
80 switch (STI.getFeatureBits() &
81 (X86::Mode16Bit | X86::Mode32Bit | X86::Mode64Bit)) {
92 llvm_unreachable("Invalid CPU mode");
96 X86GenericDisassembler::~X86GenericDisassembler() {
100 /// regionReader - a callback function that wraps the readByte method from
103 /// @param arg - The generic callback parameter. In this case, this should
104 /// be a pointer to a MemoryObject.
105 /// @param byte - A pointer to the byte to be read.
106 /// @param address - The address to be read.
107 static int regionReader(const void* arg, uint8_t* byte, uint64_t address) {
108 const MemoryObject* region = static_cast<const MemoryObject*>(arg);
109 return region->readByte(address, byte);
112 /// logger - a callback function that wraps the operator<< method from
115 /// @param arg - The generic callback parameter. This should be a pointe
116 /// to a raw_ostream.
117 /// @param log - A string to be logged. logger() adds a newline.
118 static void logger(void* arg, const char* log) {
122 raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
123 vStream << log << "\n";
127 // Public interface for the disassembler
130 MCDisassembler::DecodeStatus
131 X86GenericDisassembler::getInstruction(MCInst &instr,
133 const MemoryObject ®ion,
135 raw_ostream &vStream,
136 raw_ostream &cStream) const {
137 CommentStream = &cStream;
139 InternalInstruction internalInstr;
141 dlog_t loggerFn = logger;
142 if (&vStream == &nulls())
143 loggerFn = 0; // Disable logging completely if it's going to nulls().
145 int ret = decodeInstruction(&internalInstr,
147 (const void*)®ion,
155 size = internalInstr.readerCursor - address;
159 size = internalInstr.length;
160 return (!translateInstruction(instr, internalInstr, this)) ?
166 // Private code that translates from struct InternalInstructions to MCInsts.
169 /// translateRegister - Translates an internal register to the appropriate LLVM
170 /// register, and appends it as an operand to an MCInst.
172 /// @param mcInst - The MCInst to append to.
173 /// @param reg - The Reg to append.
174 static void translateRegister(MCInst &mcInst, Reg reg) {
175 #define ENTRY(x) X86::x,
176 uint8_t llvmRegnums[] = {
182 uint8_t llvmRegnum = llvmRegnums[reg];
183 mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
186 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
187 /// immediate Value in the MCInst.
189 /// @param Value - The immediate Value, has had any PC adjustment made by
191 /// @param isBranch - If the instruction is a branch instruction
192 /// @param Address - The starting address of the instruction
193 /// @param Offset - The byte offset to this immediate in the instruction
194 /// @param Width - The byte width of this immediate in the instruction
196 /// If the getOpInfo() function was set when setupForSymbolicDisassembly() was
197 /// called then that function is called to get any symbolic information for the
198 /// immediate in the instruction using the Address, Offset and Width. If that
199 /// returns non-zero then the symbolic information it returns is used to create
200 /// an MCExpr and that is added as an operand to the MCInst. If getOpInfo()
201 /// returns zero and isBranch is true then a symbol look up for immediate Value
202 /// is done and if a symbol is found an MCExpr is created with that, else
203 /// an MCExpr with the immediate Value is created. This function returns true
204 /// if it adds an operand to the MCInst and false otherwise.
205 static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
206 uint64_t Address, uint64_t Offset,
207 uint64_t Width, MCInst &MI,
208 const MCDisassembler *Dis) {
209 return Dis->tryAddingSymbolicOperand(MI, Value, Address, isBranch,
213 /// tryAddingPcLoadReferenceComment - trys to add a comment as to what is being
214 /// referenced by a load instruction with the base register that is the rip.
215 /// These can often be addresses in a literal pool. The Address of the
216 /// instruction and its immediate Value are used to determine the address
217 /// being referenced in the literal pool entry. The SymbolLookUp call back will
218 /// return a pointer to a literal 'C' string if the referenced address is an
219 /// address into a section with 'C' string literals.
220 static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Value,
221 const void *Decoder) {
222 const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);
223 Dis->tryAddingPcLoadReferenceComment(Value, Address);
226 static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
227 0, // SEG_OVERRIDE_NONE
236 /// translateImmediate - Appends an immediate operand to an MCInst.
238 /// @param mcInst - The MCInst to append to.
239 /// @param immediate - The immediate value to append.
240 /// @param operand - The operand, as stored in the descriptor table.
241 /// @param insn - The internal instruction.
242 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
243 const OperandSpecifier &operand,
244 InternalInstruction &insn,
245 const MCDisassembler *Dis) {
246 // Sign-extend the immediate if necessary.
248 OperandType type = (OperandType)operand.type;
250 bool isBranch = false;
252 if (type == TYPE_RELv) {
254 pcrel = insn.startLocation +
255 insn.immediateOffset + insn.immediateSize;
256 switch (insn.displacementSize) {
261 immediate |= ~(0xffull);
264 if(immediate & 0x8000)
265 immediate |= ~(0xffffull);
268 if(immediate & 0x80000000)
269 immediate |= ~(0xffffffffull);
275 // By default sign-extend all X86 immediates based on their encoding.
276 else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
277 type == TYPE_IMM64) {
278 uint32_t Opcode = mcInst.getOpcode();
279 switch (operand.encoding) {
283 // Special case those X86 instructions that use the imm8 as a set of
284 // bits, bit count, etc. and are not sign-extend.
285 if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
286 Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
287 Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
288 Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
289 Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
290 Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
291 Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
292 Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
293 Opcode != X86::VINSERTPSrr)
295 immediate |= ~(0xffull);
298 if(immediate & 0x8000)
299 immediate |= ~(0xffffull);
302 if(immediate & 0x80000000)
303 immediate |= ~(0xffffffffull);
314 mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
317 mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
320 mcInst.addOperand(MCOperand::CreateReg(X86::ZMM0 + (immediate >> 4)));
324 pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
326 immediate |= ~(0xffull);
331 pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
332 if(immediate & 0x80000000)
333 immediate |= ~(0xffffffffull);
336 // operand is 64 bits wide. Do nothing.
340 if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
341 insn.immediateOffset, insn.immediateSize,
343 mcInst.addOperand(MCOperand::CreateImm(immediate));
345 if (type == TYPE_MOFFS8 || type == TYPE_MOFFS16 ||
346 type == TYPE_MOFFS32 || type == TYPE_MOFFS64) {
347 MCOperand segmentReg;
348 segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
349 mcInst.addOperand(segmentReg);
353 /// translateRMRegister - Translates a register stored in the R/M field of the
354 /// ModR/M byte to its LLVM equivalent and appends it to an MCInst.
355 /// @param mcInst - The MCInst to append to.
356 /// @param insn - The internal instruction to extract the R/M field
358 /// @return - 0 on success; -1 otherwise
359 static bool translateRMRegister(MCInst &mcInst,
360 InternalInstruction &insn) {
361 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
362 debug("A R/M register operand may not have a SIB byte");
366 switch (insn.eaBase) {
368 debug("Unexpected EA base register");
371 debug("EA_BASE_NONE for ModR/M base");
373 #define ENTRY(x) case EA_BASE_##x:
376 debug("A R/M register operand may not have a base; "
377 "the operand must be a register.");
381 mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
389 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
390 /// fields of an internal instruction (and possibly its SIB byte) to a memory
391 /// operand in LLVM's format, and appends it to an MCInst.
393 /// @param mcInst - The MCInst to append to.
394 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
396 /// @return - 0 on success; nonzero otherwise
397 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
398 const MCDisassembler *Dis) {
399 // Addresses in an MCInst are represented as five operands:
400 // 1. basereg (register) The R/M base, or (if there is a SIB) the
402 // 2. scaleamount (immediate) 1, or (if there is a SIB) the specified
404 // 3. indexreg (register) x86_registerNONE, or (if there is a SIB)
405 // the index (which is multiplied by the
407 // 4. displacement (immediate) 0, or the displacement if there is one
408 // 5. segmentreg (register) x86_registerNONE for now, but could be set
409 // if we have segment overrides
412 MCOperand scaleAmount;
414 MCOperand displacement;
415 MCOperand segmentReg;
418 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
419 if (insn.sibBase != SIB_BASE_NONE) {
420 switch (insn.sibBase) {
422 debug("Unexpected sibBase");
426 baseReg = MCOperand::CreateReg(X86::x); break;
431 baseReg = MCOperand::CreateReg(0);
434 // Check whether we are handling VSIB addressing mode for GATHER.
435 // If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and
436 // we should use SIB_INDEX_XMM4|YMM4 for VSIB.
437 // I don't see a way to get the correct IndexReg in readSIB:
438 // We can tell whether it is VSIB or SIB after instruction ID is decoded,
439 // but instruction ID may not be decoded yet when calling readSIB.
440 uint32_t Opcode = mcInst.getOpcode();
441 bool IndexIs128 = (Opcode == X86::VGATHERDPDrm ||
442 Opcode == X86::VGATHERDPDYrm ||
443 Opcode == X86::VGATHERQPDrm ||
444 Opcode == X86::VGATHERDPSrm ||
445 Opcode == X86::VGATHERQPSrm ||
446 Opcode == X86::VPGATHERDQrm ||
447 Opcode == X86::VPGATHERDQYrm ||
448 Opcode == X86::VPGATHERQQrm ||
449 Opcode == X86::VPGATHERDDrm ||
450 Opcode == X86::VPGATHERQDrm);
451 bool IndexIs256 = (Opcode == X86::VGATHERQPDYrm ||
452 Opcode == X86::VGATHERDPSYrm ||
453 Opcode == X86::VGATHERQPSYrm ||
454 Opcode == X86::VGATHERDPDZrm ||
455 Opcode == X86::VPGATHERDQZrm ||
456 Opcode == X86::VPGATHERQQYrm ||
457 Opcode == X86::VPGATHERDDYrm ||
458 Opcode == X86::VPGATHERQDYrm);
459 bool IndexIs512 = (Opcode == X86::VGATHERQPDZrm ||
460 Opcode == X86::VGATHERDPSZrm ||
461 Opcode == X86::VGATHERQPSZrm ||
462 Opcode == X86::VPGATHERQQZrm ||
463 Opcode == X86::VPGATHERDDZrm ||
464 Opcode == X86::VPGATHERQDZrm);
465 if (IndexIs128 || IndexIs256 || IndexIs512) {
466 unsigned IndexOffset = insn.sibIndex -
467 (insn.addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX);
468 SIBIndex IndexBase = IndexIs512 ? SIB_INDEX_ZMM0 :
469 IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0;
470 insn.sibIndex = (SIBIndex)(IndexBase +
471 (insn.sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset));
474 if (insn.sibIndex != SIB_INDEX_NONE) {
475 switch (insn.sibIndex) {
477 debug("Unexpected sibIndex");
480 case SIB_INDEX_##x: \
481 indexReg = MCOperand::CreateReg(X86::x); break;
490 indexReg = MCOperand::CreateReg(0);
493 scaleAmount = MCOperand::CreateImm(insn.sibScale);
495 switch (insn.eaBase) {
497 if (insn.eaDisplacement == EA_DISP_NONE) {
498 debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
501 if (insn.mode == MODE_64BIT){
502 pcrel = insn.startLocation +
503 insn.displacementOffset + insn.displacementSize;
504 tryAddingPcLoadReferenceComment(insn.startLocation +
505 insn.displacementOffset,
506 insn.displacement + pcrel, Dis);
507 baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
510 baseReg = MCOperand::CreateReg(0);
512 indexReg = MCOperand::CreateReg(0);
515 baseReg = MCOperand::CreateReg(X86::BX);
516 indexReg = MCOperand::CreateReg(X86::SI);
519 baseReg = MCOperand::CreateReg(X86::BX);
520 indexReg = MCOperand::CreateReg(X86::DI);
523 baseReg = MCOperand::CreateReg(X86::BP);
524 indexReg = MCOperand::CreateReg(X86::SI);
527 baseReg = MCOperand::CreateReg(X86::BP);
528 indexReg = MCOperand::CreateReg(X86::DI);
531 indexReg = MCOperand::CreateReg(0);
532 switch (insn.eaBase) {
534 debug("Unexpected eaBase");
536 // Here, we will use the fill-ins defined above. However,
537 // BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
538 // sib and sib64 were handled in the top-level if, so they're only
539 // placeholders to keep the compiler happy.
542 baseReg = MCOperand::CreateReg(X86::x); break;
545 #define ENTRY(x) case EA_REG_##x:
548 debug("A R/M memory operand may not be a register; "
549 "the base field must be a base.");
554 scaleAmount = MCOperand::CreateImm(1);
557 displacement = MCOperand::CreateImm(insn.displacement);
559 segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
561 mcInst.addOperand(baseReg);
562 mcInst.addOperand(scaleAmount);
563 mcInst.addOperand(indexReg);
564 if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
565 insn.startLocation, insn.displacementOffset,
566 insn.displacementSize, mcInst, Dis))
567 mcInst.addOperand(displacement);
568 mcInst.addOperand(segmentReg);
572 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
573 /// byte of an instruction to LLVM form, and appends it to an MCInst.
575 /// @param mcInst - The MCInst to append to.
576 /// @param operand - The operand, as stored in the descriptor table.
577 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
579 /// @return - 0 on success; nonzero otherwise
580 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
581 InternalInstruction &insn, const MCDisassembler *Dis) {
582 switch (operand.type) {
584 debug("Unexpected type for a R/M operand");
604 case TYPE_CONTROLREG:
605 return translateRMRegister(mcInst, insn);
625 return translateRMMemory(mcInst, insn, Dis);
629 /// translateFPRegister - Translates a stack position on the FPU stack to its
630 /// LLVM form, and appends it to an MCInst.
632 /// @param mcInst - The MCInst to append to.
633 /// @param stackPos - The stack position to translate.
634 static void translateFPRegister(MCInst &mcInst,
636 mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
639 /// translateMaskRegister - Translates a 3-bit mask register number to
640 /// LLVM form, and appends it to an MCInst.
642 /// @param mcInst - The MCInst to append to.
643 /// @param maskRegNum - Number of mask register from 0 to 7.
644 /// @return - false on success; true otherwise.
645 static bool translateMaskRegister(MCInst &mcInst,
646 uint8_t maskRegNum) {
647 if (maskRegNum >= 8) {
648 debug("Invalid mask register number");
652 mcInst.addOperand(MCOperand::CreateReg(X86::K0 + maskRegNum));
656 /// translateOperand - Translates an operand stored in an internal instruction
657 /// to LLVM's format and appends it to an MCInst.
659 /// @param mcInst - The MCInst to append to.
660 /// @param operand - The operand, as stored in the descriptor table.
661 /// @param insn - The internal instruction.
662 /// @return - false on success; true otherwise.
663 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
664 InternalInstruction &insn,
665 const MCDisassembler *Dis) {
666 switch (operand.encoding) {
668 debug("Unhandled operand encoding during translation");
671 translateRegister(mcInst, insn.reg);
673 case ENCODING_WRITEMASK:
674 return translateMaskRegister(mcInst, insn.writemask);
676 return translateRM(mcInst, operand, insn, Dis);
683 debug("Translation of code offsets isn't supported.");
691 translateImmediate(mcInst,
692 insn.immediates[insn.numImmediatesTranslated++],
702 translateRegister(mcInst, insn.opcodeRegister);
705 translateFPRegister(mcInst, insn.modRM & 7);
708 translateRegister(mcInst, insn.vvvv);
711 return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
716 /// translateInstruction - Translates an internal instruction and all its
717 /// operands to an MCInst.
719 /// @param mcInst - The MCInst to populate with the instruction's data.
720 /// @param insn - The internal instruction.
721 /// @return - false on success; true otherwise.
722 static bool translateInstruction(MCInst &mcInst,
723 InternalInstruction &insn,
724 const MCDisassembler *Dis) {
726 debug("Instruction has no specification");
730 mcInst.setOpcode(insn.instructionID);
731 // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
732 // prefix bytes should be disassembled as xrelease and xacquire then set the
733 // opcode to those instead of the rep and repne opcodes.
734 if (insn.xAcquireRelease) {
735 if(mcInst.getOpcode() == X86::REP_PREFIX)
736 mcInst.setOpcode(X86::XRELEASE_PREFIX);
737 else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
738 mcInst.setOpcode(X86::XACQUIRE_PREFIX);
743 insn.numImmediatesTranslated = 0;
745 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
746 if (insn.operands[index].encoding != ENCODING_NONE) {
747 if (translateOperand(mcInst, insn.operands[index], insn, Dis)) {
756 static MCDisassembler *createX86Disassembler(const Target &T,
757 const MCSubtargetInfo &STI) {
758 return new X86Disassembler::X86GenericDisassembler(STI,
759 T.createMCInstrInfo());
762 extern "C" void LLVMInitializeX86Disassembler() {
763 // Register the disassembler.
764 TargetRegistry::RegisterMCDisassembler(TheX86_32Target,
765 createX86Disassembler);
766 TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
767 createX86Disassembler);