Fixed merge issue
[dyninst.git] / instructionAPI / src / InstructionDecoder-x86.C
1 /*
2  * See the dyninst/COPYRIGHT file for copyright information.
3  * 
4  * We provide the Paradyn Tools (below described as "Paradyn")
5  * on an AS IS basis, and do not warrant its validity or performance.
6  * We reserve the right to update, modify, or discontinue this
7  * software at any time.  We shall have no obligation to supply such
8  * updates or modifications or any other form of support to you.
9  * 
10  * By your use of Paradyn, you understand and agree that we (or any
11  * other person or entity with proprietary rights in Paradyn) are
12  * under no obligation to provide either maintenance services,
13  * update services, notices of latent defects, or correction of
14  * defects for Paradyn.
15  * 
16  * This library is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU Lesser General Public
18  * License as published by the Free Software Foundation; either
19  * version 2.1 of the License, or (at your option) any later version.
20  * 
21  * This library is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24  * Lesser General Public License for more details.
25  * 
26  * You should have received a copy of the GNU Lesser General Public
27  * License along with this library; if not, write to the Free Software
28  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29  */
30
31 #define INSIDE_INSTRUCTION_API
32
33 #include "common/src/Types.h"
34 #include "InstructionDecoder-x86.h"
35 #include "Expression.h"
36 #include "common/src/arch-x86.h"
37 #include "Register.h"
38 #include "Dereference.h"
39 #include "Immediate.h" 
40 #include "BinaryFunction.h"
41 #include "common/src/singleton_object_pool.h"
42
43 // #define VEX_DEBUG
44
45 using namespace std;
46 using namespace NS_x86;
47 namespace Dyninst
48 {
49     namespace InstructionAPI
50     {
51     
52         bool readsOperand(unsigned int opsema, unsigned int i)
53         {
54             switch(opsema) {
55                 case s1R2R:
56                     return (i == 0 || i == 1);
57                 case s1R:
58                 case s1RW:
59                     return i == 0;
60                 case s1W:
61                     return false;
62                 case s1W2RW:
63                 case s1W2R:   // second operand read, first operand written (e.g. mov)
64                     return i == 1;
65                 case s1RW2R:  // two operands read, first written (e.g. add)
66                 case s1RW2RW: // e.g. xchg
67                 case s1R2RW:
68                     return i == 0 || i == 1;
69                 case s1W2R3R: // e.g. imul
70                 case s1W2RW3R: // some mul
71                 case s1W2R3RW: // (stack) push & pop
72                     return i == 1 || i == 2;
73                 case s1W2W3R: // e.g. les
74                     return i == 2;
75                 case s1RW2R3RW:
76                 case s1RW2R3R: // shld/shrd
77                 case s1RW2RW3R: // [i]div, cmpxch8b
78                 case s1R2R3R:
79                     return i == 0 || i == 1 || i == 2;
80                 case s1W2R3R4R:
81                     return i == 1 || i == 2 || i == 3;
82                 case s1RW2R3R4R:
83                     return i == 0 || i == 1 || i == 2 || i == 3;
84                 case sNONE:
85                 default:
86                     return false;
87             }
88       
89         }
90       
91         bool writesOperand(unsigned int opsema, unsigned int i)
92         {
93             switch(opsema) {
94                 case s1R2R:
95                 case s1R:
96                     return false;
97                 case s1RW:
98                 case s1W:
99                 case s1W2R:   // second operand read, first operand written (e.g. mov)
100                 case s1RW2R:  // two operands read, first written (e.g. add)
101                 case s1W2R3R: // e.g. imul
102                 case s1RW2R3R: // shld/shrd
103                 case s1RW2R3R4R:
104                   return i == 0;
105                 case s1R2RW:
106                   return i == 1;
107                 case s1W2RW:
108                 case s1RW2RW: // e.g. xchg
109                 case s1W2RW3R: // some mul
110                 case s1W2W3R: // e.g. les
111                 case s1RW2RW3R: // [i]div, cmpxch8b
112                   return i == 0 || i == 1;
113                 case s1W2R3RW: // (stack) push & pop
114                   return i == 0 || i == 2;
115                 case s1RW2R3RW:
116                   return i == 0 || i == 2;
117                 case sNONE:
118                 default:
119                     return false;
120             }
121         }
122
123
124     __thread NS_x86::ia32_instruction* InstructionDecoder_x86::decodedInstruction = NULL;
125     __thread ia32_locations* InstructionDecoder_x86::locs = NULL;
126     __thread bool InstructionDecoder_x86::sizePrefixPresent = false;
127     __thread bool InstructionDecoder_x86::addrSizePrefixPresent = false;
128     INSTRUCTION_EXPORT InstructionDecoder_x86::InstructionDecoder_x86(Architecture a) :
129       InstructionDecoderImpl(a)
130     {
131       if(a == Arch_x86_64) setMode(true);
132       
133     }
134     INSTRUCTION_EXPORT InstructionDecoder_x86::~InstructionDecoder_x86()
135     {
136
137     }
138     static const unsigned char modrm_use_sib = 4;
139     
140     INSTRUCTION_EXPORT void InstructionDecoder_x86::setMode(bool is64)
141     {
142         ia32_set_mode_64(is64);
143     }
144     
145       Expression::Ptr InstructionDecoder_x86::makeSIBExpression(const InstructionDecoder::buffer& b)
146     {
147         unsigned scale;
148         Register index;
149         Register base;
150         Result_Type registerType = ia32_is_mode_64() ? u64 : u32;
151
152         int op_type = ia32_is_mode_64() ? op_q : op_d;
153         decode_SIB(locs->sib_byte, scale, index, base);
154
155         Expression::Ptr scaleAST(make_shared(singleton_object_pool<Immediate>::construct(Result(u8, dword_t(scale)))));
156         Expression::Ptr indexAST(make_shared(singleton_object_pool<RegisterAST>::construct(makeRegisterID(index, op_type,
157                                     locs->rex_x))));
158         Expression::Ptr baseAST;
159         if(base == 0x05)
160         {
161             switch(locs->modrm_mod)
162             {
163                 case 0x00:
164                     baseAST = decodeImmediate(op_d, b.start + locs->sib_position + 1, true);
165                     break;
166                 case 0x01: 
167                 case 0x02: 
168                     baseAST = make_shared(singleton_object_pool<RegisterAST>::construct(makeRegisterID(base, 
169                                                                                                op_type,
170                                                                                                locs->rex_b)));
171                     break;
172                 case 0x03:
173                 default:
174                     assert(0);
175                     break;
176             };
177         }
178         else
179         {
180             baseAST = make_shared(singleton_object_pool<RegisterAST>::construct(makeRegisterID(base, 
181                                                                                                op_type,
182                                                                                                locs->rex_b)));
183         }
184
185         if(index == 0x04 && (!(ia32_is_mode_64()) || !(locs->rex_x)))
186         {
187             return baseAST;
188         }
189         return makeAddExpression(baseAST, makeMultiplyExpression(indexAST, scaleAST, registerType), registerType);
190     }
191
192       Expression::Ptr InstructionDecoder_x86::makeModRMExpression(const InstructionDecoder::buffer& b,
193                                                                   unsigned int opType)
194     {
195        unsigned int regType = op_d;
196        Result_Type aw;
197        if(ia32_is_mode_64())
198        {
199            if(addrSizePrefixPresent) {
200                aw = u32;
201            } else {
202                aw = u64;
203                regType = op_q;
204            }
205        }
206        else
207        {
208            if(!addrSizePrefixPresent) {
209                aw = u32;
210            } else {
211                aw = u16;
212                regType = op_w;
213            }
214        }
215         if (opType == op_lea) {
216             // For an LEA, aw (address width) is insufficient, use makeSizeType
217             aw = makeSizeType(opType);
218         }
219         Expression::Ptr e =
220             makeRegisterExpression(makeRegisterID(locs->modrm_rm, regType, locs->rex_b));
221         switch(locs->modrm_mod)
222         {
223             case 0:
224                 if(locs->modrm_rm == modrm_use_sib) {
225                     e = makeSIBExpression(b);
226                 }
227                 if(locs->modrm_rm == 0x5 && !addrSizePrefixPresent)
228                 {
229                     assert(locs->opcode_position > -1);
230                     if(ia32_is_mode_64())
231                     {
232                         e = makeAddExpression(makeRegisterExpression(x86_64::rip),
233                                             getModRMDisplacement(b), aw);
234                     }
235                     else
236                     {
237                         e = getModRMDisplacement(b);
238                     }
239         
240                 }
241                 if(locs->modrm_rm == 0x6 && addrSizePrefixPresent)
242                 {
243                     e = getModRMDisplacement(b);
244                 }
245                 if(opType == op_lea)
246                 {
247                     return e;
248                 }
249                 return makeDereferenceExpression(e, makeSizeType(opType));
250                 assert(0);
251                 break;
252             case 1:
253             case 2:
254             {
255                 if(locs->modrm_rm == modrm_use_sib) {
256                     e = makeSIBExpression(b);
257                 }
258                 Expression::Ptr disp_e = makeAddExpression(e, getModRMDisplacement(b), aw);
259                 if(opType == op_lea)
260                 {
261                     return disp_e;
262                 }
263                 return makeDereferenceExpression(disp_e, makeSizeType(opType));
264             }
265             assert(0);
266             break;
267             case 3:
268                 return makeRegisterExpression(makeRegisterID(locs->modrm_rm, opType, locs->rex_b));
269             default:
270                 return Expression::Ptr();
271         
272         };
273         // can't get here, but make the compiler happy...
274         assert(0);
275         return Expression::Ptr();
276     }
277
278     Expression::Ptr InstructionDecoder_x86::decodeImmediate(unsigned int opType, const unsigned char* immStart, 
279                                                             bool isSigned)
280     {
281         // rex_w indicates we need to sign-extend also.
282         isSigned = isSigned || locs->rex_w;
283         
284         switch(opType)
285         {
286             case op_b:
287                 return Immediate::makeImmediate(Result(isSigned ? s8 : u8 ,*(const byte_t*)(immStart)));
288                 break;
289             case op_d:
290                 return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
291             case op_w:
292                 return Immediate::makeImmediate(Result(isSigned ? s16 : u16,*(const word_t*)(immStart)));
293                 break;
294             case op_q:
295                 return Immediate::makeImmediate(Result(isSigned ? s64 : u64,*(const int64_t*)(immStart)));
296                 break;
297             case op_v:
298                 if (locs->rex_w || isDefault64Insn()) {
299                     return Immediate::makeImmediate(Result(isSigned ? s64 : u64,*(const int64_t*)(immStart)));
300                 }
301                 //if(!sizePrefixPresent)
302                 //{
303                     return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
304                     //}
305                     //else
306                     //{
307                     //return Immediate::makeImmediate(Result(isSigned ? s16 : u16,*(const word_t*)(immStart)));
308                     //}
309                 break;
310             case op_z:
311                 // 32 bit mode & no prefix, or 16 bit mode & prefix => 32 bit
312                 // 16 bit mode, no prefix or 32 bit mode, prefix => 16 bit
313                 //if(!addrSizePrefixPresent)
314                 //{
315                     return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
316                     //}
317                     //else
318                     //{
319                     //return Immediate::makeImmediate(Result(isSigned ? s16 : u16,*(const word_t*)(immStart)));
320                     //}
321                 break;
322             case op_p:
323                 // 32 bit mode & no prefix, or 16 bit mode & prefix => 48 bit
324                 // 16 bit mode, no prefix or 32 bit mode, prefix => 32 bit
325                 if(!sizePrefixPresent)
326                 {
327                     return Immediate::makeImmediate(Result(isSigned ? s48 : u48,*(const int64_t*)(immStart)));
328                 }
329                 else
330                 {
331                     return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
332                 }
333
334                 break;
335             case op_a:
336             case op_dq:
337             case op_pd:
338             case op_ps:
339             case op_s:
340             case op_si:
341             case op_lea:
342             case op_allgprs:
343             case op_512:
344             case op_c:
345                 assert(!"Can't happen: opType unexpected for valid ways to decode an immediate");
346                 return Expression::Ptr();
347             default:
348                 assert(!"Can't happen: opType out of range");
349                 return Expression::Ptr();
350         }
351     }
352     
353     Expression::Ptr InstructionDecoder_x86::getModRMDisplacement(const InstructionDecoder::buffer& b)
354     {
355         int disp_pos;
356
357         if(locs->sib_position != -1)
358         {
359             disp_pos = locs->sib_position + 1;
360         }
361         else
362         {
363             disp_pos = locs->modrm_position + 1;
364         }
365         switch(locs->modrm_mod)
366         {
367             case 1:
368                 return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, (*(const byte_t*)(b.start +
369                         disp_pos)))));
370                 break;
371             case 2:
372                 if(0 && sizePrefixPresent)
373                 {
374                     return make_shared(singleton_object_pool<Immediate>::construct(Result(s16, *((const word_t*)(b.start +
375                             disp_pos)))));
376                 }
377                 else
378                 {
379                     return make_shared(singleton_object_pool<Immediate>::construct(Result(s32, *((const dword_t*)(b.start +
380                             disp_pos)))));
381                 }
382                 break;
383             case 0:
384                 // In 16-bit mode, the word displacement is modrm r/m 6
385                 if(sizePrefixPresent && !ia32_is_mode_64())
386                 {
387                     if(locs->modrm_rm == 6)
388                     {
389                         return make_shared(singleton_object_pool<Immediate>::construct(Result(s16,
390                                            *((const dword_t*)(b.start + disp_pos)))));
391                     }
392                     // TODO FIXME; this was decoding wrong, but I'm not sure
393                     // why...
394                     else if (locs->modrm_rm == 5) {
395                         assert(b.start + disp_pos + 4 <= b.end);
396                         return make_shared(singleton_object_pool<Immediate>::construct(Result(s32,
397                                            *((const dword_t*)(b.start + disp_pos)))));
398                     } else {
399                         assert(b.start + disp_pos + 1 <= b.end);
400                         return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, 0)));
401                     }
402                     break;
403                 }
404                 // ...and in 32-bit mode, the dword displacement is modrm r/m 5
405                 else
406                 {
407                     if(locs->modrm_rm == 5)
408                     {
409                         if (b.start + disp_pos + 4 <= b.end) 
410                             return make_shared(singleton_object_pool<Immediate>::construct(Result(s32,
411                                                *((const dword_t*)(b.start + disp_pos)))));
412                         else
413                             return make_shared(singleton_object_pool<Immediate>::construct(Result()));
414                     }
415                     else
416                     {
417                         if (b.start + disp_pos + 1 <= b.end)
418                             return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, 0)));
419                         else
420                             return make_shared(singleton_object_pool<Immediate>::construct(Result()));
421                     }
422                     break;
423                 }
424             default:
425                 assert(b.start + disp_pos + 1 <= b.end);
426                 return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, 0)));
427                 break;
428         }
429     }
430
431     enum intelRegBanks
432     {
433         b_8bitNoREX = 0,
434         b_16bit,
435         b_32bit,
436         b_segment,
437         b_64bit,
438         b_xmm_set0, /* XMM0 -> XMM 7 */
439         b_xmm_set1, /* XMM8 -> XMM 15 */
440         b_xmm_set2, /* XMM16 -> XMM 23 */
441         b_xmm_set3, /* XMM24 -> XMM 31 */
442         b_ymm_set0, /* YMM0 -> YMM 7 */
443         b_ymm_set1, /* YMM8 -> YMM 15 */
444         b_ymm_set2, /* YMM16 -> YMM 23 */
445         b_ymm_set3, /* YMM24 -> YMM 31 */
446         b_zmm_set0, /* ZMM0 -> ZMM 7 */
447         b_zmm_set1, /* ZMM8 -> ZMM 15 */
448         b_zmm_set2, /* ZMM16 -> ZMM 23 */
449         b_zmm_set3, /* ZMM24 -> ZMM 31 */
450         b_mm,
451         b_cr,
452         b_dr,
453         b_tr,
454         b_amd64ext,
455         b_8bitWithREX,
456         b_fpstack,
457             amd64_ext_8,
458             amd64_ext_16,
459             amd64_ext_32,
460
461         b_invalid /* should remain the final entry */
462     };
463
464     static MachRegister IntelRegTable32[][8] = {
465         { x86::al, x86::cl, x86::dl, x86::bl, x86::ah, x86::ch, x86::dh, x86::bh }, /* b_8bitNoREX */
466         { x86::ax, x86::cx, x86::dx, x86::bx, x86::sp, x86::bp, x86::si, x86::di }, /* b_16bit */
467         { x86::eax, x86::ecx, x86::edx, x86::ebx, x86::esp, x86::ebp, x86::esi, x86::edi }, /* b_32bit */
468         { x86::es, x86::cs, x86::ss, x86::ds, x86::fs, x86::gs, InvalidReg, InvalidReg }, /* b_segment */
469         { x86_64::rax, x86_64::rcx, x86_64::rdx, x86_64::rbx, x86_64::rsp, x86_64::rbp, x86_64::rsi, x86_64::rdi }, /* b_64bit */
470         { x86::xmm0, x86::xmm1, x86::xmm2, x86::xmm3, x86::xmm4, x86::xmm5, x86::xmm6, x86::xmm7 }, /* b_xmm_set0 */
471         { x86_64::xmm8, x86_64::xmm9, x86_64::xmm10, x86_64::xmm11, x86_64::xmm12, x86_64::xmm13, x86_64::xmm14, x86_64::xmm15 }, /* b_xmm_set1 */
472         { x86_64::xmm16, x86_64::xmm17, x86_64::xmm18, x86_64::xmm19, x86_64::xmm20, x86_64::xmm21, x86_64::xmm22, x86_64::xmm23 }, /* b_xmm_set2 */
473         { x86_64::xmm24, x86_64::xmm25, x86_64::xmm26, x86_64::xmm27, x86_64::xmm28, x86_64::xmm29, x86_64::xmm30, x86_64::xmm31 }, /* b_xmm_set3 */
474         { x86_64::ymm0, x86_64::ymm1, x86_64::ymm2, x86_64::ymm3, x86_64::ymm4, x86_64::ymm5, x86_64::ymm6, x86_64::ymm7 }, /* b_ymm_set0 */
475         { x86_64::ymm8, x86_64::ymm9, x86_64::ymm10, x86_64::ymm11, x86_64::ymm12, x86_64::ymm13, x86_64::ymm14, x86_64::ymm15 }, /* b_ymm_set1 */
476         { x86_64::ymm16, x86_64::ymm17, x86_64::ymm18, x86_64::ymm19, x86_64::ymm20, x86_64::ymm21, x86_64::ymm22, x86_64::ymm23 }, /* b_ymm_set2 */
477         { x86_64::ymm24, x86_64::ymm25, x86_64::ymm26, x86_64::ymm27, x86_64::ymm28, x86_64::ymm29, x86_64::ymm30, x86_64::ymm31 }, /* b_ymm_set3 */
478         { x86_64::zmm0, x86_64::zmm1, x86_64::zmm2, x86_64::zmm3, x86_64::zmm4, x86_64::zmm5, x86_64::zmm6, x86_64::zmm7 }, /* b_zmm_set0 */
479         { x86_64::zmm8, x86_64::zmm9, x86_64::zmm10, x86_64::zmm11, x86_64::zmm12, x86_64::zmm13, x86_64::zmm14, x86_64::zmm15 }, /* b_zmm_set1 */
480         { x86_64::zmm16, x86_64::zmm17, x86_64::zmm18, x86_64::zmm19, x86_64::zmm20, x86_64::zmm21, x86_64::zmm22, x86_64::zmm23 }, /* b_zmm_set2 */
481         { x86_64::zmm24, x86_64::zmm25, x86_64::zmm26, x86_64::zmm27, x86_64::zmm28, x86_64::zmm29, x86_64::zmm30, x86_64::zmm31 }, /* b_zmm_set3 */
482         { x86::mm0, x86::mm1, x86::mm2, x86::mm3, x86::mm4, x86::mm5, x86::mm6, x86::mm7 },
483         { x86::cr0, x86::cr1, x86::cr2, x86::cr3, x86::cr4, x86::cr5, x86::cr6, x86::cr7 },
484         { x86::dr0, x86::dr1, x86::dr2, x86::dr3, x86::dr4, x86::dr5, x86::dr6, x86::dr7 },
485         { x86::tr0, x86::tr1, x86::tr2, x86::tr3, x86::tr4, x86::tr5, x86::tr6, x86::tr7 },
486         { x86_64::r8, x86_64::r9, x86_64::r10, x86_64::r11, x86_64::r12, x86_64::r13, x86_64::r14, x86_64::r15 },
487         { x86_64::al, x86_64::cl, x86_64::dl, x86_64::bl, x86_64::spl, x86_64::bpl, x86_64::sil, x86_64::dil },
488         { x86::st0, x86::st1, x86::st2, x86::st3, x86::st4, x86::st5, x86::st6, x86::st7 }
489     };
490
491     static MachRegister IntelRegTable64[][8] = {
492         { x86_64::al, x86_64::cl, x86_64::dl, x86_64::bl, x86_64::ah, x86_64::ch, x86_64::dh, x86_64::bh },
493         { x86_64::ax, x86_64::cx, x86_64::dx, x86_64::bx, x86_64::sp, x86_64::bp, x86_64::si, x86_64::di },
494         { x86_64::eax, x86_64::ecx, x86_64::edx, x86_64::ebx, x86_64::esp, x86_64::ebp, x86_64::esi, x86_64::edi },
495         { x86_64::es, x86_64::cs, x86_64::ss, x86_64::ds, x86_64::fs, x86_64::gs, InvalidReg, InvalidReg },
496         { x86_64::rax, x86_64::rcx, x86_64::rdx, x86_64::rbx, x86_64::rsp, x86_64::rbp, x86_64::rsi, x86_64::rdi },
497         { x86_64::xmm0, x86_64::xmm1, x86_64::xmm2, x86_64::xmm3, x86_64::xmm4, x86_64::xmm5, x86_64::xmm6, x86_64::xmm7 }, /* b_xmm_set0 */
498         { x86_64::xmm8, x86_64::xmm9, x86_64::xmm10, x86_64::xmm11, x86_64::xmm12, x86_64::xmm13, x86_64::xmm14, x86_64::xmm15 }, /* b_xmm_set1 */
499         { x86_64::xmm16, x86_64::xmm17, x86_64::xmm18, x86_64::xmm19, x86_64::xmm20, x86_64::xmm21, x86_64::xmm22, x86_64::xmm23 }, /* b_xmm_set2 */
500         { x86_64::xmm24, x86_64::xmm25, x86_64::xmm26, x86_64::xmm27, x86_64::xmm28, x86_64::xmm29, x86_64::xmm30, x86_64::xmm31 }, /* b_xmm_set3 */
501         { x86_64::ymm0, x86_64::ymm1, x86_64::ymm2, x86_64::ymm3, x86_64::ymm4, x86_64::ymm5, x86_64::ymm6, x86_64::ymm7 }, /* b_ymm_set0 */
502         { x86_64::ymm8, x86_64::ymm9, x86_64::ymm10, x86_64::ymm11, x86_64::ymm12, x86_64::ymm13, x86_64::ymm14, x86_64::ymm15 }, /* b_ymm_set1 */
503         { x86_64::ymm16, x86_64::ymm17, x86_64::ymm18, x86_64::ymm19, x86_64::ymm20, x86_64::ymm21, x86_64::ymm22, x86_64::ymm23 }, /* b_ymm_set2 */
504         { x86_64::ymm24, x86_64::ymm25, x86_64::ymm26, x86_64::ymm27, x86_64::ymm28, x86_64::ymm29, x86_64::ymm30, x86_64::ymm31 }, /* b_ymm_set3 */
505         { x86_64::zmm0, x86_64::zmm1, x86_64::zmm2, x86_64::zmm3, x86_64::zmm4, x86_64::zmm5, x86_64::zmm6, x86_64::zmm7 }, /* b_zmm_set0 */
506         { x86_64::zmm8, x86_64::zmm9, x86_64::zmm10, x86_64::zmm11, x86_64::zmm12, x86_64::zmm13, x86_64::zmm14, x86_64::zmm15 }, /* b_zmm_set1 */
507         { x86_64::zmm16, x86_64::zmm17, x86_64::zmm18, x86_64::zmm19, x86_64::zmm20, x86_64::zmm21, x86_64::zmm22, x86_64::zmm23 }, /* b_zmm_set2 */
508         { x86_64::zmm24, x86_64::zmm25, x86_64::zmm26, x86_64::zmm27, x86_64::zmm28, x86_64::zmm29, x86_64::zmm30, x86_64::zmm31 }, /* b_zmm_set3 */
509         { x86_64::mm0, x86_64::mm1, x86_64::mm2, x86_64::mm3, x86_64::mm4, x86_64::mm5, x86_64::mm6, x86_64::mm7 },
510         { x86_64::cr0, x86_64::cr1, x86_64::cr2, x86_64::cr3, x86_64::cr4, x86_64::cr5, x86_64::cr6, x86_64::cr7 },
511         { x86_64::dr0, x86_64::dr1, x86_64::dr2, x86_64::dr3, x86_64::dr4, x86_64::dr5, x86_64::dr6, x86_64::dr7 },
512         { x86_64::tr0, x86_64::tr1, x86_64::tr2, x86_64::tr3, x86_64::tr4, x86_64::tr5, x86_64::tr6, x86_64::tr7 },
513         { x86_64::r8, x86_64::r9, x86_64::r10, x86_64::r11, x86_64::r12, x86_64::r13, x86_64::r14, x86_64::r15 },
514         { x86_64::al, x86_64::cl, x86_64::dl, x86_64::bl, x86_64::spl, x86_64::bpl, x86_64::sil, x86_64::dil },
515         { x86_64::st0, x86_64::st1, x86_64::st2, x86_64::st3, x86_64::st4, x86_64::st5, x86_64::st6, x86_64::st7 },
516             { x86_64::r8b, x86_64::r9b, x86_64::r10b, x86_64::r11b, x86_64::r12b, x86_64::r13b, x86_64::r14b, x86_64::r15b },
517             { x86_64::r8w, x86_64::r9w, x86_64::r10w, x86_64::r11w, x86_64::r12w, x86_64::r13w, x86_64::r14w, x86_64::r15w },
518             { x86_64::r8d, x86_64::r9d, x86_64::r10d, x86_64::r11d, x86_64::r12d, x86_64::r13d, x86_64::r14d, x86_64::r15d },
519     };
520
521   /* Uses the appropriate lookup table based on the 
522      decoder architecture */
523   class IntelRegTable_access {
524     public:
525         inline MachRegister operator()(Architecture arch,
526                                        intelRegBanks bank,
527                                        int index)
528         {
529             assert(index >= 0 && index < 8);
530     
531             if(arch == Arch_x86_64)
532                 return IntelRegTable64[bank][index];
533             else if(arch == Arch_x86) 
534             {
535               if(bank > b_fpstack) return InvalidReg;
536               return IntelRegTable32[bank][index];
537             }
538             assert(0);
539             return InvalidReg;
540         }
541
542   };
543   static IntelRegTable_access IntelRegTable;
544
545       bool InstructionDecoder_x86::isDefault64Insn()
546       {
547         switch(m_Operation->getID())
548         {
549         case e_jmp:
550         case e_pop:
551         case e_push:
552         case e_call:
553           return true;
554         default:
555           return false;
556         }
557         
558       }
559       
560
561     MachRegister InstructionDecoder_x86::makeRegisterID(unsigned int intelReg, unsigned int opType,
562                                         bool isExtendedReg)
563     {
564         MachRegister retVal;
565         
566
567         if(isExtendedReg)
568         {
569             switch(opType)
570             {
571                 case op_q:  
572                     retVal = IntelRegTable(m_Arch,b_amd64ext,intelReg);
573                     break;
574                 case op_d:
575                     retVal = IntelRegTable(m_Arch,amd64_ext_32,intelReg);
576                     break;
577                 case op_w:
578                     retVal = IntelRegTable(m_Arch,amd64_ext_16,intelReg);
579                     break;
580                 case op_b:
581                     retVal = IntelRegTable(m_Arch,amd64_ext_8,intelReg);
582                     break;
583                 case op_v:
584                     if (locs->rex_w || isDefault64Insn())
585                         retVal = IntelRegTable(m_Arch, b_amd64ext, intelReg);
586                     else if (!sizePrefixPresent)
587                         retVal = IntelRegTable(m_Arch, amd64_ext_32, intelReg);
588                     //else
589                     //    retVal = IntelRegTable(m_Arch, amd64_ext_16, intelReg);
590                     break;      
591                 case op_p:
592                 case op_z:
593                     //              if (!sizePrefixPresent)
594                         retVal = IntelRegTable(m_Arch, amd64_ext_32, intelReg);
595                         //                  else
596                         //  retVal = IntelRegTable(m_Arch, amd64_ext_16, intelReg);
597                     break;
598             case op_f:
599             case op_dbl:
600                 // extended reg ignored on FP regs
601                 retVal = IntelRegTable(m_Arch, b_fpstack,intelReg);
602                 break;
603                 default:
604                     retVal = InvalidReg;
605             }
606         }
607         /* Promotion to 64-bit only applies to the operand types
608            that are varible (c,v,z). Ignoring c and z because they
609            do the right thing on 32- and 64-bit code.
610         else if(locs->rex_w)
611         {
612             // AMD64 with 64-bit operands
613             retVal = IntelRegTable[b_64bit][intelReg];
614         }
615         */
616         else
617         {
618             switch(opType)
619             {
620                 case op_v:
621                   if(locs->rex_w || isDefault64Insn())
622                         retVal = IntelRegTable(m_Arch,b_64bit,intelReg);
623                     else
624                         retVal = IntelRegTable(m_Arch,b_32bit,intelReg);
625                     break;
626                 case op_b:
627                     if (locs->rex_byte & 0x40) {
628                         retVal = IntelRegTable(m_Arch,b_8bitWithREX,intelReg);
629                     } else {
630                         retVal = IntelRegTable(m_Arch,b_8bitNoREX,intelReg);
631                     }
632                     break;
633                 case op_q:
634                     retVal = IntelRegTable(m_Arch,b_64bit,intelReg);
635                     break;
636                 case op_w:
637                     retVal = IntelRegTable(m_Arch,b_16bit,intelReg);
638                     break;
639                 case op_f:
640                 case op_dbl:
641                     retVal = IntelRegTable(m_Arch,b_fpstack,intelReg);
642                     break;
643                 case op_d:
644                 case op_si:
645                     retVal = IntelRegTable(m_Arch,b_32bit,intelReg);
646                     break;
647                 default:
648                     retVal = IntelRegTable(m_Arch,b_32bit,intelReg);
649                     break;
650             }
651         }
652
653         if (!ia32_is_mode_64()) {
654           if ((retVal.val() & 0x00ffffff) == 0x0001000c)
655             assert(0);
656         }
657
658         return MachRegister((retVal.val() & ~retVal.getArchitecture()) | m_Arch);
659     }
660     
661     Result_Type InstructionDecoder_x86::makeSizeType(unsigned int opType)
662     {
663         switch(opType)
664         {
665             case op_b:
666             case op_c:
667                 return u8;
668             case op_d:
669             case op_ss:
670             case op_allgprs:
671             case op_si:
672                 return u32;
673             case op_w:
674             case op_a:
675                 return u16;
676             case op_q:
677             case op_sd:
678                 return u64;
679             case op_v:
680             case op_lea:
681             case op_z:
682                 if (locs->rex_w) 
683                 {
684                     return u64;
685                 }
686                 //if(ia32_is_mode_64() || !sizePrefixPresent)
687                 //{
688                     return u32;
689                     //}
690                     //else
691                     //{
692                     //return u16;
693                     //}
694                 break;
695             case op_y:
696                 if(ia32_is_mode_64())
697                         return u64;
698                 else
699                         return u32;
700                 break;
701             case op_p:
702                 // book says operand size; arch-x86 says word + word * operand size
703                 if(!ia32_is_mode_64() ^ sizePrefixPresent)
704                 {
705                     return u48;
706                 }
707                 else
708                 {
709                     return u32;
710                 }
711             case op_dq:
712             case op_qq:
713                 return u64;
714             case op_512:
715                 return m512;
716             case op_pi:
717             case op_ps:
718             case op_pd:
719                 return dbl128;
720             case op_s:
721                 return u48;
722             case op_f:
723                 return sp_float;
724             case op_dbl:
725                 return dp_float;
726             case op_14:
727                 return m14;
728             default:
729                 assert(!"Can't happen!");
730                 return u8;
731         }
732     }
733
734     enum AVX_Regtype { AVX_XMM = 0, AVX_YMM, AVX_ZMM, AVX_NONE };
735     #define AVX_TYPE_OKAY(type) ((type) >= AVX_XMM && (type) <= AVX_ZMM)
736     /** 
737      * Decode an avx register based on the type of prefix. Returns true if the
738      * given configuration is invalid and should be rejected.
739      */
740     bool decodeAVX(intelRegBanks& bank, int* bank_index, int regnum, AVX_Regtype type, ia32_prefixes& pref, unsigned int admet)
741     {
742
743         /* Check to see if this is just a normal MMX register access */
744         if(type >= AVX_NONE || type < 0)
745         {
746 #ifdef VEX_DEBUG
747             printf("VEX OPERAND:  REGNUM: %d  ", regnum);
748             printf("REG_TYPE: AVX_NONE (%d)\n", type);
749 #endif
750             /* Only registers XMM0 - XMM15 are usable */
751
752             /* The register must be valid */
753             if(regnum < 0) 
754                 return true;
755
756             if(regnum < 8)
757             {
758                 bank = b_xmm_set0;
759                 *bank_index = regnum;
760             } else if(regnum < 16)
761             {
762                 bank = b_xmm_set1;
763                 *bank_index = regnum - 8;
764             } else {
765                 /* Value is out of the valid range */
766                 return true;
767             }
768
769             /* Return success */
770             return false;
771         }
772
773         switch(admet)
774         {
775             case am_V: case am_YV: case am_XV:
776                 switch(pref.vex_type)
777                 {
778                     case VEX_TYPE_EVEX:
779                         regnum |= pref.vex_R << 4;
780                         regnum |= pref.vex_r << 3;
781                         break;
782                     default:break;
783                 }
784                 break;
785             case am_U: case am_YU: case am_XU:
786             case am_W: case am_YW: case am_XW:
787                 switch(pref.vex_type)
788                 {
789                     case VEX_TYPE_EVEX:
790                         regnum |= pref.vex_x << 4;
791                         regnum |= pref.vex_b << 3;
792                         break;
793                     default: break;
794                 }
795                 break;
796             default: break;
797         }
798 #ifdef VEX_DEBUG
799         printf("VEX OPERAND:  REGNUM: %d  ", regnum);
800 #endif
801
802         /* Operand is potentially XMM, YMM or ZMM */
803         int setnum = 0;
804         if(regnum < 8)
805         {
806             setnum = 0;
807             *bank_index = regnum;
808         } else if(regnum < 16)
809         {
810             setnum = 1;
811             *bank_index = regnum - 8;
812         } else if(regnum < 24)
813         {
814             setnum = 2;
815             *bank_index = regnum - 16;
816         } else if(regnum < 32){
817             setnum = 3;
818             *bank_index = regnum - 24;
819         } else {
820 #ifdef VEX_DEBUG
821             printf("AVX REGISTER NUMBER:   %d   is invalid!!\n", regnum);
822 #endif
823             return false;
824         }
825
826         switch(type)
827         {
828             case AVX_XMM:
829 #ifdef VEX_DEBUG
830                 printf("REG_TYPE: AVX_XMM (%d)\n", type);
831 #endif
832                 if(setnum == 0)
833                     bank = b_xmm_set0;
834                 else if(setnum == 1)
835                     bank = b_xmm_set1;
836                 else if(setnum == 2)
837                     bank = b_xmm_set2;
838                 else if(setnum == 3)
839                     bank = b_xmm_set3;
840                 else return true;
841                 break;
842             case AVX_YMM:
843 #ifdef VEX_DEBUG
844                 printf("REG_TYPE: AVX_YMM (%d)\n", type);
845 #endif
846                 if(setnum == 0)
847                     bank = b_ymm_set0;
848                 else if(setnum == 1)
849                     bank = b_ymm_set1;
850                 else if(setnum == 2)
851                     bank = b_ymm_set2;
852                 else if(setnum == 3)
853                     bank = b_ymm_set3;
854                 else return true;
855                 break;
856             case AVX_ZMM:
857 #ifdef VEX_DEBUG
858                 printf("REG_TYPE: AVX_ZMM (%d)\n", type);
859 #endif
860                 if(setnum == 0)
861                     bank = b_zmm_set0;
862                 else if(setnum == 1)
863                     bank = b_zmm_set1;
864                 else if(setnum == 2)
865                     bank = b_zmm_set2;
866                 else if(setnum == 3)
867                     bank = b_zmm_set3;
868                 else return true;
869                 break;
870             default:
871                 return true;
872         }
873
874         /* Return Success */
875         return false;
876     }
877
878     bool InstructionDecoder_x86::decodeOneOperand(const InstructionDecoder::buffer& b,
879                                                   const ia32_operand& operand,
880                                                   int & imm_index, /* immediate operand index */
881                                                   const Instruction* insn_to_complete, bool isRead, bool isWritten)
882     {
883         bool isCFT = false;
884         bool isCall = false;
885         bool isConditional = false;
886         InsnCategory cat = insn_to_complete->getCategory();
887
888         if(cat == c_BranchInsn || cat == c_CallInsn)
889             {
890             isCFT = true;
891             if(cat == c_CallInsn)
892             {
893                 isCall = true;
894             }
895             }
896
897         if(cat == c_BranchInsn && insn_to_complete->getOperation().getID() != e_jmp) 
898         {
899                 isConditional = true;
900         }
901
902         /* There must be a preliminary decoded instruction */
903         if(!decodedInstruction)
904             assert(!"No decoded instruction!\n");
905
906         unsigned int optype = operand.optype;
907         AVX_Regtype avx_type = AVX_NONE; /* The AVX register type (if VEX prefixed) */
908         intelRegBanks bank = b_invalid; /* Specifies an AVX bank to use for register decoding */
909         int bank_index = -1; /* Specifies a bank index for an AVX register */
910         ia32_prefixes& pref = *decodedInstruction->getPrefix();
911         int regnum; /* Used to keep track of some register positions */
912
913         if(pref.vex_present)
914         {
915             /* Get the AVX type from the prefix */
916             avx_type = (AVX_Regtype)pref.vex_ll;
917         }
918
919         if (sizePrefixPresent && ((optype == op_v) 
920                 || (optype == op_z)) && (operand.admet != am_J)) 
921         {
922             optype = op_w;
923         }
924
925         if(optype == op_y) 
926         {
927             if(ia32_is_mode_64() && locs->rex_w)
928             {
929                 optype = op_q;
930             } else {
931                 optype = op_d;
932             }
933         }
934      
935         switch(operand.admet)
936         {
937             case 0:
938                 // No operand
939                 assert(!"Mismatched number of operands--check tables");
940                 return false;
941             case am_A:
942                 {
943                     // am_A only shows up as a far call/jump.  
944                     // Position 1 should be universally safe.
945                     Expression::Ptr addr(decodeImmediate(optype, b.start + 1));
946                     insn_to_complete->addSuccessor(addr, isCall, false, false, false);
947                 }
948                 break;
949
950             case am_C:
951                 {
952                     Expression::Ptr op(makeRegisterExpression(
953                             IntelRegTable(m_Arch,b_cr,locs->modrm_reg)));
954                     insn_to_complete->appendOperand(op, isRead, isWritten);
955                 }
956                 break;
957
958             case am_D:
959                 {
960                     Expression::Ptr op(makeRegisterExpression(
961                                 IntelRegTable(m_Arch,b_dr,locs->modrm_reg)));
962                     insn_to_complete->appendOperand(op, isRead, isWritten);
963                 }
964                 break;
965
966             case am_E:
967                 // am_M is like am_E, except that mod of 0x03 should 
968                 // never occur (am_M specified memory,
969                 // mod of 0x03 specifies direct register access).
970             case am_M:
971                 // am_R is the inverse of am_M; it should only have a mod of 3
972             case am_R:
973                 // can be am_R or am_M  
974             case am_RM: 
975                 if(isCFT)
976                 {
977                     insn_to_complete->addSuccessor(
978                             makeModRMExpression(b, optype), 
979                             isCall, true, false, false);
980                 } else {
981                     insn_to_complete->appendOperand(
982                             makeModRMExpression(b, optype), 
983                             isRead, isWritten);
984                 }
985                 break;
986
987             case am_F:
988                 {
989                     Expression::Ptr op(makeRegisterExpression(x86::flags));
990                     insn_to_complete->appendOperand(op, isRead, isWritten);
991                 }
992                 break;
993
994             case am_G:
995                 {
996                     Expression::Ptr op(makeRegisterExpression(
997                             makeRegisterID(locs->modrm_reg, optype, locs->rex_r)));
998                     insn_to_complete->appendOperand(op, isRead, isWritten);
999                 }
1000                 break;
1001
1002             case am_I:
1003                 insn_to_complete->appendOperand(decodeImmediate(optype, b.start +
1004                 locs->imm_position[imm_index++]),
1005                 isRead, isWritten);
1006                 break;
1007             case am_J:
1008                 {
1009                     Expression::Ptr Offset(decodeImmediate(optype,
1010                         b.start + locs->imm_position[imm_index++],
1011                         true));
1012                     Expression::Ptr EIP(makeRegisterExpression(MachRegister::getPC(m_Arch)));
1013                     Expression::Ptr InsnSize(make_shared(singleton_object_pool<Immediate>::construct(Result(u8,
1014                                                                                                                   decodedInstruction->getSize()))));
1015                     Expression::Ptr postEIP(makeAddExpression(EIP, InsnSize, u32));
1016                     Expression::Ptr op(makeAddExpression(Offset, postEIP, u32));
1017                     insn_to_complete->addSuccessor(op, isCall, false, isConditional, false);
1018                     if (isConditional)
1019                         insn_to_complete->addSuccessor(postEIP, false, false, true, true);
1020                 }
1021                 break;
1022
1023             case am_H: /* Could be XMM, YMM or ZMM */
1024                 /* Make sure this register class is valid for VEX */
1025                 if(!AVX_TYPE_OKAY(avx_type) || !pref.vex_present)
1026                     return false;
1027
1028                 /* Grab the correct bank and bank index for this type of register */
1029                 if(decodeAVX(bank, &bank_index, pref.vex_vvvv_reg, avx_type, pref, operand.admet))
1030                     return false;
1031
1032                 /* Append the operand */
1033                 insn_to_complete->appendOperand(makeRegisterExpression(
1034                         IntelRegTable(m_Arch, bank, bank_index)), 
1035                         isRead, isWritten);
1036                 break;
1037
1038             case am_XH: /* Must be XMM */
1039                 /* Make sure we are using a valid VEX register class */
1040                 if(!AVX_TYPE_OKAY(avx_type) || !pref.vex_present)
1041                     return false;
1042
1043                 /* Constrain register type to only the XMM banks */
1044                 avx_type = AVX_XMM;
1045
1046                 /* Grab the correct bank and bank index for this type of register */
1047                 if(decodeAVX(bank, &bank_index, pref.vex_vvvv_reg, avx_type, pref, operand.admet))
1048                     return false;
1049
1050                 insn_to_complete->appendOperand(makeRegisterExpression(
1051                         IntelRegTable(m_Arch, bank, bank_index)), 
1052                         isRead, isWritten);
1053                 break;
1054
1055             case am_YH: /* Could be XMM or YMM */
1056                 /* Make sure we are using a valid VEX register class */
1057                 if(!AVX_TYPE_OKAY(avx_type) || !pref.vex_present)
1058                     return false;
1059
1060                 /* Constrain to only XMM or YMM registers */
1061                 if(avx_type != AVX_XMM && avx_type != AVX_YMM)
1062                     avx_type = AVX_YMM;
1063
1064                 /* Grab the correct bank and bank index for this type of register */
1065                 if(decodeAVX(bank, &bank_index, pref.vex_vvvv_reg, avx_type, pref, operand.admet))
1066                     return false;
1067
1068                 /* Append the operand */
1069                 insn_to_complete->appendOperand(makeRegisterExpression(
1070                         IntelRegTable(m_Arch, bank, bank_index)), 
1071                         isRead, isWritten);
1072                 break;
1073
1074             case am_U: /* Could be XMM, YMM, or ZMM (or possibly non VEX)*/
1075
1076                 /* Is this a vex prefixed instruction? */  
1077                 if(pref.vex_present)
1078                 {
1079                     if(!AVX_TYPE_OKAY(avx_type))
1080                         return false;
1081                 }
1082
1083                 /* Grab the register bank and index */
1084                 if(decodeAVX(bank, &bank_index, locs->modrm_rm, AVX_XMM, pref, operand.admet))
1085                     return false;
1086
1087                 /* Append the operand */
1088                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1089                 break;
1090             case am_XU: /* Must be XMM (must be VEX) */
1091                 /* Make sure this register class is valid */
1092                 if(!AVX_TYPE_OKAY(avx_type) || !pref.vex_present)
1093                     return false;
1094   
1095                 /* Constrain register to XMM banks only */        
1096                 avx_type = AVX_XMM;
1097
1098                 /* Get the register bank and index for this register */
1099                 if(decodeAVX(bank, &bank_index, locs->modrm_rm, avx_type, pref, operand.admet))
1100                     return false;
1101
1102                 /* Append the operand */
1103                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1104                 break;
1105             case am_YU: /* Must be XMM or YMM (must be VEX) */
1106                 /* Make sure this register class is valid */
1107                 if(!AVX_TYPE_OKAY(avx_type) || !pref.vex_present)
1108                     return false;
1109
1110                 /* Constrain to either XMM or YMM registers */
1111                 if(avx_type != AVX_XMM && avx_type != AVX_YMM)
1112                     avx_type = AVX_YMM;
1113
1114                 /* Get the register bank and index */
1115                 if(decodeAVX(bank, &bank_index, locs->modrm_rm, avx_type, pref, operand.admet))
1116                     return false;
1117
1118                 /* Append the operand */
1119                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1120                 break;
1121             case am_W: /* Could be XMM, YMM, or ZMM (or possibly not VEX) */
1122
1123                 if(pref.vex_present)
1124                 {
1125                     if(!AVX_TYPE_OKAY(avx_type))
1126                         return false;
1127                 }
1128
1129                         switch(locs->modrm_mod)
1130                         {
1131                     /* Direct dereference */
1132                             case 0x00:
1133                             case 0x01:
1134                             case 0x02:
1135                                     insn_to_complete->appendOperand(makeModRMExpression(b, makeSizeType(optype)), isRead, isWritten);
1136                                 break;
1137                             case 0x03:
1138                         /* Just the register is used */
1139                         if(decodeAVX(bank, &bank_index, locs->modrm_rm, avx_type, pref, operand.admet))
1140                             return false;
1141                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1142                         break;
1143                     default:
1144                         assert(!"2-bit value modrm_mod out of range");
1145                         break;
1146                 }
1147                 break;
1148             case am_XW: /* Must be XMM (must be VEX) */
1149
1150                 /* Make sure this vex is okay */
1151                 if(!AVX_TYPE_OKAY(avx_type) || !pref.vex_present)
1152                     return false;
1153          
1154                 /* Constrain to the XMM banks */ 
1155                 avx_type = AVX_XMM;
1156
1157                 switch(locs->modrm_mod)
1158                             {
1159                     /* Direct dereference */
1160                     case 0x00:
1161                     case 0x01:
1162                     case 0x02:
1163                         insn_to_complete->appendOperand(makeModRMExpression(b, makeSizeType(optype)), isRead, isWritten);
1164                         break;
1165                     case 0x03:
1166                         /* Just the register is used */
1167                         if(decodeAVX(bank, &bank_index, locs->modrm_rm, avx_type, pref, operand.admet))
1168                             return false;
1169                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1170                         break;
1171                     default:
1172                         assert(!"2-bit value modrm_mod out of range");
1173                                 break;
1174                             }
1175                 break;
1176             case am_YW: /* Must be either YMM or XMM (must be VEX) */
1177
1178                 /* Make sure the register class is okay and we have a vex prefix */
1179                 if(!AVX_TYPE_OKAY(avx_type) || !pref.vex_present)
1180                     return false;
1181
1182                 /* Constrain to either XMM or YMM registers */
1183                 if(avx_type != AVX_XMM && avx_type != AVX_YMM)
1184                     avx_type = AVX_YMM;
1185
1186                 switch(locs->modrm_mod)
1187                 {
1188                     /* Direct dereference */
1189                     case 0x00:
1190                     case 0x01:
1191                     case 0x02:
1192                         insn_to_complete->appendOperand(makeModRMExpression(b, makeSizeType(optype)), isRead, isWritten);
1193                         break;
1194                     case 0x03:
1195                         /* Just the register is used */
1196                         if(decodeAVX(bank, &bank_index, locs->modrm_rm, avx_type, pref, operand.admet))
1197                             return false;
1198
1199                         /* Append the operand */
1200                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1201                         break;
1202                             default:
1203                                 assert(!"2-bit value modrm_mod out of range");
1204                                 break;
1205                 }
1206                         break;
1207                     case am_X:
1208                     {
1209                         MachRegister si_reg;
1210                         if(m_Arch == Arch_x86)
1211                         {
1212                                 if(addrSizePrefixPresent)
1213                                 {
1214                                         si_reg = x86::si;
1215                         } else {
1216                                         si_reg = x86::esi;
1217                                 }
1218                     } else {
1219                                 if(addrSizePrefixPresent)
1220                                 {
1221                                         si_reg = x86_64::esi;
1222                         } else {
1223                                         si_reg = x86_64::rsi;
1224                                 }
1225                         }
1226
1227                         Expression::Ptr ds(makeRegisterExpression(m_Arch == Arch_x86 ? x86::ds : x86_64::ds));
1228                         Expression::Ptr si(makeRegisterExpression(si_reg));
1229                     Expression::Ptr segmentOffset(make_shared(singleton_object_pool<Immediate>::construct(Result(u32, 0x10))));
1230                         Expression::Ptr ds_segment = makeMultiplyExpression(ds, segmentOffset, u32);
1231                         Expression::Ptr ds_si = makeAddExpression(ds_segment, si, u32);
1232                     insn_to_complete->appendOperand(makeDereferenceExpression(ds_si, makeSizeType(optype)), isRead, isWritten);
1233                     }
1234                     break;
1235                     case am_Y:
1236                     {
1237                         MachRegister di_reg;
1238                         if(m_Arch == Arch_x86)
1239                         {
1240                                 if(addrSizePrefixPresent)
1241                                 {
1242                                         di_reg = x86::di;
1243                         } else {
1244                                         di_reg = x86::edi;
1245                                 }
1246                     } else {
1247                                 if(addrSizePrefixPresent)
1248                                 {
1249                                         di_reg = x86_64::edi;
1250                         } else {
1251                                         di_reg = x86_64::rdi;
1252                                 }
1253                         }
1254                         Expression::Ptr es(makeRegisterExpression(m_Arch == Arch_x86 ? x86::es : x86_64::es));
1255                         Expression::Ptr di(makeRegisterExpression(di_reg));
1256
1257                         Immediate::Ptr imm(make_shared(singleton_object_pool<Immediate>::construct(Result(u32, 0x10))));
1258                         Expression::Ptr es_segment(makeMultiplyExpression(es,imm, u32));
1259                         Expression::Ptr es_di(makeAddExpression(es_segment, di, u32));
1260                         insn_to_complete->appendOperand(makeDereferenceExpression(es_di, makeSizeType(optype)),
1261                                                        isRead, isWritten);
1262
1263                     }
1264                     break;
1265                     case am_tworeghack:
1266                         if(optype == op_edxeax)
1267                         {
1268                             Expression::Ptr edx(makeRegisterExpression(m_Arch == Arch_x86 ? x86::edx : x86_64::edx));
1269                             Expression::Ptr eax(makeRegisterExpression(m_Arch == Arch_x86 ? x86::eax : x86_64::eax));
1270                     Expression::Ptr highAddr = makeMultiplyExpression(edx, Immediate::makeImmediate(Result(u64, 2^32)), u64);
1271                             Expression::Ptr addr = makeAddExpression(highAddr, eax, u64);
1272                             Expression::Ptr op = makeDereferenceExpression(addr, u64);
1273                             insn_to_complete->appendOperand(op, isRead, isWritten);
1274                 } else if (optype == op_ecxebx)
1275                         {
1276                             Expression::Ptr ecx(makeRegisterExpression(m_Arch == Arch_x86 ? x86::ecx : x86_64::ecx));
1277                             Expression::Ptr ebx(makeRegisterExpression(m_Arch == Arch_x86 ? x86::ebx : x86_64::ebx));
1278                             Expression::Ptr highAddr = makeMultiplyExpression(ecx,
1279                                     Immediate::makeImmediate(Result(u64, 2^32)), u64);
1280                             Expression::Ptr addr = makeAddExpression(highAddr, ebx, u64);
1281                             Expression::Ptr op = makeDereferenceExpression(addr, u64);
1282                             insn_to_complete->appendOperand(op, isRead, isWritten);
1283                         }
1284                     break;
1285                     
1286                     case am_reg:
1287                     {
1288                         MachRegister r(optype);
1289                         int size = r.size();
1290                     if((m_Arch == Arch_x86_64) && (r.regClass() == (unsigned int)x86::GPR) && (size == 4))
1291                         {
1292                             int reg_size = isDefault64Insn() ? op_q : op_v;
1293                             if(sizePrefixPresent)
1294                             {
1295                                 reg_size = op_w;
1296                             }
1297                             // implicit regs are not extended
1298                             r = makeRegisterID((r.val() & 0xFF), reg_size, false);
1299                             entryID entryid = decodedInstruction->getEntry()->getID(locs);
1300                             if(locs->rex_b && insn_to_complete->m_Operands.empty() &&
1301                                (entryid == e_push || entryid == e_pop || entryid == e_xchg || ((*(b.start + locs->opcode_position) & 0xf0) == 0xb0)))
1302                             {
1303                                 r = MachRegister((r.val()) | x86_64::r8.val());
1304                                 assert(r.name() != "<INVALID_REG>");
1305                             }
1306                     } else {
1307                             r = MachRegister((r.val() & ~r.getArchitecture()) | m_Arch);
1308                             
1309                             entryID entryid = decodedInstruction->getEntry()->getID(locs);
1310                             if(insn_to_complete->m_Operands.empty() && 
1311                                (entryid == e_push || entryid == e_pop || entryid == e_xchg || ((*(b.start + locs->opcode_position) & 0xf0) == 0xb0) ) )
1312                             {
1313                                 unsigned int opcode_byte = *(b.start+locs->opcode_position);
1314                                 unsigned int reg_id = (opcode_byte & 0x07);
1315                                 if(locs->rex_b) 
1316                                 {
1317                                     // FP stack registers are not affected by the rex_b bit in AM_REG.
1318                                     if(r.regClass() == (unsigned) x86::GPR)
1319                                     {
1320                                         int reg_op_type = op_d;
1321                                         switch(size)
1322                                         {
1323                                         case 1:
1324                                             reg_op_type = op_b;
1325                                             break;
1326                                         case 2:
1327                                             reg_op_type = op_w;
1328                                             break;
1329                                         case 8:
1330                                             reg_op_type = op_q;
1331                                             break;
1332                                         default:
1333                                             break;
1334                                         }
1335
1336                                         r = makeRegisterID(reg_id, reg_op_type, true);
1337                                         assert(r.name() != "<INVALID_REG>");
1338                                     }
1339                             } else if((r.size() == 1) && (locs->rex_byte & 0x40))
1340                                 {
1341                                     r = makeRegisterID(reg_id, op_b, false);
1342                                     assert(r.name() != "<INVALID_REG>");
1343                                 }
1344                             }
1345
1346                         if(sizePrefixPresent && (r.regClass() == (unsigned int)x86::GPR) && r.size() >= 4)
1347                             {
1348                                 r = MachRegister((r.val() & ~x86::FULL) | x86::W_REG);
1349                                 assert(r.name() != "<INVALID_REG>");
1350                             }
1351                         }
1352                         Expression::Ptr op(makeRegisterExpression(r));
1353                         insn_to_complete->appendOperand(op, isRead, isWritten);
1354                     }
1355                     break;
1356                 case am_stackH:
1357                 case am_stackP:
1358                 // handled elsewhere
1359                     break;
1360                 case am_allgprs:
1361                     if(m_Arch == Arch_x86)
1362                     {
1363                         insn_to_complete->appendOperand(makeRegisterExpression(x86::eax), isRead, isWritten);
1364                         insn_to_complete->appendOperand(makeRegisterExpression(x86::ecx), isRead, isWritten);
1365                         insn_to_complete->appendOperand(makeRegisterExpression(x86::edx), isRead, isWritten);
1366                         insn_to_complete->appendOperand(makeRegisterExpression(x86::ebx), isRead, isWritten);
1367                         insn_to_complete->appendOperand(makeRegisterExpression(x86::esp), isRead, isWritten);
1368                         insn_to_complete->appendOperand(makeRegisterExpression(x86::ebp), isRead, isWritten);
1369                         insn_to_complete->appendOperand(makeRegisterExpression(x86::esi), isRead, isWritten);
1370                         insn_to_complete->appendOperand(makeRegisterExpression(x86::edi), isRead, isWritten);
1371                 } else {
1372                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::eax), isRead, isWritten);
1373                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::ecx), isRead, isWritten);
1374                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::edx), isRead, isWritten);
1375                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::ebx), isRead, isWritten);
1376                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::esp), isRead, isWritten);
1377                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::ebp), isRead, isWritten);
1378                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::esi), isRead, isWritten);
1379                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::edi), isRead, isWritten);
1380                     }
1381                     break;
1382             case am_ImplImm:
1383                   insn_to_complete->appendOperand(Immediate::makeImmediate(Result(makeSizeType(optype), 1)), isRead, isWritten);
1384                   break;
1385                 default:
1386                     printf("decodeOneOperand() called with unknown addressing method %d\n", operand.admet);
1387                     // assert(0);
1388                 return false;
1389         }
1390       
1391                 return true;
1392             }
1393
1394     extern ia32_entry invalid;
1395     void InstructionDecoder_x86::doIA32Decode(InstructionDecoder::buffer& b)
1396     {
1397         if(decodedInstruction == NULL)
1398         {
1399             decodedInstruction = reinterpret_cast<ia32_instruction*>(malloc(sizeof(ia32_instruction)));
1400             assert(decodedInstruction);
1401         }
1402         if(locs == NULL)
1403         {
1404             locs = reinterpret_cast<ia32_locations*>(malloc(sizeof(ia32_locations)));
1405             assert(locs);
1406         }
1407         locs = new(locs) ia32_locations; //reinit();
1408         assert(locs->sib_position == -1);
1409         decodedInstruction = new (decodedInstruction) ia32_instruction(NULL, NULL, locs);
1410         ia32_decode(IA32_DECODE_PREFIXES, b.start, *decodedInstruction);
1411         sizePrefixPresent = (decodedInstruction->getPrefix()->getOperSzPrefix() == 0x66);
1412         if (decodedInstruction->getPrefix()->rexW()) {
1413            // as per 2.2.1.2 - rex.w overrides 66h
1414            sizePrefixPresent = false;
1415         }
1416         addrSizePrefixPresent = (decodedInstruction->getPrefix()->getAddrSzPrefix() == 0x67);
1417         static ia32_entry invalid = { e_No_Entry, 0, 0, false, { {0,0}, {0,0}, {0,0} }, 0, 0 };
1418         if(decodedInstruction->getEntry()) {
1419             // check prefix validity
1420             // lock prefix only allowed on certain insns.
1421             // TODO: refine further to check memory written operand
1422             if(decodedInstruction->getPrefix()->getPrefix(0) == PREFIX_LOCK)
1423             {
1424                 switch(decodedInstruction->getEntry()->id)
1425                 {
1426                 case e_add:
1427                 case e_adc:
1428                 case e_and:
1429                 case e_btc:
1430                 case e_btr:
1431                 case e_bts:
1432                 case e_cmpxch:
1433                 case e_cmpxch8b:
1434                 case e_dec:
1435                 case e_inc:
1436                 case e_neg:
1437                 case e_not:
1438                 case e_or:
1439                 case e_sbb:
1440                 case e_sub:
1441                 case e_xor:
1442                 case e_xadd:
1443                 case e_xchg:
1444                     break;
1445                 default:
1446                     m_Operation =make_shared(singleton_object_pool<Operation>::construct(&invalid,
1447                                     decodedInstruction->getPrefix(), locs, m_Arch));
1448                     return;
1449                 }
1450             }
1451             m_Operation = make_shared(singleton_object_pool<Operation>::construct(decodedInstruction->getEntry(),
1452                                     decodedInstruction->getPrefix(), locs, m_Arch));
1453             
1454       } else {
1455                 // Gap parsing can trigger this case; in particular, when it encounters prefixes in an invalid order.
1456                 // Notably, if a REX prefix (0x40-0x48) appears followed by another prefix (0x66, 0x67, etc)
1457                 // we'll reject the instruction as invalid and send it back with no entry.  Since this is a common
1458                 // byte sequence to see in, for example, ASCII strings, we want to simply accept this and move on, not
1459                 // yell at the user.
1460             m_Operation = make_shared(singleton_object_pool<Operation>::construct(&invalid,
1461                                     decodedInstruction->getPrefix(), locs, m_Arch));
1462         }
1463
1464     }
1465     
1466     void InstructionDecoder_x86::decodeOpcode(InstructionDecoder::buffer& b)
1467     {
1468         doIA32Decode(b);
1469         b.start += decodedInstruction->getSize();
1470     }
1471     
1472         bool InstructionDecoder_x86::decodeOperands(const Instruction* insn_to_complete)
1473     {
1474        int imm_index = 0; // handle multiple immediate operands
1475         if(!decodedInstruction || !decodedInstruction->getEntry()) return false;
1476         unsigned int opsema = decodedInstruction->getEntry()->opsema & 0xFF;
1477         InstructionDecoder::buffer b(insn_to_complete->ptr(), insn_to_complete->size());
1478
1479         if (decodedInstruction->getEntry()->getID() == e_ret_near ||
1480             decodedInstruction->getEntry()->getID() == e_ret_far) {
1481            Expression::Ptr ret_addr = makeDereferenceExpression(makeRegisterExpression(ia32_is_mode_64() ? x86_64::rsp : x86::esp), 
1482                                                                 ia32_is_mode_64() ? u64 : u32);
1483            insn_to_complete->addSuccessor(ret_addr, false, true, false, false);
1484         }
1485
1486         for(int i = 0; i < 3; i++)
1487         {
1488             if(decodedInstruction->getEntry()->operands[i].admet == 0 && 
1489                decodedInstruction->getEntry()->operands[i].optype == 0)
1490                 return true;
1491             if(!decodeOneOperand(b,
1492                                  decodedInstruction->getEntry()->operands[i], 
1493                                  imm_index, 
1494                                  insn_to_complete, 
1495                                  readsOperand(opsema, i),
1496                                  writesOperand(opsema, i)))
1497             {
1498                 return false;
1499             }
1500         }
1501
1502         /* Does this instruction have a 4th operand? */
1503         if((decodedInstruction->getEntry()->opsema & 0xFFFF) >= s4OP)
1504         {
1505           if(!decodeOneOperand(b,
1506             {am_I, op_b}, /* This is always an IMM8 */
1507             imm_index,
1508             insn_to_complete,
1509             readsOperand(opsema, 3),
1510             writesOperand(opsema, 3)))
1511             {
1512                 return false;
1513             }
1514         }
1515     
1516         return true;
1517     }
1518
1519     
1520       INSTRUCTION_EXPORT Instruction::Ptr InstructionDecoder_x86::decode(InstructionDecoder::buffer& b)
1521     {
1522         return InstructionDecoderImpl::decode(b);
1523     }
1524     void InstructionDecoder_x86::doDelayedDecode(const Instruction* insn_to_complete)
1525     {
1526       InstructionDecoder::buffer b(insn_to_complete->ptr(), insn_to_complete->size());
1527       //insn_to_complete->m_Operands.reserve(4);
1528       doIA32Decode(b);        
1529       decodeOperands(insn_to_complete);
1530     }
1531     
1532 };
1533 };
1534