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