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