bnd: Drop bnd prefix for relaxed short jmp instructions
[platform/upstream/nasm.git] / assemble.c
1 /* ----------------------------------------------------------------------- *
2  *
3  *   Copyright 1996-2013 The NASM Authors - All Rights Reserved
4  *   See the file AUTHORS included with the NASM distribution for
5  *   the specific copyright holders.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following
9  *   conditions are met:
10  *
11  *   * Redistributions of source code must retain the above copyright
12  *     notice, this list of conditions and the following disclaimer.
13  *   * Redistributions in binary form must reproduce the above
14  *     copyright notice, this list of conditions and the following
15  *     disclaimer in the documentation and/or other materials provided
16  *     with the distribution.
17  *
18  *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19  *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20  *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21  *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23  *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29  *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30  *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * ----------------------------------------------------------------------- */
33
34 /*
35  * assemble.c   code generation for the Netwide Assembler
36  *
37  * the actual codes (C syntax, i.e. octal):
38  * \0            - terminates the code. (Unless it's a literal of course.)
39  * \1..\4        - that many literal bytes follow in the code stream
40  * \5            - add 4 to the primary operand number (b, low octdigit)
41  * \6            - add 4 to the secondary operand number (a, middle octdigit)
42  * \7            - add 4 to both the primary and the secondary operand number
43  * \10..\13      - a literal byte follows in the code stream, to be added
44  *                 to the register value of operand 0..3
45  * \14..\17      - the position of index register operand in MIB (BND insns)
46  * \20..\23      - a byte immediate operand, from operand 0..3
47  * \24..\27      - a zero-extended byte immediate operand, from operand 0..3
48  * \30..\33      - a word immediate operand, from operand 0..3
49  * \34..\37      - select between \3[0-3] and \4[0-3] depending on 16/32 bit
50  *                 assembly mode or the operand-size override on the operand
51  * \40..\43      - a long immediate operand, from operand 0..3
52  * \44..\47      - select between \3[0-3], \4[0-3] and \5[4-7]
53  *                 depending on the address size of the instruction.
54  * \50..\53      - a byte relative operand, from operand 0..3
55  * \54..\57      - a qword immediate operand, from operand 0..3
56  * \60..\63      - a word relative operand, from operand 0..3
57  * \64..\67      - select between \6[0-3] and \7[0-3] depending on 16/32 bit
58  *                 assembly mode or the operand-size override on the operand
59  * \70..\73      - a long relative operand, from operand 0..3
60  * \74..\77      - a word constant, from the _segment_ part of operand 0..3
61  * \1ab          - a ModRM, calculated on EA in operand a, with the spare
62  *                 field the register value of operand b.
63  * \172\ab       - the register number from operand a in bits 7..4, with
64  *                 the 4-bit immediate from operand b in bits 3..0.
65  * \173\xab      - the register number from operand a in bits 7..4, with
66  *                 the value b in bits 3..0.
67  * \174..\177    - the register number from operand 0..3 in bits 7..4, and
68  *                 an arbitrary value in bits 3..0 (assembled as zero.)
69  * \2ab          - a ModRM, calculated on EA in operand a, with the spare
70  *                 field equal to digit b.
71  *
72  * \240..\243    - this instruction uses EVEX rather than REX or VEX/XOP, with the
73  *                 V field taken from operand 0..3.
74  * \250          - this instruction uses EVEX rather than REX or VEX/XOP, with the
75  *                 V field set to 1111b.
76  * EVEX prefixes are followed by the sequence:
77  * \cm\wlp\tup    where cm is:
78  *                  cc 000 0mm
79  *                  c = 2 for EVEX and m is the legacy escape (0f, 0f38, 0f3a)
80  *                and wlp is:
81  *                  00 wwl lpp
82  *                  [l0]  ll = 0 (.128, .lz)
83  *                  [l1]  ll = 1 (.256)
84  *                  [l2]  ll = 2 (.512)
85  *                  [lig] ll = 3 for EVEX.L'L don't care (always assembled as 0)
86  *
87  *                  [w0]  ww = 0 for W = 0
88  *                  [w1]  ww = 1 for W = 1
89  *                  [wig] ww = 2 for W don't care (always assembled as 0)
90  *                  [ww]  ww = 3 for W used as REX.W
91  *
92  *                  [p0]  pp = 0 for no prefix
93  *                  [60]  pp = 1 for legacy prefix 60
94  *                  [f3]  pp = 2
95  *                  [f2]  pp = 3
96  *
97  *                tup is tuple type for Disp8*N from %tuple_codes in insns.pl
98  *                    (compressed displacement encoding)
99  *
100  * \254..\257    - a signed 32-bit operand to be extended to 64 bits.
101  * \260..\263    - this instruction uses VEX/XOP rather than REX, with the
102  *                 V field taken from operand 0..3.
103  * \270          - this instruction uses VEX/XOP rather than REX, with the
104  *                 V field set to 1111b.
105  *
106  * VEX/XOP prefixes are followed by the sequence:
107  * \tmm\wlp        where mm is the M field; and wlp is:
108  *                 00 wwl lpp
109  *                 [l0]  ll = 0 for L = 0 (.128, .lz)
110  *                 [l1]  ll = 1 for L = 1 (.256)
111  *                 [lig] ll = 2 for L don't care (always assembled as 0)
112  *
113  *                 [w0]  ww = 0 for W = 0
114  *                 [w1 ] ww = 1 for W = 1
115  *                 [wig] ww = 2 for W don't care (always assembled as 0)
116  *                 [ww]  ww = 3 for W used as REX.W
117  *
118  * t = 0 for VEX (C4/C5), t = 1 for XOP (8F).
119  *
120  * \271          - instruction takes XRELEASE (F3) with or without lock
121  * \272          - instruction takes XACQUIRE/XRELEASE with or without lock
122  * \273          - instruction takes XACQUIRE/XRELEASE with lock only
123  * \274..\277    - a byte immediate operand, from operand 0..3, sign-extended
124  *                 to the operand size (if o16/o32/o64 present) or the bit size
125  * \310          - indicates fixed 16-bit address size, i.e. optional 0x67.
126  * \311          - indicates fixed 32-bit address size, i.e. optional 0x67.
127  * \312          - (disassembler only) invalid with non-default address size.
128  * \313          - indicates fixed 64-bit address size, 0x67 invalid.
129  * \314          - (disassembler only) invalid with REX.B
130  * \315          - (disassembler only) invalid with REX.X
131  * \316          - (disassembler only) invalid with REX.R
132  * \317          - (disassembler only) invalid with REX.W
133  * \320          - indicates fixed 16-bit operand size, i.e. optional 0x66.
134  * \321          - indicates fixed 32-bit operand size, i.e. optional 0x66.
135  * \322          - indicates that this instruction is only valid when the
136  *                 operand size is the default (instruction to disassembler,
137  *                 generates no code in the assembler)
138  * \323          - indicates fixed 64-bit operand size, REX on extensions only.
139  * \324          - indicates 64-bit operand size requiring REX prefix.
140  * \325          - instruction which always uses spl/bpl/sil/dil
141  * \326          - instruction not valid with 0xF3 REP prefix.  Hint for
142                    disassembler only; for SSE instructions.
143  * \330          - a literal byte follows in the code stream, to be added
144  *                 to the condition code value of the instruction.
145  * \331          - instruction not valid with REP prefix.  Hint for
146  *                 disassembler only; for SSE instructions.
147  * \332          - REP prefix (0xF2 byte) used as opcode extension.
148  * \333          - REP prefix (0xF3 byte) used as opcode extension.
149  * \334          - LOCK prefix used as REX.R (used in non-64-bit mode)
150  * \335          - disassemble a rep (0xF3 byte) prefix as repe not rep.
151  * \336          - force a REP(E) prefix (0xF3) even if not specified.
152  * \337          - force a REPNE prefix (0xF2) even if not specified.
153  *                 \336-\337 are still listed as prefixes in the disassembler.
154  * \340          - reserve <operand 0> bytes of uninitialized storage.
155  *                 Operand 0 had better be a segmentless constant.
156  * \341          - this instruction needs a WAIT "prefix"
157  * \360          - no SSE prefix (== \364\331)
158  * \361          - 66 SSE prefix (== \366\331)
159  * \364          - operand-size prefix (0x66) not permitted
160  * \365          - address-size prefix (0x67) not permitted
161  * \366          - operand-size prefix (0x66) used as opcode extension
162  * \367          - address-size prefix (0x67) used as opcode extension
163  * \370,\371     - match only if operand 0 meets byte jump criteria.
164  *                 370 is used for Jcc, 371 is used for JMP.
165  * \373          - assemble 0x03 if bits==16, 0x05 if bits==32;
166  *                 used for conditional jump over longer jump
167  * \374          - this instruction takes an XMM VSIB memory EA
168  * \375          - this instruction takes an YMM VSIB memory EA
169  * \376          - this instruction takes an ZMM VSIB memory EA
170  */
171
172 #include "compiler.h"
173
174 #include <stdio.h>
175 #include <string.h>
176 #include <inttypes.h>
177
178 #include "nasm.h"
179 #include "nasmlib.h"
180 #include "assemble.h"
181 #include "insns.h"
182 #include "tables.h"
183 #include "disp8.h"
184
185 enum match_result {
186     /*
187      * Matching errors.  These should be sorted so that more specific
188      * errors come later in the sequence.
189      */
190     MERR_INVALOP,
191     MERR_OPSIZEMISSING,
192     MERR_OPSIZEMISMATCH,
193     MERR_BRNUMMISMATCH,
194     MERR_BADCPU,
195     MERR_BADMODE,
196     MERR_BADHLE,
197     MERR_ENCMISMATCH,
198     MERR_BADBND,
199     /*
200      * Matching success; the conditional ones first
201      */
202     MOK_JUMP,   /* Matching OK but needs jmp_match() */
203     MOK_GOOD    /* Matching unconditionally OK */
204 };
205
206 typedef struct {
207     enum ea_type type;            /* what kind of EA is this? */
208     int sib_present;              /* is a SIB byte necessary? */
209     int bytes;                    /* # of bytes of offset needed */
210     int size;                     /* lazy - this is sib+bytes+1 */
211     uint8_t modrm, sib, rex, rip; /* the bytes themselves */
212     int8_t disp8;                  /* compressed displacement for EVEX */
213 } ea;
214
215 #define GEN_SIB(scale, index, base)                 \
216         (((scale) << 6) | ((index) << 3) | ((base)))
217
218 #define GEN_MODRM(mod, reg, rm)                     \
219         (((mod) << 6) | (((reg) & 7) << 3) | ((rm) & 7))
220
221 static iflags_t cpu;            /* cpu level received from nasm.c */
222 static efunc errfunc;
223 static struct ofmt *outfmt;
224 static ListGen *list;
225
226 static int64_t calcsize(int32_t, int64_t, int, insn *,
227                         const struct itemplate *);
228 static void gencode(int32_t segment, int64_t offset, int bits,
229                     insn * ins, const struct itemplate *temp,
230                     int64_t insn_end);
231 static enum match_result find_match(const struct itemplate **tempp,
232                                     insn *instruction,
233                                     int32_t segment, int64_t offset, int bits);
234 static enum match_result matches(const struct itemplate *, insn *, int bits);
235 static opflags_t regflag(const operand *);
236 static int32_t regval(const operand *);
237 static int rexflags(int, opflags_t, int);
238 static int op_rexflags(const operand *, int);
239 static int op_evexflags(const operand *, int, uint8_t);
240 static void add_asp(insn *, int);
241
242 static enum ea_type process_ea(operand *, ea *, int, int, opflags_t, insn *);
243
244 static int has_prefix(insn * ins, enum prefix_pos pos, int prefix)
245 {
246     return ins->prefixes[pos] == prefix;
247 }
248
249 static void assert_no_prefix(insn * ins, enum prefix_pos pos)
250 {
251     if (ins->prefixes[pos])
252         errfunc(ERR_NONFATAL, "invalid %s prefix",
253                 prefix_name(ins->prefixes[pos]));
254 }
255
256 static const char *size_name(int size)
257 {
258     switch (size) {
259     case 1:
260         return "byte";
261     case 2:
262         return "word";
263     case 4:
264         return "dword";
265     case 8:
266         return "qword";
267     case 10:
268         return "tword";
269     case 16:
270         return "oword";
271     case 32:
272         return "yword";
273     case 64:
274         return "zword";
275     default:
276         return "???";
277     }
278 }
279
280 static void warn_overflow(int pass, int size)
281 {
282     errfunc(ERR_WARNING | pass | ERR_WARN_NOV,
283             "%s data exceeds bounds", size_name(size));
284 }
285
286 static void warn_overflow_const(int64_t data, int size)
287 {
288     if (overflow_general(data, size))
289         warn_overflow(ERR_PASS1, size);
290 }
291
292 static void warn_overflow_opd(const struct operand *o, int size)
293 {
294     if (o->wrt == NO_SEG && o->segment == NO_SEG) {
295         if (overflow_general(o->offset, size))
296             warn_overflow(ERR_PASS2, size);
297     }
298 }
299
300 /*
301  * This routine wrappers the real output format's output routine,
302  * in order to pass a copy of the data off to the listing file
303  * generator at the same time.
304  */
305 static void out(int64_t offset, int32_t segto, const void *data,
306                 enum out_type type, uint64_t size,
307                 int32_t segment, int32_t wrt)
308 {
309     static int32_t lineno = 0;     /* static!!! */
310     static char *lnfname = NULL;
311     uint8_t p[8];
312
313     if (type == OUT_ADDRESS && segment == NO_SEG && wrt == NO_SEG) {
314         /*
315          * This is a non-relocated address, and we're going to
316          * convert it into RAWDATA format.
317          */
318         uint8_t *q = p;
319
320         if (size > 8) {
321             errfunc(ERR_PANIC, "OUT_ADDRESS with size > 8");
322             return;
323         }
324
325         WRITEADDR(q, *(int64_t *)data, size);
326         data = p;
327         type = OUT_RAWDATA;
328     }
329
330     list->output(offset, data, type, size);
331
332     /*
333      * this call to src_get determines when we call the
334      * debug-format-specific "linenum" function
335      * it updates lineno and lnfname to the current values
336      * returning 0 if "same as last time", -2 if lnfname
337      * changed, and the amount by which lineno changed,
338      * if it did. thus, these variables must be static
339      */
340
341     if (src_get(&lineno, &lnfname))
342         outfmt->current_dfmt->linenum(lnfname, lineno, segto);
343
344     outfmt->output(segto, data, type, size, segment, wrt);
345 }
346
347 static void out_imm8(int64_t offset, int32_t segment, struct operand *opx)
348 {
349     if (opx->segment != NO_SEG) {
350         uint64_t data = opx->offset;
351         out(offset, segment, &data, OUT_ADDRESS, 1, opx->segment, opx->wrt);
352     } else {
353         uint8_t byte = opx->offset;
354         out(offset, segment, &byte, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
355     }
356 }
357
358 static bool jmp_match(int32_t segment, int64_t offset, int bits,
359                       insn * ins, const struct itemplate *temp)
360 {
361     int64_t isize;
362     const uint8_t *code = temp->code;
363     uint8_t c = code[0];
364     bool is_byte;
365
366     if (((c & ~1) != 0370) || (ins->oprs[0].type & STRICT))
367         return false;
368     if (!optimizing)
369         return false;
370     if (optimizing < 0 && c == 0371)
371         return false;
372
373     isize = calcsize(segment, offset, bits, ins, temp);
374
375     if (ins->oprs[0].opflags & OPFLAG_UNKNOWN)
376         /* Be optimistic in pass 1 */
377         return true;
378
379     if (ins->oprs[0].segment != segment)
380         return false;
381
382     isize = ins->oprs[0].offset - offset - isize; /* isize is delta */
383     is_byte = (isize >= -128 && isize <= 127); /* is it byte size? */
384
385     if (is_byte && c == 0371 && ins->prefixes[PPS_REP] == P_BND) {
386         /* jmp short (opcode eb) cannot be used with bnd prefix. */
387         ins->prefixes[PPS_REP] = P_none;
388     }
389
390     return is_byte;
391 }
392
393 int64_t assemble(int32_t segment, int64_t offset, int bits, iflags_t cp,
394                  insn * instruction, struct ofmt *output, efunc error,
395                  ListGen * listgen)
396 {
397     const struct itemplate *temp;
398     int j;
399     enum match_result m;
400     int64_t insn_end;
401     int32_t itimes;
402     int64_t start = offset;
403     int64_t wsize;              /* size for DB etc. */
404
405     errfunc = error;            /* to pass to other functions */
406     cpu = cp;
407     outfmt = output;            /* likewise */
408     list = listgen;             /* and again */
409
410     wsize = idata_bytes(instruction->opcode);
411     if (wsize == -1)
412         return 0;
413
414     if (wsize) {
415         extop *e;
416         int32_t t = instruction->times;
417         if (t < 0)
418             errfunc(ERR_PANIC,
419                     "instruction->times < 0 (%ld) in assemble()", t);
420
421         while (t--) {           /* repeat TIMES times */
422             list_for_each(e, instruction->eops) {
423                 if (e->type == EOT_DB_NUMBER) {
424                     if (wsize > 8) {
425                         errfunc(ERR_NONFATAL,
426                                 "integer supplied to a DT, DO or DY"
427                                 " instruction");
428                     } else {
429                         out(offset, segment, &e->offset,
430                             OUT_ADDRESS, wsize, e->segment, e->wrt);
431                         offset += wsize;
432                     }
433                 } else if (e->type == EOT_DB_STRING ||
434                            e->type == EOT_DB_STRING_FREE) {
435                     int align;
436
437                     out(offset, segment, e->stringval,
438                         OUT_RAWDATA, e->stringlen, NO_SEG, NO_SEG);
439                     align = e->stringlen % wsize;
440
441                     if (align) {
442                         align = wsize - align;
443                         out(offset, segment, zero_buffer,
444                             OUT_RAWDATA, align, NO_SEG, NO_SEG);
445                     }
446                     offset += e->stringlen + align;
447                 }
448             }
449             if (t > 0 && t == instruction->times - 1) {
450                 /*
451                  * Dummy call to list->output to give the offset to the
452                  * listing module.
453                  */
454                 list->output(offset, NULL, OUT_RAWDATA, 0);
455                 list->uplevel(LIST_TIMES);
456             }
457         }
458         if (instruction->times > 1)
459             list->downlevel(LIST_TIMES);
460         return offset - start;
461     }
462
463     if (instruction->opcode == I_INCBIN) {
464         const char *fname = instruction->eops->stringval;
465         FILE *fp;
466
467         fp = fopen(fname, "rb");
468         if (!fp) {
469             error(ERR_NONFATAL, "`incbin': unable to open file `%s'",
470                   fname);
471         } else if (fseek(fp, 0L, SEEK_END) < 0) {
472             error(ERR_NONFATAL, "`incbin': unable to seek on file `%s'",
473                   fname);
474             fclose(fp);
475         } else {
476             static char buf[4096];
477             size_t t = instruction->times;
478             size_t base = 0;
479             size_t len;
480
481             len = ftell(fp);
482             if (instruction->eops->next) {
483                 base = instruction->eops->next->offset;
484                 len -= base;
485                 if (instruction->eops->next->next &&
486                     len > (size_t)instruction->eops->next->next->offset)
487                     len = (size_t)instruction->eops->next->next->offset;
488             }
489             /*
490              * Dummy call to list->output to give the offset to the
491              * listing module.
492              */
493             list->output(offset, NULL, OUT_RAWDATA, 0);
494             list->uplevel(LIST_INCBIN);
495             while (t--) {
496                 size_t l;
497
498                 fseek(fp, base, SEEK_SET);
499                 l = len;
500                 while (l > 0) {
501                     int32_t m;
502                     m = fread(buf, 1, l > sizeof(buf) ? sizeof(buf) : l, fp);
503                     if (!m) {
504                         /*
505                          * This shouldn't happen unless the file
506                          * actually changes while we are reading
507                          * it.
508                          */
509                         error(ERR_NONFATAL,
510                               "`incbin': unexpected EOF while"
511                               " reading file `%s'", fname);
512                         t = 0;  /* Try to exit cleanly */
513                         break;
514                     }
515                     out(offset, segment, buf, OUT_RAWDATA, m,
516                         NO_SEG, NO_SEG);
517                     l -= m;
518                 }
519             }
520             list->downlevel(LIST_INCBIN);
521             if (instruction->times > 1) {
522                 /*
523                  * Dummy call to list->output to give the offset to the
524                  * listing module.
525                  */
526                 list->output(offset, NULL, OUT_RAWDATA, 0);
527                 list->uplevel(LIST_TIMES);
528                 list->downlevel(LIST_TIMES);
529             }
530             fclose(fp);
531             return instruction->times * len;
532         }
533         return 0;               /* if we're here, there's an error */
534     }
535
536     /* Check to see if we need an address-size prefix */
537     add_asp(instruction, bits);
538
539     m = find_match(&temp, instruction, segment, offset, bits);
540
541     if (m == MOK_GOOD) {
542         /* Matches! */
543         int64_t insn_size = calcsize(segment, offset, bits, instruction, temp);
544         itimes = instruction->times;
545         if (insn_size < 0)  /* shouldn't be, on pass two */
546             error(ERR_PANIC, "errors made it through from pass one");
547         else
548             while (itimes--) {
549                 for (j = 0; j < MAXPREFIX; j++) {
550                     uint8_t c = 0;
551                     switch (instruction->prefixes[j]) {
552                     case P_WAIT:
553                         c = 0x9B;
554                         break;
555                     case P_LOCK:
556                         c = 0xF0;
557                         break;
558                     case P_REPNE:
559                     case P_REPNZ:
560                     case P_XACQUIRE:
561                     case P_BND:
562                         c = 0xF2;
563                         break;
564                     case P_REPE:
565                     case P_REPZ:
566                     case P_REP:
567                     case P_XRELEASE:
568                         c = 0xF3;
569                         break;
570                     case R_CS:
571                         if (bits == 64) {
572                             error(ERR_WARNING | ERR_PASS2,
573                                   "cs segment base generated, but will be ignored in 64-bit mode");
574                         }
575                         c = 0x2E;
576                         break;
577                     case R_DS:
578                         if (bits == 64) {
579                             error(ERR_WARNING | ERR_PASS2,
580                                   "ds segment base generated, but will be ignored in 64-bit mode");
581                         }
582                         c = 0x3E;
583                         break;
584                     case R_ES:
585                         if (bits == 64) {
586                             error(ERR_WARNING | ERR_PASS2,
587                                   "es segment base generated, but will be ignored in 64-bit mode");
588                         }
589                         c = 0x26;
590                         break;
591                     case R_FS:
592                         c = 0x64;
593                         break;
594                     case R_GS:
595                         c = 0x65;
596                         break;
597                     case R_SS:
598                         if (bits == 64) {
599                             error(ERR_WARNING | ERR_PASS2,
600                                   "ss segment base generated, but will be ignored in 64-bit mode");
601                         }
602                         c = 0x36;
603                         break;
604                     case R_SEGR6:
605                     case R_SEGR7:
606                         error(ERR_NONFATAL,
607                               "segr6 and segr7 cannot be used as prefixes");
608                         break;
609                     case P_A16:
610                         if (bits == 64) {
611                             error(ERR_NONFATAL,
612                                   "16-bit addressing is not supported "
613                                   "in 64-bit mode");
614                         } else if (bits != 16)
615                             c = 0x67;
616                         break;
617                     case P_A32:
618                         if (bits != 32)
619                             c = 0x67;
620                         break;
621                     case P_A64:
622                         if (bits != 64) {
623                             error(ERR_NONFATAL,
624                                   "64-bit addressing is only supported "
625                                   "in 64-bit mode");
626                         }
627                         break;
628                     case P_ASP:
629                         c = 0x67;
630                         break;
631                     case P_O16:
632                         if (bits != 16)
633                             c = 0x66;
634                         break;
635                     case P_O32:
636                         if (bits == 16)
637                             c = 0x66;
638                         break;
639                     case P_O64:
640                         /* REX.W */
641                         break;
642                     case P_OSP:
643                         c = 0x66;
644                         break;
645                     case P_EVEX:
646                         /* EVEX */
647                         break;
648                     case P_none:
649                         break;
650                     default:
651                         error(ERR_PANIC, "invalid instruction prefix");
652                     }
653                     if (c != 0) {
654                         out(offset, segment, &c, OUT_RAWDATA, 1,
655                             NO_SEG, NO_SEG);
656                         offset++;
657                     }
658                 }
659                 insn_end = offset + insn_size;
660                 gencode(segment, offset, bits, instruction,
661                         temp, insn_end);
662                 offset += insn_size;
663                 if (itimes > 0 && itimes == instruction->times - 1) {
664                     /*
665                      * Dummy call to list->output to give the offset to the
666                      * listing module.
667                      */
668                     list->output(offset, NULL, OUT_RAWDATA, 0);
669                     list->uplevel(LIST_TIMES);
670                 }
671             }
672         if (instruction->times > 1)
673             list->downlevel(LIST_TIMES);
674         return offset - start;
675     } else {
676         /* No match */
677         switch (m) {
678         case MERR_OPSIZEMISSING:
679             error(ERR_NONFATAL, "operation size not specified");
680             break;
681         case MERR_OPSIZEMISMATCH:
682             error(ERR_NONFATAL, "mismatch in operand sizes");
683             break;
684         case MERR_BRNUMMISMATCH:
685             error(ERR_NONFATAL,
686                   "mismatch in the number of broadcasting elements");
687             break;
688         case MERR_BADCPU:
689             error(ERR_NONFATAL, "no instruction for this cpu level");
690             break;
691         case MERR_BADMODE:
692             error(ERR_NONFATAL, "instruction not supported in %d-bit mode",
693                   bits);
694             break;
695         case MERR_BADBND:
696             error(ERR_NONFATAL, "bnd prefix is not allowed");
697             break;
698         default:
699             error(ERR_NONFATAL,
700                   "invalid combination of opcode and operands");
701             break;
702         }
703     }
704     return 0;
705 }
706
707 int64_t insn_size(int32_t segment, int64_t offset, int bits, iflags_t cp,
708                   insn * instruction, efunc error)
709 {
710     const struct itemplate *temp;
711     enum match_result m;
712
713     errfunc = error;            /* to pass to other functions */
714     cpu = cp;
715
716     if (instruction->opcode == I_none)
717         return 0;
718
719     if (instruction->opcode == I_DB || instruction->opcode == I_DW ||
720         instruction->opcode == I_DD || instruction->opcode == I_DQ ||
721         instruction->opcode == I_DT || instruction->opcode == I_DO ||
722         instruction->opcode == I_DY) {
723         extop *e;
724         int32_t isize, osize, wsize;
725
726         isize = 0;
727         wsize = idata_bytes(instruction->opcode);
728
729         list_for_each(e, instruction->eops) {
730             int32_t align;
731
732             osize = 0;
733             if (e->type == EOT_DB_NUMBER) {
734                 osize = 1;
735                 warn_overflow_const(e->offset, wsize);
736             } else if (e->type == EOT_DB_STRING ||
737                        e->type == EOT_DB_STRING_FREE)
738                 osize = e->stringlen;
739
740             align = (-osize) % wsize;
741             if (align < 0)
742                 align += wsize;
743             isize += osize + align;
744         }
745         return isize * instruction->times;
746     }
747
748     if (instruction->opcode == I_INCBIN) {
749         const char *fname = instruction->eops->stringval;
750         FILE *fp;
751         int64_t val = 0;
752         size_t len;
753
754         fp = fopen(fname, "rb");
755         if (!fp)
756             error(ERR_NONFATAL, "`incbin': unable to open file `%s'",
757                   fname);
758         else if (fseek(fp, 0L, SEEK_END) < 0)
759             error(ERR_NONFATAL, "`incbin': unable to seek on file `%s'",
760                   fname);
761         else {
762             len = ftell(fp);
763             if (instruction->eops->next) {
764                 len -= instruction->eops->next->offset;
765                 if (instruction->eops->next->next &&
766                     len > (size_t)instruction->eops->next->next->offset) {
767                     len = (size_t)instruction->eops->next->next->offset;
768                 }
769             }
770             val = instruction->times * len;
771         }
772         if (fp)
773             fclose(fp);
774         return val;
775     }
776
777     /* Check to see if we need an address-size prefix */
778     add_asp(instruction, bits);
779
780     m = find_match(&temp, instruction, segment, offset, bits);
781     if (m == MOK_GOOD) {
782         /* we've matched an instruction. */
783         int64_t isize;
784         int j;
785
786         isize = calcsize(segment, offset, bits, instruction, temp);
787         if (isize < 0)
788             return -1;
789         for (j = 0; j < MAXPREFIX; j++) {
790             switch (instruction->prefixes[j]) {
791             case P_A16:
792                 if (bits != 16)
793                     isize++;
794                 break;
795             case P_A32:
796                 if (bits != 32)
797                     isize++;
798                 break;
799             case P_O16:
800                 if (bits != 16)
801                     isize++;
802                 break;
803             case P_O32:
804                 if (bits == 16)
805                     isize++;
806                 break;
807             case P_A64:
808             case P_O64:
809             case P_EVEX:
810             case P_none:
811                 break;
812             default:
813                 isize++;
814                 break;
815             }
816         }
817         return isize * instruction->times;
818     } else {
819         return -1;                  /* didn't match any instruction */
820     }
821 }
822
823 static void bad_hle_warn(const insn * ins, uint8_t hleok)
824 {
825     enum prefixes rep_pfx = ins->prefixes[PPS_REP];
826     enum whatwarn { w_none, w_lock, w_inval } ww;
827     static const enum whatwarn warn[2][4] =
828     {
829         { w_inval, w_inval, w_none, w_lock }, /* XACQUIRE */
830         { w_inval, w_none,  w_none, w_lock }, /* XRELEASE */
831     };
832     unsigned int n;
833
834     n = (unsigned int)rep_pfx - P_XACQUIRE;
835     if (n > 1)
836         return;                 /* Not XACQUIRE/XRELEASE */
837
838     ww = warn[n][hleok];
839     if (!is_class(MEMORY, ins->oprs[0].type))
840         ww = w_inval;           /* HLE requires operand 0 to be memory */
841
842     switch (ww) {
843     case w_none:
844         break;
845
846     case w_lock:
847         if (ins->prefixes[PPS_LOCK] != P_LOCK) {
848             errfunc(ERR_WARNING | ERR_WARN_HLE | ERR_PASS2,
849                     "%s with this instruction requires lock",
850                     prefix_name(rep_pfx));
851         }
852         break;
853
854     case w_inval:
855         errfunc(ERR_WARNING | ERR_WARN_HLE | ERR_PASS2,
856                 "%s invalid with this instruction",
857                 prefix_name(rep_pfx));
858         break;
859     }
860 }
861
862 /* Common construct */
863 #define case3(x) case (x): case (x)+1: case (x)+2
864 #define case4(x) case3(x): case (x)+3
865
866 static int64_t calcsize(int32_t segment, int64_t offset, int bits,
867                         insn * ins, const struct itemplate *temp)
868 {
869     const uint8_t *codes = temp->code;
870     int64_t length = 0;
871     uint8_t c;
872     int rex_mask = ~0;
873     int op1, op2;
874     struct operand *opx;
875     uint8_t opex = 0;
876     enum ea_type eat;
877     uint8_t hleok = 0;
878     bool lockcheck = true;
879     enum reg_enum mib_index = R_none;   /* For a separate index MIB reg form */
880
881     ins->rex = 0;               /* Ensure REX is reset */
882     eat = EA_SCALAR;            /* Expect a scalar EA */
883     memset(ins->evex_p, 0, 3);  /* Ensure EVEX is reset */
884
885     if (ins->prefixes[PPS_OSIZE] == P_O64)
886         ins->rex |= REX_W;
887
888     (void)segment;              /* Don't warn that this parameter is unused */
889     (void)offset;               /* Don't warn that this parameter is unused */
890
891     while (*codes) {
892         c = *codes++;
893         op1 = (c & 3) + ((opex & 1) << 2);
894         op2 = ((c >> 3) & 3) + ((opex & 2) << 1);
895         opx = &ins->oprs[op1];
896         opex = 0;               /* For the next iteration */
897
898         switch (c) {
899         case4(01):
900             codes += c, length += c;
901             break;
902
903         case3(05):
904             opex = c;
905             break;
906
907         case4(010):
908             ins->rex |=
909                 op_rexflags(opx, REX_B|REX_H|REX_P|REX_W);
910             codes++, length++;
911             break;
912
913         case4(014):
914             /* this is an index reg of MIB operand */
915             mib_index = opx->basereg;
916             break;
917
918         case4(020):
919         case4(024):
920             length++;
921             break;
922
923         case4(030):
924             length += 2;
925             break;
926
927         case4(034):
928             if (opx->type & (BITS16 | BITS32 | BITS64))
929                 length += (opx->type & BITS16) ? 2 : 4;
930             else
931                 length += (bits == 16) ? 2 : 4;
932             break;
933
934         case4(040):
935             length += 4;
936             break;
937
938         case4(044):
939             length += ins->addr_size >> 3;
940             break;
941
942         case4(050):
943             length++;
944             break;
945
946         case4(054):
947             length += 8; /* MOV reg64/imm */
948             break;
949
950         case4(060):
951             length += 2;
952             break;
953
954         case4(064):
955             if (opx->type & (BITS16 | BITS32 | BITS64))
956                 length += (opx->type & BITS16) ? 2 : 4;
957             else
958                 length += (bits == 16) ? 2 : 4;
959             break;
960
961         case4(070):
962             length += 4;
963             break;
964
965         case4(074):
966             length += 2;
967             break;
968
969         case 0172:
970         case 0173:
971             codes++;
972             length++;
973             break;
974
975         case4(0174):
976             length++;
977             break;
978
979         case4(0240):
980             ins->rex |= REX_EV;
981             ins->vexreg = regval(opx);
982             ins->evex_p[2] |= op_evexflags(opx, EVEX_P2VP, 2); /* High-16 NDS */
983             ins->vex_cm = *codes++;
984             ins->vex_wlp = *codes++;
985             ins->evex_tuple = (*codes++ - 0300);
986             break;
987
988         case 0250:
989             ins->rex |= REX_EV;
990             ins->vexreg = 0;
991             ins->vex_cm = *codes++;
992             ins->vex_wlp = *codes++;
993             ins->evex_tuple = (*codes++ - 0300);
994             break;
995
996         case4(0254):
997             length += 4;
998             break;
999
1000         case4(0260):
1001             ins->rex |= REX_V;
1002             ins->vexreg = regval(opx);
1003             ins->vex_cm = *codes++;
1004             ins->vex_wlp = *codes++;
1005             break;
1006
1007         case 0270:
1008             ins->rex |= REX_V;
1009             ins->vexreg = 0;
1010             ins->vex_cm = *codes++;
1011             ins->vex_wlp = *codes++;
1012             break;
1013
1014         case3(0271):
1015             hleok = c & 3;
1016             break;
1017
1018         case4(0274):
1019             length++;
1020             break;
1021
1022         case4(0300):
1023             break;
1024
1025         case 0310:
1026             if (bits == 64)
1027                 return -1;
1028             length += (bits != 16) && !has_prefix(ins, PPS_ASIZE, P_A16);
1029             break;
1030
1031         case 0311:
1032             length += (bits != 32) && !has_prefix(ins, PPS_ASIZE, P_A32);
1033             break;
1034
1035         case 0312:
1036             break;
1037
1038         case 0313:
1039             if (bits != 64 || has_prefix(ins, PPS_ASIZE, P_A16) ||
1040                 has_prefix(ins, PPS_ASIZE, P_A32))
1041                 return -1;
1042             break;
1043
1044         case4(0314):
1045             break;
1046
1047         case 0320:
1048         {
1049             enum prefixes pfx = ins->prefixes[PPS_OSIZE];
1050             if (pfx == P_O16)
1051                 break;
1052             if (pfx != P_none)
1053                 errfunc(ERR_WARNING | ERR_PASS2, "invalid operand size prefix");
1054             else
1055                 ins->prefixes[PPS_OSIZE] = P_O16;
1056             break;
1057         }
1058
1059         case 0321:
1060         {
1061             enum prefixes pfx = ins->prefixes[PPS_OSIZE];
1062             if (pfx == P_O32)
1063                 break;
1064             if (pfx != P_none)
1065                 errfunc(ERR_WARNING | ERR_PASS2, "invalid operand size prefix");
1066             else
1067                 ins->prefixes[PPS_OSIZE] = P_O32;
1068             break;
1069         }
1070
1071         case 0322:
1072             break;
1073
1074         case 0323:
1075             rex_mask &= ~REX_W;
1076             break;
1077
1078         case 0324:
1079             ins->rex |= REX_W;
1080             break;
1081
1082         case 0325:
1083             ins->rex |= REX_NH;
1084             break;
1085
1086         case 0326:
1087             break;
1088
1089         case 0330:
1090             codes++, length++;
1091             break;
1092
1093         case 0331:
1094             break;
1095
1096         case 0332:
1097         case 0333:
1098             length++;
1099             break;
1100
1101         case 0334:
1102             ins->rex |= REX_L;
1103             break;
1104
1105         case 0335:
1106             break;
1107
1108         case 0336:
1109             if (!ins->prefixes[PPS_REP])
1110                 ins->prefixes[PPS_REP] = P_REP;
1111             break;
1112
1113         case 0337:
1114             if (!ins->prefixes[PPS_REP])
1115                 ins->prefixes[PPS_REP] = P_REPNE;
1116             break;
1117
1118         case 0340:
1119             if (ins->oprs[0].segment != NO_SEG)
1120                 errfunc(ERR_NONFATAL, "attempt to reserve non-constant"
1121                         " quantity of BSS space");
1122             else
1123                 length += ins->oprs[0].offset;
1124             break;
1125
1126         case 0341:
1127             if (!ins->prefixes[PPS_WAIT])
1128                 ins->prefixes[PPS_WAIT] = P_WAIT;
1129             break;
1130
1131         case 0360:
1132             break;
1133
1134         case 0361:
1135             length++;
1136             break;
1137
1138         case 0364:
1139         case 0365:
1140             break;
1141
1142         case 0366:
1143         case 0367:
1144             length++;
1145             break;
1146
1147         case 0370:
1148         case 0371:
1149             break;
1150
1151         case 0373:
1152             length++;
1153             break;
1154
1155         case 0374:
1156             eat = EA_XMMVSIB;
1157             break;
1158
1159         case 0375:
1160             eat = EA_YMMVSIB;
1161             break;
1162
1163         case 0376:
1164             eat = EA_ZMMVSIB;
1165             break;
1166
1167         case4(0100):
1168         case4(0110):
1169         case4(0120):
1170         case4(0130):
1171         case4(0200):
1172         case4(0204):
1173         case4(0210):
1174         case4(0214):
1175         case4(0220):
1176         case4(0224):
1177         case4(0230):
1178         case4(0234):
1179             {
1180                 ea ea_data;
1181                 int rfield;
1182                 opflags_t rflags;
1183                 struct operand *opy = &ins->oprs[op2];
1184                 struct operand *op_er_sae;
1185
1186                 ea_data.rex = 0;           /* Ensure ea.REX is initially 0 */
1187
1188                 if (c <= 0177) {
1189                     /* pick rfield from operand b (opx) */
1190                     rflags = regflag(opx);
1191                     rfield = nasm_regvals[opx->basereg];
1192                 } else {
1193                     rflags = 0;
1194                     rfield = c & 7;
1195                 }
1196
1197                 /* EVEX.b1 : evex_brerop contains the operand position */
1198                 op_er_sae = (ins->evex_brerop >= 0 ?
1199                              &ins->oprs[ins->evex_brerop] : NULL);
1200
1201                 if (op_er_sae && (op_er_sae->decoflags & (ER | SAE))) {
1202                     /* set EVEX.b */
1203                     ins->evex_p[2] |= EVEX_P2B;
1204                     if (op_er_sae->decoflags & ER) {
1205                         /* set EVEX.RC (rounding control) */
1206                         ins->evex_p[2] |= ((ins->evex_rm - BRC_RN) << 5)
1207                                           & EVEX_P2RC;
1208                     }
1209                 } else {
1210                     /* set EVEX.L'L (vector length) */
1211                     ins->evex_p[2] |= ((ins->vex_wlp << (5 - 2)) & EVEX_P2LL);
1212                     ins->evex_p[1] |= ((ins->vex_wlp << (7 - 4)) & EVEX_P1W);
1213                     if (opy->decoflags & BRDCAST_MASK) {
1214                         /* set EVEX.b */
1215                         ins->evex_p[2] |= EVEX_P2B;
1216                     }
1217                 }
1218
1219                 /*
1220                  * if a separate form of MIB (ICC style) is used,
1221                  * the index reg info is merged into mem operand
1222                  */
1223                 if (mib_index != R_none) {
1224                     opy->indexreg = mib_index;
1225                     opy->scale = 1;
1226                     opy->hintbase = mib_index;
1227                     opy->hinttype = EAH_NOTBASE;
1228                 }
1229
1230                 /*
1231                  * only for mib operands, make a single reg index [reg*1].
1232                  * gas uses this form to explicitly denote index register.
1233                  */
1234                 if ((temp->flags & IF_MIB) &&
1235                     (opy->indexreg == -1 && opy->hintbase == opy->basereg &&
1236                      opy->hinttype == EAH_NOTBASE)) {
1237                     opy->indexreg = opy->basereg;
1238                     opy->basereg  = -1;
1239                     opy->scale    = 1;
1240                 }
1241
1242                 if (process_ea(opy, &ea_data, bits,
1243                                rfield, rflags, ins) != eat) {
1244                     errfunc(ERR_NONFATAL, "invalid effective address");
1245                     return -1;
1246                 } else {
1247                     ins->rex |= ea_data.rex;
1248                     length += ea_data.size;
1249                 }
1250             }
1251             break;
1252
1253         default:
1254             errfunc(ERR_PANIC, "internal instruction table corrupt"
1255                     ": instruction code \\%o (0x%02X) given", c, c);
1256             break;
1257         }
1258     }
1259
1260     ins->rex &= rex_mask;
1261
1262     if (ins->rex & REX_NH) {
1263         if (ins->rex & REX_H) {
1264             errfunc(ERR_NONFATAL, "instruction cannot use high registers");
1265             return -1;
1266         }
1267         ins->rex &= ~REX_P;        /* Don't force REX prefix due to high reg */
1268     }
1269
1270     if (ins->rex & (REX_V | REX_EV)) {
1271         int bad32 = REX_R|REX_W|REX_X|REX_B;
1272
1273         if (ins->rex & REX_H) {
1274             errfunc(ERR_NONFATAL, "cannot use high register in AVX instruction");
1275             return -1;
1276         }
1277         switch (ins->vex_wlp & 060) {
1278         case 000:
1279         case 040:
1280             ins->rex &= ~REX_W;
1281             break;
1282         case 020:
1283             ins->rex |= REX_W;
1284             bad32 &= ~REX_W;
1285             break;
1286         case 060:
1287             /* Follow REX_W */
1288             break;
1289         }
1290
1291         if (bits != 64 && ((ins->rex & bad32) || ins->vexreg > 7)) {
1292             errfunc(ERR_NONFATAL, "invalid operands in non-64-bit mode");
1293             return -1;
1294         } else if (!(ins->rex & REX_EV) &&
1295                    ((ins->vexreg > 15) || (ins->evex_p[0] & 0xf0))) {
1296             errfunc(ERR_NONFATAL, "invalid high-16 register in non-AVX-512");
1297             return -1;
1298         }
1299         if (ins->rex & REX_EV)
1300             length += 4;
1301         else if (ins->vex_cm != 1 || (ins->rex & (REX_W|REX_X|REX_B)))
1302             length += 3;
1303         else
1304             length += 2;
1305     } else if (ins->rex & REX_REAL) {
1306         if (ins->rex & REX_H) {
1307             errfunc(ERR_NONFATAL, "cannot use high register in rex instruction");
1308             return -1;
1309         } else if (bits == 64) {
1310             length++;
1311         } else if ((ins->rex & REX_L) &&
1312                    !(ins->rex & (REX_P|REX_W|REX_X|REX_B)) &&
1313                    cpu >= IF_X86_64) {
1314             /* LOCK-as-REX.R */
1315             assert_no_prefix(ins, PPS_LOCK);
1316             lockcheck = false;  /* Already errored, no need for warning */
1317             length++;
1318         } else {
1319             errfunc(ERR_NONFATAL, "invalid operands in non-64-bit mode");
1320             return -1;
1321         }
1322     }
1323
1324     if (has_prefix(ins, PPS_LOCK, P_LOCK) && lockcheck &&
1325         (!(temp->flags & IF_LOCK) || !is_class(MEMORY, ins->oprs[0].type))) {
1326         errfunc(ERR_WARNING | ERR_WARN_LOCK | ERR_PASS2 ,
1327                 "instruction is not lockable");
1328     }
1329
1330     bad_hle_warn(ins, hleok);
1331
1332     return length;
1333 }
1334
1335 static inline unsigned int emit_rex(insn *ins, int32_t segment, int64_t offset, int bits)
1336 {
1337     if (bits == 64) {
1338         if ((ins->rex & REX_REAL) && !(ins->rex & (REX_V | REX_EV))) {
1339             ins->rex = (ins->rex & REX_REAL) | REX_P;
1340             out(offset, segment, &ins->rex, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1341             ins->rex = 0;
1342             return 1;
1343         }
1344     }
1345
1346     return 0;
1347 }
1348
1349 static void gencode(int32_t segment, int64_t offset, int bits,
1350                     insn * ins, const struct itemplate *temp,
1351                     int64_t insn_end)
1352 {
1353     uint8_t c;
1354     uint8_t bytes[4];
1355     int64_t size;
1356     int64_t data;
1357     int op1, op2;
1358     struct operand *opx;
1359     const uint8_t *codes = temp->code;
1360     uint8_t opex = 0;
1361     enum ea_type eat = EA_SCALAR;
1362
1363     while (*codes) {
1364         c = *codes++;
1365         op1 = (c & 3) + ((opex & 1) << 2);
1366         op2 = ((c >> 3) & 3) + ((opex & 2) << 1);
1367         opx = &ins->oprs[op1];
1368         opex = 0;                /* For the next iteration */
1369
1370         switch (c) {
1371         case 01:
1372         case 02:
1373         case 03:
1374         case 04:
1375             offset += emit_rex(ins, segment, offset, bits);
1376             out(offset, segment, codes, OUT_RAWDATA, c, NO_SEG, NO_SEG);
1377             codes += c;
1378             offset += c;
1379             break;
1380
1381         case 05:
1382         case 06:
1383         case 07:
1384             opex = c;
1385             break;
1386
1387         case4(010):
1388             offset += emit_rex(ins, segment, offset, bits);
1389             bytes[0] = *codes++ + (regval(opx) & 7);
1390             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1391             offset += 1;
1392             break;
1393
1394         case4(014):
1395             break;
1396
1397         case4(020):
1398             if (opx->offset < -256 || opx->offset > 255) {
1399                 errfunc(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1400                         "byte value exceeds bounds");
1401             }
1402             out_imm8(offset, segment, opx);
1403             offset += 1;
1404             break;
1405
1406         case4(024):
1407             if (opx->offset < 0 || opx->offset > 255)
1408                 errfunc(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1409                         "unsigned byte value exceeds bounds");
1410             out_imm8(offset, segment, opx);
1411             offset += 1;
1412             break;
1413
1414         case4(030):
1415             warn_overflow_opd(opx, 2);
1416             data = opx->offset;
1417             out(offset, segment, &data, OUT_ADDRESS, 2,
1418                 opx->segment, opx->wrt);
1419             offset += 2;
1420             break;
1421
1422         case4(034):
1423             if (opx->type & (BITS16 | BITS32))
1424                 size = (opx->type & BITS16) ? 2 : 4;
1425             else
1426                 size = (bits == 16) ? 2 : 4;
1427             warn_overflow_opd(opx, size);
1428             data = opx->offset;
1429             out(offset, segment, &data, OUT_ADDRESS, size,
1430                 opx->segment, opx->wrt);
1431             offset += size;
1432             break;
1433
1434         case4(040):
1435             warn_overflow_opd(opx, 4);
1436             data = opx->offset;
1437             out(offset, segment, &data, OUT_ADDRESS, 4,
1438                 opx->segment, opx->wrt);
1439             offset += 4;
1440             break;
1441
1442         case4(044):
1443             data = opx->offset;
1444             size = ins->addr_size >> 3;
1445             warn_overflow_opd(opx, size);
1446             out(offset, segment, &data, OUT_ADDRESS, size,
1447                 opx->segment, opx->wrt);
1448             offset += size;
1449             break;
1450
1451         case4(050):
1452             if (opx->segment != segment) {
1453                 data = opx->offset;
1454                 out(offset, segment, &data,
1455                     OUT_REL1ADR, insn_end - offset,
1456                     opx->segment, opx->wrt);
1457             } else {
1458                 data = opx->offset - insn_end;
1459                 if (data > 127 || data < -128)
1460                     errfunc(ERR_NONFATAL, "short jump is out of range");
1461                 out(offset, segment, &data,
1462                     OUT_ADDRESS, 1, NO_SEG, NO_SEG);
1463             }
1464             offset += 1;
1465             break;
1466
1467         case4(054):
1468             data = (int64_t)opx->offset;
1469             out(offset, segment, &data, OUT_ADDRESS, 8,
1470                 opx->segment, opx->wrt);
1471             offset += 8;
1472             break;
1473
1474         case4(060):
1475             if (opx->segment != segment) {
1476                 data = opx->offset;
1477                 out(offset, segment, &data,
1478                     OUT_REL2ADR, insn_end - offset,
1479                     opx->segment, opx->wrt);
1480             } else {
1481                 data = opx->offset - insn_end;
1482                 out(offset, segment, &data,
1483                     OUT_ADDRESS, 2, NO_SEG, NO_SEG);
1484             }
1485             offset += 2;
1486             break;
1487
1488         case4(064):
1489             if (opx->type & (BITS16 | BITS32 | BITS64))
1490                 size = (opx->type & BITS16) ? 2 : 4;
1491             else
1492                 size = (bits == 16) ? 2 : 4;
1493             if (opx->segment != segment) {
1494                 data = opx->offset;
1495                 out(offset, segment, &data,
1496                     size == 2 ? OUT_REL2ADR : OUT_REL4ADR,
1497                     insn_end - offset, opx->segment, opx->wrt);
1498             } else {
1499                 data = opx->offset - insn_end;
1500                 out(offset, segment, &data,
1501                     OUT_ADDRESS, size, NO_SEG, NO_SEG);
1502             }
1503             offset += size;
1504             break;
1505
1506         case4(070):
1507             if (opx->segment != segment) {
1508                 data = opx->offset;
1509                 out(offset, segment, &data,
1510                     OUT_REL4ADR, insn_end - offset,
1511                     opx->segment, opx->wrt);
1512             } else {
1513                 data = opx->offset - insn_end;
1514                 out(offset, segment, &data,
1515                     OUT_ADDRESS, 4, NO_SEG, NO_SEG);
1516             }
1517             offset += 4;
1518             break;
1519
1520         case4(074):
1521             if (opx->segment == NO_SEG)
1522                 errfunc(ERR_NONFATAL, "value referenced by FAR is not"
1523                         " relocatable");
1524             data = 0;
1525             out(offset, segment, &data, OUT_ADDRESS, 2,
1526                 outfmt->segbase(1 + opx->segment),
1527                 opx->wrt);
1528             offset += 2;
1529             break;
1530
1531         case 0172:
1532             c = *codes++;
1533             opx = &ins->oprs[c >> 3];
1534             bytes[0] = nasm_regvals[opx->basereg] << 4;
1535             opx = &ins->oprs[c & 7];
1536             if (opx->segment != NO_SEG || opx->wrt != NO_SEG) {
1537                 errfunc(ERR_NONFATAL,
1538                         "non-absolute expression not permitted as argument %d",
1539                         c & 7);
1540             } else {
1541                 if (opx->offset & ~15) {
1542                     errfunc(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1543                             "four-bit argument exceeds bounds");
1544                 }
1545                 bytes[0] |= opx->offset & 15;
1546             }
1547             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1548             offset++;
1549             break;
1550
1551         case 0173:
1552             c = *codes++;
1553             opx = &ins->oprs[c >> 4];
1554             bytes[0] = nasm_regvals[opx->basereg] << 4;
1555             bytes[0] |= c & 15;
1556             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1557             offset++;
1558             break;
1559
1560         case4(0174):
1561             bytes[0] = nasm_regvals[opx->basereg] << 4;
1562             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1563             offset++;
1564             break;
1565
1566         case4(0254):
1567             data = opx->offset;
1568             if (opx->wrt == NO_SEG && opx->segment == NO_SEG &&
1569                 (int32_t)data != (int64_t)data) {
1570                 errfunc(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1571                         "signed dword immediate exceeds bounds");
1572             }
1573             out(offset, segment, &data, OUT_ADDRESS, 4,
1574                 opx->segment, opx->wrt);
1575             offset += 4;
1576             break;
1577
1578         case4(0240):
1579         case 0250:
1580             codes += 3;
1581             ins->evex_p[2] |= op_evexflags(&ins->oprs[0],
1582                                            EVEX_P2Z | EVEX_P2AAA, 2);
1583             ins->evex_p[2] ^= EVEX_P2VP;        /* 1's complement */
1584             bytes[0] = 0x62;
1585             /* EVEX.X can be set by either REX or EVEX for different reasons */
1586             bytes[1] = ((((ins->rex & 7) << 5) |
1587                          (ins->evex_p[0] & (EVEX_P0X | EVEX_P0RP))) ^ 0xf0) |
1588                        (ins->vex_cm & 3);
1589             bytes[2] = ((ins->rex & REX_W) << (7 - 3)) |
1590                        ((~ins->vexreg & 15) << 3) |
1591                        (1 << 2) | (ins->vex_wlp & 3);
1592             bytes[3] = ins->evex_p[2];
1593             out(offset, segment, &bytes, OUT_RAWDATA, 4, NO_SEG, NO_SEG);
1594             offset += 4;
1595             break;
1596
1597         case4(0260):
1598         case 0270:
1599             codes += 2;
1600             if (ins->vex_cm != 1 || (ins->rex & (REX_W|REX_X|REX_B))) {
1601                 bytes[0] = (ins->vex_cm >> 6) ? 0x8f : 0xc4;
1602                 bytes[1] = (ins->vex_cm & 31) | ((~ins->rex & 7) << 5);
1603                 bytes[2] = ((ins->rex & REX_W) << (7-3)) |
1604                     ((~ins->vexreg & 15)<< 3) | (ins->vex_wlp & 07);
1605                 out(offset, segment, &bytes, OUT_RAWDATA, 3, NO_SEG, NO_SEG);
1606                 offset += 3;
1607             } else {
1608                 bytes[0] = 0xc5;
1609                 bytes[1] = ((~ins->rex & REX_R) << (7-2)) |
1610                     ((~ins->vexreg & 15) << 3) | (ins->vex_wlp & 07);
1611                 out(offset, segment, &bytes, OUT_RAWDATA, 2, NO_SEG, NO_SEG);
1612                 offset += 2;
1613             }
1614             break;
1615
1616         case 0271:
1617         case 0272:
1618         case 0273:
1619             break;
1620
1621         case4(0274):
1622         {
1623             uint64_t uv, um;
1624             int s;
1625
1626             if (ins->rex & REX_W)
1627                 s = 64;
1628             else if (ins->prefixes[PPS_OSIZE] == P_O16)
1629                 s = 16;
1630             else if (ins->prefixes[PPS_OSIZE] == P_O32)
1631                 s = 32;
1632             else
1633                 s = bits;
1634
1635             um = (uint64_t)2 << (s-1);
1636             uv = opx->offset;
1637
1638             if (uv > 127 && uv < (uint64_t)-128 &&
1639                 (uv < um-128 || uv > um-1)) {
1640                 /* If this wasn't explicitly byte-sized, warn as though we
1641                  * had fallen through to the imm16/32/64 case.
1642                  */
1643                 errfunc(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1644                         "%s value exceeds bounds",
1645                         (opx->type & BITS8) ? "signed byte" :
1646                         s == 16 ? "word" :
1647                         s == 32 ? "dword" :
1648                         "signed dword");
1649             }
1650             if (opx->segment != NO_SEG) {
1651                 data = uv;
1652                 out(offset, segment, &data, OUT_ADDRESS, 1,
1653                     opx->segment, opx->wrt);
1654             } else {
1655                 bytes[0] = uv;
1656                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG,
1657                     NO_SEG);
1658             }
1659             offset += 1;
1660             break;
1661         }
1662
1663         case4(0300):
1664             break;
1665
1666         case 0310:
1667             if (bits == 32 && !has_prefix(ins, PPS_ASIZE, P_A16)) {
1668                 *bytes = 0x67;
1669                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1670                 offset += 1;
1671             } else
1672                 offset += 0;
1673             break;
1674
1675         case 0311:
1676             if (bits != 32 && !has_prefix(ins, PPS_ASIZE, P_A32)) {
1677                 *bytes = 0x67;
1678                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1679                 offset += 1;
1680             } else
1681                 offset += 0;
1682             break;
1683
1684         case 0312:
1685             break;
1686
1687         case 0313:
1688             ins->rex = 0;
1689             break;
1690
1691         case4(0314):
1692             break;
1693
1694         case 0320:
1695         case 0321:
1696             break;
1697
1698         case 0322:
1699         case 0323:
1700             break;
1701
1702         case 0324:
1703             ins->rex |= REX_W;
1704             break;
1705
1706         case 0325:
1707             break;
1708
1709         case 0326:
1710             break;
1711
1712         case 0330:
1713             *bytes = *codes++ ^ get_cond_opcode(ins->condition);
1714             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1715             offset += 1;
1716             break;
1717
1718         case 0331:
1719             break;
1720
1721         case 0332:
1722         case 0333:
1723             *bytes = c - 0332 + 0xF2;
1724             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1725             offset += 1;
1726             break;
1727
1728         case 0334:
1729             if (ins->rex & REX_R) {
1730                 *bytes = 0xF0;
1731                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1732                 offset += 1;
1733             }
1734             ins->rex &= ~(REX_L|REX_R);
1735             break;
1736
1737         case 0335:
1738             break;
1739
1740         case 0336:
1741         case 0337:
1742             break;
1743
1744         case 0340:
1745             if (ins->oprs[0].segment != NO_SEG)
1746                 errfunc(ERR_PANIC, "non-constant BSS size in pass two");
1747             else {
1748                 int64_t size = ins->oprs[0].offset;
1749                 if (size > 0)
1750                     out(offset, segment, NULL,
1751                         OUT_RESERVE, size, NO_SEG, NO_SEG);
1752                 offset += size;
1753             }
1754             break;
1755
1756         case 0341:
1757             break;
1758
1759         case 0360:
1760             break;
1761
1762         case 0361:
1763             bytes[0] = 0x66;
1764             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1765             offset += 1;
1766             break;
1767
1768         case 0364:
1769         case 0365:
1770             break;
1771
1772         case 0366:
1773         case 0367:
1774             *bytes = c - 0366 + 0x66;
1775             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1776             offset += 1;
1777             break;
1778
1779         case3(0370):
1780             break;
1781
1782         case 0373:
1783             *bytes = bits == 16 ? 3 : 5;
1784             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1785             offset += 1;
1786             break;
1787
1788         case 0374:
1789             eat = EA_XMMVSIB;
1790             break;
1791
1792         case 0375:
1793             eat = EA_YMMVSIB;
1794             break;
1795
1796         case 0376:
1797             eat = EA_ZMMVSIB;
1798             break;
1799
1800         case4(0100):
1801         case4(0110):
1802         case4(0120):
1803         case4(0130):
1804         case4(0200):
1805         case4(0204):
1806         case4(0210):
1807         case4(0214):
1808         case4(0220):
1809         case4(0224):
1810         case4(0230):
1811         case4(0234):
1812             {
1813                 ea ea_data;
1814                 int rfield;
1815                 opflags_t rflags;
1816                 uint8_t *p;
1817                 int32_t s;
1818                 struct operand *opy = &ins->oprs[op2];
1819
1820                 if (c <= 0177) {
1821                     /* pick rfield from operand b (opx) */
1822                     rflags = regflag(opx);
1823                     rfield = nasm_regvals[opx->basereg];
1824                 } else {
1825                     /* rfield is constant */
1826                     rflags = 0;
1827                     rfield = c & 7;
1828                 }
1829
1830                 if (process_ea(opy, &ea_data, bits,
1831                                rfield, rflags, ins) != eat)
1832                     errfunc(ERR_NONFATAL, "invalid effective address");
1833
1834                 p = bytes;
1835                 *p++ = ea_data.modrm;
1836                 if (ea_data.sib_present)
1837                     *p++ = ea_data.sib;
1838
1839                 s = p - bytes;
1840                 out(offset, segment, bytes, OUT_RAWDATA, s, NO_SEG, NO_SEG);
1841
1842                 /*
1843                  * Make sure the address gets the right offset in case
1844                  * the line breaks in the .lst file (BR 1197827)
1845                  */
1846                 offset += s;
1847                 s = 0;
1848
1849                 switch (ea_data.bytes) {
1850                 case 0:
1851                     break;
1852                 case 1:
1853                 case 2:
1854                 case 4:
1855                 case 8:
1856                     /* use compressed displacement, if available */
1857                     data = ea_data.disp8 ? ea_data.disp8 : opy->offset;
1858                     s += ea_data.bytes;
1859                     if (ea_data.rip) {
1860                         if (opy->segment == segment) {
1861                             data -= insn_end;
1862                             if (overflow_signed(data, ea_data.bytes))
1863                                 warn_overflow(ERR_PASS2, ea_data.bytes);
1864                             out(offset, segment, &data, OUT_ADDRESS,
1865                                 ea_data.bytes, NO_SEG, NO_SEG);
1866                         } else {
1867                             /* overflow check in output/linker? */
1868                             out(offset, segment, &data,        OUT_REL4ADR,
1869                                 insn_end - offset, opy->segment, opy->wrt);
1870                         }
1871                     } else {
1872                         if (overflow_general(data, ins->addr_size >> 3) ||
1873                             signed_bits(data, ins->addr_size) !=
1874                             signed_bits(data, ea_data.bytes * 8))
1875                             warn_overflow(ERR_PASS2, ea_data.bytes);
1876
1877                         out(offset, segment, &data, OUT_ADDRESS,
1878                             ea_data.bytes, opy->segment, opy->wrt);
1879                     }
1880                     break;
1881                 default:
1882                     /* Impossible! */
1883                     errfunc(ERR_PANIC,
1884                             "Invalid amount of bytes (%d) for offset?!",
1885                             ea_data.bytes);
1886                     break;
1887                 }
1888                 offset += s;
1889             }
1890             break;
1891
1892         default:
1893             errfunc(ERR_PANIC, "internal instruction table corrupt"
1894                     ": instruction code \\%o (0x%02X) given", c, c);
1895             break;
1896         }
1897     }
1898 }
1899
1900 static opflags_t regflag(const operand * o)
1901 {
1902     if (!is_register(o->basereg))
1903         errfunc(ERR_PANIC, "invalid operand passed to regflag()");
1904     return nasm_reg_flags[o->basereg];
1905 }
1906
1907 static int32_t regval(const operand * o)
1908 {
1909     if (!is_register(o->basereg))
1910         errfunc(ERR_PANIC, "invalid operand passed to regval()");
1911     return nasm_regvals[o->basereg];
1912 }
1913
1914 static int op_rexflags(const operand * o, int mask)
1915 {
1916     opflags_t flags;
1917     int val;
1918
1919     if (!is_register(o->basereg))
1920         errfunc(ERR_PANIC, "invalid operand passed to op_rexflags()");
1921
1922     flags = nasm_reg_flags[o->basereg];
1923     val = nasm_regvals[o->basereg];
1924
1925     return rexflags(val, flags, mask);
1926 }
1927
1928 static int rexflags(int val, opflags_t flags, int mask)
1929 {
1930     int rex = 0;
1931
1932     if (val >= 0 && (val & 8))
1933         rex |= REX_B|REX_X|REX_R;
1934     if (flags & BITS64)
1935         rex |= REX_W;
1936     if (!(REG_HIGH & ~flags))                   /* AH, CH, DH, BH */
1937         rex |= REX_H;
1938     else if (!(REG8 & ~flags) && val >= 4)      /* SPL, BPL, SIL, DIL */
1939         rex |= REX_P;
1940
1941     return rex & mask;
1942 }
1943
1944 static int evexflags(int val, decoflags_t deco,
1945                      int mask, uint8_t byte)
1946 {
1947     int evex = 0;
1948
1949     switch (byte) {
1950     case 0:
1951         if (val >= 0 && (val & 16))
1952             evex |= (EVEX_P0RP | EVEX_P0X);
1953         break;
1954     case 2:
1955         if (val >= 0 && (val & 16))
1956             evex |= EVEX_P2VP;
1957         if (deco & Z)
1958             evex |= EVEX_P2Z;
1959         if (deco & OPMASK_MASK)
1960             evex |= deco & EVEX_P2AAA;
1961         break;
1962     }
1963     return evex & mask;
1964 }
1965
1966 static int op_evexflags(const operand * o, int mask, uint8_t byte)
1967 {
1968     int val;
1969
1970     if (!is_register(o->basereg))
1971         errfunc(ERR_PANIC, "invalid operand passed to op_evexflags()");
1972
1973     val = nasm_regvals[o->basereg];
1974
1975     return evexflags(val, o->decoflags, mask, byte);
1976 }
1977
1978 static enum match_result find_match(const struct itemplate **tempp,
1979                                     insn *instruction,
1980                                     int32_t segment, int64_t offset, int bits)
1981 {
1982     const struct itemplate *temp;
1983     enum match_result m, merr;
1984     opflags_t xsizeflags[MAX_OPERANDS];
1985     bool opsizemissing = false;
1986     int8_t broadcast = instruction->evex_brerop;
1987     int i;
1988
1989     /* broadcasting uses a different data element size */
1990     for (i = 0; i < instruction->operands; i++)
1991         if (i == broadcast)
1992             xsizeflags[i] = instruction->oprs[i].decoflags & BRSIZE_MASK;
1993         else
1994             xsizeflags[i] = instruction->oprs[i].type & SIZE_MASK;
1995
1996     merr = MERR_INVALOP;
1997
1998     for (temp = nasm_instructions[instruction->opcode];
1999          temp->opcode != I_none; temp++) {
2000         m = matches(temp, instruction, bits);
2001         if (m == MOK_JUMP) {
2002             if (jmp_match(segment, offset, bits, instruction, temp))
2003                 m = MOK_GOOD;
2004             else
2005                 m = MERR_INVALOP;
2006         } else if (m == MERR_OPSIZEMISSING &&
2007                    (temp->flags & IF_SMASK) != IF_SX) {
2008             /*
2009              * Missing operand size and a candidate for fuzzy matching...
2010              */
2011             for (i = 0; i < temp->operands; i++)
2012                 if (i == broadcast)
2013                     xsizeflags[i] |= temp->deco[i] & BRSIZE_MASK;
2014                 else
2015                     xsizeflags[i] |= temp->opd[i] & SIZE_MASK;
2016             opsizemissing = true;
2017         }
2018         if (m > merr)
2019             merr = m;
2020         if (merr == MOK_GOOD)
2021             goto done;
2022     }
2023
2024     /* No match, but see if we can get a fuzzy operand size match... */
2025     if (!opsizemissing)
2026         goto done;
2027
2028     for (i = 0; i < instruction->operands; i++) {
2029         /*
2030          * We ignore extrinsic operand sizes on registers, so we should
2031          * never try to fuzzy-match on them.  This also resolves the case
2032          * when we have e.g. "xmmrm128" in two different positions.
2033          */
2034         if (is_class(REGISTER, instruction->oprs[i].type))
2035             continue;
2036
2037         /* This tests if xsizeflags[i] has more than one bit set */
2038         if ((xsizeflags[i] & (xsizeflags[i]-1)))
2039             goto done;                /* No luck */
2040
2041         if (i == broadcast) {
2042             instruction->oprs[i].decoflags |= xsizeflags[i];
2043             instruction->oprs[i].type |= (xsizeflags[i] == BR_BITS32 ?
2044                                           BITS32 : BITS64);
2045         } else {
2046             instruction->oprs[i].type |= xsizeflags[i]; /* Set the size */
2047         }
2048     }
2049
2050     /* Try matching again... */
2051     for (temp = nasm_instructions[instruction->opcode];
2052          temp->opcode != I_none; temp++) {
2053         m = matches(temp, instruction, bits);
2054         if (m == MOK_JUMP) {
2055             if (jmp_match(segment, offset, bits, instruction, temp))
2056                 m = MOK_GOOD;
2057             else
2058                 m = MERR_INVALOP;
2059         }
2060         if (m > merr)
2061             merr = m;
2062         if (merr == MOK_GOOD)
2063             goto done;
2064     }
2065
2066 done:
2067     *tempp = temp;
2068     return merr;
2069 }
2070
2071 static enum match_result matches(const struct itemplate *itemp,
2072                                  insn *instruction, int bits)
2073 {
2074     opflags_t size[MAX_OPERANDS], asize;
2075     bool opsizemissing = false;
2076     int i, oprs;
2077
2078     /*
2079      * Check the opcode
2080      */
2081     if (itemp->opcode != instruction->opcode)
2082         return MERR_INVALOP;
2083
2084     /*
2085      * Count the operands
2086      */
2087     if (itemp->operands != instruction->operands)
2088         return MERR_INVALOP;
2089
2090     /*
2091      * Is it legal?
2092      */
2093     if (!(optimizing > 0) && (itemp->flags & IF_OPT))
2094         return MERR_INVALOP;
2095
2096     /*
2097      * Check that no spurious colons or TOs are present
2098      */
2099     for (i = 0; i < itemp->operands; i++)
2100         if (instruction->oprs[i].type & ~itemp->opd[i] & (COLON | TO))
2101             return MERR_INVALOP;
2102
2103     /*
2104      * Process size flags
2105      */
2106     switch (itemp->flags & IF_SMASK) {
2107     case IF_SB:
2108         asize = BITS8;
2109         break;
2110     case IF_SW:
2111         asize = BITS16;
2112         break;
2113     case IF_SD:
2114         asize = BITS32;
2115         break;
2116     case IF_SQ:
2117         asize = BITS64;
2118         break;
2119     case IF_SO:
2120         asize = BITS128;
2121         break;
2122     case IF_SY:
2123         asize = BITS256;
2124         break;
2125     case IF_SZ:
2126         asize = BITS512;
2127         break;
2128     case IF_SIZE:
2129         switch (bits) {
2130         case 16:
2131             asize = BITS16;
2132             break;
2133         case 32:
2134             asize = BITS32;
2135             break;
2136         case 64:
2137             asize = BITS64;
2138             break;
2139         default:
2140             asize = 0;
2141             break;
2142         }
2143         break;
2144     default:
2145         asize = 0;
2146         break;
2147     }
2148
2149     if (itemp->flags & IF_ARMASK) {
2150         /* S- flags only apply to a specific operand */
2151         i = ((itemp->flags & IF_ARMASK) >> IF_ARSHFT) - 1;
2152         memset(size, 0, sizeof size);
2153         size[i] = asize;
2154     } else {
2155         /* S- flags apply to all operands */
2156         for (i = 0; i < MAX_OPERANDS; i++)
2157             size[i] = asize;
2158     }
2159
2160     /*
2161      * Check that the operand flags all match up,
2162      * it's a bit tricky so lets be verbose:
2163      *
2164      * 1) Find out the size of operand. If instruction
2165      *    doesn't have one specified -- we're trying to
2166      *    guess it either from template (IF_S* flag) or
2167      *    from code bits.
2168      *
2169      * 2) If template operand do not match the instruction OR
2170      *    template has an operand size specified AND this size differ
2171      *    from which instruction has (perhaps we got it from code bits)
2172      *    we are:
2173      *      a)  Check that only size of instruction and operand is differ
2174      *          other characteristics do match
2175      *      b)  Perhaps it's a register specified in instruction so
2176      *          for such a case we just mark that operand as "size
2177      *          missing" and this will turn on fuzzy operand size
2178      *          logic facility (handled by a caller)
2179      */
2180     for (i = 0; i < itemp->operands; i++) {
2181         opflags_t type = instruction->oprs[i].type;
2182         decoflags_t deco = instruction->oprs[i].decoflags;
2183         bool is_broadcast = deco & BRDCAST_MASK;
2184         uint8_t brcast_num = 0;
2185         opflags_t template_opsize, insn_opsize;
2186
2187         if (!(type & SIZE_MASK))
2188             type |= size[i];
2189
2190         insn_opsize     = type & SIZE_MASK;
2191         if (!is_broadcast) {
2192             template_opsize = itemp->opd[i] & SIZE_MASK;
2193         } else {
2194             decoflags_t deco_brsize = itemp->deco[i] & BRSIZE_MASK;
2195             /*
2196              * when broadcasting, the element size depends on
2197              * the instruction type. decorator flag should match.
2198              */
2199
2200             if (deco_brsize) {
2201                 template_opsize = (deco_brsize == BR_BITS32 ? BITS32 : BITS64);
2202                 /* calculate the proper number : {1to<brcast_num>} */
2203                 brcast_num = (itemp->opd[i] & SIZE_MASK) / BITS128 *
2204                                 BITS64 / template_opsize * 2;
2205             } else {
2206                 template_opsize = 0;
2207             }
2208         }
2209
2210         if ((itemp->opd[i] & ~type & ~SIZE_MASK) ||
2211             (deco & ~itemp->deco[i] & ~BRNUM_MASK)) {
2212             return MERR_INVALOP;
2213         } else if (template_opsize) {
2214             if (template_opsize != insn_opsize) {
2215                 if (insn_opsize) {
2216                     return MERR_INVALOP;
2217                 } else if (!is_class(REGISTER, type)) {
2218                     /*
2219                      * Note: we don't honor extrinsic operand sizes for registers,
2220                      * so "missing operand size" for a register should be
2221                      * considered a wildcard match rather than an error.
2222                      */
2223                     opsizemissing = true;
2224                 }
2225             } else if (is_broadcast &&
2226                        (brcast_num !=
2227                         (8U << ((deco & BRNUM_MASK) >> BRNUM_SHIFT)))) {
2228                 /*
2229                  * broadcasting opsize matches but the number of repeated memory
2230                  * element does not match.
2231                  * if 64b double precision float is broadcasted to zmm (512b),
2232                  * broadcasting decorator must be {1to8}.
2233                  */
2234                 return MERR_BRNUMMISMATCH;
2235             }
2236         } else if (is_register(instruction->oprs[i].basereg) &&
2237                    nasm_regvals[instruction->oprs[i].basereg] >= 16 &&
2238                    !(itemp->flags & IF_AVX512)) {
2239             return MERR_ENCMISMATCH;
2240         } else if (instruction->prefixes[PPS_EVEX] &&
2241                    !(itemp->flags & IF_AVX512)) {
2242             return MERR_ENCMISMATCH;
2243         }
2244     }
2245
2246     if (opsizemissing)
2247         return MERR_OPSIZEMISSING;
2248
2249     /*
2250      * Check operand sizes
2251      */
2252     if (itemp->flags & (IF_SM | IF_SM2)) {
2253         oprs = (itemp->flags & IF_SM2 ? 2 : itemp->operands);
2254         for (i = 0; i < oprs; i++) {
2255             asize = itemp->opd[i] & SIZE_MASK;
2256             if (asize) {
2257                 for (i = 0; i < oprs; i++)
2258                     size[i] = asize;
2259                 break;
2260             }
2261         }
2262     } else {
2263         oprs = itemp->operands;
2264     }
2265
2266     for (i = 0; i < itemp->operands; i++) {
2267         if (!(itemp->opd[i] & SIZE_MASK) &&
2268             (instruction->oprs[i].type & SIZE_MASK & ~size[i]))
2269             return MERR_OPSIZEMISMATCH;
2270     }
2271
2272     /*
2273      * Check template is okay at the set cpu level
2274      */
2275     if (((itemp->flags & IF_PLEVEL) > cpu))
2276         return MERR_BADCPU;
2277
2278     /*
2279      * Verify the appropriate long mode flag.
2280      */
2281     if ((itemp->flags & (bits == 64 ? IF_NOLONG : IF_LONG)))
2282         return MERR_BADMODE;
2283
2284     /*
2285      * If we have a HLE prefix, look for the NOHLE flag
2286      */
2287     if ((itemp->flags & IF_NOHLE) &&
2288         (has_prefix(instruction, PPS_REP, P_XACQUIRE) ||
2289          has_prefix(instruction, PPS_REP, P_XRELEASE)))
2290         return MERR_BADHLE;
2291
2292     /*
2293      * Check if special handling needed for Jumps
2294      */
2295     if ((itemp->code[0] & ~1) == 0370)
2296         return MOK_JUMP;
2297
2298     /*
2299      * Check if BND prefix is allowed
2300      */
2301     if ((IF_BND & ~itemp->flags) &&
2302         has_prefix(instruction, PPS_REP, P_BND))
2303         return MERR_BADBND;
2304
2305     return MOK_GOOD;
2306 }
2307
2308 /*
2309  * Check if ModR/M.mod should/can be 01.
2310  * - EAF_BYTEOFFS is set
2311  * - offset can fit in a byte when EVEX is not used
2312  * - offset can be compressed when EVEX is used
2313  */
2314 #define IS_MOD_01()     (input->eaflags & EAF_BYTEOFFS ||       \
2315                          (o >= -128 && o <= 127 &&              \
2316                           seg == NO_SEG && !forw_ref &&         \
2317                           !(input->eaflags & EAF_WORDOFFS) &&   \
2318                           !(ins->rex & REX_EV)) ||              \
2319                          (ins->rex & REX_EV &&                  \
2320                           is_disp8n(input, ins, &output->disp8)))
2321
2322 static enum ea_type process_ea(operand *input, ea *output, int bits,
2323                                int rfield, opflags_t rflags, insn *ins)
2324 {
2325     bool forw_ref = !!(input->opflags & OPFLAG_UNKNOWN);
2326     int addrbits = ins->addr_size;
2327
2328     output->type    = EA_SCALAR;
2329     output->rip     = false;
2330     output->disp8   = 0;
2331
2332     /* REX flags for the rfield operand */
2333     output->rex     |= rexflags(rfield, rflags, REX_R | REX_P | REX_W | REX_H);
2334     /* EVEX.R' flag for the REG operand */
2335     ins->evex_p[0]  |= evexflags(rfield, 0, EVEX_P0RP, 0);
2336
2337     if (is_class(REGISTER, input->type)) {
2338         /*
2339          * It's a direct register.
2340          */
2341         if (!is_register(input->basereg))
2342             goto err;
2343
2344         if (!is_reg_class(REG_EA, input->basereg))
2345             goto err;
2346
2347         /* broadcasting is not available with a direct register operand. */
2348         if (input->decoflags & BRDCAST_MASK) {
2349             nasm_error(ERR_NONFATAL, "Broadcasting not allowed from a register");
2350             goto err;
2351         }
2352
2353         output->rex         |= op_rexflags(input, REX_B | REX_P | REX_W | REX_H);
2354         ins->evex_p[0]      |= op_evexflags(input, EVEX_P0X, 0);
2355         output->sib_present = false;    /* no SIB necessary */
2356         output->bytes       = 0;        /* no offset necessary either */
2357         output->modrm       = GEN_MODRM(3, rfield, nasm_regvals[input->basereg]);
2358     } else {
2359         /*
2360          * It's a memory reference.
2361          */
2362
2363         /* Embedded rounding or SAE is not available with a mem ref operand. */
2364         if (input->decoflags & (ER | SAE)) {
2365             nasm_error(ERR_NONFATAL,
2366                        "Embedded rounding is available only with reg-reg op.");
2367             return -1;
2368         }
2369
2370         if (input->basereg == -1 &&
2371             (input->indexreg == -1 || input->scale == 0)) {
2372             /*
2373              * It's a pure offset.
2374              */
2375             if (bits == 64 && ((input->type & IP_REL) == IP_REL) &&
2376                 input->segment == NO_SEG) {
2377                 nasm_error(ERR_WARNING | ERR_PASS1, "absolute address can not be RIP-relative");
2378                 input->type &= ~IP_REL;
2379                 input->type |= MEMORY;
2380             }
2381
2382             if (input->eaflags & EAF_BYTEOFFS ||
2383                 (input->eaflags & EAF_WORDOFFS &&
2384                  input->disp_size != (addrbits != 16 ? 32 : 16))) {
2385                 nasm_error(ERR_WARNING | ERR_PASS1, "displacement size ignored on absolute address");
2386             }
2387
2388             if (bits == 64 && (~input->type & IP_REL)) {
2389                 output->sib_present = true;
2390                 output->sib         = GEN_SIB(0, 4, 5);
2391                 output->bytes       = 4;
2392                 output->modrm       = GEN_MODRM(0, rfield, 4);
2393                 output->rip         = false;
2394             } else {
2395                 output->sib_present = false;
2396                 output->bytes       = (addrbits != 16 ? 4 : 2);
2397                 output->modrm       = GEN_MODRM(0, rfield, (addrbits != 16 ? 5 : 6));
2398                 output->rip         = bits == 64;
2399             }
2400         } else {
2401             /*
2402              * It's an indirection.
2403              */
2404             int i = input->indexreg, b = input->basereg, s = input->scale;
2405             int32_t seg = input->segment;
2406             int hb = input->hintbase, ht = input->hinttype;
2407             int t, it, bt;              /* register numbers */
2408             opflags_t x, ix, bx;        /* register flags */
2409
2410             if (s == 0)
2411                 i = -1;         /* make this easy, at least */
2412
2413             if (is_register(i)) {
2414                 it = nasm_regvals[i];
2415                 ix = nasm_reg_flags[i];
2416             } else {
2417                 it = -1;
2418                 ix = 0;
2419             }
2420
2421             if (is_register(b)) {
2422                 bt = nasm_regvals[b];
2423                 bx = nasm_reg_flags[b];
2424             } else {
2425                 bt = -1;
2426                 bx = 0;
2427             }
2428
2429             /* if either one are a vector register... */
2430             if ((ix|bx) & (XMMREG|YMMREG|ZMMREG) & ~REG_EA) {
2431                 opflags_t sok = BITS32 | BITS64;
2432                 int32_t o = input->offset;
2433                 int mod, scale, index, base;
2434
2435                 /*
2436                  * For a vector SIB, one has to be a vector and the other,
2437                  * if present, a GPR.  The vector must be the index operand.
2438                  */
2439                 if (it == -1 || (bx & (XMMREG|YMMREG|ZMMREG) & ~REG_EA)) {
2440                     if (s == 0)
2441                         s = 1;
2442                     else if (s != 1)
2443                         goto err;
2444
2445                     t = bt, bt = it, it = t;
2446                     x = bx, bx = ix, ix = x;
2447                 }
2448
2449                 if (bt != -1) {
2450                     if (REG_GPR & ~bx)
2451                         goto err;
2452                     if (!(REG64 & ~bx) || !(REG32 & ~bx))
2453                         sok &= bx;
2454                     else
2455                         goto err;
2456                 }
2457
2458                 /*
2459                  * While we're here, ensure the user didn't specify
2460                  * WORD or QWORD
2461                  */
2462                 if (input->disp_size == 16 || input->disp_size == 64)
2463                     goto err;
2464
2465                 if (addrbits == 16 ||
2466                     (addrbits == 32 && !(sok & BITS32)) ||
2467                     (addrbits == 64 && !(sok & BITS64)))
2468                     goto err;
2469
2470                 output->type = ((ix & ZMMREG & ~REG_EA) ? EA_ZMMVSIB
2471                                 : ((ix & YMMREG & ~REG_EA)
2472                                 ? EA_YMMVSIB : EA_XMMVSIB));
2473
2474                 output->rex    |= rexflags(it, ix, REX_X);
2475                 output->rex    |= rexflags(bt, bx, REX_B);
2476                 ins->evex_p[2] |= evexflags(it, 0, EVEX_P2VP, 2);
2477
2478                 index = it & 7; /* it is known to be != -1 */
2479
2480                 switch (s) {
2481                 case 1:
2482                     scale = 0;
2483                     break;
2484                 case 2:
2485                     scale = 1;
2486                     break;
2487                 case 4:
2488                     scale = 2;
2489                     break;
2490                 case 8:
2491                     scale = 3;
2492                     break;
2493                 default:   /* then what the smeg is it? */
2494                     goto err;    /* panic */
2495                 }
2496                 
2497                 if (bt == -1) {
2498                     base = 5;
2499                     mod = 0;
2500                 } else {
2501                     base = (bt & 7);
2502                     if (base != REG_NUM_EBP && o == 0 &&
2503                         seg == NO_SEG && !forw_ref &&
2504                         !(input->eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2505                         mod = 0;
2506                     else if (IS_MOD_01())
2507                         mod = 1;
2508                     else
2509                         mod = 2;
2510                 }
2511
2512                 output->sib_present = true;
2513                 output->bytes       = (bt == -1 || mod == 2 ? 4 : mod);
2514                 output->modrm       = GEN_MODRM(mod, rfield, 4);
2515                 output->sib         = GEN_SIB(scale, index, base);
2516             } else if ((ix|bx) & (BITS32|BITS64)) {
2517                 /*
2518                  * it must be a 32/64-bit memory reference. Firstly we have
2519                  * to check that all registers involved are type E/Rxx.
2520                  */
2521                 opflags_t sok = BITS32 | BITS64;
2522                 int32_t o = input->offset;
2523
2524                 if (it != -1) {
2525                     if (!(REG64 & ~ix) || !(REG32 & ~ix))
2526                         sok &= ix;
2527                     else
2528                         goto err;
2529                 }
2530
2531                 if (bt != -1) {
2532                     if (REG_GPR & ~bx)
2533                         goto err; /* Invalid register */
2534                     if (~sok & bx & SIZE_MASK)
2535                         goto err; /* Invalid size */
2536                     sok &= bx;
2537                 }
2538
2539                 /*
2540                  * While we're here, ensure the user didn't specify
2541                  * WORD or QWORD
2542                  */
2543                 if (input->disp_size == 16 || input->disp_size == 64)
2544                     goto err;
2545
2546                 if (addrbits == 16 ||
2547                     (addrbits == 32 && !(sok & BITS32)) ||
2548                     (addrbits == 64 && !(sok & BITS64)))
2549                     goto err;
2550
2551                 /* now reorganize base/index */
2552                 if (s == 1 && bt != it && bt != -1 && it != -1 &&
2553                     ((hb == b && ht == EAH_NOTBASE) ||
2554                      (hb == i && ht == EAH_MAKEBASE))) {
2555                     /* swap if hints say so */
2556                     t = bt, bt = it, it = t;
2557                     x = bx, bx = ix, ix = x;
2558                 }
2559                 if (bt == it)     /* convert EAX+2*EAX to 3*EAX */
2560                     bt = -1, bx = 0, s++;
2561                 if (bt == -1 && s == 1 && !(hb == i && ht == EAH_NOTBASE)) {
2562                     /* make single reg base, unless hint */
2563                     bt = it, bx = ix, it = -1, ix = 0;
2564                 }
2565                 if (((s == 2 && it != REG_NUM_ESP && !(input->eaflags & EAF_TIMESTWO)) ||
2566                       s == 3 || s == 5 || s == 9) && bt == -1)
2567                     bt = it, bx = ix, s--; /* convert 3*EAX to EAX+2*EAX */
2568                 if (it == -1 && (bt & 7) != REG_NUM_ESP &&
2569                     (input->eaflags & EAF_TIMESTWO))
2570                     it = bt, ix = bx, bt = -1, bx = 0, s = 1;
2571                 /* convert [NOSPLIT EAX] to sib format with 0x0 displacement */
2572                 if (s == 1 && it == REG_NUM_ESP) {
2573                     /* swap ESP into base if scale is 1 */
2574                     t = it, it = bt, bt = t;
2575                     x = ix, ix = bx, bx = x;
2576                 }
2577                 if (it == REG_NUM_ESP ||
2578                     (s != 1 && s != 2 && s != 4 && s != 8 && it != -1))
2579                     goto err;        /* wrong, for various reasons */
2580
2581                 output->rex |= rexflags(it, ix, REX_X);
2582                 output->rex |= rexflags(bt, bx, REX_B);
2583
2584                 if (it == -1 && (bt & 7) != REG_NUM_ESP) {
2585                     /* no SIB needed */
2586                     int mod, rm;
2587
2588                     if (bt == -1) {
2589                         rm = 5;
2590                         mod = 0;
2591                     } else {
2592                         rm = (bt & 7);
2593                         if (rm != REG_NUM_EBP && o == 0 &&
2594                             seg == NO_SEG && !forw_ref &&
2595                             !(input->eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2596                             mod = 0;
2597                         else if (IS_MOD_01())
2598                             mod = 1;
2599                         else
2600                             mod = 2;
2601                     }
2602
2603                     output->sib_present = false;
2604                     output->bytes       = (bt == -1 || mod == 2 ? 4 : mod);
2605                     output->modrm       = GEN_MODRM(mod, rfield, rm);
2606                 } else {
2607                     /* we need a SIB */
2608                     int mod, scale, index, base;
2609
2610                     if (it == -1)
2611                         index = 4, s = 1;
2612                     else
2613                         index = (it & 7);
2614
2615                     switch (s) {
2616                     case 1:
2617                         scale = 0;
2618                         break;
2619                     case 2:
2620                         scale = 1;
2621                         break;
2622                     case 4:
2623                         scale = 2;
2624                         break;
2625                     case 8:
2626                         scale = 3;
2627                         break;
2628                     default:   /* then what the smeg is it? */
2629                         goto err;    /* panic */
2630                     }
2631
2632                     if (bt == -1) {
2633                         base = 5;
2634                         mod = 0;
2635                     } else {
2636                         base = (bt & 7);
2637                         if (base != REG_NUM_EBP && o == 0 &&
2638                             seg == NO_SEG && !forw_ref &&
2639                             !(input->eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2640                             mod = 0;
2641                         else if (IS_MOD_01())
2642                             mod = 1;
2643                         else
2644                             mod = 2;
2645                     }
2646
2647                     output->sib_present = true;
2648                     output->bytes       = (bt == -1 || mod == 2 ? 4 : mod);
2649                     output->modrm       = GEN_MODRM(mod, rfield, 4);
2650                     output->sib         = GEN_SIB(scale, index, base);
2651                 }
2652             } else {            /* it's 16-bit */
2653                 int mod, rm;
2654                 int16_t o = input->offset;
2655
2656                 /* check for 64-bit long mode */
2657                 if (addrbits == 64)
2658                     goto err;
2659
2660                 /* check all registers are BX, BP, SI or DI */
2661                 if ((b != -1 && b != R_BP && b != R_BX && b != R_SI && b != R_DI) ||
2662                     (i != -1 && i != R_BP && i != R_BX && i != R_SI && i != R_DI))
2663                     goto err;
2664
2665                 /* ensure the user didn't specify DWORD/QWORD */
2666                 if (input->disp_size == 32 || input->disp_size == 64)
2667                     goto err;
2668
2669                 if (s != 1 && i != -1)
2670                     goto err;        /* no can do, in 16-bit EA */
2671                 if (b == -1 && i != -1) {
2672                     int tmp = b;
2673                     b = i;
2674                     i = tmp;
2675                 }               /* swap */
2676                 if ((b == R_SI || b == R_DI) && i != -1) {
2677                     int tmp = b;
2678                     b = i;
2679                     i = tmp;
2680                 }
2681                 /* have BX/BP as base, SI/DI index */
2682                 if (b == i)
2683                     goto err;        /* shouldn't ever happen, in theory */
2684                 if (i != -1 && b != -1 &&
2685                     (i == R_BP || i == R_BX || b == R_SI || b == R_DI))
2686                     goto err;        /* invalid combinations */
2687                 if (b == -1)            /* pure offset: handled above */
2688                     goto err;        /* so if it gets to here, panic! */
2689
2690                 rm = -1;
2691                 if (i != -1)
2692                     switch (i * 256 + b) {
2693                     case R_SI * 256 + R_BX:
2694                         rm = 0;
2695                         break;
2696                     case R_DI * 256 + R_BX:
2697                         rm = 1;
2698                         break;
2699                     case R_SI * 256 + R_BP:
2700                         rm = 2;
2701                         break;
2702                     case R_DI * 256 + R_BP:
2703                         rm = 3;
2704                         break;
2705                 } else
2706                     switch (b) {
2707                     case R_SI:
2708                         rm = 4;
2709                         break;
2710                     case R_DI:
2711                         rm = 5;
2712                         break;
2713                     case R_BP:
2714                         rm = 6;
2715                         break;
2716                     case R_BX:
2717                         rm = 7;
2718                         break;
2719                     }
2720                 if (rm == -1)           /* can't happen, in theory */
2721                     goto err;        /* so panic if it does */
2722
2723                 if (o == 0 && seg == NO_SEG && !forw_ref && rm != 6 &&
2724                     !(input->eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2725                     mod = 0;
2726                 else if (IS_MOD_01())
2727                     mod = 1;
2728                 else
2729                     mod = 2;
2730
2731                 output->sib_present = false;    /* no SIB - it's 16-bit */
2732                 output->bytes       = mod;      /* bytes of offset needed */
2733                 output->modrm       = GEN_MODRM(mod, rfield, rm);
2734             }
2735         }
2736     }
2737
2738     output->size = 1 + output->sib_present + output->bytes;
2739     return output->type;
2740
2741 err:
2742     return output->type = EA_INVALID;
2743 }
2744
2745 static void add_asp(insn *ins, int addrbits)
2746 {
2747     int j, valid;
2748     int defdisp;
2749
2750     valid = (addrbits == 64) ? 64|32 : 32|16;
2751
2752     switch (ins->prefixes[PPS_ASIZE]) {
2753     case P_A16:
2754         valid &= 16;
2755         break;
2756     case P_A32:
2757         valid &= 32;
2758         break;
2759     case P_A64:
2760         valid &= 64;
2761         break;
2762     case P_ASP:
2763         valid &= (addrbits == 32) ? 16 : 32;
2764         break;
2765     default:
2766         break;
2767     }
2768
2769     for (j = 0; j < ins->operands; j++) {
2770         if (is_class(MEMORY, ins->oprs[j].type)) {
2771             opflags_t i, b;
2772
2773             /* Verify as Register */
2774             if (!is_register(ins->oprs[j].indexreg))
2775                 i = 0;
2776             else
2777                 i = nasm_reg_flags[ins->oprs[j].indexreg];
2778
2779             /* Verify as Register */
2780             if (!is_register(ins->oprs[j].basereg))
2781                 b = 0;
2782             else
2783                 b = nasm_reg_flags[ins->oprs[j].basereg];
2784
2785             if (ins->oprs[j].scale == 0)
2786                 i = 0;
2787
2788             if (!i && !b) {
2789                 int ds = ins->oprs[j].disp_size;
2790                 if ((addrbits != 64 && ds > 8) ||
2791                     (addrbits == 64 && ds == 16))
2792                     valid &= ds;
2793             } else {
2794                 if (!(REG16 & ~b))
2795                     valid &= 16;
2796                 if (!(REG32 & ~b))
2797                     valid &= 32;
2798                 if (!(REG64 & ~b))
2799                     valid &= 64;
2800
2801                 if (!(REG16 & ~i))
2802                     valid &= 16;
2803                 if (!(REG32 & ~i))
2804                     valid &= 32;
2805                 if (!(REG64 & ~i))
2806                     valid &= 64;
2807             }
2808         }
2809     }
2810
2811     if (valid & addrbits) {
2812         ins->addr_size = addrbits;
2813     } else if (valid & ((addrbits == 32) ? 16 : 32)) {
2814         /* Add an address size prefix */
2815         ins->prefixes[PPS_ASIZE] = (addrbits == 32) ? P_A16 : P_A32;;
2816         ins->addr_size = (addrbits == 32) ? 16 : 32;
2817     } else {
2818         /* Impossible... */
2819         errfunc(ERR_NONFATAL, "impossible combination of address sizes");
2820         ins->addr_size = addrbits; /* Error recovery */
2821     }
2822
2823     defdisp = ins->addr_size == 16 ? 16 : 32;
2824
2825     for (j = 0; j < ins->operands; j++) {
2826         if (!(MEM_OFFS & ~ins->oprs[j].type) &&
2827             (ins->oprs[j].disp_size ? ins->oprs[j].disp_size : defdisp) != ins->addr_size) {
2828             /*
2829              * mem_offs sizes must match the address size; if not,
2830              * strip the MEM_OFFS bit and match only EA instructions
2831              */
2832             ins->oprs[j].type &= ~(MEM_OFFS & ~MEMORY);
2833         }
2834     }
2835 }