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