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"
36 using namespace llvm::X86Disassembler;
38 void x86DisassemblerDebug(const char *file,
41 dbgs() << file << ":" << line << ": " << s;
44 const char *x86DisassemblerGetInstrName(unsigned Opcode, const void *mii) {
45 const MCInstrInfo *MII = static_cast<const MCInstrInfo *>(mii);
46 return MII->getName(Opcode);
49 #define debug(s) DEBUG(x86DisassemblerDebug(__FILE__, __LINE__, s));
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
67 extern Target TheX86_32Target, TheX86_64Target;
71 static bool translateInstruction(MCInst &target,
72 InternalInstruction &source,
73 const MCDisassembler *Dis);
75 X86GenericDisassembler::X86GenericDisassembler(const MCSubtargetInfo &STI,
76 DisassemblerMode mode,
77 const MCInstrInfo *MII)
78 : MCDisassembler(STI), MII(MII), fMode(mode) {}
80 X86GenericDisassembler::~X86GenericDisassembler() {
84 /// regionReader - a callback function that wraps the readByte method from
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);
96 /// logger - a callback function that wraps the operator<< method from
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) {
106 raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
107 vStream << log << "\n";
111 // Public interface for the disassembler
114 MCDisassembler::DecodeStatus
115 X86GenericDisassembler::getInstruction(MCInst &instr,
117 const MemoryObject ®ion,
119 raw_ostream &vStream,
120 raw_ostream &cStream) const {
121 CommentStream = &cStream;
123 InternalInstruction internalInstr;
125 dlog_t loggerFn = logger;
126 if (&vStream == &nulls())
127 loggerFn = 0; // Disable logging completely if it's going to nulls().
129 int ret = decodeInstruction(&internalInstr,
131 (const void*)®ion,
139 size = internalInstr.readerCursor - address;
143 size = internalInstr.length;
144 return (!translateInstruction(instr, internalInstr, this)) ?
150 // Private code that translates from struct InternalInstructions to MCInsts.
153 /// translateRegister - Translates an internal register to the appropriate LLVM
154 /// register, and appends it as an operand to an MCInst.
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[] = {
166 uint8_t llvmRegnum = llvmRegnums[reg];
167 mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
170 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
171 /// immediate Value in the MCInst.
173 /// @param Value - The immediate Value, has had any PC adjustment made by
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
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,
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);
210 /// translateImmediate - Appends an immediate operand to an MCInst.
212 /// @param mcInst - The MCInst to append to.
213 /// @param immediate - The immediate value to append.
214 /// @param operand - The operand, as stored in the descriptor table.
215 /// @param insn - The internal instruction.
216 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
217 const OperandSpecifier &operand,
218 InternalInstruction &insn,
219 const MCDisassembler *Dis) {
220 // Sign-extend the immediate if necessary.
222 OperandType type = (OperandType)operand.type;
224 bool isBranch = false;
226 if (type == TYPE_RELv) {
228 pcrel = insn.startLocation +
229 insn.immediateOffset + insn.immediateSize;
230 switch (insn.displacementSize) {
235 immediate |= ~(0xffull);
238 if(immediate & 0x8000)
239 immediate |= ~(0xffffull);
242 if(immediate & 0x80000000)
243 immediate |= ~(0xffffffffull);
249 // By default sign-extend all X86 immediates based on their encoding.
250 else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
251 type == TYPE_IMM64) {
252 uint32_t Opcode = mcInst.getOpcode();
253 switch (operand.encoding) {
257 // Special case those X86 instructions that use the imm8 as a set of
258 // bits, bit count, etc. and are not sign-extend.
259 if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
260 Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
261 Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
262 Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
263 Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
264 Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
265 Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
266 Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
267 Opcode != X86::VINSERTPSrr)
269 immediate |= ~(0xffull);
272 if(immediate & 0x8000)
273 immediate |= ~(0xffffull);
276 if(immediate & 0x80000000)
277 immediate |= ~(0xffffffffull);
288 mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
291 mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
294 mcInst.addOperand(MCOperand::CreateReg(X86::ZMM0 + (immediate >> 4)));
298 pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
300 immediate |= ~(0xffull);
305 pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
306 if(immediate & 0x80000000)
307 immediate |= ~(0xffffffffull);
310 // operand is 64 bits wide. Do nothing.
314 if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
315 insn.immediateOffset, insn.immediateSize,
317 mcInst.addOperand(MCOperand::CreateImm(immediate));
320 /// translateRMRegister - Translates a register stored in the R/M field of the
321 /// ModR/M byte to its LLVM equivalent and appends it to an MCInst.
322 /// @param mcInst - The MCInst to append to.
323 /// @param insn - The internal instruction to extract the R/M field
325 /// @return - 0 on success; -1 otherwise
326 static bool translateRMRegister(MCInst &mcInst,
327 InternalInstruction &insn) {
328 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
329 debug("A R/M register operand may not have a SIB byte");
333 switch (insn.eaBase) {
335 debug("Unexpected EA base register");
338 debug("EA_BASE_NONE for ModR/M base");
340 #define ENTRY(x) case EA_BASE_##x:
343 debug("A R/M register operand may not have a base; "
344 "the operand must be a register.");
348 mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
356 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
357 /// fields of an internal instruction (and possibly its SIB byte) to a memory
358 /// operand in LLVM's format, and appends it to an MCInst.
360 /// @param mcInst - The MCInst to append to.
361 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
363 /// @return - 0 on success; nonzero otherwise
364 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
365 const MCDisassembler *Dis) {
366 // Addresses in an MCInst are represented as five operands:
367 // 1. basereg (register) The R/M base, or (if there is a SIB) the
369 // 2. scaleamount (immediate) 1, or (if there is a SIB) the specified
371 // 3. indexreg (register) x86_registerNONE, or (if there is a SIB)
372 // the index (which is multiplied by the
374 // 4. displacement (immediate) 0, or the displacement if there is one
375 // 5. segmentreg (register) x86_registerNONE for now, but could be set
376 // if we have segment overrides
379 MCOperand scaleAmount;
381 MCOperand displacement;
382 MCOperand segmentReg;
385 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
386 if (insn.sibBase != SIB_BASE_NONE) {
387 switch (insn.sibBase) {
389 debug("Unexpected sibBase");
393 baseReg = MCOperand::CreateReg(X86::x); break;
398 baseReg = MCOperand::CreateReg(0);
401 // Check whether we are handling VSIB addressing mode for GATHER.
402 // If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and
403 // we should use SIB_INDEX_XMM4|YMM4 for VSIB.
404 // I don't see a way to get the correct IndexReg in readSIB:
405 // We can tell whether it is VSIB or SIB after instruction ID is decoded,
406 // but instruction ID may not be decoded yet when calling readSIB.
407 uint32_t Opcode = mcInst.getOpcode();
408 bool IndexIs128 = (Opcode == X86::VGATHERDPDrm ||
409 Opcode == X86::VGATHERDPDYrm ||
410 Opcode == X86::VGATHERQPDrm ||
411 Opcode == X86::VGATHERDPSrm ||
412 Opcode == X86::VGATHERQPSrm ||
413 Opcode == X86::VPGATHERDQrm ||
414 Opcode == X86::VPGATHERDQYrm ||
415 Opcode == X86::VPGATHERQQrm ||
416 Opcode == X86::VPGATHERDDrm ||
417 Opcode == X86::VPGATHERQDrm);
418 bool IndexIs256 = (Opcode == X86::VGATHERQPDYrm ||
419 Opcode == X86::VGATHERDPSYrm ||
420 Opcode == X86::VGATHERQPSYrm ||
421 Opcode == X86::VPGATHERQQYrm ||
422 Opcode == X86::VPGATHERDDYrm ||
423 Opcode == X86::VPGATHERQDYrm);
424 if (IndexIs128 || IndexIs256) {
425 unsigned IndexOffset = insn.sibIndex -
426 (insn.addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX);
427 SIBIndex IndexBase = IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0;
428 insn.sibIndex = (SIBIndex)(IndexBase +
429 (insn.sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset));
432 if (insn.sibIndex != SIB_INDEX_NONE) {
433 switch (insn.sibIndex) {
435 debug("Unexpected sibIndex");
438 case SIB_INDEX_##x: \
439 indexReg = MCOperand::CreateReg(X86::x); break;
448 indexReg = MCOperand::CreateReg(0);
451 scaleAmount = MCOperand::CreateImm(insn.sibScale);
453 switch (insn.eaBase) {
455 if (insn.eaDisplacement == EA_DISP_NONE) {
456 debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
459 if (insn.mode == MODE_64BIT){
460 pcrel = insn.startLocation +
461 insn.displacementOffset + insn.displacementSize;
462 tryAddingPcLoadReferenceComment(insn.startLocation +
463 insn.displacementOffset,
464 insn.displacement + pcrel, Dis);
465 baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
468 baseReg = MCOperand::CreateReg(0);
470 indexReg = MCOperand::CreateReg(0);
473 baseReg = MCOperand::CreateReg(X86::BX);
474 indexReg = MCOperand::CreateReg(X86::SI);
477 baseReg = MCOperand::CreateReg(X86::BX);
478 indexReg = MCOperand::CreateReg(X86::DI);
481 baseReg = MCOperand::CreateReg(X86::BP);
482 indexReg = MCOperand::CreateReg(X86::SI);
485 baseReg = MCOperand::CreateReg(X86::BP);
486 indexReg = MCOperand::CreateReg(X86::DI);
489 indexReg = MCOperand::CreateReg(0);
490 switch (insn.eaBase) {
492 debug("Unexpected eaBase");
494 // Here, we will use the fill-ins defined above. However,
495 // BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
496 // sib and sib64 were handled in the top-level if, so they're only
497 // placeholders to keep the compiler happy.
500 baseReg = MCOperand::CreateReg(X86::x); break;
503 #define ENTRY(x) case EA_REG_##x:
506 debug("A R/M memory operand may not be a register; "
507 "the base field must be a base.");
512 scaleAmount = MCOperand::CreateImm(1);
515 displacement = MCOperand::CreateImm(insn.displacement);
517 static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
518 0, // SEG_OVERRIDE_NONE
527 segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
529 mcInst.addOperand(baseReg);
530 mcInst.addOperand(scaleAmount);
531 mcInst.addOperand(indexReg);
532 if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
533 insn.startLocation, insn.displacementOffset,
534 insn.displacementSize, mcInst, Dis))
535 mcInst.addOperand(displacement);
536 mcInst.addOperand(segmentReg);
540 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
541 /// byte of an instruction to LLVM form, and appends it to an MCInst.
543 /// @param mcInst - The MCInst to append to.
544 /// @param operand - The operand, as stored in the descriptor table.
545 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
547 /// @return - 0 on success; nonzero otherwise
548 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
549 InternalInstruction &insn, const MCDisassembler *Dis) {
550 switch (operand.type) {
552 debug("Unexpected type for a R/M operand");
569 case TYPE_CONTROLREG:
570 return translateRMRegister(mcInst, insn);
590 return translateRMMemory(mcInst, insn, Dis);
594 /// translateFPRegister - Translates a stack position on the FPU stack to its
595 /// LLVM form, and appends it to an MCInst.
597 /// @param mcInst - The MCInst to append to.
598 /// @param stackPos - The stack position to translate.
599 /// @return - 0 on success; nonzero otherwise.
600 static bool translateFPRegister(MCInst &mcInst,
603 debug("Invalid FP stack position");
607 mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
612 /// translateOperand - Translates an operand stored in an internal instruction
613 /// to LLVM's format and appends it to an MCInst.
615 /// @param mcInst - The MCInst to append to.
616 /// @param operand - The operand, as stored in the descriptor table.
617 /// @param insn - The internal instruction.
618 /// @return - false on success; true otherwise.
619 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
620 InternalInstruction &insn,
621 const MCDisassembler *Dis) {
622 switch (operand.encoding) {
624 debug("Unhandled operand encoding during translation");
627 translateRegister(mcInst, insn.reg);
630 return translateRM(mcInst, operand, insn, Dis);
637 debug("Translation of code offsets isn't supported.");
645 translateImmediate(mcInst,
646 insn.immediates[insn.numImmediatesTranslated++],
655 translateRegister(mcInst, insn.opcodeRegister);
658 return translateFPRegister(mcInst, insn.opcodeModifier);
660 translateRegister(mcInst, insn.opcodeRegister);
663 translateRegister(mcInst, insn.vvvv);
666 return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
671 /// translateInstruction - Translates an internal instruction and all its
672 /// operands to an MCInst.
674 /// @param mcInst - The MCInst to populate with the instruction's data.
675 /// @param insn - The internal instruction.
676 /// @return - false on success; true otherwise.
677 static bool translateInstruction(MCInst &mcInst,
678 InternalInstruction &insn,
679 const MCDisassembler *Dis) {
681 debug("Instruction has no specification");
685 mcInst.setOpcode(insn.instructionID);
686 // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
687 // prefix bytes should be disassembled as xrelease and xacquire then set the
688 // opcode to those instead of the rep and repne opcodes.
689 if (insn.xAcquireRelease) {
690 if(mcInst.getOpcode() == X86::REP_PREFIX)
691 mcInst.setOpcode(X86::XRELEASE_PREFIX);
692 else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
693 mcInst.setOpcode(X86::XACQUIRE_PREFIX);
698 insn.numImmediatesTranslated = 0;
700 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
701 if (insn.operands[index].encoding != ENCODING_NONE) {
702 if (translateOperand(mcInst, insn.operands[index], insn, Dis)) {
711 static MCDisassembler *createX86_32Disassembler(const Target &T,
712 const MCSubtargetInfo &STI) {
713 return new X86Disassembler::X86GenericDisassembler(STI, MODE_32BIT,
714 T.createMCInstrInfo());
717 static MCDisassembler *createX86_64Disassembler(const Target &T,
718 const MCSubtargetInfo &STI) {
719 return new X86Disassembler::X86GenericDisassembler(STI, MODE_64BIT,
720 T.createMCInstrInfo());
723 extern "C" void LLVMInitializeX86Disassembler() {
724 // Register the disassembler.
725 TargetRegistry::RegisterMCDisassembler(TheX86_32Target,
726 createX86_32Disassembler);
727 TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
728 createX86_64Disassembler);