1 //===-- X86Disassembler.cpp - Disassembler for x86 and x86_64 -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is part of the X86 Disassembler.
10 // It contains code to translate the data produced by the decoder into
11 // MCInsts.
12 //
13 //
14 // The X86 disassembler is a table-driven disassembler for the 16-, 32-, and
15 // 64-bit X86 instruction sets. The main decode sequence for an assembly
16 // instruction in this disassembler is:
17 //
18 // 1. Read the prefix bytes and determine the attributes of the instruction.
19 // These attributes, recorded in enum attributeBits
20 // (X86DisassemblerDecoderCommon.h), form a bitmask. The table CONTEXTS_SYM
21 // provides a mapping from bitmasks to contexts, which are represented by
22 // enum InstructionContext (ibid.).
23 //
24 // 2. Read the opcode, and determine what kind of opcode it is. The
25 // disassembler distinguishes four kinds of opcodes, which are enumerated in
26 // OpcodeType (X86DisassemblerDecoderCommon.h): one-byte (0xnn), two-byte
27 // (0x0f 0xnn), three-byte-38 (0x0f 0x38 0xnn), or three-byte-3a
28 // (0x0f 0x3a 0xnn). Mandatory prefixes are treated as part of the context.
29 //
30 // 3. Depending on the opcode type, look in one of four ClassDecision structures
31 // (X86DisassemblerDecoderCommon.h). Use the opcode class to determine which
32 // OpcodeDecision (ibid.) to look the opcode in. Look up the opcode, to get
33 // a ModRMDecision (ibid.).
34 //
35 // 4. Some instructions, such as escape opcodes or extended opcodes, or even
36 // instructions that have ModRM*Reg / ModRM*Mem forms in LLVM, need the
37 // ModR/M byte to complete decode. The ModRMDecision's type is an entry from
38 // ModRMDecisionType (X86DisassemblerDecoderCommon.h) that indicates if the
39 // ModR/M byte is required and how to interpret it.
40 //
41 // 5. After resolving the ModRMDecision, the disassembler has a unique ID
42 // of type InstrUID (X86DisassemblerDecoderCommon.h). Looking this ID up in
43 // INSTRUCTIONS_SYM yields the name of the instruction and the encodings and
44 // meanings of its operands.
45 //
46 // 6. For each operand, its encoding is an entry from OperandEncoding
47 // (X86DisassemblerDecoderCommon.h) and its type is an entry from
48 // OperandType (ibid.). The encoding indicates how to read it from the
49 // instruction; the type indicates how to interpret the value once it has
50 // been read. For example, a register operand could be stored in the R/M
51 // field of the ModR/M byte, the REG field of the ModR/M byte, or added to
52 // the main opcode. This is orthogonal from its meaning (an GPR or an XMM
53 // register, for instance). Given this information, the operands can be
54 // extracted and interpreted.
55 //
56 // 7. As the last step, the disassembler translates the instruction information
57 // and operands into a format understandable by the client - in this case, an
58 // MCInst for use by the MC infrastructure.
59 //
60 // The disassembler is broken broadly into two parts: the table emitter that
61 // emits the instruction decode tables discussed above during compilation, and
62 // the disassembler itself. The table emitter is documented in more detail in
63 // utils/TableGen/X86DisassemblerEmitter.h.
64 //
65 // X86Disassembler.cpp contains the code responsible for step 7, and for
66 // invoking the decoder to execute steps 1-6.
67 // X86DisassemblerDecoderCommon.h contains the definitions needed by both the
68 // table emitter and the disassembler.
69 // X86DisassemblerDecoder.h contains the public interface of the decoder,
70 // factored out into C for possible use by other projects.
71 // X86DisassemblerDecoder.c contains the source code of the decoder, which is
72 // responsible for steps 1-6.
73 //
74 //===----------------------------------------------------------------------===//
75
76 #include "MCTargetDesc/X86BaseInfo.h"
77 #include "MCTargetDesc/X86MCTargetDesc.h"
78 #include "TargetInfo/X86TargetInfo.h"
79 #include "X86DisassemblerDecoder.h"
80 #include "llvm/MC/MCContext.h"
81 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
82 #include "llvm/MC/MCExpr.h"
83 #include "llvm/MC/MCInst.h"
84 #include "llvm/MC/MCInstrInfo.h"
85 #include "llvm/MC/MCSubtargetInfo.h"
86 #include "llvm/MC/TargetRegistry.h"
87 #include "llvm/Support/Debug.h"
88 #include "llvm/Support/Format.h"
89 #include "llvm/Support/raw_ostream.h"
90
91 using namespace llvm;
92 using namespace llvm::X86Disassembler;
93
94 #define DEBUG_TYPE "x86-disassembler"
95
96 #define debug(s) LLVM_DEBUG(dbgs() << __LINE__ << ": " << s);
97
98 // Specifies whether a ModR/M byte is needed and (if so) which
99 // instruction each possible value of the ModR/M byte corresponds to. Once
100 // this information is known, we have narrowed down to a single instruction.
101 struct ModRMDecision {
102 uint8_t modrm_type;
103 uint16_t instructionIDs;
104 };
105
106 // Specifies which set of ModR/M->instruction tables to look at
107 // given a particular opcode.
108 struct OpcodeDecision {
109 ModRMDecision modRMDecisions[256];
110 };
111
112 // Specifies which opcode->instruction tables to look at given
113 // a particular context (set of attributes). Since there are many possible
114 // contexts, the decoder first uses CONTEXTS_SYM to determine which context
115 // applies given a specific set of attributes. Hence there are only IC_max
116 // entries in this table, rather than 2^(ATTR_max).
117 struct ContextDecision {
118 OpcodeDecision opcodeDecisions[IC_max];
119 };
120
121 #include "X86GenDisassemblerTables.inc"
122
decode(OpcodeType type,InstructionContext insnContext,uint8_t opcode,uint8_t modRM)123 static InstrUID decode(OpcodeType type, InstructionContext insnContext,
124 uint8_t opcode, uint8_t modRM) {
125 const struct ModRMDecision *dec;
126
127 switch (type) {
128 case ONEBYTE:
129 dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
130 break;
131 case TWOBYTE:
132 dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
133 break;
134 case THREEBYTE_38:
135 dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
136 break;
137 case THREEBYTE_3A:
138 dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
139 break;
140 case XOP8_MAP:
141 dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
142 break;
143 case XOP9_MAP:
144 dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
145 break;
146 case XOPA_MAP:
147 dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
148 break;
149 case THREEDNOW_MAP:
150 dec =
151 &THREEDNOW_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
152 break;
153 case MAP4:
154 dec = &MAP4_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
155 break;
156 case MAP5:
157 dec = &MAP5_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
158 break;
159 case MAP6:
160 dec = &MAP6_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
161 break;
162 case MAP7:
163 dec = &MAP7_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
164 break;
165 }
166
167 switch (dec->modrm_type) {
168 default:
169 llvm_unreachable("Corrupt table! Unknown modrm_type");
170 return 0;
171 case MODRM_ONEENTRY:
172 return modRMTable[dec->instructionIDs];
173 case MODRM_SPLITRM:
174 if (modFromModRM(modRM) == 0x3)
175 return modRMTable[dec->instructionIDs + 1];
176 return modRMTable[dec->instructionIDs];
177 case MODRM_SPLITREG:
178 if (modFromModRM(modRM) == 0x3)
179 return modRMTable[dec->instructionIDs + ((modRM & 0x38) >> 3) + 8];
180 return modRMTable[dec->instructionIDs + ((modRM & 0x38) >> 3)];
181 case MODRM_SPLITMISC:
182 if (modFromModRM(modRM) == 0x3)
183 return modRMTable[dec->instructionIDs + (modRM & 0x3f) + 8];
184 return modRMTable[dec->instructionIDs + ((modRM & 0x38) >> 3)];
185 case MODRM_FULL:
186 return modRMTable[dec->instructionIDs + modRM];
187 }
188 }
189
peek(struct InternalInstruction * insn,uint8_t & byte)190 static bool peek(struct InternalInstruction *insn, uint8_t &byte) {
191 uint64_t offset = insn->readerCursor - insn->startLocation;
192 if (offset >= insn->bytes.size())
193 return true;
194 byte = insn->bytes[offset];
195 return false;
196 }
197
consume(InternalInstruction * insn,T & ptr)198 template <typename T> static bool consume(InternalInstruction *insn, T &ptr) {
199 auto r = insn->bytes;
200 uint64_t offset = insn->readerCursor - insn->startLocation;
201 if (offset + sizeof(T) > r.size())
202 return true;
203 ptr = support::endian::read<T>(&r[offset], llvm::endianness::little);
204 insn->readerCursor += sizeof(T);
205 return false;
206 }
207
isREX(struct InternalInstruction * insn,uint8_t prefix)208 static bool isREX(struct InternalInstruction *insn, uint8_t prefix) {
209 return insn->mode == MODE_64BIT && prefix >= 0x40 && prefix <= 0x4f;
210 }
211
isREX2(struct InternalInstruction * insn,uint8_t prefix)212 static bool isREX2(struct InternalInstruction *insn, uint8_t prefix) {
213 return insn->mode == MODE_64BIT && prefix == 0xd5;
214 }
215
216 // Consumes all of an instruction's prefix bytes, and marks the
217 // instruction as having them. Also sets the instruction's default operand,
218 // address, and other relevant data sizes to report operands correctly.
219 //
220 // insn must not be empty.
readPrefixes(struct InternalInstruction * insn)221 static int readPrefixes(struct InternalInstruction *insn) {
222 bool isPrefix = true;
223 uint8_t byte = 0;
224 uint8_t nextByte;
225
226 LLVM_DEBUG(dbgs() << "readPrefixes()");
227
228 while (isPrefix) {
229 // If we fail reading prefixes, just stop here and let the opcode reader
230 // deal with it.
231 if (consume(insn, byte))
232 break;
233
234 // If the byte is a LOCK/REP/REPNE prefix and not a part of the opcode, then
235 // break and let it be disassembled as a normal "instruction".
236 if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0) // LOCK
237 break;
238
239 if ((byte == 0xf2 || byte == 0xf3) && !peek(insn, nextByte)) {
240 // If the byte is 0xf2 or 0xf3, and any of the following conditions are
241 // met:
242 // - it is followed by a LOCK (0xf0) prefix
243 // - it is followed by an xchg instruction
244 // then it should be disassembled as a xacquire/xrelease not repne/rep.
245 if (((nextByte == 0xf0) ||
246 ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90))) {
247 insn->xAcquireRelease = true;
248 if (!(byte == 0xf3 && nextByte == 0x90)) // PAUSE instruction support
249 break;
250 }
251 // Also if the byte is 0xf3, and the following condition is met:
252 // - it is followed by a "mov mem, reg" (opcode 0x88/0x89) or
253 // "mov mem, imm" (opcode 0xc6/0xc7) instructions.
254 // then it should be disassembled as an xrelease not rep.
255 if (byte == 0xf3 && (nextByte == 0x88 || nextByte == 0x89 ||
256 nextByte == 0xc6 || nextByte == 0xc7)) {
257 insn->xAcquireRelease = true;
258 break;
259 }
260 if (isREX(insn, nextByte)) {
261 uint8_t nnextByte;
262 // Go to REX prefix after the current one
263 if (consume(insn, nnextByte))
264 return -1;
265 // We should be able to read next byte after REX prefix
266 if (peek(insn, nnextByte))
267 return -1;
268 --insn->readerCursor;
269 }
270 }
271
272 switch (byte) {
273 case 0xf0: // LOCK
274 insn->hasLockPrefix = true;
275 break;
276 case 0xf2: // REPNE/REPNZ
277 case 0xf3: { // REP or REPE/REPZ
278 uint8_t nextByte;
279 if (peek(insn, nextByte))
280 break;
281 // TODO:
282 // 1. There could be several 0x66
283 // 2. if (nextByte == 0x66) and nextNextByte != 0x0f then
284 // it's not mandatory prefix
285 // 3. if (nextByte >= 0x40 && nextByte <= 0x4f) it's REX and we need
286 // 0x0f exactly after it to be mandatory prefix
287 if (isREX(insn, nextByte) || nextByte == 0x0f || nextByte == 0x66)
288 // The last of 0xf2 /0xf3 is mandatory prefix
289 insn->mandatoryPrefix = byte;
290 insn->repeatPrefix = byte;
291 break;
292 }
293 case 0x2e: // CS segment override -OR- Branch not taken
294 insn->segmentOverride = SEG_OVERRIDE_CS;
295 break;
296 case 0x36: // SS segment override -OR- Branch taken
297 insn->segmentOverride = SEG_OVERRIDE_SS;
298 break;
299 case 0x3e: // DS segment override
300 insn->segmentOverride = SEG_OVERRIDE_DS;
301 break;
302 case 0x26: // ES segment override
303 insn->segmentOverride = SEG_OVERRIDE_ES;
304 break;
305 case 0x64: // FS segment override
306 insn->segmentOverride = SEG_OVERRIDE_FS;
307 break;
308 case 0x65: // GS segment override
309 insn->segmentOverride = SEG_OVERRIDE_GS;
310 break;
311 case 0x66: { // Operand-size override {
312 uint8_t nextByte;
313 insn->hasOpSize = true;
314 if (peek(insn, nextByte))
315 break;
316 // 0x66 can't overwrite existing mandatory prefix and should be ignored
317 if (!insn->mandatoryPrefix && (nextByte == 0x0f || isREX(insn, nextByte)))
318 insn->mandatoryPrefix = byte;
319 break;
320 }
321 case 0x67: // Address-size override
322 insn->hasAdSize = true;
323 break;
324 default: // Not a prefix byte
325 isPrefix = false;
326 break;
327 }
328
329 if (isPrefix)
330 LLVM_DEBUG(dbgs() << format("Found prefix 0x%hhx", byte));
331 }
332
333 insn->vectorExtensionType = TYPE_NO_VEX_XOP;
334
335 if (byte == 0x62) {
336 uint8_t byte1, byte2;
337 if (consume(insn, byte1)) {
338 LLVM_DEBUG(dbgs() << "Couldn't read second byte of EVEX prefix");
339 return -1;
340 }
341
342 if (peek(insn, byte2)) {
343 LLVM_DEBUG(dbgs() << "Couldn't read third byte of EVEX prefix");
344 return -1;
345 }
346
347 if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)) {
348 insn->vectorExtensionType = TYPE_EVEX;
349 } else {
350 --insn->readerCursor; // unconsume byte1
351 --insn->readerCursor; // unconsume byte
352 }
353
354 if (insn->vectorExtensionType == TYPE_EVEX) {
355 insn->vectorExtensionPrefix[0] = byte;
356 insn->vectorExtensionPrefix[1] = byte1;
357 if (consume(insn, insn->vectorExtensionPrefix[2])) {
358 LLVM_DEBUG(dbgs() << "Couldn't read third byte of EVEX prefix");
359 return -1;
360 }
361 if (consume(insn, insn->vectorExtensionPrefix[3])) {
362 LLVM_DEBUG(dbgs() << "Couldn't read fourth byte of EVEX prefix");
363 return -1;
364 }
365
366 if (insn->mode == MODE_64BIT) {
367 // We simulate the REX prefix for simplicity's sake
368 insn->rexPrefix = 0x40 |
369 (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3) |
370 (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2) |
371 (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1) |
372 (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
373
374 // We simulate the REX2 prefix for simplicity's sake
375 insn->rex2ExtensionPrefix[1] =
376 (r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 6) |
377 (x2FromEVEX3of4(insn->vectorExtensionPrefix[2]) << 5) |
378 (b2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4);
379 }
380
381 LLVM_DEBUG(
382 dbgs() << format(
383 "Found EVEX prefix 0x%hhx 0x%hhx 0x%hhx 0x%hhx",
384 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
385 insn->vectorExtensionPrefix[2], insn->vectorExtensionPrefix[3]));
386 }
387 } else if (byte == 0xc4) {
388 uint8_t byte1;
389 if (peek(insn, byte1)) {
390 LLVM_DEBUG(dbgs() << "Couldn't read second byte of VEX");
391 return -1;
392 }
393
394 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
395 insn->vectorExtensionType = TYPE_VEX_3B;
396 else
397 --insn->readerCursor;
398
399 if (insn->vectorExtensionType == TYPE_VEX_3B) {
400 insn->vectorExtensionPrefix[0] = byte;
401 consume(insn, insn->vectorExtensionPrefix[1]);
402 consume(insn, insn->vectorExtensionPrefix[2]);
403
404 // We simulate the REX prefix for simplicity's sake
405
406 if (insn->mode == MODE_64BIT)
407 insn->rexPrefix = 0x40 |
408 (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3) |
409 (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2) |
410 (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1) |
411 (bFromVEX2of3(insn->vectorExtensionPrefix[1]) << 0);
412
413 LLVM_DEBUG(dbgs() << format("Found VEX prefix 0x%hhx 0x%hhx 0x%hhx",
414 insn->vectorExtensionPrefix[0],
415 insn->vectorExtensionPrefix[1],
416 insn->vectorExtensionPrefix[2]));
417 }
418 } else if (byte == 0xc5) {
419 uint8_t byte1;
420 if (peek(insn, byte1)) {
421 LLVM_DEBUG(dbgs() << "Couldn't read second byte of VEX");
422 return -1;
423 }
424
425 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
426 insn->vectorExtensionType = TYPE_VEX_2B;
427 else
428 --insn->readerCursor;
429
430 if (insn->vectorExtensionType == TYPE_VEX_2B) {
431 insn->vectorExtensionPrefix[0] = byte;
432 consume(insn, insn->vectorExtensionPrefix[1]);
433
434 if (insn->mode == MODE_64BIT)
435 insn->rexPrefix =
436 0x40 | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
437
438 switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
439 default:
440 break;
441 case VEX_PREFIX_66:
442 insn->hasOpSize = true;
443 break;
444 }
445
446 LLVM_DEBUG(dbgs() << format("Found VEX prefix 0x%hhx 0x%hhx",
447 insn->vectorExtensionPrefix[0],
448 insn->vectorExtensionPrefix[1]));
449 }
450 } else if (byte == 0x8f) {
451 uint8_t byte1;
452 if (peek(insn, byte1)) {
453 LLVM_DEBUG(dbgs() << "Couldn't read second byte of XOP");
454 return -1;
455 }
456
457 if ((byte1 & 0x38) != 0x0) // 0 in these 3 bits is a POP instruction.
458 insn->vectorExtensionType = TYPE_XOP;
459 else
460 --insn->readerCursor;
461
462 if (insn->vectorExtensionType == TYPE_XOP) {
463 insn->vectorExtensionPrefix[0] = byte;
464 consume(insn, insn->vectorExtensionPrefix[1]);
465 consume(insn, insn->vectorExtensionPrefix[2]);
466
467 // We simulate the REX prefix for simplicity's sake
468
469 if (insn->mode == MODE_64BIT)
470 insn->rexPrefix = 0x40 |
471 (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3) |
472 (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2) |
473 (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1) |
474 (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
475
476 switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
477 default:
478 break;
479 case VEX_PREFIX_66:
480 insn->hasOpSize = true;
481 break;
482 }
483
484 LLVM_DEBUG(dbgs() << format("Found XOP prefix 0x%hhx 0x%hhx 0x%hhx",
485 insn->vectorExtensionPrefix[0],
486 insn->vectorExtensionPrefix[1],
487 insn->vectorExtensionPrefix[2]));
488 }
489 } else if (isREX2(insn, byte)) {
490 uint8_t byte1;
491 if (peek(insn, byte1)) {
492 LLVM_DEBUG(dbgs() << "Couldn't read second byte of REX2");
493 return -1;
494 }
495 insn->rex2ExtensionPrefix[0] = byte;
496 consume(insn, insn->rex2ExtensionPrefix[1]);
497
498 // We simulate the REX prefix for simplicity's sake
499 insn->rexPrefix = 0x40 | (wFromREX2(insn->rex2ExtensionPrefix[1]) << 3) |
500 (rFromREX2(insn->rex2ExtensionPrefix[1]) << 2) |
501 (xFromREX2(insn->rex2ExtensionPrefix[1]) << 1) |
502 (bFromREX2(insn->rex2ExtensionPrefix[1]) << 0);
503 LLVM_DEBUG(dbgs() << format("Found REX2 prefix 0x%hhx 0x%hhx",
504 insn->rex2ExtensionPrefix[0],
505 insn->rex2ExtensionPrefix[1]));
506 } else if (isREX(insn, byte)) {
507 if (peek(insn, nextByte))
508 return -1;
509 insn->rexPrefix = byte;
510 LLVM_DEBUG(dbgs() << format("Found REX prefix 0x%hhx", byte));
511 } else
512 --insn->readerCursor;
513
514 if (insn->mode == MODE_16BIT) {
515 insn->registerSize = (insn->hasOpSize ? 4 : 2);
516 insn->addressSize = (insn->hasAdSize ? 4 : 2);
517 insn->displacementSize = (insn->hasAdSize ? 4 : 2);
518 insn->immediateSize = (insn->hasOpSize ? 4 : 2);
519 } else if (insn->mode == MODE_32BIT) {
520 insn->registerSize = (insn->hasOpSize ? 2 : 4);
521 insn->addressSize = (insn->hasAdSize ? 2 : 4);
522 insn->displacementSize = (insn->hasAdSize ? 2 : 4);
523 insn->immediateSize = (insn->hasOpSize ? 2 : 4);
524 } else if (insn->mode == MODE_64BIT) {
525 insn->displacementSize = 4;
526 if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
527 insn->registerSize = 8;
528 insn->addressSize = (insn->hasAdSize ? 4 : 8);
529 insn->immediateSize = 4;
530 insn->hasOpSize = false;
531 } else {
532 insn->registerSize = (insn->hasOpSize ? 2 : 4);
533 insn->addressSize = (insn->hasAdSize ? 4 : 8);
534 insn->immediateSize = (insn->hasOpSize ? 2 : 4);
535 }
536 }
537
538 return 0;
539 }
540
541 // Consumes the SIB byte to determine addressing information.
readSIB(struct InternalInstruction * insn)542 static int readSIB(struct InternalInstruction *insn) {
543 SIBBase sibBaseBase = SIB_BASE_NONE;
544 uint8_t index, base;
545
546 LLVM_DEBUG(dbgs() << "readSIB()");
547 switch (insn->addressSize) {
548 case 2:
549 default:
550 llvm_unreachable("SIB-based addressing doesn't work in 16-bit mode");
551 case 4:
552 insn->sibIndexBase = SIB_INDEX_EAX;
553 sibBaseBase = SIB_BASE_EAX;
554 break;
555 case 8:
556 insn->sibIndexBase = SIB_INDEX_RAX;
557 sibBaseBase = SIB_BASE_RAX;
558 break;
559 }
560
561 if (consume(insn, insn->sib))
562 return -1;
563
564 index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3) |
565 (x2FromREX2(insn->rex2ExtensionPrefix[1]) << 4);
566
567 if (index == 0x4) {
568 insn->sibIndex = SIB_INDEX_NONE;
569 } else {
570 insn->sibIndex = (SIBIndex)(insn->sibIndexBase + index);
571 }
572
573 insn->sibScale = 1 << scaleFromSIB(insn->sib);
574
575 base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3) |
576 (b2FromREX2(insn->rex2ExtensionPrefix[1]) << 4);
577
578 switch (base) {
579 case 0x5:
580 case 0xd:
581 switch (modFromModRM(insn->modRM)) {
582 case 0x0:
583 insn->eaDisplacement = EA_DISP_32;
584 insn->sibBase = SIB_BASE_NONE;
585 break;
586 case 0x1:
587 insn->eaDisplacement = EA_DISP_8;
588 insn->sibBase = (SIBBase)(sibBaseBase + base);
589 break;
590 case 0x2:
591 insn->eaDisplacement = EA_DISP_32;
592 insn->sibBase = (SIBBase)(sibBaseBase + base);
593 break;
594 default:
595 llvm_unreachable("Cannot have Mod = 0b11 and a SIB byte");
596 }
597 break;
598 default:
599 insn->sibBase = (SIBBase)(sibBaseBase + base);
600 break;
601 }
602
603 return 0;
604 }
605
readDisplacement(struct InternalInstruction * insn)606 static int readDisplacement(struct InternalInstruction *insn) {
607 int8_t d8;
608 int16_t d16;
609 int32_t d32;
610 LLVM_DEBUG(dbgs() << "readDisplacement()");
611
612 insn->displacementOffset = insn->readerCursor - insn->startLocation;
613 switch (insn->eaDisplacement) {
614 case EA_DISP_NONE:
615 break;
616 case EA_DISP_8:
617 if (consume(insn, d8))
618 return -1;
619 insn->displacement = d8;
620 break;
621 case EA_DISP_16:
622 if (consume(insn, d16))
623 return -1;
624 insn->displacement = d16;
625 break;
626 case EA_DISP_32:
627 if (consume(insn, d32))
628 return -1;
629 insn->displacement = d32;
630 break;
631 }
632
633 return 0;
634 }
635
636 // Consumes all addressing information (ModR/M byte, SIB byte, and displacement.
readModRM(struct InternalInstruction * insn)637 static int readModRM(struct InternalInstruction *insn) {
638 uint8_t mod, rm, reg;
639 LLVM_DEBUG(dbgs() << "readModRM()");
640
641 if (insn->consumedModRM)
642 return 0;
643
644 if (consume(insn, insn->modRM))
645 return -1;
646 insn->consumedModRM = true;
647
648 mod = modFromModRM(insn->modRM);
649 rm = rmFromModRM(insn->modRM);
650 reg = regFromModRM(insn->modRM);
651
652 // This goes by insn->registerSize to pick the correct register, which messes
653 // up if we're using (say) XMM or 8-bit register operands. That gets fixed in
654 // fixupReg().
655 switch (insn->registerSize) {
656 case 2:
657 insn->regBase = MODRM_REG_AX;
658 insn->eaRegBase = EA_REG_AX;
659 break;
660 case 4:
661 insn->regBase = MODRM_REG_EAX;
662 insn->eaRegBase = EA_REG_EAX;
663 break;
664 case 8:
665 insn->regBase = MODRM_REG_RAX;
666 insn->eaRegBase = EA_REG_RAX;
667 break;
668 }
669
670 reg |= (rFromREX(insn->rexPrefix) << 3) |
671 (r2FromREX2(insn->rex2ExtensionPrefix[1]) << 4);
672 rm |= (bFromREX(insn->rexPrefix) << 3) |
673 (b2FromREX2(insn->rex2ExtensionPrefix[1]) << 4);
674
675 if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT)
676 reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
677
678 insn->reg = (Reg)(insn->regBase + reg);
679
680 switch (insn->addressSize) {
681 case 2: {
682 EABase eaBaseBase = EA_BASE_BX_SI;
683
684 switch (mod) {
685 case 0x0:
686 if (rm == 0x6) {
687 insn->eaBase = EA_BASE_NONE;
688 insn->eaDisplacement = EA_DISP_16;
689 if (readDisplacement(insn))
690 return -1;
691 } else {
692 insn->eaBase = (EABase)(eaBaseBase + rm);
693 insn->eaDisplacement = EA_DISP_NONE;
694 }
695 break;
696 case 0x1:
697 insn->eaBase = (EABase)(eaBaseBase + rm);
698 insn->eaDisplacement = EA_DISP_8;
699 insn->displacementSize = 1;
700 if (readDisplacement(insn))
701 return -1;
702 break;
703 case 0x2:
704 insn->eaBase = (EABase)(eaBaseBase + rm);
705 insn->eaDisplacement = EA_DISP_16;
706 if (readDisplacement(insn))
707 return -1;
708 break;
709 case 0x3:
710 insn->eaBase = (EABase)(insn->eaRegBase + rm);
711 if (readDisplacement(insn))
712 return -1;
713 break;
714 }
715 break;
716 }
717 case 4:
718 case 8: {
719 EABase eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
720
721 switch (mod) {
722 case 0x0:
723 insn->eaDisplacement = EA_DISP_NONE; // readSIB may override this
724 // In determining whether RIP-relative mode is used (rm=5),
725 // or whether a SIB byte is present (rm=4),
726 // the extension bits (REX.b and EVEX.x) are ignored.
727 switch (rm & 7) {
728 case 0x4: // SIB byte is present
729 insn->eaBase = (insn->addressSize == 4 ? EA_BASE_sib : EA_BASE_sib64);
730 if (readSIB(insn) || readDisplacement(insn))
731 return -1;
732 break;
733 case 0x5: // RIP-relative
734 insn->eaBase = EA_BASE_NONE;
735 insn->eaDisplacement = EA_DISP_32;
736 if (readDisplacement(insn))
737 return -1;
738 break;
739 default:
740 insn->eaBase = (EABase)(eaBaseBase + rm);
741 break;
742 }
743 break;
744 case 0x1:
745 insn->displacementSize = 1;
746 [[fallthrough]];
747 case 0x2:
748 insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
749 switch (rm & 7) {
750 case 0x4: // SIB byte is present
751 insn->eaBase = EA_BASE_sib;
752 if (readSIB(insn) || readDisplacement(insn))
753 return -1;
754 break;
755 default:
756 insn->eaBase = (EABase)(eaBaseBase + rm);
757 if (readDisplacement(insn))
758 return -1;
759 break;
760 }
761 break;
762 case 0x3:
763 insn->eaDisplacement = EA_DISP_NONE;
764 insn->eaBase = (EABase)(insn->eaRegBase + rm);
765 break;
766 }
767 break;
768 }
769 } // switch (insn->addressSize)
770
771 return 0;
772 }
773
774 #define GENERIC_FIXUP_FUNC(name, base, prefix) \
775 static uint16_t name(struct InternalInstruction *insn, OperandType type, \
776 uint8_t index, uint8_t *valid) { \
777 *valid = 1; \
778 switch (type) { \
779 default: \
780 debug("Unhandled register type"); \
781 *valid = 0; \
782 return 0; \
783 case TYPE_Rv: \
784 return base + index; \
785 case TYPE_R8: \
786 if (insn->rexPrefix && index >= 4 && index <= 7) \
787 return prefix##_SPL + (index - 4); \
788 else \
789 return prefix##_AL + index; \
790 case TYPE_R16: \
791 return prefix##_AX + index; \
792 case TYPE_R32: \
793 return prefix##_EAX + index; \
794 case TYPE_R64: \
795 return prefix##_RAX + index; \
796 case TYPE_ZMM: \
797 return prefix##_ZMM0 + index; \
798 case TYPE_YMM: \
799 return prefix##_YMM0 + index; \
800 case TYPE_XMM: \
801 return prefix##_XMM0 + index; \
802 case TYPE_TMM: \
803 if (index > 7) \
804 *valid = 0; \
805 return prefix##_TMM0 + index; \
806 case TYPE_VK: \
807 index &= 0xf; \
808 if (index > 7) \
809 *valid = 0; \
810 return prefix##_K0 + index; \
811 case TYPE_VK_PAIR: \
812 if (index > 7) \
813 *valid = 0; \
814 return prefix##_K0_K1 + (index / 2); \
815 case TYPE_MM64: \
816 return prefix##_MM0 + (index & 0x7); \
817 case TYPE_SEGMENTREG: \
818 if ((index & 7) > 5) \
819 *valid = 0; \
820 return prefix##_ES + (index & 7); \
821 case TYPE_DEBUGREG: \
822 return prefix##_DR0 + index; \
823 case TYPE_CONTROLREG: \
824 return prefix##_CR0 + index; \
825 case TYPE_MVSIBX: \
826 return prefix##_XMM0 + index; \
827 case TYPE_MVSIBY: \
828 return prefix##_YMM0 + index; \
829 case TYPE_MVSIBZ: \
830 return prefix##_ZMM0 + index; \
831 } \
832 }
833
834 // Consult an operand type to determine the meaning of the reg or R/M field. If
835 // the operand is an XMM operand, for example, an operand would be XMM0 instead
836 // of AX, which readModRM() would otherwise misinterpret it as.
837 //
838 // @param insn - The instruction containing the operand.
839 // @param type - The operand type.
840 // @param index - The existing value of the field as reported by readModRM().
841 // @param valid - The address of a uint8_t. The target is set to 1 if the
842 // field is valid for the register class; 0 if not.
843 // @return - The proper value.
844 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG)
845 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG)
846
847 // Consult an operand specifier to determine which of the fixup*Value functions
848 // to use in correcting readModRM()'ss interpretation.
849 //
850 // @param insn - See fixup*Value().
851 // @param op - The operand specifier.
852 // @return - 0 if fixup was successful; -1 if the register returned was
853 // invalid for its class.
fixupReg(struct InternalInstruction * insn,const struct OperandSpecifier * op)854 static int fixupReg(struct InternalInstruction *insn,
855 const struct OperandSpecifier *op) {
856 uint8_t valid;
857 LLVM_DEBUG(dbgs() << "fixupReg()");
858
859 switch ((OperandEncoding)op->encoding) {
860 default:
861 debug("Expected a REG or R/M encoding in fixupReg");
862 return -1;
863 case ENCODING_VVVV:
864 insn->vvvv =
865 (Reg)fixupRegValue(insn, (OperandType)op->type, insn->vvvv, &valid);
866 if (!valid)
867 return -1;
868 break;
869 case ENCODING_REG:
870 insn->reg = (Reg)fixupRegValue(insn, (OperandType)op->type,
871 insn->reg - insn->regBase, &valid);
872 if (!valid)
873 return -1;
874 break;
875 CASE_ENCODING_RM:
876 if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT &&
877 modFromModRM(insn->modRM) == 3) {
878 // EVEX_X can extend the register id to 32 for a non-GPR register that is
879 // encoded in RM.
880 // mode : MODE_64_BIT
881 // Only 8 vector registers are available in 32 bit mode
882 // mod : 3
883 // RM encodes a register
884 switch (op->type) {
885 case TYPE_Rv:
886 case TYPE_R8:
887 case TYPE_R16:
888 case TYPE_R32:
889 case TYPE_R64:
890 break;
891 default:
892 insn->eaBase =
893 (EABase)(insn->eaBase +
894 (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4));
895 break;
896 }
897 }
898 [[fallthrough]];
899 case ENCODING_SIB:
900 if (insn->eaBase >= insn->eaRegBase) {
901 insn->eaBase = (EABase)fixupRMValue(
902 insn, (OperandType)op->type, insn->eaBase - insn->eaRegBase, &valid);
903 if (!valid)
904 return -1;
905 }
906 break;
907 }
908
909 return 0;
910 }
911
912 // Read the opcode (except the ModR/M byte in the case of extended or escape
913 // opcodes).
readOpcode(struct InternalInstruction * insn)914 static bool readOpcode(struct InternalInstruction *insn) {
915 uint8_t current;
916 LLVM_DEBUG(dbgs() << "readOpcode()");
917
918 insn->opcodeType = ONEBYTE;
919 if (insn->vectorExtensionType == TYPE_EVEX) {
920 switch (mmmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
921 default:
922 LLVM_DEBUG(
923 dbgs() << format("Unhandled mmm field for instruction (0x%hhx)",
924 mmmFromEVEX2of4(insn->vectorExtensionPrefix[1])));
925 return true;
926 case VEX_LOB_0F:
927 insn->opcodeType = TWOBYTE;
928 return consume(insn, insn->opcode);
929 case VEX_LOB_0F38:
930 insn->opcodeType = THREEBYTE_38;
931 return consume(insn, insn->opcode);
932 case VEX_LOB_0F3A:
933 insn->opcodeType = THREEBYTE_3A;
934 return consume(insn, insn->opcode);
935 case VEX_LOB_MAP4:
936 insn->opcodeType = MAP4;
937 return consume(insn, insn->opcode);
938 case VEX_LOB_MAP5:
939 insn->opcodeType = MAP5;
940 return consume(insn, insn->opcode);
941 case VEX_LOB_MAP6:
942 insn->opcodeType = MAP6;
943 return consume(insn, insn->opcode);
944 }
945 } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
946 switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
947 default:
948 LLVM_DEBUG(
949 dbgs() << format("Unhandled m-mmmm field for instruction (0x%hhx)",
950 mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])));
951 return true;
952 case VEX_LOB_0F:
953 insn->opcodeType = TWOBYTE;
954 return consume(insn, insn->opcode);
955 case VEX_LOB_0F38:
956 insn->opcodeType = THREEBYTE_38;
957 return consume(insn, insn->opcode);
958 case VEX_LOB_0F3A:
959 insn->opcodeType = THREEBYTE_3A;
960 return consume(insn, insn->opcode);
961 case VEX_LOB_MAP5:
962 insn->opcodeType = MAP5;
963 return consume(insn, insn->opcode);
964 case VEX_LOB_MAP6:
965 insn->opcodeType = MAP6;
966 return consume(insn, insn->opcode);
967 case VEX_LOB_MAP7:
968 insn->opcodeType = MAP7;
969 return consume(insn, insn->opcode);
970 }
971 } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
972 insn->opcodeType = TWOBYTE;
973 return consume(insn, insn->opcode);
974 } else if (insn->vectorExtensionType == TYPE_XOP) {
975 switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
976 default:
977 LLVM_DEBUG(
978 dbgs() << format("Unhandled m-mmmm field for instruction (0x%hhx)",
979 mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])));
980 return true;
981 case XOP_MAP_SELECT_8:
982 insn->opcodeType = XOP8_MAP;
983 return consume(insn, insn->opcode);
984 case XOP_MAP_SELECT_9:
985 insn->opcodeType = XOP9_MAP;
986 return consume(insn, insn->opcode);
987 case XOP_MAP_SELECT_A:
988 insn->opcodeType = XOPA_MAP;
989 return consume(insn, insn->opcode);
990 }
991 } else if (mFromREX2(insn->rex2ExtensionPrefix[1])) {
992 // m bit indicates opcode map 1
993 insn->opcodeType = TWOBYTE;
994 return consume(insn, insn->opcode);
995 }
996
997 if (consume(insn, current))
998 return true;
999
1000 if (current == 0x0f) {
1001 LLVM_DEBUG(
1002 dbgs() << format("Found a two-byte escape prefix (0x%hhx)", current));
1003 if (consume(insn, current))
1004 return true;
1005
1006 if (current == 0x38) {
1007 LLVM_DEBUG(dbgs() << format("Found a three-byte escape prefix (0x%hhx)",
1008 current));
1009 if (consume(insn, current))
1010 return true;
1011
1012 insn->opcodeType = THREEBYTE_38;
1013 } else if (current == 0x3a) {
1014 LLVM_DEBUG(dbgs() << format("Found a three-byte escape prefix (0x%hhx)",
1015 current));
1016 if (consume(insn, current))
1017 return true;
1018
1019 insn->opcodeType = THREEBYTE_3A;
1020 } else if (current == 0x0f) {
1021 LLVM_DEBUG(
1022 dbgs() << format("Found a 3dnow escape prefix (0x%hhx)", current));
1023
1024 // Consume operands before the opcode to comply with the 3DNow encoding
1025 if (readModRM(insn))
1026 return true;
1027
1028 if (consume(insn, current))
1029 return true;
1030
1031 insn->opcodeType = THREEDNOW_MAP;
1032 } else {
1033 LLVM_DEBUG(dbgs() << "Didn't find a three-byte escape prefix");
1034 insn->opcodeType = TWOBYTE;
1035 }
1036 } else if (insn->mandatoryPrefix)
1037 // The opcode with mandatory prefix must start with opcode escape.
1038 // If not it's legacy repeat prefix
1039 insn->mandatoryPrefix = 0;
1040
1041 // At this point we have consumed the full opcode.
1042 // Anything we consume from here on must be unconsumed.
1043 insn->opcode = current;
1044
1045 return false;
1046 }
1047
1048 // Determine whether equiv is the 16-bit equivalent of orig (32-bit or 64-bit).
is16BitEquivalent(const char * orig,const char * equiv)1049 static bool is16BitEquivalent(const char *orig, const char *equiv) {
1050 for (int i = 0;; i++) {
1051 if (orig[i] == '\0' && equiv[i] == '\0')
1052 return true;
1053 if (orig[i] == '\0' || equiv[i] == '\0')
1054 return false;
1055 if (orig[i] != equiv[i]) {
1056 if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
1057 continue;
1058 if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
1059 continue;
1060 if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
1061 continue;
1062 return false;
1063 }
1064 }
1065 }
1066
1067 // Determine whether this instruction is a 64-bit instruction.
is64Bit(const char * name)1068 static bool is64Bit(const char *name) {
1069 for (int i = 0;; ++i) {
1070 if (name[i] == '\0')
1071 return false;
1072 if (name[i] == '6' && name[i + 1] == '4')
1073 return true;
1074 }
1075 }
1076
1077 // Determine the ID of an instruction, consuming the ModR/M byte as appropriate
1078 // for extended and escape opcodes, and using a supplied attribute mask.
getInstructionIDWithAttrMask(uint16_t * instructionID,struct InternalInstruction * insn,uint16_t attrMask)1079 static int getInstructionIDWithAttrMask(uint16_t *instructionID,
1080 struct InternalInstruction *insn,
1081 uint16_t attrMask) {
1082 auto insnCtx = InstructionContext(x86DisassemblerContexts[attrMask]);
1083 const ContextDecision *decision;
1084 switch (insn->opcodeType) {
1085 case ONEBYTE:
1086 decision = &ONEBYTE_SYM;
1087 break;
1088 case TWOBYTE:
1089 decision = &TWOBYTE_SYM;
1090 break;
1091 case THREEBYTE_38:
1092 decision = &THREEBYTE38_SYM;
1093 break;
1094 case THREEBYTE_3A:
1095 decision = &THREEBYTE3A_SYM;
1096 break;
1097 case XOP8_MAP:
1098 decision = &XOP8_MAP_SYM;
1099 break;
1100 case XOP9_MAP:
1101 decision = &XOP9_MAP_SYM;
1102 break;
1103 case XOPA_MAP:
1104 decision = &XOPA_MAP_SYM;
1105 break;
1106 case THREEDNOW_MAP:
1107 decision = &THREEDNOW_MAP_SYM;
1108 break;
1109 case MAP4:
1110 decision = &MAP4_SYM;
1111 break;
1112 case MAP5:
1113 decision = &MAP5_SYM;
1114 break;
1115 case MAP6:
1116 decision = &MAP6_SYM;
1117 break;
1118 case MAP7:
1119 decision = &MAP7_SYM;
1120 break;
1121 }
1122
1123 if (decision->opcodeDecisions[insnCtx]
1124 .modRMDecisions[insn->opcode]
1125 .modrm_type != MODRM_ONEENTRY) {
1126 if (readModRM(insn))
1127 return -1;
1128 *instructionID =
1129 decode(insn->opcodeType, insnCtx, insn->opcode, insn->modRM);
1130 } else {
1131 *instructionID = decode(insn->opcodeType, insnCtx, insn->opcode, 0);
1132 }
1133
1134 return 0;
1135 }
1136
1137 // Determine the ID of an instruction, consuming the ModR/M byte as appropriate
1138 // for extended and escape opcodes. Determines the attributes and context for
1139 // the instruction before doing so.
getInstructionID(struct InternalInstruction * insn,const MCInstrInfo * mii)1140 static int getInstructionID(struct InternalInstruction *insn,
1141 const MCInstrInfo *mii) {
1142 uint16_t attrMask;
1143 uint16_t instructionID;
1144
1145 LLVM_DEBUG(dbgs() << "getID()");
1146
1147 attrMask = ATTR_NONE;
1148
1149 if (insn->mode == MODE_64BIT)
1150 attrMask |= ATTR_64BIT;
1151
1152 if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1153 attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
1154
1155 if (insn->vectorExtensionType == TYPE_EVEX) {
1156 switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
1157 case VEX_PREFIX_66:
1158 attrMask |= ATTR_OPSIZE;
1159 break;
1160 case VEX_PREFIX_F3:
1161 attrMask |= ATTR_XS;
1162 break;
1163 case VEX_PREFIX_F2:
1164 attrMask |= ATTR_XD;
1165 break;
1166 }
1167
1168 if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1169 attrMask |= ATTR_EVEXKZ;
1170 if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1171 attrMask |= ATTR_EVEXB;
1172 // nf bit is the MSB of aaa
1173 if (nfFromEVEX4of4(insn->vectorExtensionPrefix[3]) &&
1174 insn->opcodeType == MAP4)
1175 attrMask |= ATTR_EVEXNF;
1176 else if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1177 attrMask |= ATTR_EVEXK;
1178 if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1179 attrMask |= ATTR_VEXL;
1180 if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1181 attrMask |= ATTR_EVEXL2;
1182 } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
1183 switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
1184 case VEX_PREFIX_66:
1185 attrMask |= ATTR_OPSIZE;
1186 break;
1187 case VEX_PREFIX_F3:
1188 attrMask |= ATTR_XS;
1189 break;
1190 case VEX_PREFIX_F2:
1191 attrMask |= ATTR_XD;
1192 break;
1193 }
1194
1195 if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
1196 attrMask |= ATTR_VEXL;
1197 } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
1198 switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
1199 case VEX_PREFIX_66:
1200 attrMask |= ATTR_OPSIZE;
1201 if (insn->hasAdSize)
1202 attrMask |= ATTR_ADSIZE;
1203 break;
1204 case VEX_PREFIX_F3:
1205 attrMask |= ATTR_XS;
1206 break;
1207 case VEX_PREFIX_F2:
1208 attrMask |= ATTR_XD;
1209 break;
1210 }
1211
1212 if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
1213 attrMask |= ATTR_VEXL;
1214 } else if (insn->vectorExtensionType == TYPE_XOP) {
1215 switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
1216 case VEX_PREFIX_66:
1217 attrMask |= ATTR_OPSIZE;
1218 break;
1219 case VEX_PREFIX_F3:
1220 attrMask |= ATTR_XS;
1221 break;
1222 case VEX_PREFIX_F2:
1223 attrMask |= ATTR_XD;
1224 break;
1225 }
1226
1227 if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
1228 attrMask |= ATTR_VEXL;
1229 } else {
1230 return -1;
1231 }
1232 } else if (!insn->mandatoryPrefix) {
1233 // If we don't have mandatory prefix we should use legacy prefixes here
1234 if (insn->hasOpSize && (insn->mode != MODE_16BIT))
1235 attrMask |= ATTR_OPSIZE;
1236 if (insn->hasAdSize)
1237 attrMask |= ATTR_ADSIZE;
1238 if (insn->opcodeType == ONEBYTE) {
1239 if (insn->repeatPrefix == 0xf3 && (insn->opcode == 0x90))
1240 // Special support for PAUSE
1241 attrMask |= ATTR_XS;
1242 } else {
1243 if (insn->repeatPrefix == 0xf2)
1244 attrMask |= ATTR_XD;
1245 else if (insn->repeatPrefix == 0xf3)
1246 attrMask |= ATTR_XS;
1247 }
1248 } else {
1249 switch (insn->mandatoryPrefix) {
1250 case 0xf2:
1251 attrMask |= ATTR_XD;
1252 break;
1253 case 0xf3:
1254 attrMask |= ATTR_XS;
1255 break;
1256 case 0x66:
1257 if (insn->mode != MODE_16BIT)
1258 attrMask |= ATTR_OPSIZE;
1259 if (insn->hasAdSize)
1260 attrMask |= ATTR_ADSIZE;
1261 break;
1262 case 0x67:
1263 attrMask |= ATTR_ADSIZE;
1264 break;
1265 }
1266 }
1267
1268 if (insn->rexPrefix & 0x08) {
1269 attrMask |= ATTR_REXW;
1270 attrMask &= ~ATTR_ADSIZE;
1271 }
1272
1273 // Absolute jump and pushp/popp need special handling
1274 if (insn->rex2ExtensionPrefix[0] == 0xd5 && insn->opcodeType == ONEBYTE &&
1275 (insn->opcode == 0xA1 || (insn->opcode & 0xf0) == 0x50))
1276 attrMask |= ATTR_REX2;
1277
1278 if (insn->mode == MODE_16BIT) {
1279 // JCXZ/JECXZ need special handling for 16-bit mode because the meaning
1280 // of the AdSize prefix is inverted w.r.t. 32-bit mode.
1281 if (insn->opcodeType == ONEBYTE && insn->opcode == 0xE3)
1282 attrMask ^= ATTR_ADSIZE;
1283 // If we're in 16-bit mode and this is one of the relative jumps and opsize
1284 // prefix isn't present, we need to force the opsize attribute since the
1285 // prefix is inverted relative to 32-bit mode.
1286 if (!insn->hasOpSize && insn->opcodeType == ONEBYTE &&
1287 (insn->opcode == 0xE8 || insn->opcode == 0xE9))
1288 attrMask |= ATTR_OPSIZE;
1289
1290 if (!insn->hasOpSize && insn->opcodeType == TWOBYTE &&
1291 insn->opcode >= 0x80 && insn->opcode <= 0x8F)
1292 attrMask |= ATTR_OPSIZE;
1293 }
1294
1295
1296 if (getInstructionIDWithAttrMask(&instructionID, insn, attrMask))
1297 return -1;
1298
1299 // The following clauses compensate for limitations of the tables.
1300
1301 if (insn->mode != MODE_64BIT &&
1302 insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1303 // The tables can't distinquish between cases where the W-bit is used to
1304 // select register size and cases where its a required part of the opcode.
1305 if ((insn->vectorExtensionType == TYPE_EVEX &&
1306 wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
1307 (insn->vectorExtensionType == TYPE_VEX_3B &&
1308 wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
1309 (insn->vectorExtensionType == TYPE_XOP &&
1310 wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1311
1312 uint16_t instructionIDWithREXW;
1313 if (getInstructionIDWithAttrMask(&instructionIDWithREXW, insn,
1314 attrMask | ATTR_REXW)) {
1315 insn->instructionID = instructionID;
1316 insn->spec = &INSTRUCTIONS_SYM[instructionID];
1317 return 0;
1318 }
1319
1320 auto SpecName = mii->getName(instructionIDWithREXW);
1321 // If not a 64-bit instruction. Switch the opcode.
1322 if (!is64Bit(SpecName.data())) {
1323 insn->instructionID = instructionIDWithREXW;
1324 insn->spec = &INSTRUCTIONS_SYM[instructionIDWithREXW];
1325 return 0;
1326 }
1327 }
1328 }
1329
1330 // Absolute moves, umonitor, and movdir64b need special handling.
1331 // -For 16-bit mode because the meaning of the AdSize and OpSize prefixes are
1332 // inverted w.r.t.
1333 // -For 32-bit mode we need to ensure the ADSIZE prefix is observed in
1334 // any position.
1335 if ((insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) ||
1336 (insn->opcodeType == TWOBYTE && (insn->opcode == 0xAE)) ||
1337 (insn->opcodeType == THREEBYTE_38 && insn->opcode == 0xF8) ||
1338 (insn->opcodeType == MAP4 && insn->opcode == 0xF8)) {
1339 // Make sure we observed the prefixes in any position.
1340 if (insn->hasAdSize)
1341 attrMask |= ATTR_ADSIZE;
1342 if (insn->hasOpSize)
1343 attrMask |= ATTR_OPSIZE;
1344
1345 // In 16-bit, invert the attributes.
1346 if (insn->mode == MODE_16BIT) {
1347 attrMask ^= ATTR_ADSIZE;
1348
1349 // The OpSize attribute is only valid with the absolute moves.
1350 if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0))
1351 attrMask ^= ATTR_OPSIZE;
1352 }
1353
1354 if (getInstructionIDWithAttrMask(&instructionID, insn, attrMask))
1355 return -1;
1356
1357 insn->instructionID = instructionID;
1358 insn->spec = &INSTRUCTIONS_SYM[instructionID];
1359 return 0;
1360 }
1361
1362 if ((insn->mode == MODE_16BIT || insn->hasOpSize) &&
1363 !(attrMask & ATTR_OPSIZE)) {
1364 // The instruction tables make no distinction between instructions that
1365 // allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
1366 // particular spot (i.e., many MMX operations). In general we're
1367 // conservative, but in the specific case where OpSize is present but not in
1368 // the right place we check if there's a 16-bit operation.
1369 const struct InstructionSpecifier *spec;
1370 uint16_t instructionIDWithOpsize;
1371 llvm::StringRef specName, specWithOpSizeName;
1372
1373 spec = &INSTRUCTIONS_SYM[instructionID];
1374
1375 if (getInstructionIDWithAttrMask(&instructionIDWithOpsize, insn,
1376 attrMask | ATTR_OPSIZE)) {
1377 // ModRM required with OpSize but not present. Give up and return the
1378 // version without OpSize set.
1379 insn->instructionID = instructionID;
1380 insn->spec = spec;
1381 return 0;
1382 }
1383
1384 specName = mii->getName(instructionID);
1385 specWithOpSizeName = mii->getName(instructionIDWithOpsize);
1386
1387 if (is16BitEquivalent(specName.data(), specWithOpSizeName.data()) &&
1388 (insn->mode == MODE_16BIT) ^ insn->hasOpSize) {
1389 insn->instructionID = instructionIDWithOpsize;
1390 insn->spec = &INSTRUCTIONS_SYM[instructionIDWithOpsize];
1391 } else {
1392 insn->instructionID = instructionID;
1393 insn->spec = spec;
1394 }
1395 return 0;
1396 }
1397
1398 if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1399 insn->rexPrefix & 0x01) {
1400 // NOOP shouldn't decode as NOOP if REX.b is set. Instead it should decode
1401 // as XCHG %r8, %eax.
1402 const struct InstructionSpecifier *spec;
1403 uint16_t instructionIDWithNewOpcode;
1404 const struct InstructionSpecifier *specWithNewOpcode;
1405
1406 spec = &INSTRUCTIONS_SYM[instructionID];
1407
1408 // Borrow opcode from one of the other XCHGar opcodes
1409 insn->opcode = 0x91;
1410
1411 if (getInstructionIDWithAttrMask(&instructionIDWithNewOpcode, insn,
1412 attrMask)) {
1413 insn->opcode = 0x90;
1414
1415 insn->instructionID = instructionID;
1416 insn->spec = spec;
1417 return 0;
1418 }
1419
1420 specWithNewOpcode = &INSTRUCTIONS_SYM[instructionIDWithNewOpcode];
1421
1422 // Change back
1423 insn->opcode = 0x90;
1424
1425 insn->instructionID = instructionIDWithNewOpcode;
1426 insn->spec = specWithNewOpcode;
1427
1428 return 0;
1429 }
1430
1431 insn->instructionID = instructionID;
1432 insn->spec = &INSTRUCTIONS_SYM[insn->instructionID];
1433
1434 return 0;
1435 }
1436
1437 // Read an operand from the opcode field of an instruction and interprets it
1438 // appropriately given the operand width. Handles AddRegFrm instructions.
1439 //
1440 // @param insn - the instruction whose opcode field is to be read.
1441 // @param size - The width (in bytes) of the register being specified.
1442 // 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1443 // RAX.
1444 // @return - 0 on success; nonzero otherwise.
readOpcodeRegister(struct InternalInstruction * insn,uint8_t size)1445 static int readOpcodeRegister(struct InternalInstruction *insn, uint8_t size) {
1446 LLVM_DEBUG(dbgs() << "readOpcodeRegister()");
1447
1448 if (size == 0)
1449 size = insn->registerSize;
1450
1451 auto setOpcodeRegister = [&](unsigned base) {
1452 insn->opcodeRegister =
1453 (Reg)(base + ((bFromREX(insn->rexPrefix) << 3) |
1454 (b2FromREX2(insn->rex2ExtensionPrefix[1]) << 4) |
1455 (insn->opcode & 7)));
1456 };
1457
1458 switch (size) {
1459 case 1:
1460 setOpcodeRegister(MODRM_REG_AL);
1461 if (insn->rexPrefix && insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1462 insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1463 insn->opcodeRegister =
1464 (Reg)(MODRM_REG_SPL + (insn->opcodeRegister - MODRM_REG_AL - 4));
1465 }
1466
1467 break;
1468 case 2:
1469 setOpcodeRegister(MODRM_REG_AX);
1470 break;
1471 case 4:
1472 setOpcodeRegister(MODRM_REG_EAX);
1473 break;
1474 case 8:
1475 setOpcodeRegister(MODRM_REG_RAX);
1476 break;
1477 }
1478
1479 return 0;
1480 }
1481
1482 // Consume an immediate operand from an instruction, given the desired operand
1483 // size.
1484 //
1485 // @param insn - The instruction whose operand is to be read.
1486 // @param size - The width (in bytes) of the operand.
1487 // @return - 0 if the immediate was successfully consumed; nonzero
1488 // otherwise.
readImmediate(struct InternalInstruction * insn,uint8_t size)1489 static int readImmediate(struct InternalInstruction *insn, uint8_t size) {
1490 uint8_t imm8;
1491 uint16_t imm16;
1492 uint32_t imm32;
1493 uint64_t imm64;
1494
1495 LLVM_DEBUG(dbgs() << "readImmediate()");
1496
1497 assert(insn->numImmediatesConsumed < 2 && "Already consumed two immediates");
1498
1499 insn->immediateSize = size;
1500 insn->immediateOffset = insn->readerCursor - insn->startLocation;
1501
1502 switch (size) {
1503 case 1:
1504 if (consume(insn, imm8))
1505 return -1;
1506 insn->immediates[insn->numImmediatesConsumed] = imm8;
1507 break;
1508 case 2:
1509 if (consume(insn, imm16))
1510 return -1;
1511 insn->immediates[insn->numImmediatesConsumed] = imm16;
1512 break;
1513 case 4:
1514 if (consume(insn, imm32))
1515 return -1;
1516 insn->immediates[insn->numImmediatesConsumed] = imm32;
1517 break;
1518 case 8:
1519 if (consume(insn, imm64))
1520 return -1;
1521 insn->immediates[insn->numImmediatesConsumed] = imm64;
1522 break;
1523 default:
1524 llvm_unreachable("invalid size");
1525 }
1526
1527 insn->numImmediatesConsumed++;
1528
1529 return 0;
1530 }
1531
1532 // Consume vvvv from an instruction if it has a VEX prefix.
readVVVV(struct InternalInstruction * insn)1533 static int readVVVV(struct InternalInstruction *insn) {
1534 LLVM_DEBUG(dbgs() << "readVVVV()");
1535
1536 int vvvv;
1537 if (insn->vectorExtensionType == TYPE_EVEX)
1538 vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1539 vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1540 else if (insn->vectorExtensionType == TYPE_VEX_3B)
1541 vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1542 else if (insn->vectorExtensionType == TYPE_VEX_2B)
1543 vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1544 else if (insn->vectorExtensionType == TYPE_XOP)
1545 vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1546 else
1547 return -1;
1548
1549 if (insn->mode != MODE_64BIT)
1550 vvvv &= 0xf; // Can only clear bit 4. Bit 3 must be cleared later.
1551
1552 insn->vvvv = static_cast<Reg>(vvvv);
1553 return 0;
1554 }
1555
1556 // Read an mask register from the opcode field of an instruction.
1557 //
1558 // @param insn - The instruction whose opcode field is to be read.
1559 // @return - 0 on success; nonzero otherwise.
readMaskRegister(struct InternalInstruction * insn)1560 static int readMaskRegister(struct InternalInstruction *insn) {
1561 LLVM_DEBUG(dbgs() << "readMaskRegister()");
1562
1563 if (insn->vectorExtensionType != TYPE_EVEX)
1564 return -1;
1565
1566 insn->writemask =
1567 static_cast<Reg>(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1568 return 0;
1569 }
1570
1571 // Consults the specifier for an instruction and consumes all
1572 // operands for that instruction, interpreting them as it goes.
readOperands(struct InternalInstruction * insn)1573 static int readOperands(struct InternalInstruction *insn) {
1574 int hasVVVV, needVVVV;
1575 int sawRegImm = 0;
1576
1577 LLVM_DEBUG(dbgs() << "readOperands()");
1578
1579 // If non-zero vvvv specified, make sure one of the operands uses it.
1580 hasVVVV = !readVVVV(insn);
1581 needVVVV = hasVVVV && (insn->vvvv != 0);
1582
1583 for (const auto &Op : x86OperandSets[insn->spec->operands]) {
1584 switch (Op.encoding) {
1585 case ENCODING_NONE:
1586 case ENCODING_SI:
1587 case ENCODING_DI:
1588 break;
1589 CASE_ENCODING_VSIB:
1590 // VSIB can use the V2 bit so check only the other bits.
1591 if (needVVVV)
1592 needVVVV = hasVVVV & ((insn->vvvv & 0xf) != 0);
1593 if (readModRM(insn))
1594 return -1;
1595
1596 // Reject if SIB wasn't used.
1597 if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1598 return -1;
1599
1600 // If sibIndex was set to SIB_INDEX_NONE, index offset is 4.
1601 if (insn->sibIndex == SIB_INDEX_NONE)
1602 insn->sibIndex = (SIBIndex)(insn->sibIndexBase + 4);
1603
1604 // If EVEX.v2 is set this is one of the 16-31 registers.
1605 if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT &&
1606 v2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1607 insn->sibIndex = (SIBIndex)(insn->sibIndex + 16);
1608
1609 // Adjust the index register to the correct size.
1610 switch ((OperandType)Op.type) {
1611 default:
1612 debug("Unhandled VSIB index type");
1613 return -1;
1614 case TYPE_MVSIBX:
1615 insn->sibIndex =
1616 (SIBIndex)(SIB_INDEX_XMM0 + (insn->sibIndex - insn->sibIndexBase));
1617 break;
1618 case TYPE_MVSIBY:
1619 insn->sibIndex =
1620 (SIBIndex)(SIB_INDEX_YMM0 + (insn->sibIndex - insn->sibIndexBase));
1621 break;
1622 case TYPE_MVSIBZ:
1623 insn->sibIndex =
1624 (SIBIndex)(SIB_INDEX_ZMM0 + (insn->sibIndex - insn->sibIndexBase));
1625 break;
1626 }
1627
1628 // Apply the AVX512 compressed displacement scaling factor.
1629 if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1630 insn->displacement *= 1 << (Op.encoding - ENCODING_VSIB);
1631 break;
1632 case ENCODING_SIB:
1633 // Reject if SIB wasn't used.
1634 if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1635 return -1;
1636 if (readModRM(insn))
1637 return -1;
1638 if (fixupReg(insn, &Op))
1639 return -1;
1640 break;
1641 case ENCODING_REG:
1642 CASE_ENCODING_RM:
1643 if (readModRM(insn))
1644 return -1;
1645 if (fixupReg(insn, &Op))
1646 return -1;
1647 // Apply the AVX512 compressed displacement scaling factor.
1648 if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1649 insn->displacement *= 1 << (Op.encoding - ENCODING_RM);
1650 break;
1651 case ENCODING_IB:
1652 if (sawRegImm) {
1653 // Saw a register immediate so don't read again and instead split the
1654 // previous immediate. FIXME: This is a hack.
1655 insn->immediates[insn->numImmediatesConsumed] =
1656 insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1657 ++insn->numImmediatesConsumed;
1658 break;
1659 }
1660 if (readImmediate(insn, 1))
1661 return -1;
1662 if (Op.type == TYPE_XMM || Op.type == TYPE_YMM)
1663 sawRegImm = 1;
1664 break;
1665 case ENCODING_IW:
1666 if (readImmediate(insn, 2))
1667 return -1;
1668 break;
1669 case ENCODING_ID:
1670 if (readImmediate(insn, 4))
1671 return -1;
1672 break;
1673 case ENCODING_IO:
1674 if (readImmediate(insn, 8))
1675 return -1;
1676 break;
1677 case ENCODING_Iv:
1678 if (readImmediate(insn, insn->immediateSize))
1679 return -1;
1680 break;
1681 case ENCODING_Ia:
1682 if (readImmediate(insn, insn->addressSize))
1683 return -1;
1684 break;
1685 case ENCODING_IRC:
1686 insn->RC = (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 1) |
1687 lFromEVEX4of4(insn->vectorExtensionPrefix[3]);
1688 break;
1689 case ENCODING_RB:
1690 if (readOpcodeRegister(insn, 1))
1691 return -1;
1692 break;
1693 case ENCODING_RW:
1694 if (readOpcodeRegister(insn, 2))
1695 return -1;
1696 break;
1697 case ENCODING_RD:
1698 if (readOpcodeRegister(insn, 4))
1699 return -1;
1700 break;
1701 case ENCODING_RO:
1702 if (readOpcodeRegister(insn, 8))
1703 return -1;
1704 break;
1705 case ENCODING_Rv:
1706 if (readOpcodeRegister(insn, 0))
1707 return -1;
1708 break;
1709 case ENCODING_CC:
1710 insn->immediates[1] = insn->opcode & 0xf;
1711 break;
1712 case ENCODING_FP:
1713 break;
1714 case ENCODING_VVVV:
1715 needVVVV = 0; // Mark that we have found a VVVV operand.
1716 if (!hasVVVV)
1717 return -1;
1718 if (insn->mode != MODE_64BIT)
1719 insn->vvvv = static_cast<Reg>(insn->vvvv & 0x7);
1720 if (fixupReg(insn, &Op))
1721 return -1;
1722 break;
1723 case ENCODING_WRITEMASK:
1724 if (readMaskRegister(insn))
1725 return -1;
1726 break;
1727 case ENCODING_DUP:
1728 break;
1729 default:
1730 LLVM_DEBUG(dbgs() << "Encountered an operand with an unknown encoding.");
1731 return -1;
1732 }
1733 }
1734
1735 // If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail
1736 if (needVVVV)
1737 return -1;
1738
1739 return 0;
1740 }
1741
1742 namespace llvm {
1743
1744 // Fill-ins to make the compiler happy. These constants are never actually
1745 // assigned; they are just filler to make an automatically-generated switch
1746 // statement work.
1747 namespace X86 {
1748 enum {
1749 BX_SI = 500,
1750 BX_DI = 501,
1751 BP_SI = 502,
1752 BP_DI = 503,
1753 sib = 504,
1754 sib64 = 505
1755 };
1756 } // namespace X86
1757
1758 } // namespace llvm
1759
1760 static bool translateInstruction(MCInst &target,
1761 InternalInstruction &source,
1762 const MCDisassembler *Dis);
1763
1764 namespace {
1765
1766 /// Generic disassembler for all X86 platforms. All each platform class should
1767 /// have to do is subclass the constructor, and provide a different
1768 /// disassemblerMode value.
1769 class X86GenericDisassembler : public MCDisassembler {
1770 std::unique_ptr<const MCInstrInfo> MII;
1771 public:
1772 X86GenericDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx,
1773 std::unique_ptr<const MCInstrInfo> MII);
1774 public:
1775 DecodeStatus getInstruction(MCInst &instr, uint64_t &size,
1776 ArrayRef<uint8_t> Bytes, uint64_t Address,
1777 raw_ostream &cStream) const override;
1778
1779 private:
1780 DisassemblerMode fMode;
1781 };
1782
1783 } // namespace
1784
X86GenericDisassembler(const MCSubtargetInfo & STI,MCContext & Ctx,std::unique_ptr<const MCInstrInfo> MII)1785 X86GenericDisassembler::X86GenericDisassembler(
1786 const MCSubtargetInfo &STI,
1787 MCContext &Ctx,
1788 std::unique_ptr<const MCInstrInfo> MII)
1789 : MCDisassembler(STI, Ctx), MII(std::move(MII)) {
1790 const FeatureBitset &FB = STI.getFeatureBits();
1791 if (FB[X86::Is16Bit]) {
1792 fMode = MODE_16BIT;
1793 return;
1794 } else if (FB[X86::Is32Bit]) {
1795 fMode = MODE_32BIT;
1796 return;
1797 } else if (FB[X86::Is64Bit]) {
1798 fMode = MODE_64BIT;
1799 return;
1800 }
1801
1802 llvm_unreachable("Invalid CPU mode");
1803 }
1804
getInstruction(MCInst & Instr,uint64_t & Size,ArrayRef<uint8_t> Bytes,uint64_t Address,raw_ostream & CStream) const1805 MCDisassembler::DecodeStatus X86GenericDisassembler::getInstruction(
1806 MCInst &Instr, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t Address,
1807 raw_ostream &CStream) const {
1808 CommentStream = &CStream;
1809
1810 InternalInstruction Insn;
1811 memset(&Insn, 0, sizeof(InternalInstruction));
1812 Insn.bytes = Bytes;
1813 Insn.startLocation = Address;
1814 Insn.readerCursor = Address;
1815 Insn.mode = fMode;
1816
1817 if (Bytes.empty() || readPrefixes(&Insn) || readOpcode(&Insn) ||
1818 getInstructionID(&Insn, MII.get()) || Insn.instructionID == 0 ||
1819 readOperands(&Insn)) {
1820 Size = Insn.readerCursor - Address;
1821 return Fail;
1822 }
1823
1824 Insn.operands = x86OperandSets[Insn.spec->operands];
1825 Insn.length = Insn.readerCursor - Insn.startLocation;
1826 Size = Insn.length;
1827 if (Size > 15)
1828 LLVM_DEBUG(dbgs() << "Instruction exceeds 15-byte limit");
1829
1830 bool Ret = translateInstruction(Instr, Insn, this);
1831 if (!Ret) {
1832 unsigned Flags = X86::IP_NO_PREFIX;
1833 if (Insn.hasAdSize)
1834 Flags |= X86::IP_HAS_AD_SIZE;
1835 if (!Insn.mandatoryPrefix) {
1836 if (Insn.hasOpSize)
1837 Flags |= X86::IP_HAS_OP_SIZE;
1838 if (Insn.repeatPrefix == 0xf2)
1839 Flags |= X86::IP_HAS_REPEAT_NE;
1840 else if (Insn.repeatPrefix == 0xf3 &&
1841 // It should not be 'pause' f3 90
1842 Insn.opcode != 0x90)
1843 Flags |= X86::IP_HAS_REPEAT;
1844 if (Insn.hasLockPrefix)
1845 Flags |= X86::IP_HAS_LOCK;
1846 }
1847 Instr.setFlags(Flags);
1848 }
1849 return (!Ret) ? Success : Fail;
1850 }
1851
1852 //
1853 // Private code that translates from struct InternalInstructions to MCInsts.
1854 //
1855
1856 /// translateRegister - Translates an internal register to the appropriate LLVM
1857 /// register, and appends it as an operand to an MCInst.
1858 ///
1859 /// @param mcInst - The MCInst to append to.
1860 /// @param reg - The Reg to append.
translateRegister(MCInst & mcInst,Reg reg)1861 static void translateRegister(MCInst &mcInst, Reg reg) {
1862 #define ENTRY(x) X86::x,
1863 static constexpr MCPhysReg llvmRegnums[] = {ALL_REGS};
1864 #undef ENTRY
1865
1866 MCPhysReg llvmRegnum = llvmRegnums[reg];
1867 mcInst.addOperand(MCOperand::createReg(llvmRegnum));
1868 }
1869
1870 static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
1871 0, // SEG_OVERRIDE_NONE
1872 X86::CS,
1873 X86::SS,
1874 X86::DS,
1875 X86::ES,
1876 X86::FS,
1877 X86::GS
1878 };
1879
1880 /// translateSrcIndex - Appends a source index operand to an MCInst.
1881 ///
1882 /// @param mcInst - The MCInst to append to.
1883 /// @param insn - The internal instruction.
translateSrcIndex(MCInst & mcInst,InternalInstruction & insn)1884 static bool translateSrcIndex(MCInst &mcInst, InternalInstruction &insn) {
1885 unsigned baseRegNo;
1886
1887 if (insn.mode == MODE_64BIT)
1888 baseRegNo = insn.hasAdSize ? X86::ESI : X86::RSI;
1889 else if (insn.mode == MODE_32BIT)
1890 baseRegNo = insn.hasAdSize ? X86::SI : X86::ESI;
1891 else {
1892 assert(insn.mode == MODE_16BIT);
1893 baseRegNo = insn.hasAdSize ? X86::ESI : X86::SI;
1894 }
1895 MCOperand baseReg = MCOperand::createReg(baseRegNo);
1896 mcInst.addOperand(baseReg);
1897
1898 MCOperand segmentReg;
1899 segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
1900 mcInst.addOperand(segmentReg);
1901 return false;
1902 }
1903
1904 /// translateDstIndex - Appends a destination index operand to an MCInst.
1905 ///
1906 /// @param mcInst - The MCInst to append to.
1907 /// @param insn - The internal instruction.
1908
translateDstIndex(MCInst & mcInst,InternalInstruction & insn)1909 static bool translateDstIndex(MCInst &mcInst, InternalInstruction &insn) {
1910 unsigned baseRegNo;
1911
1912 if (insn.mode == MODE_64BIT)
1913 baseRegNo = insn.hasAdSize ? X86::EDI : X86::RDI;
1914 else if (insn.mode == MODE_32BIT)
1915 baseRegNo = insn.hasAdSize ? X86::DI : X86::EDI;
1916 else {
1917 assert(insn.mode == MODE_16BIT);
1918 baseRegNo = insn.hasAdSize ? X86::EDI : X86::DI;
1919 }
1920 MCOperand baseReg = MCOperand::createReg(baseRegNo);
1921 mcInst.addOperand(baseReg);
1922 return false;
1923 }
1924
1925 /// translateImmediate - Appends an immediate operand to an MCInst.
1926 ///
1927 /// @param mcInst - The MCInst to append to.
1928 /// @param immediate - The immediate value to append.
1929 /// @param operand - The operand, as stored in the descriptor table.
1930 /// @param insn - The internal instruction.
translateImmediate(MCInst & mcInst,uint64_t immediate,const OperandSpecifier & operand,InternalInstruction & insn,const MCDisassembler * Dis)1931 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
1932 const OperandSpecifier &operand,
1933 InternalInstruction &insn,
1934 const MCDisassembler *Dis) {
1935 // Sign-extend the immediate if necessary.
1936
1937 OperandType type = (OperandType)operand.type;
1938
1939 bool isBranch = false;
1940 uint64_t pcrel = 0;
1941 if (type == TYPE_REL) {
1942 isBranch = true;
1943 pcrel = insn.startLocation + insn.length;
1944 switch (operand.encoding) {
1945 default:
1946 break;
1947 case ENCODING_Iv:
1948 switch (insn.displacementSize) {
1949 default:
1950 break;
1951 case 1:
1952 if(immediate & 0x80)
1953 immediate |= ~(0xffull);
1954 break;
1955 case 2:
1956 if(immediate & 0x8000)
1957 immediate |= ~(0xffffull);
1958 break;
1959 case 4:
1960 if(immediate & 0x80000000)
1961 immediate |= ~(0xffffffffull);
1962 break;
1963 case 8:
1964 break;
1965 }
1966 break;
1967 case ENCODING_IB:
1968 if(immediate & 0x80)
1969 immediate |= ~(0xffull);
1970 break;
1971 case ENCODING_IW:
1972 if(immediate & 0x8000)
1973 immediate |= ~(0xffffull);
1974 break;
1975 case ENCODING_ID:
1976 if(immediate & 0x80000000)
1977 immediate |= ~(0xffffffffull);
1978 break;
1979 }
1980 }
1981 // By default sign-extend all X86 immediates based on their encoding.
1982 else if (type == TYPE_IMM) {
1983 switch (operand.encoding) {
1984 default:
1985 break;
1986 case ENCODING_IB:
1987 if(immediate & 0x80)
1988 immediate |= ~(0xffull);
1989 break;
1990 case ENCODING_IW:
1991 if(immediate & 0x8000)
1992 immediate |= ~(0xffffull);
1993 break;
1994 case ENCODING_ID:
1995 if(immediate & 0x80000000)
1996 immediate |= ~(0xffffffffull);
1997 break;
1998 case ENCODING_IO:
1999 break;
2000 }
2001 }
2002
2003 switch (type) {
2004 case TYPE_XMM:
2005 mcInst.addOperand(MCOperand::createReg(X86::XMM0 + (immediate >> 4)));
2006 return;
2007 case TYPE_YMM:
2008 mcInst.addOperand(MCOperand::createReg(X86::YMM0 + (immediate >> 4)));
2009 return;
2010 case TYPE_ZMM:
2011 mcInst.addOperand(MCOperand::createReg(X86::ZMM0 + (immediate >> 4)));
2012 return;
2013 default:
2014 // operand is 64 bits wide. Do nothing.
2015 break;
2016 }
2017
2018 if (!Dis->tryAddingSymbolicOperand(
2019 mcInst, immediate + pcrel, insn.startLocation, isBranch,
2020 insn.immediateOffset, insn.immediateSize, insn.length))
2021 mcInst.addOperand(MCOperand::createImm(immediate));
2022
2023 if (type == TYPE_MOFFS) {
2024 MCOperand segmentReg;
2025 segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
2026 mcInst.addOperand(segmentReg);
2027 }
2028 }
2029
2030 /// translateRMRegister - Translates a register stored in the R/M field of the
2031 /// ModR/M byte to its LLVM equivalent and appends it to an MCInst.
2032 /// @param mcInst - The MCInst to append to.
2033 /// @param insn - The internal instruction to extract the R/M field
2034 /// from.
2035 /// @return - 0 on success; -1 otherwise
translateRMRegister(MCInst & mcInst,InternalInstruction & insn)2036 static bool translateRMRegister(MCInst &mcInst,
2037 InternalInstruction &insn) {
2038 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
2039 debug("A R/M register operand may not have a SIB byte");
2040 return true;
2041 }
2042
2043 switch (insn.eaBase) {
2044 default:
2045 debug("Unexpected EA base register");
2046 return true;
2047 case EA_BASE_NONE:
2048 debug("EA_BASE_NONE for ModR/M base");
2049 return true;
2050 #define ENTRY(x) case EA_BASE_##x:
2051 ALL_EA_BASES
2052 #undef ENTRY
2053 debug("A R/M register operand may not have a base; "
2054 "the operand must be a register.");
2055 return true;
2056 #define ENTRY(x) \
2057 case EA_REG_##x: \
2058 mcInst.addOperand(MCOperand::createReg(X86::x)); break;
2059 ALL_REGS
2060 #undef ENTRY
2061 }
2062
2063 return false;
2064 }
2065
2066 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
2067 /// fields of an internal instruction (and possibly its SIB byte) to a memory
2068 /// operand in LLVM's format, and appends it to an MCInst.
2069 ///
2070 /// @param mcInst - The MCInst to append to.
2071 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
2072 /// from.
2073 /// @param ForceSIB - The instruction must use SIB.
2074 /// @return - 0 on success; nonzero otherwise
translateRMMemory(MCInst & mcInst,InternalInstruction & insn,const MCDisassembler * Dis,bool ForceSIB=false)2075 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
2076 const MCDisassembler *Dis,
2077 bool ForceSIB = false) {
2078 // Addresses in an MCInst are represented as five operands:
2079 // 1. basereg (register) The R/M base, or (if there is a SIB) the
2080 // SIB base
2081 // 2. scaleamount (immediate) 1, or (if there is a SIB) the specified
2082 // scale amount
2083 // 3. indexreg (register) x86_registerNONE, or (if there is a SIB)
2084 // the index (which is multiplied by the
2085 // scale amount)
2086 // 4. displacement (immediate) 0, or the displacement if there is one
2087 // 5. segmentreg (register) x86_registerNONE for now, but could be set
2088 // if we have segment overrides
2089
2090 MCOperand baseReg;
2091 MCOperand scaleAmount;
2092 MCOperand indexReg;
2093 MCOperand displacement;
2094 MCOperand segmentReg;
2095 uint64_t pcrel = 0;
2096
2097 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
2098 if (insn.sibBase != SIB_BASE_NONE) {
2099 switch (insn.sibBase) {
2100 default:
2101 debug("Unexpected sibBase");
2102 return true;
2103 #define ENTRY(x) \
2104 case SIB_BASE_##x: \
2105 baseReg = MCOperand::createReg(X86::x); break;
2106 ALL_SIB_BASES
2107 #undef ENTRY
2108 }
2109 } else {
2110 baseReg = MCOperand::createReg(X86::NoRegister);
2111 }
2112
2113 if (insn.sibIndex != SIB_INDEX_NONE) {
2114 switch (insn.sibIndex) {
2115 default:
2116 debug("Unexpected sibIndex");
2117 return true;
2118 #define ENTRY(x) \
2119 case SIB_INDEX_##x: \
2120 indexReg = MCOperand::createReg(X86::x); break;
2121 EA_BASES_32BIT
2122 EA_BASES_64BIT
2123 REGS_XMM
2124 REGS_YMM
2125 REGS_ZMM
2126 #undef ENTRY
2127 }
2128 } else {
2129 // Use EIZ/RIZ for a few ambiguous cases where the SIB byte is present,
2130 // but no index is used and modrm alone should have been enough.
2131 // -No base register in 32-bit mode. In 64-bit mode this is used to
2132 // avoid rip-relative addressing.
2133 // -Any base register used other than ESP/RSP/R12D/R12. Using these as a
2134 // base always requires a SIB byte.
2135 // -A scale other than 1 is used.
2136 if (!ForceSIB &&
2137 (insn.sibScale != 1 ||
2138 (insn.sibBase == SIB_BASE_NONE && insn.mode != MODE_64BIT) ||
2139 (insn.sibBase != SIB_BASE_NONE &&
2140 insn.sibBase != SIB_BASE_ESP && insn.sibBase != SIB_BASE_RSP &&
2141 insn.sibBase != SIB_BASE_R12D && insn.sibBase != SIB_BASE_R12))) {
2142 indexReg = MCOperand::createReg(insn.addressSize == 4 ? X86::EIZ :
2143 X86::RIZ);
2144 } else
2145 indexReg = MCOperand::createReg(X86::NoRegister);
2146 }
2147
2148 scaleAmount = MCOperand::createImm(insn.sibScale);
2149 } else {
2150 switch (insn.eaBase) {
2151 case EA_BASE_NONE:
2152 if (insn.eaDisplacement == EA_DISP_NONE) {
2153 debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
2154 return true;
2155 }
2156 if (insn.mode == MODE_64BIT){
2157 pcrel = insn.startLocation + insn.length;
2158 Dis->tryAddingPcLoadReferenceComment(insn.displacement + pcrel,
2159 insn.startLocation +
2160 insn.displacementOffset);
2161 // Section 2.2.1.6
2162 baseReg = MCOperand::createReg(insn.addressSize == 4 ? X86::EIP :
2163 X86::RIP);
2164 }
2165 else
2166 baseReg = MCOperand::createReg(X86::NoRegister);
2167
2168 indexReg = MCOperand::createReg(X86::NoRegister);
2169 break;
2170 case EA_BASE_BX_SI:
2171 baseReg = MCOperand::createReg(X86::BX);
2172 indexReg = MCOperand::createReg(X86::SI);
2173 break;
2174 case EA_BASE_BX_DI:
2175 baseReg = MCOperand::createReg(X86::BX);
2176 indexReg = MCOperand::createReg(X86::DI);
2177 break;
2178 case EA_BASE_BP_SI:
2179 baseReg = MCOperand::createReg(X86::BP);
2180 indexReg = MCOperand::createReg(X86::SI);
2181 break;
2182 case EA_BASE_BP_DI:
2183 baseReg = MCOperand::createReg(X86::BP);
2184 indexReg = MCOperand::createReg(X86::DI);
2185 break;
2186 default:
2187 indexReg = MCOperand::createReg(X86::NoRegister);
2188 switch (insn.eaBase) {
2189 default:
2190 debug("Unexpected eaBase");
2191 return true;
2192 // Here, we will use the fill-ins defined above. However,
2193 // BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
2194 // sib and sib64 were handled in the top-level if, so they're only
2195 // placeholders to keep the compiler happy.
2196 #define ENTRY(x) \
2197 case EA_BASE_##x: \
2198 baseReg = MCOperand::createReg(X86::x); break;
2199 ALL_EA_BASES
2200 #undef ENTRY
2201 #define ENTRY(x) case EA_REG_##x:
2202 ALL_REGS
2203 #undef ENTRY
2204 debug("A R/M memory operand may not be a register; "
2205 "the base field must be a base.");
2206 return true;
2207 }
2208 }
2209
2210 scaleAmount = MCOperand::createImm(1);
2211 }
2212
2213 displacement = MCOperand::createImm(insn.displacement);
2214
2215 segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
2216
2217 mcInst.addOperand(baseReg);
2218 mcInst.addOperand(scaleAmount);
2219 mcInst.addOperand(indexReg);
2220
2221 const uint8_t dispSize =
2222 (insn.eaDisplacement == EA_DISP_NONE) ? 0 : insn.displacementSize;
2223
2224 if (!Dis->tryAddingSymbolicOperand(
2225 mcInst, insn.displacement + pcrel, insn.startLocation, false,
2226 insn.displacementOffset, dispSize, insn.length))
2227 mcInst.addOperand(displacement);
2228 mcInst.addOperand(segmentReg);
2229 return false;
2230 }
2231
2232 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
2233 /// byte of an instruction to LLVM form, and appends it to an MCInst.
2234 ///
2235 /// @param mcInst - The MCInst to append to.
2236 /// @param operand - The operand, as stored in the descriptor table.
2237 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
2238 /// from.
2239 /// @return - 0 on success; nonzero otherwise
translateRM(MCInst & mcInst,const OperandSpecifier & operand,InternalInstruction & insn,const MCDisassembler * Dis)2240 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
2241 InternalInstruction &insn, const MCDisassembler *Dis) {
2242 switch (operand.type) {
2243 default:
2244 debug("Unexpected type for a R/M operand");
2245 return true;
2246 case TYPE_R8:
2247 case TYPE_R16:
2248 case TYPE_R32:
2249 case TYPE_R64:
2250 case TYPE_Rv:
2251 case TYPE_MM64:
2252 case TYPE_XMM:
2253 case TYPE_YMM:
2254 case TYPE_ZMM:
2255 case TYPE_TMM:
2256 case TYPE_VK_PAIR:
2257 case TYPE_VK:
2258 case TYPE_DEBUGREG:
2259 case TYPE_CONTROLREG:
2260 case TYPE_BNDR:
2261 return translateRMRegister(mcInst, insn);
2262 case TYPE_M:
2263 case TYPE_MVSIBX:
2264 case TYPE_MVSIBY:
2265 case TYPE_MVSIBZ:
2266 return translateRMMemory(mcInst, insn, Dis);
2267 case TYPE_MSIB:
2268 return translateRMMemory(mcInst, insn, Dis, true);
2269 }
2270 }
2271
2272 /// translateFPRegister - Translates a stack position on the FPU stack to its
2273 /// LLVM form, and appends it to an MCInst.
2274 ///
2275 /// @param mcInst - The MCInst to append to.
2276 /// @param stackPos - The stack position to translate.
translateFPRegister(MCInst & mcInst,uint8_t stackPos)2277 static void translateFPRegister(MCInst &mcInst,
2278 uint8_t stackPos) {
2279 mcInst.addOperand(MCOperand::createReg(X86::ST0 + stackPos));
2280 }
2281
2282 /// translateMaskRegister - Translates a 3-bit mask register number to
2283 /// LLVM form, and appends it to an MCInst.
2284 ///
2285 /// @param mcInst - The MCInst to append to.
2286 /// @param maskRegNum - Number of mask register from 0 to 7.
2287 /// @return - false on success; true otherwise.
translateMaskRegister(MCInst & mcInst,uint8_t maskRegNum)2288 static bool translateMaskRegister(MCInst &mcInst,
2289 uint8_t maskRegNum) {
2290 if (maskRegNum >= 8) {
2291 debug("Invalid mask register number");
2292 return true;
2293 }
2294
2295 mcInst.addOperand(MCOperand::createReg(X86::K0 + maskRegNum));
2296 return false;
2297 }
2298
2299 /// translateOperand - Translates an operand stored in an internal instruction
2300 /// to LLVM's format and appends it to an MCInst.
2301 ///
2302 /// @param mcInst - The MCInst to append to.
2303 /// @param operand - The operand, as stored in the descriptor table.
2304 /// @param insn - The internal instruction.
2305 /// @return - false on success; true otherwise.
translateOperand(MCInst & mcInst,const OperandSpecifier & operand,InternalInstruction & insn,const MCDisassembler * Dis)2306 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
2307 InternalInstruction &insn,
2308 const MCDisassembler *Dis) {
2309 switch (operand.encoding) {
2310 default:
2311 debug("Unhandled operand encoding during translation");
2312 return true;
2313 case ENCODING_REG:
2314 translateRegister(mcInst, insn.reg);
2315 return false;
2316 case ENCODING_WRITEMASK:
2317 return translateMaskRegister(mcInst, insn.writemask);
2318 case ENCODING_SIB:
2319 CASE_ENCODING_RM:
2320 CASE_ENCODING_VSIB:
2321 return translateRM(mcInst, operand, insn, Dis);
2322 case ENCODING_IB:
2323 case ENCODING_IW:
2324 case ENCODING_ID:
2325 case ENCODING_IO:
2326 case ENCODING_Iv:
2327 case ENCODING_Ia:
2328 translateImmediate(mcInst,
2329 insn.immediates[insn.numImmediatesTranslated++],
2330 operand,
2331 insn,
2332 Dis);
2333 return false;
2334 case ENCODING_IRC:
2335 mcInst.addOperand(MCOperand::createImm(insn.RC));
2336 return false;
2337 case ENCODING_SI:
2338 return translateSrcIndex(mcInst, insn);
2339 case ENCODING_DI:
2340 return translateDstIndex(mcInst, insn);
2341 case ENCODING_RB:
2342 case ENCODING_RW:
2343 case ENCODING_RD:
2344 case ENCODING_RO:
2345 case ENCODING_Rv:
2346 translateRegister(mcInst, insn.opcodeRegister);
2347 return false;
2348 case ENCODING_CC:
2349 mcInst.addOperand(MCOperand::createImm(insn.immediates[1]));
2350 return false;
2351 case ENCODING_FP:
2352 translateFPRegister(mcInst, insn.modRM & 7);
2353 return false;
2354 case ENCODING_VVVV:
2355 translateRegister(mcInst, insn.vvvv);
2356 return false;
2357 case ENCODING_DUP:
2358 return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
2359 insn, Dis);
2360 }
2361 }
2362
2363 /// translateInstruction - Translates an internal instruction and all its
2364 /// operands to an MCInst.
2365 ///
2366 /// @param mcInst - The MCInst to populate with the instruction's data.
2367 /// @param insn - The internal instruction.
2368 /// @return - false on success; true otherwise.
translateInstruction(MCInst & mcInst,InternalInstruction & insn,const MCDisassembler * Dis)2369 static bool translateInstruction(MCInst &mcInst,
2370 InternalInstruction &insn,
2371 const MCDisassembler *Dis) {
2372 if (!insn.spec) {
2373 debug("Instruction has no specification");
2374 return true;
2375 }
2376
2377 mcInst.clear();
2378 mcInst.setOpcode(insn.instructionID);
2379 // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
2380 // prefix bytes should be disassembled as xrelease and xacquire then set the
2381 // opcode to those instead of the rep and repne opcodes.
2382 if (insn.xAcquireRelease) {
2383 if(mcInst.getOpcode() == X86::REP_PREFIX)
2384 mcInst.setOpcode(X86::XRELEASE_PREFIX);
2385 else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
2386 mcInst.setOpcode(X86::XACQUIRE_PREFIX);
2387 }
2388
2389 insn.numImmediatesTranslated = 0;
2390
2391 for (const auto &Op : insn.operands) {
2392 if (Op.encoding != ENCODING_NONE) {
2393 if (translateOperand(mcInst, Op, insn, Dis)) {
2394 return true;
2395 }
2396 }
2397 }
2398
2399 return false;
2400 }
2401
createX86Disassembler(const Target & T,const MCSubtargetInfo & STI,MCContext & Ctx)2402 static MCDisassembler *createX86Disassembler(const Target &T,
2403 const MCSubtargetInfo &STI,
2404 MCContext &Ctx) {
2405 std::unique_ptr<const MCInstrInfo> MII(T.createMCInstrInfo());
2406 return new X86GenericDisassembler(STI, Ctx, std::move(MII));
2407 }
2408
LLVMInitializeX86Disassembler()2409 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeX86Disassembler() {
2410 // Register the disassembler.
2411 TargetRegistry::RegisterMCDisassembler(getTheX86_32Target(),
2412 createX86Disassembler);
2413 TargetRegistry::RegisterMCDisassembler(getTheX86_64Target(),
2414 createX86Disassembler);
2415 }
2416