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