1 //===-- X86DisassemblerDecoder.cpp - Disassembler decoder -----------------===//
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 the implementation of the instruction decoder.
12 // Documentation for the disassembler can be found in X86Disassembler.h.
14 //===----------------------------------------------------------------------===//
16 #include <cstdarg> /* for va_*() */
17 #include <cstdio> /* for vsnprintf() */
18 #include <cstdlib> /* for exit() */
19 #include <cstring> /* for memset() */
21 #include "X86DisassemblerDecoder.h"
23 using namespace llvm::X86Disassembler;
25 /// Specifies whether a ModR/M byte is needed and (if so) which
26 /// instruction each possible value of the ModR/M byte corresponds to. Once
27 /// this information is known, we have narrowed down to a single instruction.
28 struct ModRMDecision {
30 uint16_t instructionIDs;
33 /// Specifies which set of ModR/M->instruction tables to look at
34 /// given a particular opcode.
35 struct OpcodeDecision {
36 ModRMDecision modRMDecisions[256];
39 /// Specifies which opcode->instruction tables to look at given
40 /// a particular context (set of attributes). Since there are many possible
41 /// contexts, the decoder first uses CONTEXTS_SYM to determine which context
42 /// applies given a specific set of attributes. Hence there are only IC_max
43 /// entries in this table, rather than 2^(ATTR_max).
44 struct ContextDecision {
45 OpcodeDecision opcodeDecisions[IC_max];
48 #include "X86GenDisassemblerTables.inc"
51 #define debug(s) do { Debug(__FILE__, __LINE__, s); } while (0)
53 #define debug(s) do { } while (0)
57 * contextForAttrs - Client for the instruction context table. Takes a set of
58 * attributes and returns the appropriate decode context.
60 * @param attrMask - Attributes, from the enumeration attributeBits.
61 * @return - The InstructionContext to use when looking up an
62 * an instruction with these attributes.
64 static InstructionContext contextForAttrs(uint16_t attrMask) {
65 return static_cast<InstructionContext>(CONTEXTS_SYM[attrMask]);
69 * modRMRequired - Reads the appropriate instruction table to determine whether
70 * the ModR/M byte is required to decode a particular instruction.
72 * @param type - The opcode type (i.e., how many bytes it has).
73 * @param insnContext - The context for the instruction, as returned by
75 * @param opcode - The last byte of the instruction's opcode, not counting
76 * ModR/M extensions and escapes.
77 * @return - true if the ModR/M byte is required, false otherwise.
79 static int modRMRequired(OpcodeType type,
80 InstructionContext insnContext,
82 const struct ContextDecision* decision = nullptr;
86 decision = &ONEBYTE_SYM;
89 decision = &TWOBYTE_SYM;
92 decision = &THREEBYTE38_SYM;
95 decision = &THREEBYTE3A_SYM;
98 decision = &XOP8_MAP_SYM;
101 decision = &XOP9_MAP_SYM;
104 decision = &XOPA_MAP_SYM;
107 decision = &THREEDNOW_MAP_SYM;
111 return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].
112 modrm_type != MODRM_ONEENTRY;
116 * decode - Reads the appropriate instruction table to obtain the unique ID of
119 * @param type - See modRMRequired().
120 * @param insnContext - See modRMRequired().
121 * @param opcode - See modRMRequired().
122 * @param modRM - The ModR/M byte if required, or any value if not.
123 * @return - The UID of the instruction, or 0 on failure.
125 static InstrUID decode(OpcodeType type,
126 InstructionContext insnContext,
129 const struct ModRMDecision* dec = nullptr;
133 dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
136 dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
139 dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
142 dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
145 dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
148 dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
151 dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
154 dec = &THREEDNOW_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
158 switch (dec->modrm_type) {
160 debug("Corrupt table! Unknown modrm_type");
163 return modRMTable[dec->instructionIDs];
165 if (modFromModRM(modRM) == 0x3)
166 return modRMTable[dec->instructionIDs+1];
167 return modRMTable[dec->instructionIDs];
169 if (modFromModRM(modRM) == 0x3)
170 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)+8];
171 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
172 case MODRM_SPLITMISC:
173 if (modFromModRM(modRM) == 0x3)
174 return modRMTable[dec->instructionIDs+(modRM & 0x3f)+8];
175 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
177 return modRMTable[dec->instructionIDs+modRM];
182 * specifierForUID - Given a UID, returns the name and operand specification for
185 * @param uid - The unique ID for the instruction. This should be returned by
186 * decode(); specifierForUID will not check bounds.
187 * @return - A pointer to the specification for that instruction.
189 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
190 return &INSTRUCTIONS_SYM[uid];
194 * consumeByte - Uses the reader function provided by the user to consume one
195 * byte from the instruction's memory and advance the cursor.
197 * @param insn - The instruction with the reader function to use. The cursor
198 * for this instruction is advanced.
199 * @param byte - A pointer to a pre-allocated memory buffer to be populated
200 * with the data read.
201 * @return - 0 if the read was successful; nonzero otherwise.
203 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
204 int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
207 ++(insn->readerCursor);
213 * lookAtByte - Like consumeByte, but does not advance the cursor.
215 * @param insn - See consumeByte().
216 * @param byte - See consumeByte().
217 * @return - See consumeByte().
219 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
220 return insn->reader(insn->readerArg, byte, insn->readerCursor);
223 static void unconsumeByte(struct InternalInstruction* insn) {
224 insn->readerCursor--;
227 #define CONSUME_FUNC(name, type) \
228 static int name(struct InternalInstruction* insn, type* ptr) { \
231 for (offset = 0; offset < sizeof(type); ++offset) { \
233 int ret = insn->reader(insn->readerArg, \
235 insn->readerCursor + offset); \
238 combined = combined | ((uint64_t)byte << (offset * 8)); \
241 insn->readerCursor += sizeof(type); \
246 * consume* - Use the reader function provided by the user to consume data
247 * values of various sizes from the instruction's memory and advance the
248 * cursor appropriately. These readers perform endian conversion.
250 * @param insn - See consumeByte().
251 * @param ptr - A pointer to a pre-allocated memory of appropriate size to
252 * be populated with the data read.
253 * @return - See consumeByte().
255 CONSUME_FUNC(consumeInt8, int8_t)
256 CONSUME_FUNC(consumeInt16, int16_t)
257 CONSUME_FUNC(consumeInt32, int32_t)
258 CONSUME_FUNC(consumeUInt16, uint16_t)
259 CONSUME_FUNC(consumeUInt32, uint32_t)
260 CONSUME_FUNC(consumeUInt64, uint64_t)
263 * dbgprintf - Uses the logging function provided by the user to log a single
264 * message, typically without a carriage-return.
266 * @param insn - The instruction containing the logging function.
267 * @param format - See printf().
268 * @param ... - See printf().
270 static void dbgprintf(struct InternalInstruction* insn,
279 va_start(ap, format);
280 (void)vsnprintf(buffer, sizeof(buffer), format, ap);
283 insn->dlog(insn->dlogArg, buffer);
286 static bool isREX(struct InternalInstruction *insn, uint8_t prefix) {
287 if (insn->mode == MODE_64BIT)
288 return prefix >= 0x40 && prefix <= 0x4f;
293 * setPrefixPresent - Marks that a particular prefix is present as mandatory
295 * @param insn - The instruction to be marked as having the prefix.
296 * @param prefix - The prefix that is present.
298 static void setPrefixPresent(struct InternalInstruction *insn, uint8_t prefix) {
302 insn->hasLockPrefix = true;
306 if (lookAtByte(insn, &nextByte))
309 // 1. There could be several 0x66
310 // 2. if (nextByte == 0x66) and nextNextByte != 0x0f then
311 // it's not mandatory prefix
312 // 3. if (nextByte >= 0x40 && nextByte <= 0x4f) it's REX and we need
313 // 0x0f exactly after it to be mandatory prefix
314 if (isREX(insn, nextByte) || nextByte == 0x0f || nextByte == 0x66)
315 // The last of 0xf2 /0xf3 is mandatory prefix
316 insn->mandatoryPrefix = prefix;
317 insn->repeatPrefix = prefix;
320 if (lookAtByte(insn, &nextByte))
322 // 0x66 can't overwrite existing mandatory prefix and should be ignored
323 if (!insn->mandatoryPrefix && (nextByte == 0x0f || isREX(insn, nextByte)))
324 insn->mandatoryPrefix = prefix;
330 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
331 * instruction as having them. Also sets the instruction's default operand,
332 * address, and other relevant data sizes to report operands correctly.
334 * @param insn - The instruction whose prefixes are to be read.
335 * @return - 0 if the instruction could be read until the end of the prefix
336 * bytes, and no prefixes conflicted; nonzero otherwise.
338 static int readPrefixes(struct InternalInstruction* insn) {
339 bool isPrefix = true;
343 dbgprintf(insn, "readPrefixes()");
346 /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
347 if (consumeByte(insn, &byte))
351 * If the byte is a LOCK/REP/REPNE prefix and not a part of the opcode, then
352 * break and let it be disassembled as a normal "instruction".
354 if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0) // LOCK
357 if ((byte == 0xf2 || byte == 0xf3) && !lookAtByte(insn, &nextByte)) {
359 * If the byte is 0xf2 or 0xf3, and any of the following conditions are
361 * - it is followed by a LOCK (0xf0) prefix
362 * - it is followed by an xchg instruction
363 * then it should be disassembled as a xacquire/xrelease not repne/rep.
365 if (((nextByte == 0xf0) ||
366 ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90))) {
367 insn->xAcquireRelease = true;
368 if (!(byte == 0xf3 && nextByte == 0x90)) // PAUSE instruction support
372 * Also if the byte is 0xf3, and the following condition is met:
373 * - it is followed by a "mov mem, reg" (opcode 0x88/0x89) or
374 * "mov mem, imm" (opcode 0xc6/0xc7) instructions.
375 * then it should be disassembled as an xrelease not rep.
377 if (byte == 0xf3 && (nextByte == 0x88 || nextByte == 0x89 ||
378 nextByte == 0xc6 || nextByte == 0xc7)) {
379 insn->xAcquireRelease = true;
380 if (nextByte != 0x90) // PAUSE instruction support
383 if (isREX(insn, nextByte)) {
385 // Go to REX prefix after the current one
386 if (consumeByte(insn, &nnextByte))
388 // We should be able to read next byte after REX prefix
389 if (lookAtByte(insn, &nnextByte))
396 case 0xf0: /* LOCK */
397 case 0xf2: /* REPNE/REPNZ */
398 case 0xf3: /* REP or REPE/REPZ */
399 setPrefixPresent(insn, byte);
401 case 0x2e: /* CS segment override -OR- Branch not taken */
402 case 0x36: /* SS segment override -OR- Branch taken */
403 case 0x3e: /* DS segment override */
404 case 0x26: /* ES segment override */
405 case 0x64: /* FS segment override */
406 case 0x65: /* GS segment override */
409 insn->segmentOverride = SEG_OVERRIDE_CS;
412 insn->segmentOverride = SEG_OVERRIDE_SS;
415 insn->segmentOverride = SEG_OVERRIDE_DS;
418 insn->segmentOverride = SEG_OVERRIDE_ES;
421 insn->segmentOverride = SEG_OVERRIDE_FS;
424 insn->segmentOverride = SEG_OVERRIDE_GS;
427 debug("Unhandled override");
430 setPrefixPresent(insn, byte);
432 case 0x66: /* Operand-size override */
433 insn->hasOpSize = true;
434 setPrefixPresent(insn, byte);
436 case 0x67: /* Address-size override */
437 insn->hasAdSize = true;
438 setPrefixPresent(insn, byte);
440 default: /* Not a prefix byte */
446 dbgprintf(insn, "Found prefix 0x%hhx", byte);
449 insn->vectorExtensionType = TYPE_NO_VEX_XOP;
452 uint8_t byte1, byte2;
454 if (consumeByte(insn, &byte1)) {
455 dbgprintf(insn, "Couldn't read second byte of EVEX prefix");
459 if (lookAtByte(insn, &byte2)) {
460 dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
464 if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
465 ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
466 insn->vectorExtensionType = TYPE_EVEX;
468 unconsumeByte(insn); /* unconsume byte1 */
469 unconsumeByte(insn); /* unconsume byte */
472 if (insn->vectorExtensionType == TYPE_EVEX) {
473 insn->vectorExtensionPrefix[0] = byte;
474 insn->vectorExtensionPrefix[1] = byte1;
475 if (consumeByte(insn, &insn->vectorExtensionPrefix[2])) {
476 dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
479 if (consumeByte(insn, &insn->vectorExtensionPrefix[3])) {
480 dbgprintf(insn, "Couldn't read fourth byte of EVEX prefix");
484 /* We simulate the REX prefix for simplicity's sake */
485 if (insn->mode == MODE_64BIT) {
486 insn->rexPrefix = 0x40
487 | (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3)
488 | (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2)
489 | (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1)
490 | (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
493 dbgprintf(insn, "Found EVEX prefix 0x%hhx 0x%hhx 0x%hhx 0x%hhx",
494 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
495 insn->vectorExtensionPrefix[2], insn->vectorExtensionPrefix[3]);
497 } else if (byte == 0xc4) {
500 if (lookAtByte(insn, &byte1)) {
501 dbgprintf(insn, "Couldn't read second byte of VEX");
505 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
506 insn->vectorExtensionType = TYPE_VEX_3B;
510 if (insn->vectorExtensionType == TYPE_VEX_3B) {
511 insn->vectorExtensionPrefix[0] = byte;
512 consumeByte(insn, &insn->vectorExtensionPrefix[1]);
513 consumeByte(insn, &insn->vectorExtensionPrefix[2]);
515 /* We simulate the REX prefix for simplicity's sake */
517 if (insn->mode == MODE_64BIT)
518 insn->rexPrefix = 0x40
519 | (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3)
520 | (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2)
521 | (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1)
522 | (bFromVEX2of3(insn->vectorExtensionPrefix[1]) << 0);
524 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx",
525 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
526 insn->vectorExtensionPrefix[2]);
528 } else if (byte == 0xc5) {
531 if (lookAtByte(insn, &byte1)) {
532 dbgprintf(insn, "Couldn't read second byte of VEX");
536 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
537 insn->vectorExtensionType = TYPE_VEX_2B;
541 if (insn->vectorExtensionType == TYPE_VEX_2B) {
542 insn->vectorExtensionPrefix[0] = byte;
543 consumeByte(insn, &insn->vectorExtensionPrefix[1]);
545 if (insn->mode == MODE_64BIT)
546 insn->rexPrefix = 0x40
547 | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
549 switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
553 insn->hasOpSize = true;
557 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx",
558 insn->vectorExtensionPrefix[0],
559 insn->vectorExtensionPrefix[1]);
561 } else if (byte == 0x8f) {
564 if (lookAtByte(insn, &byte1)) {
565 dbgprintf(insn, "Couldn't read second byte of XOP");
569 if ((byte1 & 0x38) != 0x0) /* 0 in these 3 bits is a POP instruction. */
570 insn->vectorExtensionType = TYPE_XOP;
574 if (insn->vectorExtensionType == TYPE_XOP) {
575 insn->vectorExtensionPrefix[0] = byte;
576 consumeByte(insn, &insn->vectorExtensionPrefix[1]);
577 consumeByte(insn, &insn->vectorExtensionPrefix[2]);
579 /* We simulate the REX prefix for simplicity's sake */
581 if (insn->mode == MODE_64BIT)
582 insn->rexPrefix = 0x40
583 | (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3)
584 | (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2)
585 | (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1)
586 | (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
588 switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
592 insn->hasOpSize = true;
596 dbgprintf(insn, "Found XOP prefix 0x%hhx 0x%hhx 0x%hhx",
597 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
598 insn->vectorExtensionPrefix[2]);
600 } else if (isREX(insn, byte)) {
601 if (lookAtByte(insn, &nextByte))
603 insn->rexPrefix = byte;
604 dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
608 if (insn->mode == MODE_16BIT) {
609 insn->registerSize = (insn->hasOpSize ? 4 : 2);
610 insn->addressSize = (insn->hasAdSize ? 4 : 2);
611 insn->displacementSize = (insn->hasAdSize ? 4 : 2);
612 insn->immediateSize = (insn->hasOpSize ? 4 : 2);
613 } else if (insn->mode == MODE_32BIT) {
614 insn->registerSize = (insn->hasOpSize ? 2 : 4);
615 insn->addressSize = (insn->hasAdSize ? 2 : 4);
616 insn->displacementSize = (insn->hasAdSize ? 2 : 4);
617 insn->immediateSize = (insn->hasOpSize ? 2 : 4);
618 } else if (insn->mode == MODE_64BIT) {
619 if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
620 insn->registerSize = 8;
621 insn->addressSize = (insn->hasAdSize ? 4 : 8);
622 insn->displacementSize = 4;
623 insn->immediateSize = 4;
625 insn->registerSize = (insn->hasOpSize ? 2 : 4);
626 insn->addressSize = (insn->hasAdSize ? 4 : 8);
627 insn->displacementSize = (insn->hasOpSize ? 2 : 4);
628 insn->immediateSize = (insn->hasOpSize ? 2 : 4);
635 static int readModRM(struct InternalInstruction* insn);
638 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
639 * extended or escape opcodes).
641 * @param insn - The instruction whose opcode is to be read.
642 * @return - 0 if the opcode could be read successfully; nonzero otherwise.
644 static int readOpcode(struct InternalInstruction* insn) {
645 /* Determine the length of the primary opcode */
649 dbgprintf(insn, "readOpcode()");
651 insn->opcodeType = ONEBYTE;
653 if (insn->vectorExtensionType == TYPE_EVEX) {
654 switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
656 dbgprintf(insn, "Unhandled mm field for instruction (0x%hhx)",
657 mmFromEVEX2of4(insn->vectorExtensionPrefix[1]));
660 insn->opcodeType = TWOBYTE;
661 return consumeByte(insn, &insn->opcode);
663 insn->opcodeType = THREEBYTE_38;
664 return consumeByte(insn, &insn->opcode);
666 insn->opcodeType = THREEBYTE_3A;
667 return consumeByte(insn, &insn->opcode);
669 } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
670 switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
672 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
673 mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
676 insn->opcodeType = TWOBYTE;
677 return consumeByte(insn, &insn->opcode);
679 insn->opcodeType = THREEBYTE_38;
680 return consumeByte(insn, &insn->opcode);
682 insn->opcodeType = THREEBYTE_3A;
683 return consumeByte(insn, &insn->opcode);
685 } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
686 insn->opcodeType = TWOBYTE;
687 return consumeByte(insn, &insn->opcode);
688 } else if (insn->vectorExtensionType == TYPE_XOP) {
689 switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
691 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
692 mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
694 case XOP_MAP_SELECT_8:
695 insn->opcodeType = XOP8_MAP;
696 return consumeByte(insn, &insn->opcode);
697 case XOP_MAP_SELECT_9:
698 insn->opcodeType = XOP9_MAP;
699 return consumeByte(insn, &insn->opcode);
700 case XOP_MAP_SELECT_A:
701 insn->opcodeType = XOPA_MAP;
702 return consumeByte(insn, &insn->opcode);
706 if (consumeByte(insn, ¤t))
709 if (current == 0x0f) {
710 dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
712 if (consumeByte(insn, ¤t))
715 if (current == 0x38) {
716 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
718 if (consumeByte(insn, ¤t))
721 insn->opcodeType = THREEBYTE_38;
722 } else if (current == 0x3a) {
723 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
725 if (consumeByte(insn, ¤t))
728 insn->opcodeType = THREEBYTE_3A;
729 } else if (current == 0x0f) {
730 dbgprintf(insn, "Found a 3dnow escape prefix (0x%hhx)", current);
732 // Consume operands before the opcode to comply with the 3DNow encoding
736 if (consumeByte(insn, ¤t))
739 insn->opcodeType = THREEDNOW_MAP;
741 dbgprintf(insn, "Didn't find a three-byte escape prefix");
743 insn->opcodeType = TWOBYTE;
745 } else if (insn->mandatoryPrefix)
746 // The opcode with mandatory prefix must start with opcode escape.
747 // If not it's legacy repeat prefix
748 insn->mandatoryPrefix = 0;
751 * At this point we have consumed the full opcode.
752 * Anything we consume from here on must be unconsumed.
755 insn->opcode = current;
761 * getIDWithAttrMask - Determines the ID of an instruction, consuming
762 * the ModR/M byte as appropriate for extended and escape opcodes,
763 * and using a supplied attribute mask.
765 * @param instructionID - A pointer whose target is filled in with the ID of the
767 * @param insn - The instruction whose ID is to be determined.
768 * @param attrMask - The attribute mask to search.
769 * @return - 0 if the ModR/M could be read when needed or was not
770 * needed; nonzero otherwise.
772 static int getIDWithAttrMask(uint16_t* instructionID,
773 struct InternalInstruction* insn,
775 bool hasModRMExtension;
777 InstructionContext instructionClass = contextForAttrs(attrMask);
779 hasModRMExtension = modRMRequired(insn->opcodeType,
783 if (hasModRMExtension) {
787 *instructionID = decode(insn->opcodeType,
792 *instructionID = decode(insn->opcodeType,
802 * is16BitEquivalent - Determines whether two instruction names refer to
803 * equivalent instructions but one is 16-bit whereas the other is not.
805 * @param orig - The instruction that is not 16-bit
806 * @param equiv - The instruction that is 16-bit
808 static bool is16BitEquivalent(const char *orig, const char *equiv) {
812 if (orig[i] == '\0' && equiv[i] == '\0')
814 if (orig[i] == '\0' || equiv[i] == '\0')
816 if (orig[i] != equiv[i]) {
817 if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
819 if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
821 if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
829 * is64Bit - Determines whether this instruction is a 64-bit instruction.
831 * @param name - The instruction that is not 16-bit
833 static bool is64Bit(const char *name) {
839 if (name[i] == '6' && name[i+1] == '4')
845 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
846 * appropriate for extended and escape opcodes. Determines the attributes and
847 * context for the instruction before doing so.
849 * @param insn - The instruction whose ID is to be determined.
850 * @return - 0 if the ModR/M could be read when needed or was not needed;
853 static int getID(struct InternalInstruction* insn, const void *miiArg) {
855 uint16_t instructionID;
857 dbgprintf(insn, "getID()");
859 attrMask = ATTR_NONE;
861 if (insn->mode == MODE_64BIT)
862 attrMask |= ATTR_64BIT;
864 if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
865 attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
867 if (insn->vectorExtensionType == TYPE_EVEX) {
868 switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
870 attrMask |= ATTR_OPSIZE;
880 if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
881 attrMask |= ATTR_EVEXKZ;
882 if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
883 attrMask |= ATTR_EVEXB;
884 if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
885 attrMask |= ATTR_EVEXK;
886 if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
887 attrMask |= ATTR_EVEXL;
888 if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
889 attrMask |= ATTR_EVEXL2;
890 } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
891 switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
893 attrMask |= ATTR_OPSIZE;
903 if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
904 attrMask |= ATTR_VEXL;
905 } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
906 switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
908 attrMask |= ATTR_OPSIZE;
918 if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
919 attrMask |= ATTR_VEXL;
920 } else if (insn->vectorExtensionType == TYPE_XOP) {
921 switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
923 attrMask |= ATTR_OPSIZE;
933 if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
934 attrMask |= ATTR_VEXL;
938 } else if (!insn->mandatoryPrefix) {
939 // If we don't have mandatory prefix we should use legacy prefixes here
940 if (insn->hasOpSize && (insn->mode != MODE_16BIT))
941 attrMask |= ATTR_OPSIZE;
943 attrMask |= ATTR_ADSIZE;
944 if (insn->opcodeType == ONEBYTE) {
945 if (insn->repeatPrefix == 0xf3 && (insn->opcode == 0x90))
946 // Special support for PAUSE
949 if (insn->repeatPrefix == 0xf2)
951 else if (insn->repeatPrefix == 0xf3)
955 switch (insn->mandatoryPrefix) {
963 if (insn->mode != MODE_16BIT)
964 attrMask |= ATTR_OPSIZE;
967 attrMask |= ATTR_ADSIZE;
973 if (insn->rexPrefix & 0x08) {
974 attrMask |= ATTR_REXW;
975 attrMask &= ~ATTR_ADSIZE;
979 * JCXZ/JECXZ need special handling for 16-bit mode because the meaning
980 * of the AdSize prefix is inverted w.r.t. 32-bit mode.
982 if (insn->mode == MODE_16BIT && insn->opcodeType == ONEBYTE &&
983 insn->opcode == 0xE3)
984 attrMask ^= ATTR_ADSIZE;
987 * In 64-bit mode all f64 superscripted opcodes ignore opcode size prefix
988 * CALL/JMP/JCC instructions need to ignore 0x66 and consume 4 bytes
991 if ((insn->mode == MODE_64BIT) && insn->hasOpSize) {
992 switch (insn->opcode) {
995 // Take care of psubsb and other mmx instructions.
996 if (insn->opcodeType == ONEBYTE) {
997 attrMask ^= ATTR_OPSIZE;
998 insn->immediateSize = 4;
999 insn->displacementSize = 4;
1016 // Take care of lea and three byte ops.
1017 if (insn->opcodeType == TWOBYTE) {
1018 attrMask ^= ATTR_OPSIZE;
1019 insn->immediateSize = 4;
1020 insn->displacementSize = 4;
1026 if (getIDWithAttrMask(&instructionID, insn, attrMask))
1029 /* The following clauses compensate for limitations of the tables. */
1031 if (insn->mode != MODE_64BIT &&
1032 insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1034 * The tables can't distinquish between cases where the W-bit is used to
1035 * select register size and cases where its a required part of the opcode.
1037 if ((insn->vectorExtensionType == TYPE_EVEX &&
1038 wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
1039 (insn->vectorExtensionType == TYPE_VEX_3B &&
1040 wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
1041 (insn->vectorExtensionType == TYPE_XOP &&
1042 wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1044 uint16_t instructionIDWithREXW;
1045 if (getIDWithAttrMask(&instructionIDWithREXW,
1046 insn, attrMask | ATTR_REXW)) {
1047 insn->instructionID = instructionID;
1048 insn->spec = specifierForUID(instructionID);
1052 auto SpecName = GetInstrName(instructionIDWithREXW, miiArg);
1053 // If not a 64-bit instruction. Switch the opcode.
1054 if (!is64Bit(SpecName.data())) {
1055 insn->instructionID = instructionIDWithREXW;
1056 insn->spec = specifierForUID(instructionIDWithREXW);
1063 * Absolute moves, umonitor, and movdir64b need special handling.
1064 * -For 16-bit mode because the meaning of the AdSize and OpSize prefixes are
1066 * -For 32-bit mode we need to ensure the ADSIZE prefix is observed in
1069 if ((insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) ||
1070 (insn->opcodeType == TWOBYTE && (insn->opcode == 0xAE)) ||
1071 (insn->opcodeType == THREEBYTE_38 && insn->opcode == 0xF8)) {
1072 /* Make sure we observed the prefixes in any position. */
1073 if (insn->hasAdSize)
1074 attrMask |= ATTR_ADSIZE;
1075 if (insn->hasOpSize)
1076 attrMask |= ATTR_OPSIZE;
1078 /* In 16-bit, invert the attributes. */
1079 if (insn->mode == MODE_16BIT) {
1080 attrMask ^= ATTR_ADSIZE;
1082 /* The OpSize attribute is only valid with the absolute moves. */
1083 if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0))
1084 attrMask ^= ATTR_OPSIZE;
1087 if (getIDWithAttrMask(&instructionID, insn, attrMask))
1090 insn->instructionID = instructionID;
1091 insn->spec = specifierForUID(instructionID);
1095 if ((insn->mode == MODE_16BIT || insn->hasOpSize) &&
1096 !(attrMask & ATTR_OPSIZE)) {
1098 * The instruction tables make no distinction between instructions that
1099 * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
1100 * particular spot (i.e., many MMX operations). In general we're
1101 * conservative, but in the specific case where OpSize is present but not
1102 * in the right place we check if there's a 16-bit operation.
1105 const struct InstructionSpecifier *spec;
1106 uint16_t instructionIDWithOpsize;
1107 llvm::StringRef specName, specWithOpSizeName;
1109 spec = specifierForUID(instructionID);
1111 if (getIDWithAttrMask(&instructionIDWithOpsize,
1113 attrMask | ATTR_OPSIZE)) {
1115 * ModRM required with OpSize but not present; give up and return version
1116 * without OpSize set
1119 insn->instructionID = instructionID;
1124 specName = GetInstrName(instructionID, miiArg);
1125 specWithOpSizeName = GetInstrName(instructionIDWithOpsize, miiArg);
1127 if (is16BitEquivalent(specName.data(), specWithOpSizeName.data()) &&
1128 (insn->mode == MODE_16BIT) ^ insn->hasOpSize) {
1129 insn->instructionID = instructionIDWithOpsize;
1130 insn->spec = specifierForUID(instructionIDWithOpsize);
1132 insn->instructionID = instructionID;
1138 if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1139 insn->rexPrefix & 0x01) {
1141 * NOOP shouldn't decode as NOOP if REX.b is set. Instead
1142 * it should decode as XCHG %r8, %eax.
1145 const struct InstructionSpecifier *spec;
1146 uint16_t instructionIDWithNewOpcode;
1147 const struct InstructionSpecifier *specWithNewOpcode;
1149 spec = specifierForUID(instructionID);
1151 /* Borrow opcode from one of the other XCHGar opcodes */
1152 insn->opcode = 0x91;
1154 if (getIDWithAttrMask(&instructionIDWithNewOpcode,
1157 insn->opcode = 0x90;
1159 insn->instructionID = instructionID;
1164 specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
1167 insn->opcode = 0x90;
1169 insn->instructionID = instructionIDWithNewOpcode;
1170 insn->spec = specWithNewOpcode;
1175 insn->instructionID = instructionID;
1176 insn->spec = specifierForUID(insn->instructionID);
1182 * readSIB - Consumes the SIB byte to determine addressing information for an
1185 * @param insn - The instruction whose SIB byte is to be read.
1186 * @return - 0 if the SIB byte was successfully read; nonzero otherwise.
1188 static int readSIB(struct InternalInstruction* insn) {
1189 SIBBase sibBaseBase = SIB_BASE_NONE;
1190 uint8_t index, base;
1192 dbgprintf(insn, "readSIB()");
1194 if (insn->consumedSIB)
1197 insn->consumedSIB = true;
1199 switch (insn->addressSize) {
1201 dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
1204 insn->sibIndexBase = SIB_INDEX_EAX;
1205 sibBaseBase = SIB_BASE_EAX;
1208 insn->sibIndexBase = SIB_INDEX_RAX;
1209 sibBaseBase = SIB_BASE_RAX;
1213 if (consumeByte(insn, &insn->sib))
1216 index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1219 insn->sibIndex = SIB_INDEX_NONE;
1221 insn->sibIndex = (SIBIndex)(insn->sibIndexBase + index);
1224 insn->sibScale = 1 << scaleFromSIB(insn->sib);
1226 base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1231 switch (modFromModRM(insn->modRM)) {
1233 insn->eaDisplacement = EA_DISP_32;
1234 insn->sibBase = SIB_BASE_NONE;
1237 insn->eaDisplacement = EA_DISP_8;
1238 insn->sibBase = (SIBBase)(sibBaseBase + base);
1241 insn->eaDisplacement = EA_DISP_32;
1242 insn->sibBase = (SIBBase)(sibBaseBase + base);
1245 debug("Cannot have Mod = 0b11 and a SIB byte");
1250 insn->sibBase = (SIBBase)(sibBaseBase + base);
1258 * readDisplacement - Consumes the displacement of an instruction.
1260 * @param insn - The instruction whose displacement is to be read.
1261 * @return - 0 if the displacement byte was successfully read; nonzero
1264 static int readDisplacement(struct InternalInstruction* insn) {
1269 dbgprintf(insn, "readDisplacement()");
1271 if (insn->consumedDisplacement)
1274 insn->consumedDisplacement = true;
1275 insn->displacementOffset = insn->readerCursor - insn->startLocation;
1277 switch (insn->eaDisplacement) {
1279 insn->consumedDisplacement = false;
1282 if (consumeInt8(insn, &d8))
1284 insn->displacement = d8;
1287 if (consumeInt16(insn, &d16))
1289 insn->displacement = d16;
1292 if (consumeInt32(insn, &d32))
1294 insn->displacement = d32;
1298 insn->consumedDisplacement = true;
1303 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1304 * displacement) for an instruction and interprets it.
1306 * @param insn - The instruction whose addressing information is to be read.
1307 * @return - 0 if the information was successfully read; nonzero otherwise.
1309 static int readModRM(struct InternalInstruction* insn) {
1310 uint8_t mod, rm, reg, evexrm;
1312 dbgprintf(insn, "readModRM()");
1314 if (insn->consumedModRM)
1317 if (consumeByte(insn, &insn->modRM))
1319 insn->consumedModRM = true;
1321 mod = modFromModRM(insn->modRM);
1322 rm = rmFromModRM(insn->modRM);
1323 reg = regFromModRM(insn->modRM);
1326 * This goes by insn->registerSize to pick the correct register, which messes
1327 * up if we're using (say) XMM or 8-bit register operands. That gets fixed in
1330 switch (insn->registerSize) {
1332 insn->regBase = MODRM_REG_AX;
1333 insn->eaRegBase = EA_REG_AX;
1336 insn->regBase = MODRM_REG_EAX;
1337 insn->eaRegBase = EA_REG_EAX;
1340 insn->regBase = MODRM_REG_RAX;
1341 insn->eaRegBase = EA_REG_RAX;
1345 reg |= rFromREX(insn->rexPrefix) << 3;
1346 rm |= bFromREX(insn->rexPrefix) << 3;
1349 if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT) {
1350 reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1351 evexrm = xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1354 insn->reg = (Reg)(insn->regBase + reg);
1356 switch (insn->addressSize) {
1358 EABase eaBaseBase = EA_BASE_BX_SI;
1363 insn->eaBase = EA_BASE_NONE;
1364 insn->eaDisplacement = EA_DISP_16;
1365 if (readDisplacement(insn))
1368 insn->eaBase = (EABase)(eaBaseBase + rm);
1369 insn->eaDisplacement = EA_DISP_NONE;
1373 insn->eaBase = (EABase)(eaBaseBase + rm);
1374 insn->eaDisplacement = EA_DISP_8;
1375 insn->displacementSize = 1;
1376 if (readDisplacement(insn))
1380 insn->eaBase = (EABase)(eaBaseBase + rm);
1381 insn->eaDisplacement = EA_DISP_16;
1382 if (readDisplacement(insn))
1386 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1387 if (readDisplacement(insn))
1395 EABase eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1399 insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1400 // In determining whether RIP-relative mode is used (rm=5),
1401 // or whether a SIB byte is present (rm=4),
1402 // the extension bits (REX.b and EVEX.x) are ignored.
1404 case 0x4: // SIB byte is present
1405 insn->eaBase = (insn->addressSize == 4 ?
1406 EA_BASE_sib : EA_BASE_sib64);
1407 if (readSIB(insn) || readDisplacement(insn))
1410 case 0x5: // RIP-relative
1411 insn->eaBase = EA_BASE_NONE;
1412 insn->eaDisplacement = EA_DISP_32;
1413 if (readDisplacement(insn))
1417 insn->eaBase = (EABase)(eaBaseBase + rm);
1422 insn->displacementSize = 1;
1425 insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1427 case 0x4: // SIB byte is present
1428 insn->eaBase = EA_BASE_sib;
1429 if (readSIB(insn) || readDisplacement(insn))
1433 insn->eaBase = (EABase)(eaBaseBase + rm);
1434 if (readDisplacement(insn))
1440 insn->eaDisplacement = EA_DISP_NONE;
1441 insn->eaBase = (EABase)(insn->eaRegBase + rm + evexrm);
1446 } /* switch (insn->addressSize) */
1451 #define GENERIC_FIXUP_FUNC(name, base, prefix, mask) \
1452 static uint16_t name(struct InternalInstruction *insn, \
1459 debug("Unhandled register type"); \
1463 return base + index; \
1468 if (insn->rexPrefix && \
1469 index >= 4 && index <= 7) { \
1470 return prefix##_SPL + (index - 4); \
1472 return prefix##_AL + index; \
1478 return prefix##_AX + index; \
1483 return prefix##_EAX + index; \
1488 return prefix##_RAX + index; \
1490 return prefix##_ZMM0 + index; \
1492 return prefix##_YMM0 + index; \
1494 return prefix##_XMM0 + index; \
1499 return prefix##_K0 + index; \
1501 return prefix##_MM0 + (index & 0x7); \
1502 case TYPE_SEGMENTREG: \
1503 if ((index & 7) > 5) \
1505 return prefix##_ES + (index & 7); \
1506 case TYPE_DEBUGREG: \
1507 return prefix##_DR0 + index; \
1508 case TYPE_CONTROLREG: \
1509 return prefix##_CR0 + index; \
1513 return prefix##_BND0 + index; \
1515 return prefix##_XMM0 + index; \
1517 return prefix##_YMM0 + index; \
1519 return prefix##_ZMM0 + index; \
1524 * fixup*Value - Consults an operand type to determine the meaning of the
1525 * reg or R/M field. If the operand is an XMM operand, for example, an
1526 * operand would be XMM0 instead of AX, which readModRM() would otherwise
1527 * misinterpret it as.
1529 * @param insn - The instruction containing the operand.
1530 * @param type - The operand type.
1531 * @param index - The existing value of the field as reported by readModRM().
1532 * @param valid - The address of a uint8_t. The target is set to 1 if the
1533 * field is valid for the register class; 0 if not.
1534 * @return - The proper value.
1536 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG, 0x1f)
1537 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG, 0xf)
1540 * fixupReg - Consults an operand specifier to determine which of the
1541 * fixup*Value functions to use in correcting readModRM()'ss interpretation.
1543 * @param insn - See fixup*Value().
1544 * @param op - The operand specifier.
1545 * @return - 0 if fixup was successful; -1 if the register returned was
1546 * invalid for its class.
1548 static int fixupReg(struct InternalInstruction *insn,
1549 const struct OperandSpecifier *op) {
1552 dbgprintf(insn, "fixupReg()");
1554 switch ((OperandEncoding)op->encoding) {
1556 debug("Expected a REG or R/M encoding in fixupReg");
1559 insn->vvvv = (Reg)fixupRegValue(insn,
1560 (OperandType)op->type,
1567 insn->reg = (Reg)fixupRegValue(insn,
1568 (OperandType)op->type,
1569 insn->reg - insn->regBase,
1575 if (insn->eaBase >= insn->eaRegBase) {
1576 insn->eaBase = (EABase)fixupRMValue(insn,
1577 (OperandType)op->type,
1578 insn->eaBase - insn->eaRegBase,
1590 * readOpcodeRegister - Reads an operand from the opcode field of an
1591 * instruction and interprets it appropriately given the operand width.
1592 * Handles AddRegFrm instructions.
1594 * @param insn - the instruction whose opcode field is to be read.
1595 * @param size - The width (in bytes) of the register being specified.
1596 * 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1598 * @return - 0 on success; nonzero otherwise.
1600 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1601 dbgprintf(insn, "readOpcodeRegister()");
1604 size = insn->registerSize;
1608 insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1609 | (insn->opcode & 7)));
1610 if (insn->rexPrefix &&
1611 insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1612 insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1613 insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1614 + (insn->opcodeRegister - MODRM_REG_AL - 4));
1619 insn->opcodeRegister = (Reg)(MODRM_REG_AX
1620 + ((bFromREX(insn->rexPrefix) << 3)
1621 | (insn->opcode & 7)));
1624 insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1625 + ((bFromREX(insn->rexPrefix) << 3)
1626 | (insn->opcode & 7)));
1629 insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1630 + ((bFromREX(insn->rexPrefix) << 3)
1631 | (insn->opcode & 7)));
1639 * readImmediate - Consumes an immediate operand from an instruction, given the
1640 * desired operand size.
1642 * @param insn - The instruction whose operand is to be read.
1643 * @param size - The width (in bytes) of the operand.
1644 * @return - 0 if the immediate was successfully consumed; nonzero
1647 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1653 dbgprintf(insn, "readImmediate()");
1655 if (insn->numImmediatesConsumed == 2) {
1656 debug("Already consumed two immediates");
1661 size = insn->immediateSize;
1663 insn->immediateSize = size;
1664 insn->immediateOffset = insn->readerCursor - insn->startLocation;
1668 if (consumeByte(insn, &imm8))
1670 insn->immediates[insn->numImmediatesConsumed] = imm8;
1673 if (consumeUInt16(insn, &imm16))
1675 insn->immediates[insn->numImmediatesConsumed] = imm16;
1678 if (consumeUInt32(insn, &imm32))
1680 insn->immediates[insn->numImmediatesConsumed] = imm32;
1683 if (consumeUInt64(insn, &imm64))
1685 insn->immediates[insn->numImmediatesConsumed] = imm64;
1689 insn->numImmediatesConsumed++;
1695 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1697 * @param insn - The instruction whose operand is to be read.
1698 * @return - 0 if the vvvv was successfully consumed; nonzero
1701 static int readVVVV(struct InternalInstruction* insn) {
1702 dbgprintf(insn, "readVVVV()");
1705 if (insn->vectorExtensionType == TYPE_EVEX)
1706 vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1707 vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1708 else if (insn->vectorExtensionType == TYPE_VEX_3B)
1709 vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1710 else if (insn->vectorExtensionType == TYPE_VEX_2B)
1711 vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1712 else if (insn->vectorExtensionType == TYPE_XOP)
1713 vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1717 if (insn->mode != MODE_64BIT)
1718 vvvv &= 0xf; // Can only clear bit 4. Bit 3 must be cleared later.
1720 insn->vvvv = static_cast<Reg>(vvvv);
1725 * readMaskRegister - Reads an mask register from the opcode field of an
1728 * @param insn - The instruction whose opcode field is to be read.
1729 * @return - 0 on success; nonzero otherwise.
1731 static int readMaskRegister(struct InternalInstruction* insn) {
1732 dbgprintf(insn, "readMaskRegister()");
1734 if (insn->vectorExtensionType != TYPE_EVEX)
1738 static_cast<Reg>(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1743 * readOperands - Consults the specifier for an instruction and consumes all
1744 * operands for that instruction, interpreting them as it goes.
1746 * @param insn - The instruction whose operands are to be read and interpreted.
1747 * @return - 0 if all operands could be read; nonzero otherwise.
1749 static int readOperands(struct InternalInstruction* insn) {
1750 int hasVVVV, needVVVV;
1753 dbgprintf(insn, "readOperands()");
1755 /* If non-zero vvvv specified, need to make sure one of the operands
1757 hasVVVV = !readVVVV(insn);
1758 needVVVV = hasVVVV && (insn->vvvv != 0);
1760 for (const auto &Op : x86OperandSets[insn->spec->operands]) {
1761 switch (Op.encoding) {
1767 // VSIB can use the V2 bit so check only the other bits.
1769 needVVVV = hasVVVV & ((insn->vvvv & 0xf) != 0);
1770 if (readModRM(insn))
1773 // Reject if SIB wasn't used.
1774 if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1777 // If sibIndex was set to SIB_INDEX_NONE, index offset is 4.
1778 if (insn->sibIndex == SIB_INDEX_NONE)
1779 insn->sibIndex = (SIBIndex)(insn->sibIndexBase + 4);
1781 // If EVEX.v2 is set this is one of the 16-31 registers.
1782 if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT &&
1783 v2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1784 insn->sibIndex = (SIBIndex)(insn->sibIndex + 16);
1786 // Adjust the index register to the correct size.
1787 switch ((OperandType)Op.type) {
1789 debug("Unhandled VSIB index type");
1792 insn->sibIndex = (SIBIndex)(SIB_INDEX_XMM0 +
1793 (insn->sibIndex - insn->sibIndexBase));
1796 insn->sibIndex = (SIBIndex)(SIB_INDEX_YMM0 +
1797 (insn->sibIndex - insn->sibIndexBase));
1800 insn->sibIndex = (SIBIndex)(SIB_INDEX_ZMM0 +
1801 (insn->sibIndex - insn->sibIndexBase));
1805 // Apply the AVX512 compressed displacement scaling factor.
1806 if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1807 insn->displacement *= 1 << (Op.encoding - ENCODING_VSIB);
1811 if (readModRM(insn))
1813 if (fixupReg(insn, &Op))
1815 // Apply the AVX512 compressed displacement scaling factor.
1816 if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1817 insn->displacement *= 1 << (Op.encoding - ENCODING_RM);
1821 /* Saw a register immediate so don't read again and instead split the
1822 previous immediate. FIXME: This is a hack. */
1823 insn->immediates[insn->numImmediatesConsumed] =
1824 insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1825 ++insn->numImmediatesConsumed;
1828 if (readImmediate(insn, 1))
1830 if (Op.type == TYPE_XMM || Op.type == TYPE_YMM)
1834 if (readImmediate(insn, 2))
1838 if (readImmediate(insn, 4))
1842 if (readImmediate(insn, 8))
1846 if (readImmediate(insn, insn->immediateSize))
1850 if (readImmediate(insn, insn->addressSize))
1854 insn->RC = (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 1) |
1855 lFromEVEX4of4(insn->vectorExtensionPrefix[3]);
1858 if (readOpcodeRegister(insn, 1))
1862 if (readOpcodeRegister(insn, 2))
1866 if (readOpcodeRegister(insn, 4))
1870 if (readOpcodeRegister(insn, 8))
1874 if (readOpcodeRegister(insn, 0))
1880 needVVVV = 0; /* Mark that we have found a VVVV operand. */
1883 if (insn->mode != MODE_64BIT)
1884 insn->vvvv = static_cast<Reg>(insn->vvvv & 0x7);
1885 if (fixupReg(insn, &Op))
1888 case ENCODING_WRITEMASK:
1889 if (readMaskRegister(insn))
1895 dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1900 /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1901 if (needVVVV) return -1;
1907 * decodeInstruction - Reads and interprets a full instruction provided by the
1910 * @param insn - A pointer to the instruction to be populated. Must be
1912 * @param reader - The function to be used to read the instruction's bytes.
1913 * @param readerArg - A generic argument to be passed to the reader to store
1914 * any internal state.
1915 * @param logger - If non-NULL, the function to be used to write log messages
1917 * @param loggerArg - A generic argument to be passed to the logger to store
1918 * any internal state.
1919 * @param startLoc - The address (in the reader's address space) of the first
1920 * byte in the instruction.
1921 * @param mode - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1922 * decode the instruction in.
1923 * @return - 0 if the instruction's memory could be read; nonzero if
1926 int llvm::X86Disassembler::decodeInstruction(
1927 struct InternalInstruction *insn, byteReader_t reader,
1928 const void *readerArg, dlog_t logger, void *loggerArg, const void *miiArg,
1929 uint64_t startLoc, DisassemblerMode mode) {
1930 memset(insn, 0, sizeof(struct InternalInstruction));
1932 insn->reader = reader;
1933 insn->readerArg = readerArg;
1934 insn->dlog = logger;
1935 insn->dlogArg = loggerArg;
1936 insn->startLocation = startLoc;
1937 insn->readerCursor = startLoc;
1939 insn->numImmediatesConsumed = 0;
1941 if (readPrefixes(insn) ||
1943 getID(insn, miiArg) ||
1944 insn->instructionID == 0 ||
1948 insn->operands = x86OperandSets[insn->spec->operands];
1950 insn->length = insn->readerCursor - insn->startLocation;
1952 dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1953 startLoc, insn->readerCursor, insn->length);
1955 if (insn->length > 15)
1956 dbgprintf(insn, "Instruction exceeds 15-byte limit");