2008-01-03 H.J. Lu <hongjiu.lu@intel.com>
[platform/upstream/binutils.git] / gas / config / tc-i386.c
1 /* tc-i386.c -- Assemble code for the Intel 80386
2    Copyright 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4    Free Software Foundation, Inc.
5
6    This file is part of GAS, the GNU Assembler.
7
8    GAS is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3, or (at your option)
11    any later version.
12
13    GAS is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GAS; see the file COPYING.  If not, write to the Free
20    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
21    02110-1301, USA.  */
22
23 /* Intel 80386 machine specific gas.
24    Written by Eliot Dresselhaus (eliot@mgm.mit.edu).
25    x86_64 support by Jan Hubicka (jh@suse.cz)
26    VIA PadLock support by Michal Ludvig (mludvig@suse.cz)
27    Bugs & suggestions are completely welcome.  This is free software.
28    Please help us make it better.  */
29
30 #include "as.h"
31 #include "safe-ctype.h"
32 #include "subsegs.h"
33 #include "dwarf2dbg.h"
34 #include "dw2gencfi.h"
35 #include "elf/x86-64.h"
36 #include "opcodes/i386-init.h"
37
38 #ifndef REGISTER_WARNINGS
39 #define REGISTER_WARNINGS 1
40 #endif
41
42 #ifndef INFER_ADDR_PREFIX
43 #define INFER_ADDR_PREFIX 1
44 #endif
45
46 #ifndef DEFAULT_ARCH
47 #define DEFAULT_ARCH "i386"
48 #endif
49
50 #ifndef INLINE
51 #if __GNUC__ >= 2
52 #define INLINE __inline__
53 #else
54 #define INLINE
55 #endif
56 #endif
57
58 static void set_code_flag (int);
59 static void set_16bit_gcc_code_flag (int);
60 static void set_intel_syntax (int);
61 static void set_intel_mnemonic (int);
62 static void set_allow_index_reg (int);
63 static void set_cpu_arch (int);
64 #ifdef TE_PE
65 static void pe_directive_secrel (int);
66 #endif
67 static void signed_cons (int);
68 static char *output_invalid (int c);
69 static int i386_operand (char *);
70 static int i386_intel_operand (char *, int);
71 static const reg_entry *parse_register (char *, char **);
72 static char *parse_insn (char *, char *);
73 static char *parse_operands (char *, const char *);
74 static void swap_operands (void);
75 static void swap_2_operands (int, int);
76 static void optimize_imm (void);
77 static void optimize_disp (void);
78 static int match_template (void);
79 static int check_string (void);
80 static int process_suffix (void);
81 static int check_byte_reg (void);
82 static int check_long_reg (void);
83 static int check_qword_reg (void);
84 static int check_word_reg (void);
85 static int finalize_imm (void);
86 static void process_drex (void);
87 static int process_operands (void);
88 static const seg_entry *build_modrm_byte (void);
89 static void output_insn (void);
90 static void output_imm (fragS *, offsetT);
91 static void output_disp (fragS *, offsetT);
92 #ifndef I386COFF
93 static void s_bss (int);
94 #endif
95 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
96 static void handle_large_common (int small ATTRIBUTE_UNUSED);
97 #endif
98
99 static const char *default_arch = DEFAULT_ARCH;
100
101 /* 'md_assemble ()' gathers together information and puts it into a
102    i386_insn.  */
103
104 union i386_op
105   {
106     expressionS *disps;
107     expressionS *imms;
108     const reg_entry *regs;
109   };
110
111 struct _i386_insn
112   {
113     /* TM holds the template for the insn were currently assembling.  */
114     template tm;
115
116     /* SUFFIX holds the instruction mnemonic suffix if given.
117        (e.g. 'l' for 'movl')  */
118     char suffix;
119
120     /* OPERANDS gives the number of given operands.  */
121     unsigned int operands;
122
123     /* REG_OPERANDS, DISP_OPERANDS, MEM_OPERANDS, IMM_OPERANDS give the number
124        of given register, displacement, memory operands and immediate
125        operands.  */
126     unsigned int reg_operands, disp_operands, mem_operands, imm_operands;
127
128     /* TYPES [i] is the type (see above #defines) which tells us how to
129        use OP[i] for the corresponding operand.  */
130     i386_operand_type types[MAX_OPERANDS];
131
132     /* Displacement expression, immediate expression, or register for each
133        operand.  */
134     union i386_op op[MAX_OPERANDS];
135
136     /* Flags for operands.  */
137     unsigned int flags[MAX_OPERANDS];
138 #define Operand_PCrel 1
139
140     /* Relocation type for operand */
141     enum bfd_reloc_code_real reloc[MAX_OPERANDS];
142
143     /* BASE_REG, INDEX_REG, and LOG2_SCALE_FACTOR are used to encode
144        the base index byte below.  */
145     const reg_entry *base_reg;
146     const reg_entry *index_reg;
147     unsigned int log2_scale_factor;
148
149     /* SEG gives the seg_entries of this insn.  They are zero unless
150        explicit segment overrides are given.  */
151     const seg_entry *seg[2];
152
153     /* PREFIX holds all the given prefix opcodes (usually null).
154        PREFIXES is the number of prefix opcodes.  */
155     unsigned int prefixes;
156     unsigned char prefix[MAX_PREFIXES];
157
158     /* RM and SIB are the modrm byte and the sib byte where the
159        addressing modes of this insn are encoded.  DREX is the byte
160        added by the SSE5 instructions.  */
161
162     modrm_byte rm;
163     rex_byte rex;
164     sib_byte sib;
165     drex_byte drex;
166   };
167
168 typedef struct _i386_insn i386_insn;
169
170 /* List of chars besides those in app.c:symbol_chars that can start an
171    operand.  Used to prevent the scrubber eating vital white-space.  */
172 const char extra_symbol_chars[] = "*%-(["
173 #ifdef LEX_AT
174         "@"
175 #endif
176 #ifdef LEX_QM
177         "?"
178 #endif
179         ;
180
181 #if (defined (TE_I386AIX)                               \
182      || ((defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)) \
183          && !defined (TE_GNU)                           \
184          && !defined (TE_LINUX)                         \
185          && !defined (TE_NETWARE)                       \
186          && !defined (TE_FreeBSD)                       \
187          && !defined (TE_NetBSD)))
188 /* This array holds the chars that always start a comment.  If the
189    pre-processor is disabled, these aren't very useful.  The option
190    --divide will remove '/' from this list.  */
191 const char *i386_comment_chars = "#/";
192 #define SVR4_COMMENT_CHARS 1
193 #define PREFIX_SEPARATOR '\\'
194
195 #else
196 const char *i386_comment_chars = "#";
197 #define PREFIX_SEPARATOR '/'
198 #endif
199
200 /* This array holds the chars that only start a comment at the beginning of
201    a line.  If the line seems to have the form '# 123 filename'
202    .line and .file directives will appear in the pre-processed output.
203    Note that input_file.c hand checks for '#' at the beginning of the
204    first line of the input file.  This is because the compiler outputs
205    #NO_APP at the beginning of its output.
206    Also note that comments started like this one will always work if
207    '/' isn't otherwise defined.  */
208 const char line_comment_chars[] = "#/";
209
210 const char line_separator_chars[] = ";";
211
212 /* Chars that can be used to separate mant from exp in floating point
213    nums.  */
214 const char EXP_CHARS[] = "eE";
215
216 /* Chars that mean this number is a floating point constant
217    As in 0f12.456
218    or    0d1.2345e12.  */
219 const char FLT_CHARS[] = "fFdDxX";
220
221 /* Tables for lexical analysis.  */
222 static char mnemonic_chars[256];
223 static char register_chars[256];
224 static char operand_chars[256];
225 static char identifier_chars[256];
226 static char digit_chars[256];
227
228 /* Lexical macros.  */
229 #define is_mnemonic_char(x) (mnemonic_chars[(unsigned char) x])
230 #define is_operand_char(x) (operand_chars[(unsigned char) x])
231 #define is_register_char(x) (register_chars[(unsigned char) x])
232 #define is_space_char(x) ((x) == ' ')
233 #define is_identifier_char(x) (identifier_chars[(unsigned char) x])
234 #define is_digit_char(x) (digit_chars[(unsigned char) x])
235
236 /* All non-digit non-letter characters that may occur in an operand.  */
237 static char operand_special_chars[] = "%$-+(,)*._~/<>|&^!:[@]";
238
239 /* md_assemble() always leaves the strings it's passed unaltered.  To
240    effect this we maintain a stack of saved characters that we've smashed
241    with '\0's (indicating end of strings for various sub-fields of the
242    assembler instruction).  */
243 static char save_stack[32];
244 static char *save_stack_p;
245 #define END_STRING_AND_SAVE(s) \
246         do { *save_stack_p++ = *(s); *(s) = '\0'; } while (0)
247 #define RESTORE_END_STRING(s) \
248         do { *(s) = *--save_stack_p; } while (0)
249
250 /* The instruction we're assembling.  */
251 static i386_insn i;
252
253 /* Possible templates for current insn.  */
254 static const templates *current_templates;
255
256 /* Per instruction expressionS buffers: max displacements & immediates.  */
257 static expressionS disp_expressions[MAX_MEMORY_OPERANDS];
258 static expressionS im_expressions[MAX_IMMEDIATE_OPERANDS];
259
260 /* Current operand we are working on.  */
261 static int this_operand;
262
263 /* We support four different modes.  FLAG_CODE variable is used to distinguish
264    these.  */
265
266 enum flag_code {
267         CODE_32BIT,
268         CODE_16BIT,
269         CODE_64BIT };
270
271 static enum flag_code flag_code;
272 static unsigned int object_64bit;
273 static int use_rela_relocations = 0;
274
275 /* The names used to print error messages.  */
276 static const char *flag_code_names[] =
277   {
278     "32",
279     "16",
280     "64"
281   };
282
283 /* 1 for intel syntax,
284    0 if att syntax.  */
285 static int intel_syntax = 0;
286
287 /* 1 for intel mnemonic,
288    0 if att mnemonic.  */
289 static int intel_mnemonic = !SYSV386_COMPAT;
290
291 /* 1 if support old (<= 2.8.1) versions of gcc.  */
292 static int old_gcc = OLDGCC_COMPAT;
293
294 /* 1 if register prefix % not required.  */
295 static int allow_naked_reg = 0;
296
297 /* 1 if pseudo index register, eiz/riz, is allowed .  */
298 static int allow_index_reg = 0;
299
300 /* Register prefix used for error message.  */
301 static const char *register_prefix = "%";
302
303 /* Used in 16 bit gcc mode to add an l suffix to call, ret, enter,
304    leave, push, and pop instructions so that gcc has the same stack
305    frame as in 32 bit mode.  */
306 static char stackop_size = '\0';
307
308 /* Non-zero to optimize code alignment.  */
309 int optimize_align_code = 1;
310
311 /* Non-zero to quieten some warnings.  */
312 static int quiet_warnings = 0;
313
314 /* CPU name.  */
315 static const char *cpu_arch_name = NULL;
316 static const char *cpu_sub_arch_name = NULL;
317
318 /* CPU feature flags.  */
319 static i386_cpu_flags cpu_arch_flags = CPU_UNKNOWN_FLAGS;
320
321 /* If we have selected a cpu we are generating instructions for.  */
322 static int cpu_arch_tune_set = 0;
323
324 /* Cpu we are generating instructions for.  */
325 static enum processor_type cpu_arch_tune = PROCESSOR_UNKNOWN;
326
327 /* CPU feature flags of cpu we are generating instructions for.  */
328 static i386_cpu_flags cpu_arch_tune_flags;
329
330 /* CPU instruction set architecture used.  */
331 static enum processor_type cpu_arch_isa = PROCESSOR_UNKNOWN;
332
333 /* CPU feature flags of instruction set architecture used.  */
334 static i386_cpu_flags cpu_arch_isa_flags;
335
336 /* If set, conditional jumps are not automatically promoted to handle
337    larger than a byte offset.  */
338 static unsigned int no_cond_jump_promotion = 0;
339
340 /* Pre-defined "_GLOBAL_OFFSET_TABLE_".  */
341 static symbolS *GOT_symbol;
342
343 /* The dwarf2 return column, adjusted for 32 or 64 bit.  */
344 unsigned int x86_dwarf2_return_column;
345
346 /* The dwarf2 data alignment, adjusted for 32 or 64 bit.  */
347 int x86_cie_data_alignment;
348
349 /* Interface to relax_segment.
350    There are 3 major relax states for 386 jump insns because the
351    different types of jumps add different sizes to frags when we're
352    figuring out what sort of jump to choose to reach a given label.  */
353
354 /* Types.  */
355 #define UNCOND_JUMP 0
356 #define COND_JUMP 1
357 #define COND_JUMP86 2
358
359 /* Sizes.  */
360 #define CODE16  1
361 #define SMALL   0
362 #define SMALL16 (SMALL | CODE16)
363 #define BIG     2
364 #define BIG16   (BIG | CODE16)
365
366 #ifndef INLINE
367 #ifdef __GNUC__
368 #define INLINE __inline__
369 #else
370 #define INLINE
371 #endif
372 #endif
373
374 #define ENCODE_RELAX_STATE(type, size) \
375   ((relax_substateT) (((type) << 2) | (size)))
376 #define TYPE_FROM_RELAX_STATE(s) \
377   ((s) >> 2)
378 #define DISP_SIZE_FROM_RELAX_STATE(s) \
379     ((((s) & 3) == BIG ? 4 : (((s) & 3) == BIG16 ? 2 : 1)))
380
381 /* This table is used by relax_frag to promote short jumps to long
382    ones where necessary.  SMALL (short) jumps may be promoted to BIG
383    (32 bit long) ones, and SMALL16 jumps to BIG16 (16 bit long).  We
384    don't allow a short jump in a 32 bit code segment to be promoted to
385    a 16 bit offset jump because it's slower (requires data size
386    prefix), and doesn't work, unless the destination is in the bottom
387    64k of the code segment (The top 16 bits of eip are zeroed).  */
388
389 const relax_typeS md_relax_table[] =
390 {
391   /* The fields are:
392      1) most positive reach of this state,
393      2) most negative reach of this state,
394      3) how many bytes this mode will have in the variable part of the frag
395      4) which index into the table to try if we can't fit into this one.  */
396
397   /* UNCOND_JUMP states.  */
398   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (UNCOND_JUMP, BIG)},
399   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (UNCOND_JUMP, BIG16)},
400   /* dword jmp adds 4 bytes to frag:
401      0 extra opcode bytes, 4 displacement bytes.  */
402   {0, 0, 4, 0},
403   /* word jmp adds 2 byte2 to frag:
404      0 extra opcode bytes, 2 displacement bytes.  */
405   {0, 0, 2, 0},
406
407   /* COND_JUMP states.  */
408   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP, BIG)},
409   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP, BIG16)},
410   /* dword conditionals adds 5 bytes to frag:
411      1 extra opcode byte, 4 displacement bytes.  */
412   {0, 0, 5, 0},
413   /* word conditionals add 3 bytes to frag:
414      1 extra opcode byte, 2 displacement bytes.  */
415   {0, 0, 3, 0},
416
417   /* COND_JUMP86 states.  */
418   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP86, BIG)},
419   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP86, BIG16)},
420   /* dword conditionals adds 5 bytes to frag:
421      1 extra opcode byte, 4 displacement bytes.  */
422   {0, 0, 5, 0},
423   /* word conditionals add 4 bytes to frag:
424      1 displacement byte and a 3 byte long branch insn.  */
425   {0, 0, 4, 0}
426 };
427
428 static const arch_entry cpu_arch[] =
429 {
430   {"generic32", PROCESSOR_GENERIC32,
431    CPU_GENERIC32_FLAGS },
432   {"generic64", PROCESSOR_GENERIC64,
433    CPU_GENERIC64_FLAGS },
434   {"i8086", PROCESSOR_UNKNOWN,
435    CPU_NONE_FLAGS },
436   {"i186", PROCESSOR_UNKNOWN,
437    CPU_I186_FLAGS },
438   {"i286", PROCESSOR_UNKNOWN,
439    CPU_I286_FLAGS },
440   {"i386", PROCESSOR_I386,
441    CPU_I386_FLAGS },
442   {"i486", PROCESSOR_I486,
443    CPU_I486_FLAGS },
444   {"i586", PROCESSOR_PENTIUM,
445    CPU_I586_FLAGS },
446   {"i686", PROCESSOR_PENTIUMPRO,
447    CPU_I686_FLAGS },
448   {"pentium", PROCESSOR_PENTIUM,
449    CPU_I586_FLAGS },
450   {"pentiumpro",PROCESSOR_PENTIUMPRO,
451    CPU_I686_FLAGS },
452   {"pentiumii", PROCESSOR_PENTIUMPRO,
453    CPU_P2_FLAGS },
454   {"pentiumiii",PROCESSOR_PENTIUMPRO,
455    CPU_P3_FLAGS },
456   {"pentium4", PROCESSOR_PENTIUM4,
457    CPU_P4_FLAGS },
458   {"prescott", PROCESSOR_NOCONA,
459    CPU_CORE_FLAGS },
460   {"nocona", PROCESSOR_NOCONA,
461    CPU_NOCONA_FLAGS },
462   {"yonah", PROCESSOR_CORE,
463    CPU_CORE_FLAGS },
464   {"core", PROCESSOR_CORE,
465    CPU_CORE_FLAGS },
466   {"merom", PROCESSOR_CORE2,
467    CPU_CORE2_FLAGS },
468   {"core2", PROCESSOR_CORE2,
469    CPU_CORE2_FLAGS },
470   {"k6", PROCESSOR_K6,
471    CPU_K6_FLAGS },
472   {"k6_2", PROCESSOR_K6,
473    CPU_K6_2_FLAGS },
474   {"athlon", PROCESSOR_ATHLON,
475    CPU_ATHLON_FLAGS },
476   {"sledgehammer", PROCESSOR_K8,
477    CPU_K8_FLAGS },
478   {"opteron", PROCESSOR_K8,
479    CPU_K8_FLAGS },
480   {"k8", PROCESSOR_K8,
481    CPU_K8_FLAGS },
482   {"amdfam10", PROCESSOR_AMDFAM10,
483    CPU_AMDFAM10_FLAGS },
484   {".mmx", PROCESSOR_UNKNOWN,
485    CPU_MMX_FLAGS },
486   {".sse", PROCESSOR_UNKNOWN,
487    CPU_SSE_FLAGS },
488   {".sse2", PROCESSOR_UNKNOWN,
489    CPU_SSE2_FLAGS },
490   {".sse3", PROCESSOR_UNKNOWN,
491    CPU_SSE3_FLAGS },
492   {".ssse3", PROCESSOR_UNKNOWN,
493    CPU_SSSE3_FLAGS },
494   {".sse4.1", PROCESSOR_UNKNOWN,
495    CPU_SSE4_1_FLAGS },
496   {".sse4.2", PROCESSOR_UNKNOWN,
497    CPU_SSE4_2_FLAGS },
498   {".sse4", PROCESSOR_UNKNOWN,
499    CPU_SSE4_2_FLAGS },
500   {".3dnow", PROCESSOR_UNKNOWN,
501    CPU_3DNOW_FLAGS },
502   {".3dnowa", PROCESSOR_UNKNOWN,
503    CPU_3DNOWA_FLAGS },
504   {".padlock", PROCESSOR_UNKNOWN,
505    CPU_PADLOCK_FLAGS },
506   {".pacifica", PROCESSOR_UNKNOWN,
507    CPU_SVME_FLAGS },
508   {".svme", PROCESSOR_UNKNOWN,
509    CPU_SVME_FLAGS },
510   {".sse4a", PROCESSOR_UNKNOWN,
511    CPU_SSE4A_FLAGS },
512   {".abm", PROCESSOR_UNKNOWN,
513    CPU_ABM_FLAGS },
514   {".sse5", PROCESSOR_UNKNOWN,
515    CPU_SSE5_FLAGS },
516 };
517
518 const pseudo_typeS md_pseudo_table[] =
519 {
520 #if !defined(OBJ_AOUT) && !defined(USE_ALIGN_PTWO)
521   {"align", s_align_bytes, 0},
522 #else
523   {"align", s_align_ptwo, 0},
524 #endif
525   {"arch", set_cpu_arch, 0},
526 #ifndef I386COFF
527   {"bss", s_bss, 0},
528 #endif
529   {"ffloat", float_cons, 'f'},
530   {"dfloat", float_cons, 'd'},
531   {"tfloat", float_cons, 'x'},
532   {"value", cons, 2},
533   {"slong", signed_cons, 4},
534   {"noopt", s_ignore, 0},
535   {"optim", s_ignore, 0},
536   {"code16gcc", set_16bit_gcc_code_flag, CODE_16BIT},
537   {"code16", set_code_flag, CODE_16BIT},
538   {"code32", set_code_flag, CODE_32BIT},
539   {"code64", set_code_flag, CODE_64BIT},
540   {"intel_syntax", set_intel_syntax, 1},
541   {"att_syntax", set_intel_syntax, 0},
542   {"intel_mnemonic", set_intel_mnemonic, 1},
543   {"att_mnemonic", set_intel_mnemonic, 0},
544   {"allow_index_reg", set_allow_index_reg, 1},
545   {"disallow_index_reg", set_allow_index_reg, 0},
546 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
547   {"largecomm", handle_large_common, 0},
548 #else
549   {"file", (void (*) (int)) dwarf2_directive_file, 0},
550   {"loc", dwarf2_directive_loc, 0},
551   {"loc_mark_labels", dwarf2_directive_loc_mark_labels, 0},
552 #endif
553 #ifdef TE_PE
554   {"secrel32", pe_directive_secrel, 0},
555 #endif
556   {0, 0, 0}
557 };
558
559 /* For interface with expression ().  */
560 extern char *input_line_pointer;
561
562 /* Hash table for instruction mnemonic lookup.  */
563 static struct hash_control *op_hash;
564
565 /* Hash table for register lookup.  */
566 static struct hash_control *reg_hash;
567 \f
568 void
569 i386_align_code (fragS *fragP, int count)
570 {
571   /* Various efficient no-op patterns for aligning code labels.
572      Note: Don't try to assemble the instructions in the comments.
573      0L and 0w are not legal.  */
574   static const char f32_1[] =
575     {0x90};                                     /* nop                  */
576   static const char f32_2[] =
577     {0x66,0x90};                                /* xchg %ax,%ax */
578   static const char f32_3[] =
579     {0x8d,0x76,0x00};                           /* leal 0(%esi),%esi    */
580   static const char f32_4[] =
581     {0x8d,0x74,0x26,0x00};                      /* leal 0(%esi,1),%esi  */
582   static const char f32_5[] =
583     {0x90,                                      /* nop                  */
584      0x8d,0x74,0x26,0x00};                      /* leal 0(%esi,1),%esi  */
585   static const char f32_6[] =
586     {0x8d,0xb6,0x00,0x00,0x00,0x00};            /* leal 0L(%esi),%esi   */
587   static const char f32_7[] =
588     {0x8d,0xb4,0x26,0x00,0x00,0x00,0x00};       /* leal 0L(%esi,1),%esi */
589   static const char f32_8[] =
590     {0x90,                                      /* nop                  */
591      0x8d,0xb4,0x26,0x00,0x00,0x00,0x00};       /* leal 0L(%esi,1),%esi */
592   static const char f32_9[] =
593     {0x89,0xf6,                                 /* movl %esi,%esi       */
594      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
595   static const char f32_10[] =
596     {0x8d,0x76,0x00,                            /* leal 0(%esi),%esi    */
597      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
598   static const char f32_11[] =
599     {0x8d,0x74,0x26,0x00,                       /* leal 0(%esi,1),%esi  */
600      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
601   static const char f32_12[] =
602     {0x8d,0xb6,0x00,0x00,0x00,0x00,             /* leal 0L(%esi),%esi   */
603      0x8d,0xbf,0x00,0x00,0x00,0x00};            /* leal 0L(%edi),%edi   */
604   static const char f32_13[] =
605     {0x8d,0xb6,0x00,0x00,0x00,0x00,             /* leal 0L(%esi),%esi   */
606      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
607   static const char f32_14[] =
608     {0x8d,0xb4,0x26,0x00,0x00,0x00,0x00,        /* leal 0L(%esi,1),%esi */
609      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
610   static const char f16_3[] =
611     {0x8d,0x74,0x00};                           /* lea 0(%esi),%esi     */
612   static const char f16_4[] =
613     {0x8d,0xb4,0x00,0x00};                      /* lea 0w(%si),%si      */
614   static const char f16_5[] =
615     {0x90,                                      /* nop                  */
616      0x8d,0xb4,0x00,0x00};                      /* lea 0w(%si),%si      */
617   static const char f16_6[] =
618     {0x89,0xf6,                                 /* mov %si,%si          */
619      0x8d,0xbd,0x00,0x00};                      /* lea 0w(%di),%di      */
620   static const char f16_7[] =
621     {0x8d,0x74,0x00,                            /* lea 0(%si),%si       */
622      0x8d,0xbd,0x00,0x00};                      /* lea 0w(%di),%di      */
623   static const char f16_8[] =
624     {0x8d,0xb4,0x00,0x00,                       /* lea 0w(%si),%si      */
625      0x8d,0xbd,0x00,0x00};                      /* lea 0w(%di),%di      */
626   static const char jump_31[] =
627     {0xeb,0x1d,0x90,0x90,0x90,0x90,0x90,        /* jmp .+31; lotsa nops */
628      0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,
629      0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,
630      0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90};
631   static const char *const f32_patt[] = {
632     f32_1, f32_2, f32_3, f32_4, f32_5, f32_6, f32_7, f32_8,
633     f32_9, f32_10, f32_11, f32_12, f32_13, f32_14
634   };
635   static const char *const f16_patt[] = {
636     f32_1, f32_2, f16_3, f16_4, f16_5, f16_6, f16_7, f16_8
637   };
638   /* nopl (%[re]ax) */
639   static const char alt_3[] =
640     {0x0f,0x1f,0x00};
641   /* nopl 0(%[re]ax) */
642   static const char alt_4[] =
643     {0x0f,0x1f,0x40,0x00};
644   /* nopl 0(%[re]ax,%[re]ax,1) */
645   static const char alt_5[] =
646     {0x0f,0x1f,0x44,0x00,0x00};
647   /* nopw 0(%[re]ax,%[re]ax,1) */
648   static const char alt_6[] =
649     {0x66,0x0f,0x1f,0x44,0x00,0x00};
650   /* nopl 0L(%[re]ax) */
651   static const char alt_7[] =
652     {0x0f,0x1f,0x80,0x00,0x00,0x00,0x00};
653   /* nopl 0L(%[re]ax,%[re]ax,1) */
654   static const char alt_8[] =
655     {0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
656   /* nopw 0L(%[re]ax,%[re]ax,1) */
657   static const char alt_9[] =
658     {0x66,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
659   /* nopw %cs:0L(%[re]ax,%[re]ax,1) */
660   static const char alt_10[] =
661     {0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
662   /* data16
663      nopw %cs:0L(%[re]ax,%[re]ax,1) */
664   static const char alt_long_11[] =
665     {0x66,
666      0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
667   /* data16
668      data16
669      nopw %cs:0L(%[re]ax,%[re]ax,1) */
670   static const char alt_long_12[] =
671     {0x66,
672      0x66,
673      0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
674   /* data16
675      data16
676      data16
677      nopw %cs:0L(%[re]ax,%[re]ax,1) */
678   static const char alt_long_13[] =
679     {0x66,
680      0x66,
681      0x66,
682      0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
683   /* data16
684      data16
685      data16
686      data16
687      nopw %cs:0L(%[re]ax,%[re]ax,1) */
688   static const char alt_long_14[] =
689     {0x66,
690      0x66,
691      0x66,
692      0x66,
693      0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
694   /* data16
695      data16
696      data16
697      data16
698      data16
699      nopw %cs:0L(%[re]ax,%[re]ax,1) */
700   static const char alt_long_15[] =
701     {0x66,
702      0x66,
703      0x66,
704      0x66,
705      0x66,
706      0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
707   /* nopl 0(%[re]ax,%[re]ax,1)
708      nopw 0(%[re]ax,%[re]ax,1) */
709   static const char alt_short_11[] =
710     {0x0f,0x1f,0x44,0x00,0x00,
711      0x66,0x0f,0x1f,0x44,0x00,0x00};
712   /* nopw 0(%[re]ax,%[re]ax,1)
713      nopw 0(%[re]ax,%[re]ax,1) */
714   static const char alt_short_12[] =
715     {0x66,0x0f,0x1f,0x44,0x00,0x00,
716      0x66,0x0f,0x1f,0x44,0x00,0x00};
717   /* nopw 0(%[re]ax,%[re]ax,1)
718      nopl 0L(%[re]ax) */
719   static const char alt_short_13[] =
720     {0x66,0x0f,0x1f,0x44,0x00,0x00,
721      0x0f,0x1f,0x80,0x00,0x00,0x00,0x00};
722   /* nopl 0L(%[re]ax)
723      nopl 0L(%[re]ax) */
724   static const char alt_short_14[] =
725     {0x0f,0x1f,0x80,0x00,0x00,0x00,0x00,
726      0x0f,0x1f,0x80,0x00,0x00,0x00,0x00};
727   /* nopl 0L(%[re]ax)
728      nopl 0L(%[re]ax,%[re]ax,1) */
729   static const char alt_short_15[] =
730     {0x0f,0x1f,0x80,0x00,0x00,0x00,0x00,
731      0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
732   static const char *const alt_short_patt[] = {
733     f32_1, f32_2, alt_3, alt_4, alt_5, alt_6, alt_7, alt_8,
734     alt_9, alt_10, alt_short_11, alt_short_12, alt_short_13,
735     alt_short_14, alt_short_15
736   };
737   static const char *const alt_long_patt[] = {
738     f32_1, f32_2, alt_3, alt_4, alt_5, alt_6, alt_7, alt_8,
739     alt_9, alt_10, alt_long_11, alt_long_12, alt_long_13,
740     alt_long_14, alt_long_15
741   };
742
743   /* Only align for at least a positive non-zero boundary. */
744   if (count <= 0 || count > MAX_MEM_FOR_RS_ALIGN_CODE)
745     return;
746
747   /* We need to decide which NOP sequence to use for 32bit and
748      64bit. When -mtune= is used:
749
750      1. For PROCESSOR_I386, PROCESSOR_I486, PROCESSOR_PENTIUM and
751      PROCESSOR_GENERIC32, f32_patt will be used.
752      2. For PROCESSOR_PENTIUMPRO, PROCESSOR_PENTIUM4, PROCESSOR_NOCONA,
753      PROCESSOR_CORE, PROCESSOR_CORE2, and PROCESSOR_GENERIC64,
754      alt_long_patt will be used.
755      3. For PROCESSOR_ATHLON, PROCESSOR_K6, PROCESSOR_K8 and
756      PROCESSOR_AMDFAM10, alt_short_patt will be used.
757
758      When -mtune= isn't used, alt_long_patt will be used if
759      cpu_arch_isa_flags has Cpu686. Otherwise, f32_patt will
760      be used.
761
762      When -march= or .arch is used, we can't use anything beyond
763      cpu_arch_isa_flags.   */
764
765   if (flag_code == CODE_16BIT)
766     {
767       if (count > 8)
768         {
769           memcpy (fragP->fr_literal + fragP->fr_fix,
770                   jump_31, count);
771           /* Adjust jump offset.  */
772           fragP->fr_literal[fragP->fr_fix + 1] = count - 2;
773         }
774       else
775         memcpy (fragP->fr_literal + fragP->fr_fix,
776                 f16_patt[count - 1], count);
777     }
778   else
779     {
780       const char *const *patt = NULL;
781
782       if (cpu_arch_isa == PROCESSOR_UNKNOWN)
783         {
784           /* PROCESSOR_UNKNOWN means that all ISAs may be used.  */
785           switch (cpu_arch_tune)
786             {
787             case PROCESSOR_UNKNOWN:
788               /* We use cpu_arch_isa_flags to check if we SHOULD
789                  optimize for Cpu686.  */
790               if (cpu_arch_isa_flags.bitfield.cpui686)
791                 patt = alt_long_patt;
792               else
793                 patt = f32_patt;
794               break;
795             case PROCESSOR_PENTIUMPRO:
796             case PROCESSOR_PENTIUM4:
797             case PROCESSOR_NOCONA:
798             case PROCESSOR_CORE:
799             case PROCESSOR_CORE2:
800             case PROCESSOR_GENERIC64:
801               patt = alt_long_patt;
802               break;
803             case PROCESSOR_K6:
804             case PROCESSOR_ATHLON:
805             case PROCESSOR_K8:
806             case PROCESSOR_AMDFAM10:
807               patt = alt_short_patt;
808               break;
809             case PROCESSOR_I386:
810             case PROCESSOR_I486:
811             case PROCESSOR_PENTIUM:
812             case PROCESSOR_GENERIC32:
813               patt = f32_patt;
814               break;
815             }
816         }
817       else
818         {
819           switch (cpu_arch_tune)
820             {
821             case PROCESSOR_UNKNOWN:
822               /* When cpu_arch_isa is net, cpu_arch_tune shouldn't be
823                  PROCESSOR_UNKNOWN.  */
824               abort ();
825               break;
826
827             case PROCESSOR_I386:
828             case PROCESSOR_I486:
829             case PROCESSOR_PENTIUM:
830             case PROCESSOR_K6:
831             case PROCESSOR_ATHLON:
832             case PROCESSOR_K8:
833             case PROCESSOR_AMDFAM10:
834             case PROCESSOR_GENERIC32:
835               /* We use cpu_arch_isa_flags to check if we CAN optimize
836                  for Cpu686.  */
837               if (cpu_arch_isa_flags.bitfield.cpui686)
838                 patt = alt_short_patt;
839               else
840                 patt = f32_patt;
841               break;
842             case PROCESSOR_PENTIUMPRO:
843             case PROCESSOR_PENTIUM4:
844             case PROCESSOR_NOCONA:
845             case PROCESSOR_CORE:
846             case PROCESSOR_CORE2:
847               if (cpu_arch_isa_flags.bitfield.cpui686)
848                 patt = alt_long_patt;
849               else
850                 patt = f32_patt;
851               break;
852             case PROCESSOR_GENERIC64:
853               patt = alt_long_patt;
854               break;
855             }
856         }
857
858       if (patt == f32_patt)
859         {
860           /* If the padding is less than 15 bytes, we use the normal
861              ones.  Otherwise, we use a jump instruction and adjust
862              its offset.  */
863           if (count < 15)
864             memcpy (fragP->fr_literal + fragP->fr_fix,
865                     patt[count - 1], count);
866           else
867             {
868               memcpy (fragP->fr_literal + fragP->fr_fix,
869                       jump_31, count);
870               /* Adjust jump offset.  */
871               fragP->fr_literal[fragP->fr_fix + 1] = count - 2;
872             }
873         }
874       else
875         {
876           /* Maximum length of an instruction is 15 byte.  If the
877              padding is greater than 15 bytes and we don't use jump,
878              we have to break it into smaller pieces.  */
879           int padding = count;
880           while (padding > 15)
881             {
882               padding -= 15;
883               memcpy (fragP->fr_literal + fragP->fr_fix + padding,
884                       patt [14], 15);
885             }
886
887           if (padding)
888             memcpy (fragP->fr_literal + fragP->fr_fix,
889                     patt [padding - 1], padding);
890         }
891     }
892   fragP->fr_var = count;
893 }
894
895 static INLINE int
896 uints_all_zero (const unsigned int *x, unsigned int size)
897 {
898   switch (size)
899     {
900     case 3:
901       if (x[2])
902         return 0;
903     case 2:
904       if (x[1])
905         return 0;
906     case 1:
907       return !x[0];
908     default:
909       abort ();
910     }
911 }
912
913 static INLINE void
914 uints_set (unsigned int *x, unsigned int v, unsigned int size)
915 {
916   switch (size)
917     {
918     case 3:
919       x[2] = v;
920     case 2:
921       x[1] = v;
922     case 1:
923       x[0] = v;
924       break;
925     default:
926       abort ();
927     }
928 }
929
930 static INLINE int
931 uints_equal (const unsigned int *x, const unsigned int *y,
932              unsigned int size)
933 {
934   switch (size)
935     {
936     case 3:
937       if (x[2] != y [2])
938         return 0;
939     case 2:
940       if (x[1] != y [1])
941         return 0;
942     case 1:
943       return x[0] == y [0];
944       break;
945     default:
946       abort ();
947     }
948 }
949
950 #define UINTS_ALL_ZERO(x) \
951   uints_all_zero ((x).array, ARRAY_SIZE ((x).array))
952 #define UINTS_SET(x, v) \
953   uints_set ((x).array, v, ARRAY_SIZE ((x).array))
954 #define UINTS_CLEAR(x) \
955   uints_set ((x).array, 0, ARRAY_SIZE ((x).array))
956 #define UINTS_EQUAL(x, y) \
957   uints_equal ((x).array, (y).array, ARRAY_SIZE ((x).array))
958
959 static INLINE int
960 cpu_flags_check_cpu64 (i386_cpu_flags f)
961 {
962   return !((flag_code == CODE_64BIT && f.bitfield.cpuno64)
963            || (flag_code != CODE_64BIT && f.bitfield.cpu64));
964 }
965
966 static INLINE i386_cpu_flags
967 cpu_flags_and (i386_cpu_flags x, i386_cpu_flags y)
968 {
969   switch (ARRAY_SIZE (x.array))
970     {
971     case 3:
972       x.array [2] &= y.array [2];
973     case 2:
974       x.array [1] &= y.array [1];
975     case 1:
976       x.array [0] &= y.array [0];
977       break;
978     default:
979       abort ();
980     }
981   return x;
982 }
983
984 static INLINE i386_cpu_flags
985 cpu_flags_or (i386_cpu_flags x, i386_cpu_flags y)
986 {
987   switch (ARRAY_SIZE (x.array))
988     {
989     case 3:
990       x.array [2] |= y.array [2];
991     case 2:
992       x.array [1] |= y.array [1];
993     case 1:
994       x.array [0] |= y.array [0];
995       break;
996     default:
997       abort ();
998     }
999   return x;
1000 }
1001
1002 /* Return 3 if there is a perfect match, 2 if compatible with 64bit,
1003    1 if compatible with arch, 0 if there is no match.  */
1004
1005 static int
1006 cpu_flags_match (i386_cpu_flags x)
1007 {
1008   int overlap = cpu_flags_check_cpu64 (x) ? 2 : 0;
1009
1010   x.bitfield.cpu64 = 0;
1011   x.bitfield.cpuno64 = 0;
1012
1013   if (UINTS_ALL_ZERO (x))
1014     overlap |= 1;
1015   else
1016     {
1017       i386_cpu_flags cpu = cpu_arch_flags;
1018
1019       cpu.bitfield.cpu64 = 0;
1020       cpu.bitfield.cpuno64 = 0;
1021       cpu = cpu_flags_and (x, cpu);
1022       overlap |= UINTS_ALL_ZERO (cpu) ? 0 : 1;
1023     }
1024   return overlap;
1025 }
1026
1027 static INLINE i386_operand_type
1028 operand_type_and (i386_operand_type x, i386_operand_type y)
1029 {
1030   switch (ARRAY_SIZE (x.array))
1031     {
1032     case 3:
1033       x.array [2] &= y.array [2];
1034     case 2:
1035       x.array [1] &= y.array [1];
1036     case 1:
1037       x.array [0] &= y.array [0];
1038       break;
1039     default:
1040       abort ();
1041     }
1042   return x;
1043 }
1044
1045 static INLINE i386_operand_type
1046 operand_type_or (i386_operand_type x, i386_operand_type y)
1047 {
1048   switch (ARRAY_SIZE (x.array))
1049     {
1050     case 3:
1051       x.array [2] |= y.array [2];
1052     case 2:
1053       x.array [1] |= y.array [1];
1054     case 1:
1055       x.array [0] |= y.array [0];
1056       break;
1057     default:
1058       abort ();
1059     }
1060   return x;
1061 }
1062
1063 static INLINE i386_operand_type
1064 operand_type_xor (i386_operand_type x, i386_operand_type y)
1065 {
1066   switch (ARRAY_SIZE (x.array))
1067     {
1068     case 3:
1069       x.array [2] ^= y.array [2];
1070     case 2:
1071       x.array [1] ^= y.array [1];
1072     case 1:
1073       x.array [0] ^= y.array [0];
1074       break;
1075     default:
1076       abort ();
1077     }
1078   return x;
1079 }
1080
1081 static const i386_operand_type acc32 = OPERAND_TYPE_ACC32;
1082 static const i386_operand_type acc64 = OPERAND_TYPE_ACC64;
1083 static const i386_operand_type control = OPERAND_TYPE_CONTROL;
1084 static const i386_operand_type reg16_inoutportreg
1085   = OPERAND_TYPE_REG16_INOUTPORTREG;
1086 static const i386_operand_type disp16 = OPERAND_TYPE_DISP16;
1087 static const i386_operand_type disp32 = OPERAND_TYPE_DISP32;
1088 static const i386_operand_type disp32s = OPERAND_TYPE_DISP32S;
1089 static const i386_operand_type disp16_32 = OPERAND_TYPE_DISP16_32;
1090 static const i386_operand_type anydisp
1091   = OPERAND_TYPE_ANYDISP;
1092 static const i386_operand_type regxmm = OPERAND_TYPE_REGXMM;
1093 static const i386_operand_type imm8 = OPERAND_TYPE_IMM8;
1094 static const i386_operand_type imm8s = OPERAND_TYPE_IMM8S;
1095 static const i386_operand_type imm16 = OPERAND_TYPE_IMM16;
1096 static const i386_operand_type imm32 = OPERAND_TYPE_IMM32;
1097 static const i386_operand_type imm32s = OPERAND_TYPE_IMM32S;
1098 static const i386_operand_type imm64 = OPERAND_TYPE_IMM64;
1099 static const i386_operand_type imm16_32 = OPERAND_TYPE_IMM16_32;
1100 static const i386_operand_type imm16_32s = OPERAND_TYPE_IMM16_32S;
1101 static const i386_operand_type imm16_32_32s = OPERAND_TYPE_IMM16_32_32S;
1102
1103 enum operand_type
1104 {
1105   reg,
1106   imm,
1107   disp,
1108   anymem
1109 };
1110
1111 static INLINE int
1112 operand_type_check (i386_operand_type t, enum operand_type c)
1113 {
1114   switch (c)
1115     {
1116     case reg:
1117       return (t.bitfield.reg8
1118               || t.bitfield.reg16
1119               || t.bitfield.reg32
1120               || t.bitfield.reg64);
1121
1122     case imm:
1123       return (t.bitfield.imm8
1124               || t.bitfield.imm8s
1125               || t.bitfield.imm16
1126               || t.bitfield.imm32
1127               || t.bitfield.imm32s
1128               || t.bitfield.imm64);
1129
1130     case disp:
1131       return (t.bitfield.disp8
1132               || t.bitfield.disp16
1133               || t.bitfield.disp32
1134               || t.bitfield.disp32s
1135               || t.bitfield.disp64);
1136
1137     case anymem:
1138       return (t.bitfield.disp8
1139               || t.bitfield.disp16
1140               || t.bitfield.disp32
1141               || t.bitfield.disp32s
1142               || t.bitfield.disp64
1143               || t.bitfield.baseindex);
1144
1145     default:
1146       abort ();
1147     }
1148 }
1149
1150 static INLINE int
1151 operand_type_match (i386_operand_type overlap,
1152                     i386_operand_type given)
1153 {
1154   i386_operand_type temp = overlap;
1155
1156   temp.bitfield.jumpabsolute = 0;
1157   if (UINTS_ALL_ZERO (temp))
1158     return 0;
1159
1160   return (given.bitfield.baseindex == overlap.bitfield.baseindex
1161           && given.bitfield.jumpabsolute == overlap.bitfield.jumpabsolute);
1162 }
1163
1164 /* If given types r0 and r1 are registers they must be of the same type
1165    unless the expected operand type register overlap is null.
1166    Note that Acc in a template matches every size of reg.  */
1167
1168 static INLINE int
1169 operand_type_register_match (i386_operand_type m0,
1170                              i386_operand_type g0,
1171                              i386_operand_type t0,
1172                              i386_operand_type m1,
1173                              i386_operand_type g1,
1174                              i386_operand_type t1)
1175 {
1176   if (!operand_type_check (g0, reg))
1177     return 1;
1178
1179   if (!operand_type_check (g1, reg))
1180     return 1;
1181
1182   if (g0.bitfield.reg8 == g1.bitfield.reg8
1183       && g0.bitfield.reg16 == g1.bitfield.reg16
1184       && g0.bitfield.reg32 == g1.bitfield.reg32
1185       && g0.bitfield.reg64 == g1.bitfield.reg64)
1186     return 1;
1187
1188   if (m0.bitfield.acc)
1189     {
1190       t0.bitfield.reg8 = 1;
1191       t0.bitfield.reg16 = 1;
1192       t0.bitfield.reg32 = 1;
1193       t0.bitfield.reg64 = 1;
1194     }
1195
1196   if (m1.bitfield.acc)
1197     {
1198       t1.bitfield.reg8 = 1;
1199       t1.bitfield.reg16 = 1;
1200       t1.bitfield.reg32 = 1;
1201       t1.bitfield.reg64 = 1;
1202     }
1203
1204   return (!(t0.bitfield.reg8 & t1.bitfield.reg8)
1205           && !(t0.bitfield.reg16 & t1.bitfield.reg16)
1206           && !(t0.bitfield.reg32 & t1.bitfield.reg32)
1207           && !(t0.bitfield.reg64 & t1.bitfield.reg64));
1208 }
1209
1210 static INLINE unsigned int
1211 mode_from_disp_size (i386_operand_type t)
1212 {
1213   if (t.bitfield.disp8)
1214     return 1;
1215   else if (t.bitfield.disp16
1216            || t.bitfield.disp32
1217            || t.bitfield.disp32s)
1218     return 2;
1219   else
1220     return 0;
1221 }
1222
1223 static INLINE int
1224 fits_in_signed_byte (offsetT num)
1225 {
1226   return (num >= -128) && (num <= 127);
1227 }
1228
1229 static INLINE int
1230 fits_in_unsigned_byte (offsetT num)
1231 {
1232   return (num & 0xff) == num;
1233 }
1234
1235 static INLINE int
1236 fits_in_unsigned_word (offsetT num)
1237 {
1238   return (num & 0xffff) == num;
1239 }
1240
1241 static INLINE int
1242 fits_in_signed_word (offsetT num)
1243 {
1244   return (-32768 <= num) && (num <= 32767);
1245 }
1246
1247 static INLINE int
1248 fits_in_signed_long (offsetT num ATTRIBUTE_UNUSED)
1249 {
1250 #ifndef BFD64
1251   return 1;
1252 #else
1253   return (!(((offsetT) -1 << 31) & num)
1254           || (((offsetT) -1 << 31) & num) == ((offsetT) -1 << 31));
1255 #endif
1256 }                               /* fits_in_signed_long() */
1257
1258 static INLINE int
1259 fits_in_unsigned_long (offsetT num ATTRIBUTE_UNUSED)
1260 {
1261 #ifndef BFD64
1262   return 1;
1263 #else
1264   return (num & (((offsetT) 2 << 31) - 1)) == num;
1265 #endif
1266 }                               /* fits_in_unsigned_long() */
1267
1268 static i386_operand_type
1269 smallest_imm_type (offsetT num)
1270 {
1271   i386_operand_type t;
1272  
1273   UINTS_CLEAR (t);
1274   t.bitfield.imm64 = 1;
1275
1276   if (cpu_arch_tune != PROCESSOR_I486 && num == 1)
1277     {
1278       /* This code is disabled on the 486 because all the Imm1 forms
1279          in the opcode table are slower on the i486.  They're the
1280          versions with the implicitly specified single-position
1281          displacement, which has another syntax if you really want to
1282          use that form.  */
1283       t.bitfield.imm1 = 1;
1284       t.bitfield.imm8 = 1;
1285       t.bitfield.imm8s = 1;
1286       t.bitfield.imm16 = 1;
1287       t.bitfield.imm32 = 1;
1288       t.bitfield.imm32s = 1;
1289     }
1290   else if (fits_in_signed_byte (num))
1291     {
1292       t.bitfield.imm8 = 1;
1293       t.bitfield.imm8s = 1;
1294       t.bitfield.imm16 = 1;
1295       t.bitfield.imm32 = 1;
1296       t.bitfield.imm32s = 1;
1297     }
1298   else if (fits_in_unsigned_byte (num))
1299     {
1300       t.bitfield.imm8 = 1;
1301       t.bitfield.imm16 = 1;
1302       t.bitfield.imm32 = 1;
1303       t.bitfield.imm32s = 1;
1304     }
1305   else if (fits_in_signed_word (num) || fits_in_unsigned_word (num))
1306     {
1307       t.bitfield.imm16 = 1;
1308       t.bitfield.imm32 = 1;
1309       t.bitfield.imm32s = 1;
1310     }
1311   else if (fits_in_signed_long (num))
1312     {
1313       t.bitfield.imm32 = 1;
1314       t.bitfield.imm32s = 1;
1315     }
1316   else if (fits_in_unsigned_long (num))
1317     t.bitfield.imm32 = 1;
1318
1319   return t;
1320 }
1321
1322 static offsetT
1323 offset_in_range (offsetT val, int size)
1324 {
1325   addressT mask;
1326
1327   switch (size)
1328     {
1329     case 1: mask = ((addressT) 1 <<  8) - 1; break;
1330     case 2: mask = ((addressT) 1 << 16) - 1; break;
1331     case 4: mask = ((addressT) 2 << 31) - 1; break;
1332 #ifdef BFD64
1333     case 8: mask = ((addressT) 2 << 63) - 1; break;
1334 #endif
1335     default: abort ();
1336     }
1337
1338   /* If BFD64, sign extend val.  */
1339   if (!use_rela_relocations)
1340     if ((val & ~(((addressT) 2 << 31) - 1)) == 0)
1341       val = (val ^ ((addressT) 1 << 31)) - ((addressT) 1 << 31);
1342
1343   if ((val & ~mask) != 0 && (val & ~mask) != ~mask)
1344     {
1345       char buf1[40], buf2[40];
1346
1347       sprint_value (buf1, val);
1348       sprint_value (buf2, val & mask);
1349       as_warn (_("%s shortened to %s"), buf1, buf2);
1350     }
1351   return val & mask;
1352 }
1353
1354 /* Returns 0 if attempting to add a prefix where one from the same
1355    class already exists, 1 if non rep/repne added, 2 if rep/repne
1356    added.  */
1357 static int
1358 add_prefix (unsigned int prefix)
1359 {
1360   int ret = 1;
1361   unsigned int q;
1362
1363   if (prefix >= REX_OPCODE && prefix < REX_OPCODE + 16
1364       && flag_code == CODE_64BIT)
1365     {
1366       if ((i.prefix[REX_PREFIX] & prefix & REX_W)
1367           || ((i.prefix[REX_PREFIX] & (REX_R | REX_X | REX_B))
1368               && (prefix & (REX_R | REX_X | REX_B))))
1369         ret = 0;
1370       q = REX_PREFIX;
1371     }
1372   else
1373     {
1374       switch (prefix)
1375         {
1376         default:
1377           abort ();
1378
1379         case CS_PREFIX_OPCODE:
1380         case DS_PREFIX_OPCODE:
1381         case ES_PREFIX_OPCODE:
1382         case FS_PREFIX_OPCODE:
1383         case GS_PREFIX_OPCODE:
1384         case SS_PREFIX_OPCODE:
1385           q = SEG_PREFIX;
1386           break;
1387
1388         case REPNE_PREFIX_OPCODE:
1389         case REPE_PREFIX_OPCODE:
1390           ret = 2;
1391           /* fall thru */
1392         case LOCK_PREFIX_OPCODE:
1393           q = LOCKREP_PREFIX;
1394           break;
1395
1396         case FWAIT_OPCODE:
1397           q = WAIT_PREFIX;
1398           break;
1399
1400         case ADDR_PREFIX_OPCODE:
1401           q = ADDR_PREFIX;
1402           break;
1403
1404         case DATA_PREFIX_OPCODE:
1405           q = DATA_PREFIX;
1406           break;
1407         }
1408       if (i.prefix[q] != 0)
1409         ret = 0;
1410     }
1411
1412   if (ret)
1413     {
1414       if (!i.prefix[q])
1415         ++i.prefixes;
1416       i.prefix[q] |= prefix;
1417     }
1418   else
1419     as_bad (_("same type of prefix used twice"));
1420
1421   return ret;
1422 }
1423
1424 static void
1425 set_code_flag (int value)
1426 {
1427   flag_code = value;
1428   if (flag_code == CODE_64BIT)
1429     {
1430       cpu_arch_flags.bitfield.cpu64 = 1;
1431       cpu_arch_flags.bitfield.cpuno64 = 0;
1432     }
1433   else
1434     {
1435       cpu_arch_flags.bitfield.cpu64 = 0;
1436       cpu_arch_flags.bitfield.cpuno64 = 1;
1437     }
1438   if (value == CODE_64BIT && !cpu_arch_flags.bitfield.cpulm )
1439     {
1440       as_bad (_("64bit mode not supported on this CPU."));
1441     }
1442   if (value == CODE_32BIT && !cpu_arch_flags.bitfield.cpui386)
1443     {
1444       as_bad (_("32bit mode not supported on this CPU."));
1445     }
1446   stackop_size = '\0';
1447 }
1448
1449 static void
1450 set_16bit_gcc_code_flag (int new_code_flag)
1451 {
1452   flag_code = new_code_flag;
1453   if (flag_code != CODE_16BIT)
1454     abort ();
1455   cpu_arch_flags.bitfield.cpu64 = 0;
1456   cpu_arch_flags.bitfield.cpuno64 = 1;
1457   stackop_size = LONG_MNEM_SUFFIX;
1458 }
1459
1460 static void
1461 set_intel_syntax (int syntax_flag)
1462 {
1463   /* Find out if register prefixing is specified.  */
1464   int ask_naked_reg = 0;
1465
1466   SKIP_WHITESPACE ();
1467   if (!is_end_of_line[(unsigned char) *input_line_pointer])
1468     {
1469       char *string = input_line_pointer;
1470       int e = get_symbol_end ();
1471
1472       if (strcmp (string, "prefix") == 0)
1473         ask_naked_reg = 1;
1474       else if (strcmp (string, "noprefix") == 0)
1475         ask_naked_reg = -1;
1476       else
1477         as_bad (_("bad argument to syntax directive."));
1478       *input_line_pointer = e;
1479     }
1480   demand_empty_rest_of_line ();
1481
1482   intel_syntax = syntax_flag;
1483
1484   if (ask_naked_reg == 0)
1485     allow_naked_reg = (intel_syntax
1486                        && (bfd_get_symbol_leading_char (stdoutput) != '\0'));
1487   else
1488     allow_naked_reg = (ask_naked_reg < 0);
1489
1490   identifier_chars['%'] = intel_syntax && allow_naked_reg ? '%' : 0;
1491   identifier_chars['$'] = intel_syntax ? '$' : 0;
1492   register_prefix = allow_naked_reg ? "" : "%";
1493 }
1494
1495 static void
1496 set_intel_mnemonic (int mnemonic_flag)
1497 {
1498   /* Find out if register prefixing is specified.  */
1499   int ask_naked_reg = 0;
1500
1501   SKIP_WHITESPACE ();
1502   if (!is_end_of_line[(unsigned char) *input_line_pointer])
1503     {
1504       char *string = input_line_pointer;
1505       int e = get_symbol_end ();
1506
1507       if (strcmp (string, "prefix") == 0)
1508         ask_naked_reg = 1;
1509       else if (strcmp (string, "noprefix") == 0)
1510         ask_naked_reg = -1;
1511       else
1512         as_bad (_("bad argument to syntax directive."));
1513       *input_line_pointer = e;
1514     }
1515   demand_empty_rest_of_line ();
1516
1517   /* intel_mnemonic implies intel_syntax.  */
1518   intel_mnemonic = intel_syntax = mnemonic_flag;
1519
1520   if (ask_naked_reg == 0)
1521     allow_naked_reg = (intel_mnemonic
1522                        && (bfd_get_symbol_leading_char (stdoutput) != '\0'));
1523   else
1524     allow_naked_reg = (ask_naked_reg < 0);
1525
1526   identifier_chars['%'] = intel_mnemonic && allow_naked_reg ? '%' : 0;
1527   identifier_chars['$'] = intel_mnemonic ? '$' : 0;
1528   register_prefix = allow_naked_reg ? "" : "%";
1529 }
1530
1531 static void
1532 set_allow_index_reg (int flag)
1533 {
1534   allow_index_reg = flag;
1535 }
1536
1537 static void
1538 set_cpu_arch (int dummy ATTRIBUTE_UNUSED)
1539 {
1540   SKIP_WHITESPACE ();
1541
1542   if (!is_end_of_line[(unsigned char) *input_line_pointer])
1543     {
1544       char *string = input_line_pointer;
1545       int e = get_symbol_end ();
1546       unsigned int i;
1547       i386_cpu_flags flags;
1548
1549       for (i = 0; i < ARRAY_SIZE (cpu_arch); i++)
1550         {
1551           if (strcmp (string, cpu_arch[i].name) == 0)
1552             {
1553               if (*string != '.')
1554                 {
1555                   cpu_arch_name = cpu_arch[i].name;
1556                   cpu_sub_arch_name = NULL;
1557                   cpu_arch_flags = cpu_arch[i].flags;
1558                   if (flag_code == CODE_64BIT)
1559                     {
1560                       cpu_arch_flags.bitfield.cpu64 = 1;
1561                       cpu_arch_flags.bitfield.cpuno64 = 0;
1562                     }
1563                   else
1564                     {
1565                       cpu_arch_flags.bitfield.cpu64 = 0;
1566                       cpu_arch_flags.bitfield.cpuno64 = 1;
1567                     }
1568                   cpu_arch_isa = cpu_arch[i].type;
1569                   cpu_arch_isa_flags = cpu_arch[i].flags;
1570                   if (!cpu_arch_tune_set)
1571                     {
1572                       cpu_arch_tune = cpu_arch_isa;
1573                       cpu_arch_tune_flags = cpu_arch_isa_flags;
1574                     }
1575                   break;
1576                 }
1577
1578               flags = cpu_flags_or (cpu_arch_flags,
1579                                     cpu_arch[i].flags);
1580               if (!UINTS_EQUAL (flags, cpu_arch_flags))
1581                 {
1582                   cpu_sub_arch_name = cpu_arch[i].name;
1583                   cpu_arch_flags = flags;
1584                 }
1585               *input_line_pointer = e;
1586               demand_empty_rest_of_line ();
1587               return;
1588             }
1589         }
1590       if (i >= ARRAY_SIZE (cpu_arch))
1591         as_bad (_("no such architecture: `%s'"), string);
1592
1593       *input_line_pointer = e;
1594     }
1595   else
1596     as_bad (_("missing cpu architecture"));
1597
1598   no_cond_jump_promotion = 0;
1599   if (*input_line_pointer == ','
1600       && !is_end_of_line[(unsigned char) input_line_pointer[1]])
1601     {
1602       char *string = ++input_line_pointer;
1603       int e = get_symbol_end ();
1604
1605       if (strcmp (string, "nojumps") == 0)
1606         no_cond_jump_promotion = 1;
1607       else if (strcmp (string, "jumps") == 0)
1608         ;
1609       else
1610         as_bad (_("no such architecture modifier: `%s'"), string);
1611
1612       *input_line_pointer = e;
1613     }
1614
1615   demand_empty_rest_of_line ();
1616 }
1617
1618 unsigned long
1619 i386_mach ()
1620 {
1621   if (!strcmp (default_arch, "x86_64"))
1622     return bfd_mach_x86_64;
1623   else if (!strcmp (default_arch, "i386"))
1624     return bfd_mach_i386_i386;
1625   else
1626     as_fatal (_("Unknown architecture"));
1627 }
1628 \f
1629 void
1630 md_begin ()
1631 {
1632   const char *hash_err;
1633
1634   /* Initialize op_hash hash table.  */
1635   op_hash = hash_new ();
1636
1637   {
1638     const template *optab;
1639     templates *core_optab;
1640
1641     /* Setup for loop.  */
1642     optab = i386_optab;
1643     core_optab = (templates *) xmalloc (sizeof (templates));
1644     core_optab->start = optab;
1645
1646     while (1)
1647       {
1648         ++optab;
1649         if (optab->name == NULL
1650             || strcmp (optab->name, (optab - 1)->name) != 0)
1651           {
1652             /* different name --> ship out current template list;
1653                add to hash table; & begin anew.  */
1654             core_optab->end = optab;
1655             hash_err = hash_insert (op_hash,
1656                                     (optab - 1)->name,
1657                                     (PTR) core_optab);
1658             if (hash_err)
1659               {
1660                 as_fatal (_("Internal Error:  Can't hash %s: %s"),
1661                           (optab - 1)->name,
1662                           hash_err);
1663               }
1664             if (optab->name == NULL)
1665               break;
1666             core_optab = (templates *) xmalloc (sizeof (templates));
1667             core_optab->start = optab;
1668           }
1669       }
1670   }
1671
1672   /* Initialize reg_hash hash table.  */
1673   reg_hash = hash_new ();
1674   {
1675     const reg_entry *regtab;
1676     unsigned int regtab_size = i386_regtab_size;
1677
1678     for (regtab = i386_regtab; regtab_size--; regtab++)
1679       {
1680         hash_err = hash_insert (reg_hash, regtab->reg_name, (PTR) regtab);
1681         if (hash_err)
1682           as_fatal (_("Internal Error:  Can't hash %s: %s"),
1683                     regtab->reg_name,
1684                     hash_err);
1685       }
1686   }
1687
1688   /* Fill in lexical tables:  mnemonic_chars, operand_chars.  */
1689   {
1690     int c;
1691     char *p;
1692
1693     for (c = 0; c < 256; c++)
1694       {
1695         if (ISDIGIT (c))
1696           {
1697             digit_chars[c] = c;
1698             mnemonic_chars[c] = c;
1699             register_chars[c] = c;
1700             operand_chars[c] = c;
1701           }
1702         else if (ISLOWER (c))
1703           {
1704             mnemonic_chars[c] = c;
1705             register_chars[c] = c;
1706             operand_chars[c] = c;
1707           }
1708         else if (ISUPPER (c))
1709           {
1710             mnemonic_chars[c] = TOLOWER (c);
1711             register_chars[c] = mnemonic_chars[c];
1712             operand_chars[c] = c;
1713           }
1714
1715         if (ISALPHA (c) || ISDIGIT (c))
1716           identifier_chars[c] = c;
1717         else if (c >= 128)
1718           {
1719             identifier_chars[c] = c;
1720             operand_chars[c] = c;
1721           }
1722       }
1723
1724 #ifdef LEX_AT
1725     identifier_chars['@'] = '@';
1726 #endif
1727 #ifdef LEX_QM
1728     identifier_chars['?'] = '?';
1729     operand_chars['?'] = '?';
1730 #endif
1731     digit_chars['-'] = '-';
1732     mnemonic_chars['-'] = '-';
1733     mnemonic_chars['.'] = '.';
1734     identifier_chars['_'] = '_';
1735     identifier_chars['.'] = '.';
1736
1737     for (p = operand_special_chars; *p != '\0'; p++)
1738       operand_chars[(unsigned char) *p] = *p;
1739   }
1740
1741 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
1742   if (IS_ELF)
1743     {
1744       record_alignment (text_section, 2);
1745       record_alignment (data_section, 2);
1746       record_alignment (bss_section, 2);
1747     }
1748 #endif
1749
1750   if (flag_code == CODE_64BIT)
1751     {
1752       x86_dwarf2_return_column = 16;
1753       x86_cie_data_alignment = -8;
1754     }
1755   else
1756     {
1757       x86_dwarf2_return_column = 8;
1758       x86_cie_data_alignment = -4;
1759     }
1760 }
1761
1762 void
1763 i386_print_statistics (FILE *file)
1764 {
1765   hash_print_statistics (file, "i386 opcode", op_hash);
1766   hash_print_statistics (file, "i386 register", reg_hash);
1767 }
1768 \f
1769 #ifdef DEBUG386
1770
1771 /* Debugging routines for md_assemble.  */
1772 static void pte (template *);
1773 static void pt (i386_operand_type);
1774 static void pe (expressionS *);
1775 static void ps (symbolS *);
1776
1777 static void
1778 pi (char *line, i386_insn *x)
1779 {
1780   unsigned int i;
1781
1782   fprintf (stdout, "%s: template ", line);
1783   pte (&x->tm);
1784   fprintf (stdout, "  address: base %s  index %s  scale %x\n",
1785            x->base_reg ? x->base_reg->reg_name : "none",
1786            x->index_reg ? x->index_reg->reg_name : "none",
1787            x->log2_scale_factor);
1788   fprintf (stdout, "  modrm:  mode %x  reg %x  reg/mem %x\n",
1789            x->rm.mode, x->rm.reg, x->rm.regmem);
1790   fprintf (stdout, "  sib:  base %x  index %x  scale %x\n",
1791            x->sib.base, x->sib.index, x->sib.scale);
1792   fprintf (stdout, "  rex: 64bit %x  extX %x  extY %x  extZ %x\n",
1793            (x->rex & REX_W) != 0,
1794            (x->rex & REX_R) != 0,
1795            (x->rex & REX_X) != 0,
1796            (x->rex & REX_B) != 0);
1797   fprintf (stdout, "  drex:  reg %d rex 0x%x\n", 
1798            x->drex.reg, x->drex.rex);
1799   for (i = 0; i < x->operands; i++)
1800     {
1801       fprintf (stdout, "    #%d:  ", i + 1);
1802       pt (x->types[i]);
1803       fprintf (stdout, "\n");
1804       if (x->types[i].bitfield.reg8
1805           || x->types[i].bitfield.reg16
1806           || x->types[i].bitfield.reg32
1807           || x->types[i].bitfield.reg64
1808           || x->types[i].bitfield.regmmx
1809           || x->types[i].bitfield.regxmm
1810           || x->types[i].bitfield.sreg2
1811           || x->types[i].bitfield.sreg3
1812           || x->types[i].bitfield.control
1813           || x->types[i].bitfield.debug
1814           || x->types[i].bitfield.test)
1815         fprintf (stdout, "%s\n", x->op[i].regs->reg_name);
1816       if (operand_type_check (x->types[i], imm))
1817         pe (x->op[i].imms);
1818       if (operand_type_check (x->types[i], disp))
1819         pe (x->op[i].disps);
1820     }
1821 }
1822
1823 static void
1824 pte (template *t)
1825 {
1826   unsigned int i;
1827   fprintf (stdout, " %d operands ", t->operands);
1828   fprintf (stdout, "opcode %x ", t->base_opcode);
1829   if (t->extension_opcode != None)
1830     fprintf (stdout, "ext %x ", t->extension_opcode);
1831   if (t->opcode_modifier.d)
1832     fprintf (stdout, "D");
1833   if (t->opcode_modifier.w)
1834     fprintf (stdout, "W");
1835   fprintf (stdout, "\n");
1836   for (i = 0; i < t->operands; i++)
1837     {
1838       fprintf (stdout, "    #%d type ", i + 1);
1839       pt (t->operand_types[i]);
1840       fprintf (stdout, "\n");
1841     }
1842 }
1843
1844 static void
1845 pe (expressionS *e)
1846 {
1847   fprintf (stdout, "    operation     %d\n", e->X_op);
1848   fprintf (stdout, "    add_number    %ld (%lx)\n",
1849            (long) e->X_add_number, (long) e->X_add_number);
1850   if (e->X_add_symbol)
1851     {
1852       fprintf (stdout, "    add_symbol    ");
1853       ps (e->X_add_symbol);
1854       fprintf (stdout, "\n");
1855     }
1856   if (e->X_op_symbol)
1857     {
1858       fprintf (stdout, "    op_symbol    ");
1859       ps (e->X_op_symbol);
1860       fprintf (stdout, "\n");
1861     }
1862 }
1863
1864 static void
1865 ps (symbolS *s)
1866 {
1867   fprintf (stdout, "%s type %s%s",
1868            S_GET_NAME (s),
1869            S_IS_EXTERNAL (s) ? "EXTERNAL " : "",
1870            segment_name (S_GET_SEGMENT (s)));
1871 }
1872
1873 static struct type_name
1874   {
1875     i386_operand_type mask;
1876     const char *name;
1877   }
1878 const type_names[] =
1879 {
1880   { OPERAND_TYPE_REG8, "r8" },
1881   { OPERAND_TYPE_REG16, "r16" },
1882   { OPERAND_TYPE_REG32, "r32" },
1883   { OPERAND_TYPE_REG64, "r64" },
1884   { OPERAND_TYPE_IMM8, "i8" },
1885   { OPERAND_TYPE_IMM8, "i8s" },
1886   { OPERAND_TYPE_IMM16, "i16" },
1887   { OPERAND_TYPE_IMM32, "i32" },
1888   { OPERAND_TYPE_IMM32S, "i32s" },
1889   { OPERAND_TYPE_IMM64, "i64" },
1890   { OPERAND_TYPE_IMM1, "i1" },
1891   { OPERAND_TYPE_BASEINDEX, "BaseIndex" },
1892   { OPERAND_TYPE_DISP8, "d8" },
1893   { OPERAND_TYPE_DISP16, "d16" },
1894   { OPERAND_TYPE_DISP32, "d32" },
1895   { OPERAND_TYPE_DISP32S, "d32s" },
1896   { OPERAND_TYPE_DISP64, "d64" },
1897   { OPERAND_TYPE_INOUTPORTREG, "InOutPortReg" },
1898   { OPERAND_TYPE_SHIFTCOUNT, "ShiftCount" },
1899   { OPERAND_TYPE_CONTROL, "control reg" },
1900   { OPERAND_TYPE_TEST, "test reg" },
1901   { OPERAND_TYPE_DEBUG, "debug reg" },
1902   { OPERAND_TYPE_FLOATREG, "FReg" },
1903   { OPERAND_TYPE_FLOATACC, "FAcc" },
1904   { OPERAND_TYPE_SREG2, "SReg2" },
1905   { OPERAND_TYPE_SREG3, "SReg3" },
1906   { OPERAND_TYPE_ACC, "Acc" },
1907   { OPERAND_TYPE_JUMPABSOLUTE, "Jump Absolute" },
1908   { OPERAND_TYPE_REGMMX, "rMMX" },
1909   { OPERAND_TYPE_REGXMM, "rXMM" },
1910   { OPERAND_TYPE_ESSEG, "es" },
1911 };
1912
1913 static void
1914 pt (i386_operand_type t)
1915 {
1916   unsigned int j;
1917   i386_operand_type a;
1918
1919   for (j = 0; j < ARRAY_SIZE (type_names); j++)
1920     {
1921       a = operand_type_and (t, type_names[j].mask);
1922       if (!UINTS_ALL_ZERO (a))
1923         fprintf (stdout, "%s, ",  type_names[j].name);
1924     }
1925   fflush (stdout);
1926 }
1927
1928 #endif /* DEBUG386 */
1929 \f
1930 static bfd_reloc_code_real_type
1931 reloc (unsigned int size,
1932        int pcrel,
1933        int sign,
1934        bfd_reloc_code_real_type other)
1935 {
1936   if (other != NO_RELOC)
1937     {
1938       reloc_howto_type *reloc;
1939
1940       if (size == 8)
1941         switch (other)
1942           {
1943           case BFD_RELOC_X86_64_GOT32:
1944             return BFD_RELOC_X86_64_GOT64;
1945             break;
1946           case BFD_RELOC_X86_64_PLTOFF64:
1947             return BFD_RELOC_X86_64_PLTOFF64;
1948             break;
1949           case BFD_RELOC_X86_64_GOTPC32:
1950             other = BFD_RELOC_X86_64_GOTPC64;
1951             break;
1952           case BFD_RELOC_X86_64_GOTPCREL:
1953             other = BFD_RELOC_X86_64_GOTPCREL64;
1954             break;
1955           case BFD_RELOC_X86_64_TPOFF32:
1956             other = BFD_RELOC_X86_64_TPOFF64;
1957             break;
1958           case BFD_RELOC_X86_64_DTPOFF32:
1959             other = BFD_RELOC_X86_64_DTPOFF64;
1960             break;
1961           default:
1962             break;
1963           }
1964
1965       /* Sign-checking 4-byte relocations in 16-/32-bit code is pointless.  */
1966       if (size == 4 && flag_code != CODE_64BIT)
1967         sign = -1;
1968
1969       reloc = bfd_reloc_type_lookup (stdoutput, other);
1970       if (!reloc)
1971         as_bad (_("unknown relocation (%u)"), other);
1972       else if (size != bfd_get_reloc_size (reloc))
1973         as_bad (_("%u-byte relocation cannot be applied to %u-byte field"),
1974                 bfd_get_reloc_size (reloc),
1975                 size);
1976       else if (pcrel && !reloc->pc_relative)
1977         as_bad (_("non-pc-relative relocation for pc-relative field"));
1978       else if ((reloc->complain_on_overflow == complain_overflow_signed
1979                 && !sign)
1980                || (reloc->complain_on_overflow == complain_overflow_unsigned
1981                    && sign > 0))
1982         as_bad (_("relocated field and relocation type differ in signedness"));
1983       else
1984         return other;
1985       return NO_RELOC;
1986     }
1987
1988   if (pcrel)
1989     {
1990       if (!sign)
1991         as_bad (_("there are no unsigned pc-relative relocations"));
1992       switch (size)
1993         {
1994         case 1: return BFD_RELOC_8_PCREL;
1995         case 2: return BFD_RELOC_16_PCREL;
1996         case 4: return BFD_RELOC_32_PCREL;
1997         case 8: return BFD_RELOC_64_PCREL;
1998         }
1999       as_bad (_("cannot do %u byte pc-relative relocation"), size);
2000     }
2001   else
2002     {
2003       if (sign > 0)
2004         switch (size)
2005           {
2006           case 4: return BFD_RELOC_X86_64_32S;
2007           }
2008       else
2009         switch (size)
2010           {
2011           case 1: return BFD_RELOC_8;
2012           case 2: return BFD_RELOC_16;
2013           case 4: return BFD_RELOC_32;
2014           case 8: return BFD_RELOC_64;
2015           }
2016       as_bad (_("cannot do %s %u byte relocation"),
2017               sign > 0 ? "signed" : "unsigned", size);
2018     }
2019
2020   abort ();
2021   return BFD_RELOC_NONE;
2022 }
2023
2024 /* Here we decide which fixups can be adjusted to make them relative to
2025    the beginning of the section instead of the symbol.  Basically we need
2026    to make sure that the dynamic relocations are done correctly, so in
2027    some cases we force the original symbol to be used.  */
2028
2029 int
2030 tc_i386_fix_adjustable (fixS *fixP ATTRIBUTE_UNUSED)
2031 {
2032 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
2033   if (!IS_ELF)
2034     return 1;
2035
2036   /* Don't adjust pc-relative references to merge sections in 64-bit
2037      mode.  */
2038   if (use_rela_relocations
2039       && (S_GET_SEGMENT (fixP->fx_addsy)->flags & SEC_MERGE) != 0
2040       && fixP->fx_pcrel)
2041     return 0;
2042
2043   /* The x86_64 GOTPCREL are represented as 32bit PCrel relocations
2044      and changed later by validate_fix.  */
2045   if (GOT_symbol && fixP->fx_subsy == GOT_symbol
2046       && fixP->fx_r_type == BFD_RELOC_32_PCREL)
2047     return 0;
2048
2049   /* adjust_reloc_syms doesn't know about the GOT.  */
2050   if (fixP->fx_r_type == BFD_RELOC_386_GOTOFF
2051       || fixP->fx_r_type == BFD_RELOC_386_PLT32
2052       || fixP->fx_r_type == BFD_RELOC_386_GOT32
2053       || fixP->fx_r_type == BFD_RELOC_386_TLS_GD
2054       || fixP->fx_r_type == BFD_RELOC_386_TLS_LDM
2055       || fixP->fx_r_type == BFD_RELOC_386_TLS_LDO_32
2056       || fixP->fx_r_type == BFD_RELOC_386_TLS_IE_32
2057       || fixP->fx_r_type == BFD_RELOC_386_TLS_IE
2058       || fixP->fx_r_type == BFD_RELOC_386_TLS_GOTIE
2059       || fixP->fx_r_type == BFD_RELOC_386_TLS_LE_32
2060       || fixP->fx_r_type == BFD_RELOC_386_TLS_LE
2061       || fixP->fx_r_type == BFD_RELOC_386_TLS_GOTDESC
2062       || fixP->fx_r_type == BFD_RELOC_386_TLS_DESC_CALL
2063       || fixP->fx_r_type == BFD_RELOC_X86_64_PLT32
2064       || fixP->fx_r_type == BFD_RELOC_X86_64_GOT32
2065       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTPCREL
2066       || fixP->fx_r_type == BFD_RELOC_X86_64_TLSGD
2067       || fixP->fx_r_type == BFD_RELOC_X86_64_TLSLD
2068       || fixP->fx_r_type == BFD_RELOC_X86_64_DTPOFF32
2069       || fixP->fx_r_type == BFD_RELOC_X86_64_DTPOFF64
2070       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTTPOFF
2071       || fixP->fx_r_type == BFD_RELOC_X86_64_TPOFF32
2072       || fixP->fx_r_type == BFD_RELOC_X86_64_TPOFF64
2073       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTOFF64
2074       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTPC32_TLSDESC
2075       || fixP->fx_r_type == BFD_RELOC_X86_64_TLSDESC_CALL
2076       || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
2077       || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
2078     return 0;
2079 #endif
2080   return 1;
2081 }
2082
2083 static int
2084 intel_float_operand (const char *mnemonic)
2085 {
2086   /* Note that the value returned is meaningful only for opcodes with (memory)
2087      operands, hence the code here is free to improperly handle opcodes that
2088      have no operands (for better performance and smaller code). */
2089
2090   if (mnemonic[0] != 'f')
2091     return 0; /* non-math */
2092
2093   switch (mnemonic[1])
2094     {
2095     /* fclex, fdecstp, fdisi, femms, feni, fincstp, finit, fsetpm, and
2096        the fs segment override prefix not currently handled because no
2097        call path can make opcodes without operands get here */
2098     case 'i':
2099       return 2 /* integer op */;
2100     case 'l':
2101       if (mnemonic[2] == 'd' && (mnemonic[3] == 'c' || mnemonic[3] == 'e'))
2102         return 3; /* fldcw/fldenv */
2103       break;
2104     case 'n':
2105       if (mnemonic[2] != 'o' /* fnop */)
2106         return 3; /* non-waiting control op */
2107       break;
2108     case 'r':
2109       if (mnemonic[2] == 's')
2110         return 3; /* frstor/frstpm */
2111       break;
2112     case 's':
2113       if (mnemonic[2] == 'a')
2114         return 3; /* fsave */
2115       if (mnemonic[2] == 't')
2116         {
2117           switch (mnemonic[3])
2118             {
2119             case 'c': /* fstcw */
2120             case 'd': /* fstdw */
2121             case 'e': /* fstenv */
2122             case 's': /* fsts[gw] */
2123               return 3;
2124             }
2125         }
2126       break;
2127     case 'x':
2128       if (mnemonic[2] == 'r' || mnemonic[2] == 's')
2129         return 0; /* fxsave/fxrstor are not really math ops */
2130       break;
2131     }
2132
2133   return 1;
2134 }
2135
2136 /* This is the guts of the machine-dependent assembler.  LINE points to a
2137    machine dependent instruction.  This function is supposed to emit
2138    the frags/bytes it assembles to.  */
2139
2140 void
2141 md_assemble (line)
2142      char *line;
2143 {
2144   unsigned int j;
2145   char mnemonic[MAX_MNEM_SIZE];
2146
2147   /* Initialize globals.  */
2148   memset (&i, '\0', sizeof (i));
2149   for (j = 0; j < MAX_OPERANDS; j++)
2150     i.reloc[j] = NO_RELOC;
2151   memset (disp_expressions, '\0', sizeof (disp_expressions));
2152   memset (im_expressions, '\0', sizeof (im_expressions));
2153   save_stack_p = save_stack;
2154
2155   /* First parse an instruction mnemonic & call i386_operand for the operands.
2156      We assume that the scrubber has arranged it so that line[0] is the valid
2157      start of a (possibly prefixed) mnemonic.  */
2158
2159   line = parse_insn (line, mnemonic);
2160   if (line == NULL)
2161     return;
2162
2163   line = parse_operands (line, mnemonic);
2164   if (line == NULL)
2165     return;
2166
2167   /* Now we've parsed the mnemonic into a set of templates, and have the
2168      operands at hand.  */
2169
2170   /* All intel opcodes have reversed operands except for "bound" and
2171      "enter".  We also don't reverse intersegment "jmp" and "call"
2172      instructions with 2 immediate operands so that the immediate segment
2173      precedes the offset, as it does when in AT&T mode. */
2174   if (intel_syntax
2175       && i.operands > 1
2176       && (strcmp (mnemonic, "bound") != 0)
2177       && (strcmp (mnemonic, "invlpga") != 0)
2178       && !(operand_type_check (i.types[0], imm)
2179            && operand_type_check (i.types[1], imm)))
2180     swap_operands ();
2181
2182   /* The order of the immediates should be reversed
2183      for 2 immediates extrq and insertq instructions */
2184   if (i.imm_operands == 2
2185       && (strcmp (mnemonic, "extrq") == 0
2186           || strcmp (mnemonic, "insertq") == 0))
2187       swap_2_operands (0, 1);
2188
2189   if (i.imm_operands)
2190     optimize_imm ();
2191
2192   /* Don't optimize displacement for movabs since it only takes 64bit
2193      displacement.  */
2194   if (i.disp_operands
2195       && (flag_code != CODE_64BIT
2196           || strcmp (mnemonic, "movabs") != 0))
2197     optimize_disp ();
2198
2199   /* Next, we find a template that matches the given insn,
2200      making sure the overlap of the given operands types is consistent
2201      with the template operand types.  */
2202
2203   if (!match_template ())
2204     return;
2205
2206   if (intel_syntax)
2207     {
2208       /* Undo AT&T Mnemonic brokenness when in Intel mode.  See
2209          i386-opc.tbl.  */
2210       if (!intel_mnemonic
2211           && (i.tm.base_opcode & 0xfffffde0) == 0xdce0)
2212         i.tm.base_opcode ^= Opcode_FloatR;
2213
2214       /* Zap movzx and movsx suffix.  The suffix may have been set from
2215          "word ptr" or "byte ptr" on the source operand, but we'll use
2216          the suffix later to choose the destination register.  */
2217       if ((i.tm.base_opcode & ~9) == 0x0fb6)
2218         {
2219           if (i.reg_operands < 2
2220               && !i.suffix
2221               && (!i.tm.opcode_modifier.no_bsuf
2222                   || !i.tm.opcode_modifier.no_wsuf
2223                   || !i.tm.opcode_modifier.no_lsuf
2224                   || !i.tm.opcode_modifier.no_ssuf
2225                   || !i.tm.opcode_modifier.no_ldsuf
2226                   || !i.tm.opcode_modifier.no_qsuf))
2227             as_bad (_("ambiguous operand size for `%s'"), i.tm.name);
2228
2229           i.suffix = 0;
2230         }
2231     }
2232
2233   if (i.tm.opcode_modifier.fwait)
2234     if (!add_prefix (FWAIT_OPCODE))
2235       return;
2236
2237   /* Check string instruction segment overrides.  */
2238   if (i.tm.opcode_modifier.isstring && i.mem_operands != 0)
2239     {
2240       if (!check_string ())
2241         return;
2242     }
2243
2244   if (!process_suffix ())
2245     return;
2246
2247   /* Make still unresolved immediate matches conform to size of immediate
2248      given in i.suffix.  */
2249   if (!finalize_imm ())
2250     return;
2251
2252   if (i.types[0].bitfield.imm1)
2253     i.imm_operands = 0; /* kludge for shift insns.  */
2254
2255   for (j = 0; j < 3; j++)
2256     if (i.types[j].bitfield.inoutportreg
2257         || i.types[j].bitfield.shiftcount
2258         || i.types[j].bitfield.acc
2259         || i.types[j].bitfield.floatacc)
2260       i.reg_operands--;
2261
2262   if (i.tm.opcode_modifier.immext)
2263     {
2264       expressionS *exp;
2265
2266       if (i.tm.cpu_flags.bitfield.cpusse3 && i.operands > 0)
2267         {
2268           /* Streaming SIMD extensions 3 Instructions have the fixed
2269              operands with an opcode suffix which is coded in the same
2270              place as an 8-bit immediate field would be. Here we check
2271              those operands and remove them afterwards.  */
2272           unsigned int x;
2273
2274           for (x = 0; x < i.operands; x++)
2275             if (i.op[x].regs->reg_num != x)
2276               as_bad (_("can't use register '%s%s' as operand %d in '%s'."),
2277                       register_prefix,
2278                       i.op[x].regs->reg_name,
2279                       x + 1,
2280                       i.tm.name);
2281           i.operands = 0;
2282         }
2283
2284       /* These AMD 3DNow! and Intel Katmai New Instructions have an
2285          opcode suffix which is coded in the same place as an 8-bit
2286          immediate field would be.  Here we fake an 8-bit immediate
2287          operand from the opcode suffix stored in tm.extension_opcode.
2288          SSE5 also uses this encoding, for some of its 3 argument
2289          instructions.  */
2290
2291       assert (i.imm_operands == 0
2292               && (i.operands <= 2
2293                   || (i.tm.cpu_flags.bitfield.cpusse5
2294                       && i.operands <= 3)));
2295
2296       exp = &im_expressions[i.imm_operands++];
2297       i.op[i.operands].imms = exp;
2298       UINTS_CLEAR (i.types[i.operands]);
2299       i.types[i.operands].bitfield.imm8 = 1;
2300       i.operands++;
2301       exp->X_op = O_constant;
2302       exp->X_add_number = i.tm.extension_opcode;
2303       i.tm.extension_opcode = None;
2304     }
2305
2306   /* For insns with operands there are more diddles to do to the opcode.  */
2307   if (i.operands)
2308     {
2309       if (!process_operands ())
2310         return;
2311     }
2312   else if (!quiet_warnings && i.tm.opcode_modifier.ugh)
2313     {
2314       /* UnixWare fsub no args is alias for fsubp, fadd -> faddp, etc.  */
2315       as_warn (_("translating to `%sp'"), i.tm.name);
2316     }
2317
2318   /* Handle conversion of 'int $3' --> special int3 insn.  */
2319   if (i.tm.base_opcode == INT_OPCODE && i.op[0].imms->X_add_number == 3)
2320     {
2321       i.tm.base_opcode = INT3_OPCODE;
2322       i.imm_operands = 0;
2323     }
2324
2325   if ((i.tm.opcode_modifier.jump
2326        || i.tm.opcode_modifier.jumpbyte
2327        || i.tm.opcode_modifier.jumpdword)
2328       && i.op[0].disps->X_op == O_constant)
2329     {
2330       /* Convert "jmp constant" (and "call constant") to a jump (call) to
2331          the absolute address given by the constant.  Since ix86 jumps and
2332          calls are pc relative, we need to generate a reloc.  */
2333       i.op[0].disps->X_add_symbol = &abs_symbol;
2334       i.op[0].disps->X_op = O_symbol;
2335     }
2336
2337   if (i.tm.opcode_modifier.rex64)
2338     i.rex |= REX_W;
2339
2340   /* For 8 bit registers we need an empty rex prefix.  Also if the
2341      instruction already has a prefix, we need to convert old
2342      registers to new ones.  */
2343
2344   if ((i.types[0].bitfield.reg8
2345        && (i.op[0].regs->reg_flags & RegRex64) != 0)
2346       || (i.types[1].bitfield.reg8
2347           && (i.op[1].regs->reg_flags & RegRex64) != 0)
2348       || ((i.types[0].bitfield.reg8
2349            || i.types[1].bitfield.reg8)
2350           && i.rex != 0))
2351     {
2352       int x;
2353
2354       i.rex |= REX_OPCODE;
2355       for (x = 0; x < 2; x++)
2356         {
2357           /* Look for 8 bit operand that uses old registers.  */
2358           if (i.types[x].bitfield.reg8
2359               && (i.op[x].regs->reg_flags & RegRex64) == 0)
2360             {
2361               /* In case it is "hi" register, give up.  */
2362               if (i.op[x].regs->reg_num > 3)
2363                 as_bad (_("can't encode register '%s%s' in an "
2364                           "instruction requiring REX prefix."),
2365                         register_prefix, i.op[x].regs->reg_name);
2366
2367               /* Otherwise it is equivalent to the extended register.
2368                  Since the encoding doesn't change this is merely
2369                  cosmetic cleanup for debug output.  */
2370
2371               i.op[x].regs = i.op[x].regs + 8;
2372             }
2373         }
2374     }
2375
2376   /* If the instruction has the DREX attribute (aka SSE5), don't emit a
2377      REX prefix.  */
2378   if (i.tm.opcode_modifier.drex || i.tm.opcode_modifier.drexc)
2379     {
2380       i.drex.rex = i.rex;
2381       i.rex = 0;
2382     }
2383   else if (i.rex != 0)
2384     add_prefix (REX_OPCODE | i.rex);
2385
2386   /* We are ready to output the insn.  */
2387   output_insn ();
2388 }
2389
2390 static char *
2391 parse_insn (char *line, char *mnemonic)
2392 {
2393   char *l = line;
2394   char *token_start = l;
2395   char *mnem_p;
2396   int supported;
2397   const template *t;
2398
2399   /* Non-zero if we found a prefix only acceptable with string insns.  */
2400   const char *expecting_string_instruction = NULL;
2401
2402   while (1)
2403     {
2404       mnem_p = mnemonic;
2405       while ((*mnem_p = mnemonic_chars[(unsigned char) *l]) != 0)
2406         {
2407           mnem_p++;
2408           if (mnem_p >= mnemonic + MAX_MNEM_SIZE)
2409             {
2410               as_bad (_("no such instruction: `%s'"), token_start);
2411               return NULL;
2412             }
2413           l++;
2414         }
2415       if (!is_space_char (*l)
2416           && *l != END_OF_INSN
2417           && (intel_syntax
2418               || (*l != PREFIX_SEPARATOR
2419                   && *l != ',')))
2420         {
2421           as_bad (_("invalid character %s in mnemonic"),
2422                   output_invalid (*l));
2423           return NULL;
2424         }
2425       if (token_start == l)
2426         {
2427           if (!intel_syntax && *l == PREFIX_SEPARATOR)
2428             as_bad (_("expecting prefix; got nothing"));
2429           else
2430             as_bad (_("expecting mnemonic; got nothing"));
2431           return NULL;
2432         }
2433
2434       /* Look up instruction (or prefix) via hash table.  */
2435       current_templates = hash_find (op_hash, mnemonic);
2436
2437       if (*l != END_OF_INSN
2438           && (!is_space_char (*l) || l[1] != END_OF_INSN)
2439           && current_templates
2440           && current_templates->start->opcode_modifier.isprefix)
2441         {
2442           if (!cpu_flags_check_cpu64 (current_templates->start->cpu_flags))
2443             {
2444               as_bad ((flag_code != CODE_64BIT
2445                        ? _("`%s' is only supported in 64-bit mode")
2446                        : _("`%s' is not supported in 64-bit mode")),
2447                       current_templates->start->name);
2448               return NULL;
2449             }
2450           /* If we are in 16-bit mode, do not allow addr16 or data16.
2451              Similarly, in 32-bit mode, do not allow addr32 or data32.  */
2452           if ((current_templates->start->opcode_modifier.size16
2453                || current_templates->start->opcode_modifier.size32)
2454               && flag_code != CODE_64BIT
2455               && (current_templates->start->opcode_modifier.size32
2456                   ^ (flag_code == CODE_16BIT)))
2457             {
2458               as_bad (_("redundant %s prefix"),
2459                       current_templates->start->name);
2460               return NULL;
2461             }
2462           /* Add prefix, checking for repeated prefixes.  */
2463           switch (add_prefix (current_templates->start->base_opcode))
2464             {
2465             case 0:
2466               return NULL;
2467             case 2:
2468               expecting_string_instruction = current_templates->start->name;
2469               break;
2470             }
2471           /* Skip past PREFIX_SEPARATOR and reset token_start.  */
2472           token_start = ++l;
2473         }
2474       else
2475         break;
2476     }
2477
2478   if (!current_templates)
2479     {
2480       /* See if we can get a match by trimming off a suffix.  */
2481       switch (mnem_p[-1])
2482         {
2483         case WORD_MNEM_SUFFIX:
2484           if (intel_syntax && (intel_float_operand (mnemonic) & 2))
2485             i.suffix = SHORT_MNEM_SUFFIX;
2486           else
2487         case BYTE_MNEM_SUFFIX:
2488         case QWORD_MNEM_SUFFIX:
2489           i.suffix = mnem_p[-1];
2490           mnem_p[-1] = '\0';
2491           current_templates = hash_find (op_hash, mnemonic);
2492           break;
2493         case SHORT_MNEM_SUFFIX:
2494         case LONG_MNEM_SUFFIX:
2495           if (!intel_syntax)
2496             {
2497               i.suffix = mnem_p[-1];
2498               mnem_p[-1] = '\0';
2499               current_templates = hash_find (op_hash, mnemonic);
2500             }
2501           break;
2502
2503           /* Intel Syntax.  */
2504         case 'd':
2505           if (intel_syntax)
2506             {
2507               if (intel_float_operand (mnemonic) == 1)
2508                 i.suffix = SHORT_MNEM_SUFFIX;
2509               else
2510                 i.suffix = LONG_MNEM_SUFFIX;
2511               mnem_p[-1] = '\0';
2512               current_templates = hash_find (op_hash, mnemonic);
2513             }
2514           break;
2515         }
2516       if (!current_templates)
2517         {
2518           as_bad (_("no such instruction: `%s'"), token_start);
2519           return NULL;
2520         }
2521     }
2522
2523   if (current_templates->start->opcode_modifier.jump
2524       || current_templates->start->opcode_modifier.jumpbyte)
2525     {
2526       /* Check for a branch hint.  We allow ",pt" and ",pn" for
2527          predict taken and predict not taken respectively.
2528          I'm not sure that branch hints actually do anything on loop
2529          and jcxz insns (JumpByte) for current Pentium4 chips.  They
2530          may work in the future and it doesn't hurt to accept them
2531          now.  */
2532       if (l[0] == ',' && l[1] == 'p')
2533         {
2534           if (l[2] == 't')
2535             {
2536               if (!add_prefix (DS_PREFIX_OPCODE))
2537                 return NULL;
2538               l += 3;
2539             }
2540           else if (l[2] == 'n')
2541             {
2542               if (!add_prefix (CS_PREFIX_OPCODE))
2543                 return NULL;
2544               l += 3;
2545             }
2546         }
2547     }
2548   /* Any other comma loses.  */
2549   if (*l == ',')
2550     {
2551       as_bad (_("invalid character %s in mnemonic"),
2552               output_invalid (*l));
2553       return NULL;
2554     }
2555
2556   /* Check if instruction is supported on specified architecture.  */
2557   supported = 0;
2558   for (t = current_templates->start; t < current_templates->end; ++t)
2559     {
2560       supported |= cpu_flags_match (t->cpu_flags);
2561       if (supported == 3)
2562         goto skip;
2563     }
2564
2565   if (!(supported & 2))
2566     {
2567       as_bad (flag_code == CODE_64BIT
2568               ? _("`%s' is not supported in 64-bit mode")
2569               : _("`%s' is only supported in 64-bit mode"),
2570               current_templates->start->name);
2571       return NULL;
2572     }
2573   if (!(supported & 1))
2574     {
2575       as_bad (_("`%s' is not supported on `%s%s'"),
2576               current_templates->start->name, cpu_arch_name,
2577               cpu_sub_arch_name ? cpu_sub_arch_name : "");
2578       return NULL;
2579     }
2580
2581 skip:
2582   if (!cpu_arch_flags.bitfield.cpui386
2583            && (flag_code != CODE_16BIT))
2584     {
2585       as_warn (_("use .code16 to ensure correct addressing mode"));
2586     }
2587
2588   /* Check for rep/repne without a string instruction.  */
2589   if (expecting_string_instruction)
2590     {
2591       static templates override;
2592
2593       for (t = current_templates->start; t < current_templates->end; ++t)
2594         if (t->opcode_modifier.isstring)
2595           break;
2596       if (t >= current_templates->end)
2597         {
2598           as_bad (_("expecting string instruction after `%s'"),
2599                   expecting_string_instruction);
2600           return NULL;
2601         }
2602       for (override.start = t; t < current_templates->end; ++t)
2603         if (!t->opcode_modifier.isstring)
2604           break;
2605       override.end = t;
2606       current_templates = &override;
2607     }
2608
2609   return l;
2610 }
2611
2612 static char *
2613 parse_operands (char *l, const char *mnemonic)
2614 {
2615   char *token_start;
2616
2617   /* 1 if operand is pending after ','.  */
2618   unsigned int expecting_operand = 0;
2619
2620   /* Non-zero if operand parens not balanced.  */
2621   unsigned int paren_not_balanced;
2622
2623   while (*l != END_OF_INSN)
2624     {
2625       /* Skip optional white space before operand.  */
2626       if (is_space_char (*l))
2627         ++l;
2628       if (!is_operand_char (*l) && *l != END_OF_INSN)
2629         {
2630           as_bad (_("invalid character %s before operand %d"),
2631                   output_invalid (*l),
2632                   i.operands + 1);
2633           return NULL;
2634         }
2635       token_start = l;  /* after white space */
2636       paren_not_balanced = 0;
2637       while (paren_not_balanced || *l != ',')
2638         {
2639           if (*l == END_OF_INSN)
2640             {
2641               if (paren_not_balanced)
2642                 {
2643                   if (!intel_syntax)
2644                     as_bad (_("unbalanced parenthesis in operand %d."),
2645                             i.operands + 1);
2646                   else
2647                     as_bad (_("unbalanced brackets in operand %d."),
2648                             i.operands + 1);
2649                   return NULL;
2650                 }
2651               else
2652                 break;  /* we are done */
2653             }
2654           else if (!is_operand_char (*l) && !is_space_char (*l))
2655             {
2656               as_bad (_("invalid character %s in operand %d"),
2657                       output_invalid (*l),
2658                       i.operands + 1);
2659               return NULL;
2660             }
2661           if (!intel_syntax)
2662             {
2663               if (*l == '(')
2664                 ++paren_not_balanced;
2665               if (*l == ')')
2666                 --paren_not_balanced;
2667             }
2668           else
2669             {
2670               if (*l == '[')
2671                 ++paren_not_balanced;
2672               if (*l == ']')
2673                 --paren_not_balanced;
2674             }
2675           l++;
2676         }
2677       if (l != token_start)
2678         {                       /* Yes, we've read in another operand.  */
2679           unsigned int operand_ok;
2680           this_operand = i.operands++;
2681           if (i.operands > MAX_OPERANDS)
2682             {
2683               as_bad (_("spurious operands; (%d operands/instruction max)"),
2684                       MAX_OPERANDS);
2685               return NULL;
2686             }
2687           /* Now parse operand adding info to 'i' as we go along.  */
2688           END_STRING_AND_SAVE (l);
2689
2690           if (intel_syntax)
2691             operand_ok =
2692               i386_intel_operand (token_start,
2693                                   intel_float_operand (mnemonic));
2694           else
2695             operand_ok = i386_operand (token_start);
2696
2697           RESTORE_END_STRING (l);
2698           if (!operand_ok)
2699             return NULL;
2700         }
2701       else
2702         {
2703           if (expecting_operand)
2704             {
2705             expecting_operand_after_comma:
2706               as_bad (_("expecting operand after ','; got nothing"));
2707               return NULL;
2708             }
2709           if (*l == ',')
2710             {
2711               as_bad (_("expecting operand before ','; got nothing"));
2712               return NULL;
2713             }
2714         }
2715
2716       /* Now *l must be either ',' or END_OF_INSN.  */
2717       if (*l == ',')
2718         {
2719           if (*++l == END_OF_INSN)
2720             {
2721               /* Just skip it, if it's \n complain.  */
2722               goto expecting_operand_after_comma;
2723             }
2724           expecting_operand = 1;
2725         }
2726     }
2727   return l;
2728 }
2729
2730 static void
2731 swap_2_operands (int xchg1, int xchg2)
2732 {
2733   union i386_op temp_op;
2734   i386_operand_type temp_type;
2735   enum bfd_reloc_code_real temp_reloc;
2736
2737   temp_type = i.types[xchg2];
2738   i.types[xchg2] = i.types[xchg1];
2739   i.types[xchg1] = temp_type;
2740   temp_op = i.op[xchg2];
2741   i.op[xchg2] = i.op[xchg1];
2742   i.op[xchg1] = temp_op;
2743   temp_reloc = i.reloc[xchg2];
2744   i.reloc[xchg2] = i.reloc[xchg1];
2745   i.reloc[xchg1] = temp_reloc;
2746 }
2747
2748 static void
2749 swap_operands (void)
2750 {
2751   switch (i.operands)
2752     {
2753     case 4:
2754       swap_2_operands (1, i.operands - 2);
2755     case 3:
2756     case 2:
2757       swap_2_operands (0, i.operands - 1);
2758       break;
2759     default:
2760       abort ();
2761     }
2762
2763   if (i.mem_operands == 2)
2764     {
2765       const seg_entry *temp_seg;
2766       temp_seg = i.seg[0];
2767       i.seg[0] = i.seg[1];
2768       i.seg[1] = temp_seg;
2769     }
2770 }
2771
2772 /* Try to ensure constant immediates are represented in the smallest
2773    opcode possible.  */
2774 static void
2775 optimize_imm (void)
2776 {
2777   char guess_suffix = 0;
2778   int op;
2779
2780   if (i.suffix)
2781     guess_suffix = i.suffix;
2782   else if (i.reg_operands)
2783     {
2784       /* Figure out a suffix from the last register operand specified.
2785          We can't do this properly yet, ie. excluding InOutPortReg,
2786          but the following works for instructions with immediates.
2787          In any case, we can't set i.suffix yet.  */
2788       for (op = i.operands; --op >= 0;)
2789         if (i.types[op].bitfield.reg8)
2790           { 
2791             guess_suffix = BYTE_MNEM_SUFFIX;
2792             break;
2793           }
2794         else if (i.types[op].bitfield.reg16)
2795           {
2796             guess_suffix = WORD_MNEM_SUFFIX;
2797             break;
2798           }
2799         else if (i.types[op].bitfield.reg32)
2800           {
2801             guess_suffix = LONG_MNEM_SUFFIX;
2802             break;
2803           }
2804         else if (i.types[op].bitfield.reg64)
2805           {
2806             guess_suffix = QWORD_MNEM_SUFFIX;
2807             break;
2808           }
2809     }
2810   else if ((flag_code == CODE_16BIT) ^ (i.prefix[DATA_PREFIX] != 0))
2811     guess_suffix = WORD_MNEM_SUFFIX;
2812
2813   for (op = i.operands; --op >= 0;)
2814     if (operand_type_check (i.types[op], imm))
2815       {
2816         switch (i.op[op].imms->X_op)
2817           {
2818           case O_constant:
2819             /* If a suffix is given, this operand may be shortened.  */
2820             switch (guess_suffix)
2821               {
2822               case LONG_MNEM_SUFFIX:
2823                 i.types[op].bitfield.imm32 = 1;
2824                 i.types[op].bitfield.imm64 = 1;
2825                 break;
2826               case WORD_MNEM_SUFFIX:
2827                 i.types[op].bitfield.imm16 = 1;
2828                 i.types[op].bitfield.imm32 = 1;
2829                 i.types[op].bitfield.imm32s = 1;
2830                 i.types[op].bitfield.imm64 = 1;
2831                 break;
2832               case BYTE_MNEM_SUFFIX:
2833                 i.types[op].bitfield.imm8 = 1;
2834                 i.types[op].bitfield.imm8s = 1;
2835                 i.types[op].bitfield.imm16 = 1;
2836                 i.types[op].bitfield.imm32 = 1;
2837                 i.types[op].bitfield.imm32s = 1;
2838                 i.types[op].bitfield.imm64 = 1;
2839                 break;
2840               }
2841
2842             /* If this operand is at most 16 bits, convert it
2843                to a signed 16 bit number before trying to see
2844                whether it will fit in an even smaller size.
2845                This allows a 16-bit operand such as $0xffe0 to
2846                be recognised as within Imm8S range.  */
2847             if ((i.types[op].bitfield.imm16)
2848                 && (i.op[op].imms->X_add_number & ~(offsetT) 0xffff) == 0)
2849               {
2850                 i.op[op].imms->X_add_number =
2851                   (((i.op[op].imms->X_add_number & 0xffff) ^ 0x8000) - 0x8000);
2852               }
2853             if ((i.types[op].bitfield.imm32)
2854                 && ((i.op[op].imms->X_add_number & ~(((offsetT) 2 << 31) - 1))
2855                     == 0))
2856               {
2857                 i.op[op].imms->X_add_number = ((i.op[op].imms->X_add_number
2858                                                 ^ ((offsetT) 1 << 31))
2859                                                - ((offsetT) 1 << 31));
2860               }
2861             i.types[op]
2862               = operand_type_or (i.types[op],
2863                                  smallest_imm_type (i.op[op].imms->X_add_number));
2864
2865             /* We must avoid matching of Imm32 templates when 64bit
2866                only immediate is available.  */
2867             if (guess_suffix == QWORD_MNEM_SUFFIX)
2868               i.types[op].bitfield.imm32 = 0;
2869             break;
2870
2871           case O_absent:
2872           case O_register:
2873             abort ();
2874
2875             /* Symbols and expressions.  */
2876           default:
2877             /* Convert symbolic operand to proper sizes for matching, but don't
2878                prevent matching a set of insns that only supports sizes other
2879                than those matching the insn suffix.  */
2880             {
2881               i386_operand_type mask, allowed;
2882               const template *t;
2883
2884               UINTS_CLEAR (mask);
2885               UINTS_CLEAR (allowed);
2886
2887               for (t = current_templates->start;
2888                    t < current_templates->end;
2889                    ++t)
2890                 allowed = operand_type_or (allowed,
2891                                            t->operand_types[op]);
2892               switch (guess_suffix)
2893                 {
2894                 case QWORD_MNEM_SUFFIX:
2895                   mask.bitfield.imm64 = 1;
2896                   mask.bitfield.imm32s = 1;
2897                   break;
2898                 case LONG_MNEM_SUFFIX:
2899                   mask.bitfield.imm32 = 1;
2900                   break;
2901                 case WORD_MNEM_SUFFIX:
2902                   mask.bitfield.imm16 = 1;
2903                   break;
2904                 case BYTE_MNEM_SUFFIX:
2905                   mask.bitfield.imm8 = 1;
2906                   break;
2907                 default:
2908                   break;
2909                 }
2910               allowed = operand_type_and (mask, allowed);
2911               if (!UINTS_ALL_ZERO (allowed))
2912                 i.types[op] = operand_type_and (i.types[op], mask);
2913             }
2914             break;
2915           }
2916       }
2917 }
2918
2919 /* Try to use the smallest displacement type too.  */
2920 static void
2921 optimize_disp (void)
2922 {
2923   int op;
2924
2925   for (op = i.operands; --op >= 0;)
2926     if (operand_type_check (i.types[op], disp))
2927       {
2928         if (i.op[op].disps->X_op == O_constant)
2929           {
2930             offsetT disp = i.op[op].disps->X_add_number;
2931
2932             if (i.types[op].bitfield.disp16
2933                 && (disp & ~(offsetT) 0xffff) == 0)
2934               {
2935                 /* If this operand is at most 16 bits, convert
2936                    to a signed 16 bit number and don't use 64bit
2937                    displacement.  */
2938                 disp = (((disp & 0xffff) ^ 0x8000) - 0x8000);
2939                 i.types[op].bitfield.disp64 = 0;
2940               }
2941             if (i.types[op].bitfield.disp32
2942                 && (disp & ~(((offsetT) 2 << 31) - 1)) == 0)
2943               {
2944                 /* If this operand is at most 32 bits, convert
2945                    to a signed 32 bit number and don't use 64bit
2946                    displacement.  */
2947                 disp &= (((offsetT) 2 << 31) - 1);
2948                 disp = (disp ^ ((offsetT) 1 << 31)) - ((addressT) 1 << 31);
2949                 i.types[op].bitfield.disp64 = 0;
2950               }
2951             if (!disp && i.types[op].bitfield.baseindex)
2952               {
2953                 i.types[op].bitfield.disp8 = 0;
2954                 i.types[op].bitfield.disp16 = 0;
2955                 i.types[op].bitfield.disp32 = 0;
2956                 i.types[op].bitfield.disp32s = 0;
2957                 i.types[op].bitfield.disp64 = 0;
2958                 i.op[op].disps = 0;
2959                 i.disp_operands--;
2960               }
2961             else if (flag_code == CODE_64BIT)
2962               {
2963                 if (fits_in_signed_long (disp))
2964                   {
2965                     i.types[op].bitfield.disp64 = 0;
2966                     i.types[op].bitfield.disp32s = 1;
2967                   }
2968                 if (fits_in_unsigned_long (disp))
2969                   i.types[op].bitfield.disp32 = 1;
2970               }
2971             if ((i.types[op].bitfield.disp32
2972                  || i.types[op].bitfield.disp32s
2973                  || i.types[op].bitfield.disp16)
2974                 && fits_in_signed_byte (disp))
2975               i.types[op].bitfield.disp8 = 1;
2976           }
2977         else if (i.reloc[op] == BFD_RELOC_386_TLS_DESC_CALL
2978                  || i.reloc[op] == BFD_RELOC_X86_64_TLSDESC_CALL)
2979           {
2980             fix_new_exp (frag_now, frag_more (0) - frag_now->fr_literal, 0,
2981                          i.op[op].disps, 0, i.reloc[op]);
2982             i.types[op].bitfield.disp8 = 0;
2983             i.types[op].bitfield.disp16 = 0;
2984             i.types[op].bitfield.disp32 = 0;
2985             i.types[op].bitfield.disp32s = 0;
2986             i.types[op].bitfield.disp64 = 0;
2987           }
2988         else
2989           /* We only support 64bit displacement on constants.  */
2990           i.types[op].bitfield.disp64 = 0;
2991       }
2992 }
2993
2994 static int
2995 match_template (void)
2996 {
2997   /* Points to template once we've found it.  */
2998   const template *t;
2999   i386_operand_type overlap0, overlap1, overlap2, overlap3;
3000   unsigned int found_reverse_match;
3001   i386_opcode_modifier suffix_check;
3002   i386_operand_type operand_types [MAX_OPERANDS];
3003   int addr_prefix_disp;
3004   unsigned int j;
3005   unsigned int found_cpu_match;
3006
3007 #if MAX_OPERANDS != 4
3008 # error "MAX_OPERANDS must be 4."
3009 #endif
3010
3011   found_reverse_match = 0;
3012   addr_prefix_disp = -1;
3013
3014   memset (&suffix_check, 0, sizeof (suffix_check));
3015   if (i.suffix == BYTE_MNEM_SUFFIX)
3016     suffix_check.no_bsuf = 1;
3017   else if (i.suffix == WORD_MNEM_SUFFIX)
3018     suffix_check.no_wsuf = 1;
3019   else if (i.suffix == SHORT_MNEM_SUFFIX)
3020     suffix_check.no_ssuf = 1;
3021   else if (i.suffix == LONG_MNEM_SUFFIX)
3022     suffix_check.no_lsuf = 1;
3023   else if (i.suffix == QWORD_MNEM_SUFFIX)
3024     suffix_check.no_qsuf = 1;
3025   else if (i.suffix == LONG_DOUBLE_MNEM_SUFFIX)
3026     suffix_check.no_ldsuf = 1;
3027   else if (i.suffix == XMMWORD_MNEM_SUFFIX)
3028     suffix_check.xmmword = 1;
3029
3030   for (t = current_templates->start; t < current_templates->end; t++)
3031     {
3032       addr_prefix_disp = -1;
3033
3034       /* Must have right number of operands.  */
3035       if (i.operands != t->operands)
3036         continue;
3037
3038       /* Check AT&T mnemonic and old gcc support. */
3039       if (t->opcode_modifier.attmnemonic
3040           && (intel_mnemonic
3041               || (!old_gcc
3042                   && t->opcode_modifier.oldgcc)))
3043         continue;
3044
3045       /* Check Intel mnemonic. */
3046       if (!intel_mnemonic && t->opcode_modifier.intelmnemonic)
3047         continue;
3048
3049       /* Check the suffix, except for some instructions in intel mode.  */
3050       if ((!intel_syntax || !t->opcode_modifier.ignoresize)
3051           && ((t->opcode_modifier.no_bsuf && suffix_check.no_bsuf)
3052               || (t->opcode_modifier.no_wsuf && suffix_check.no_wsuf)
3053               || (t->opcode_modifier.no_lsuf && suffix_check.no_lsuf)
3054               || (t->opcode_modifier.no_ssuf && suffix_check.no_ssuf)
3055               || (t->opcode_modifier.no_qsuf && suffix_check.no_qsuf)
3056               || (t->opcode_modifier.no_ldsuf && suffix_check.no_ldsuf)))
3057         continue;
3058
3059       /* Check the memory size in Intel mode when it is provided if
3060          needed.  */
3061       if (intel_syntax
3062           && i.suffix
3063           && t->opcode_modifier.checksize
3064           && (!t->opcode_modifier.byte || !suffix_check.no_bsuf)
3065           && (!t->opcode_modifier.word || !suffix_check.no_wsuf)
3066           && (!t->opcode_modifier.dword || !suffix_check.no_lsuf)
3067           && (!t->opcode_modifier.qword || !suffix_check.no_qsuf)
3068           && (!t->opcode_modifier.xmmword || !suffix_check.xmmword))
3069         continue;
3070
3071       for (j = 0; j < MAX_OPERANDS; j++)
3072         operand_types [j] = t->operand_types [j];
3073
3074       /* In general, don't allow 64-bit operands in 32-bit mode.  */
3075       if (i.suffix == QWORD_MNEM_SUFFIX
3076           && flag_code != CODE_64BIT
3077           && (intel_syntax
3078               ? (!t->opcode_modifier.ignoresize
3079                  && !intel_float_operand (t->name))
3080               : intel_float_operand (t->name) != 2)
3081           && ((!operand_types[0].bitfield.regmmx
3082                && !operand_types[0].bitfield.regxmm)
3083               || (!operand_types[t->operands > 1].bitfield.regmmx
3084                   && !!operand_types[t->operands > 1].bitfield.regxmm))
3085           && (t->base_opcode != 0x0fc7
3086               || t->extension_opcode != 1 /* cmpxchg8b */))
3087         continue;
3088
3089       /* Do not verify operands when there are none.  */
3090       else 
3091         {
3092           found_cpu_match = cpu_flags_match (t->cpu_flags) == 3;
3093           if (!t->operands)
3094             {
3095               if (!found_cpu_match)
3096                 continue;
3097               /* We've found a match; break out of loop.  */
3098               break;
3099             }
3100         }
3101
3102       /* Address size prefix will turn Disp64/Disp32/Disp16 operand
3103          into Disp32/Disp16/Disp32 operand.  */
3104       if (i.prefix[ADDR_PREFIX] != 0)
3105           {
3106             /* There should be only one Disp operand.  */
3107             switch (flag_code)
3108             {
3109             case CODE_16BIT:
3110               for (j = 0; j < MAX_OPERANDS; j++)
3111                 {
3112                   if (operand_types[j].bitfield.disp16)
3113                     {
3114                       addr_prefix_disp = j;
3115                       operand_types[j].bitfield.disp32 = 1;
3116                       operand_types[j].bitfield.disp16 = 0;
3117                       break;
3118                     }
3119                 }
3120               break;
3121             case CODE_32BIT:
3122               for (j = 0; j < MAX_OPERANDS; j++)
3123                 {
3124                   if (operand_types[j].bitfield.disp32)
3125                     {
3126                       addr_prefix_disp = j;
3127                       operand_types[j].bitfield.disp32 = 0;
3128                       operand_types[j].bitfield.disp16 = 1;
3129                       break;
3130                     }
3131                 }
3132               break;
3133             case CODE_64BIT:
3134               for (j = 0; j < MAX_OPERANDS; j++)
3135                 {
3136                   if (operand_types[j].bitfield.disp64)
3137                     {
3138                       addr_prefix_disp = j;
3139                       operand_types[j].bitfield.disp64 = 0;
3140                       operand_types[j].bitfield.disp32 = 1;
3141                       break;
3142                     }
3143                 }
3144               break;
3145             }
3146           }
3147
3148       overlap0 = operand_type_and (i.types[0], operand_types[0]);
3149       switch (t->operands)
3150         {
3151         case 1:
3152           if (!operand_type_match (overlap0, i.types[0]))
3153             continue;
3154           break;
3155         case 2:
3156           /* xchg %eax, %eax is a special case. It is an aliase for nop
3157              only in 32bit mode and we can use opcode 0x90.  In 64bit
3158              mode, we can't use 0x90 for xchg %eax, %eax since it should
3159              zero-extend %eax to %rax.  */
3160           if (flag_code == CODE_64BIT
3161               && t->base_opcode == 0x90
3162               && UINTS_EQUAL (i.types [0], acc32)
3163               && UINTS_EQUAL (i.types [1], acc32))
3164             continue;
3165         case 3:
3166         case 4:
3167           overlap1 = operand_type_and (i.types[1], operand_types[1]);
3168           if (!operand_type_match (overlap0, i.types[0])
3169               || !operand_type_match (overlap1, i.types[1])
3170               /* monitor in SSE3 is a very special case.  The first
3171                  register and the second register may have different
3172                  sizes.  The same applies to crc32 in SSE4.2.  It is
3173                  also true for invlpga, vmload, vmrun and vmsave in
3174                  SVME.  */
3175               || !((t->base_opcode == 0x0f01
3176                     && (t->extension_opcode == 0xc8
3177                         || t->extension_opcode == 0xd8
3178                         || t->extension_opcode == 0xda
3179                         || t->extension_opcode == 0xdb
3180                         || t->extension_opcode == 0xdf))
3181                    || t->base_opcode == 0xf20f38f1
3182                    || operand_type_register_match (overlap0, i.types[0],
3183                                                    operand_types[0],
3184                                                    overlap1, i.types[1],
3185                                                    operand_types[1])))
3186             {
3187               /* Check if other direction is valid ...  */
3188               if (!t->opcode_modifier.d && !t->opcode_modifier.floatd)
3189                 continue;
3190
3191               /* Try reversing direction of operands.  */
3192               overlap0 = operand_type_and (i.types[0], operand_types[1]);
3193               overlap1 = operand_type_and (i.types[1], operand_types[0]);
3194               if (!operand_type_match (overlap0, i.types[0])
3195                   || !operand_type_match (overlap1, i.types[1])
3196                   || !operand_type_register_match (overlap0, i.types[0],
3197                                                    operand_types[1],
3198                                                    overlap1, i.types[1],
3199                                                    operand_types[0]))
3200                 {
3201                   /* Does not match either direction.  */
3202                   continue;
3203                 }
3204               /* found_reverse_match holds which of D or FloatDR
3205                  we've found.  */
3206               if (t->opcode_modifier.d)
3207                 found_reverse_match = Opcode_D;
3208               else if (t->opcode_modifier.floatd)
3209                 found_reverse_match = Opcode_FloatD;
3210               else
3211                 found_reverse_match = 0;
3212               if (t->opcode_modifier.floatr)
3213                 found_reverse_match |= Opcode_FloatR;
3214             }
3215           else
3216             {
3217               /* Found a forward 2 operand match here.  */
3218               switch (t->operands)
3219                 {
3220                 case 4:
3221                   overlap3 = operand_type_and (i.types[3],
3222                                                operand_types[3]);
3223                 case 3:
3224                   overlap2 = operand_type_and (i.types[2],
3225                                                operand_types[2]);
3226                   break;
3227                 }
3228
3229               switch (t->operands)
3230                 {
3231                 case 4:
3232                   if (!operand_type_match (overlap3, i.types[3])
3233                       || !operand_type_register_match (overlap2,
3234                                                        i.types[2],
3235                                                        operand_types[2],
3236                                                        overlap3,
3237                                                        i.types[3],
3238                                                        operand_types[3]))
3239                     continue;
3240                 case 3:
3241                   /* Here we make use of the fact that there are no
3242                      reverse match 3 operand instructions, and all 3
3243                      operand instructions only need to be checked for
3244                      register consistency between operands 2 and 3.  */
3245                   if (!operand_type_match (overlap2, i.types[2])
3246                       || !operand_type_register_match (overlap1,
3247                                                        i.types[1],
3248                                                        operand_types[1],
3249                                                        overlap2,
3250                                                        i.types[2],
3251                                                        operand_types[2]))
3252                     continue;
3253                   break;
3254                 }
3255             }
3256           /* Found either forward/reverse 2, 3 or 4 operand match here:
3257              slip through to break.  */
3258         }
3259       if (!found_cpu_match)
3260         {
3261           found_reverse_match = 0;
3262           continue;
3263         }
3264       /* We've found a match; break out of loop.  */
3265       break;
3266     }
3267
3268   if (t == current_templates->end)
3269     {
3270       /* We found no match.  */
3271       as_bad (_("suffix or operands invalid for `%s'"),
3272               current_templates->start->name);
3273       return 0;
3274     }
3275
3276   if (!quiet_warnings)
3277     {
3278       if (!intel_syntax
3279           && (i.types[0].bitfield.jumpabsolute
3280               != operand_types[0].bitfield.jumpabsolute))
3281         {
3282           as_warn (_("indirect %s without `*'"), t->name);
3283         }
3284
3285       if (t->opcode_modifier.isprefix
3286           && t->opcode_modifier.ignoresize)
3287         {
3288           /* Warn them that a data or address size prefix doesn't
3289              affect assembly of the next line of code.  */
3290           as_warn (_("stand-alone `%s' prefix"), t->name);
3291         }
3292     }
3293
3294   /* Copy the template we found.  */
3295   i.tm = *t;
3296
3297   if (addr_prefix_disp != -1)
3298     i.tm.operand_types[addr_prefix_disp]
3299       = operand_types[addr_prefix_disp];
3300
3301   if (found_reverse_match)
3302     {
3303       /* If we found a reverse match we must alter the opcode
3304          direction bit.  found_reverse_match holds bits to change
3305          (different for int & float insns).  */
3306
3307       i.tm.base_opcode ^= found_reverse_match;
3308
3309       i.tm.operand_types[0] = operand_types[1];
3310       i.tm.operand_types[1] = operand_types[0];
3311     }
3312
3313   return 1;
3314 }
3315
3316 static int
3317 check_string (void)
3318 {
3319   int mem_op = operand_type_check (i.types[0], anymem) ? 0 : 1;
3320   if (i.tm.operand_types[mem_op].bitfield.esseg)
3321     {
3322       if (i.seg[0] != NULL && i.seg[0] != &es)
3323         {
3324           as_bad (_("`%s' operand %d must use `%%es' segment"),
3325                   i.tm.name,
3326                   mem_op + 1);
3327           return 0;
3328         }
3329       /* There's only ever one segment override allowed per instruction.
3330          This instruction possibly has a legal segment override on the
3331          second operand, so copy the segment to where non-string
3332          instructions store it, allowing common code.  */
3333       i.seg[0] = i.seg[1];
3334     }
3335   else if (i.tm.operand_types[mem_op + 1].bitfield.esseg)
3336     {
3337       if (i.seg[1] != NULL && i.seg[1] != &es)
3338         {
3339           as_bad (_("`%s' operand %d must use `%%es' segment"),
3340                   i.tm.name,
3341                   mem_op + 2);
3342           return 0;
3343         }
3344     }
3345   return 1;
3346 }
3347
3348 static int
3349 process_suffix (void)
3350 {
3351   /* If matched instruction specifies an explicit instruction mnemonic
3352      suffix, use it.  */
3353   if (i.tm.opcode_modifier.size16)
3354     i.suffix = WORD_MNEM_SUFFIX;
3355   else if (i.tm.opcode_modifier.size32)
3356     i.suffix = LONG_MNEM_SUFFIX;
3357   else if (i.tm.opcode_modifier.size64)
3358     i.suffix = QWORD_MNEM_SUFFIX;
3359   else if (i.reg_operands)
3360     {
3361       /* If there's no instruction mnemonic suffix we try to invent one
3362          based on register operands.  */
3363       if (!i.suffix)
3364         {
3365           /* We take i.suffix from the last register operand specified,
3366              Destination register type is more significant than source
3367              register type.  crc32 in SSE4.2 prefers source register
3368              type. */
3369           if (i.tm.base_opcode == 0xf20f38f1)
3370             {
3371               if (i.types[0].bitfield.reg16)
3372                 i.suffix = WORD_MNEM_SUFFIX;
3373               else if (i.types[0].bitfield.reg32)
3374                 i.suffix = LONG_MNEM_SUFFIX;
3375               else if (i.types[0].bitfield.reg64)
3376                 i.suffix = QWORD_MNEM_SUFFIX;
3377             }
3378           else if (i.tm.base_opcode == 0xf20f38f0)
3379             {
3380               if (i.types[0].bitfield.reg8)
3381                 i.suffix = BYTE_MNEM_SUFFIX;
3382             }
3383
3384           if (!i.suffix)
3385             {
3386               int op;
3387
3388               if (i.tm.base_opcode == 0xf20f38f1
3389                   || i.tm.base_opcode == 0xf20f38f0)
3390                 {
3391                   /* We have to know the operand size for crc32.  */
3392                   as_bad (_("ambiguous memory operand size for `%s`"),
3393                           i.tm.name);
3394                   return 0;
3395                 }
3396
3397               for (op = i.operands; --op >= 0;)
3398                 if (!i.tm.operand_types[op].bitfield.inoutportreg)
3399                   {
3400                     if (i.types[op].bitfield.reg8)
3401                       {
3402                         i.suffix = BYTE_MNEM_SUFFIX;
3403                         break;
3404                       }
3405                     else if (i.types[op].bitfield.reg16)
3406                       {
3407                         i.suffix = WORD_MNEM_SUFFIX;
3408                         break;
3409                       }
3410                     else if (i.types[op].bitfield.reg32)
3411                       {
3412                         i.suffix = LONG_MNEM_SUFFIX;
3413                         break;
3414                       }
3415                     else if (i.types[op].bitfield.reg64)
3416                       {
3417                         i.suffix = QWORD_MNEM_SUFFIX;
3418                         break;
3419                       }
3420                   }
3421             }
3422         }
3423       else if (i.suffix == BYTE_MNEM_SUFFIX)
3424         {
3425           if (!check_byte_reg ())
3426             return 0;
3427         }
3428       else if (i.suffix == LONG_MNEM_SUFFIX)
3429         {
3430           if (!check_long_reg ())
3431             return 0;
3432         }
3433       else if (i.suffix == QWORD_MNEM_SUFFIX)
3434         {
3435           if (intel_syntax
3436               && i.tm.opcode_modifier.ignoresize
3437               && i.tm.opcode_modifier.no_qsuf)
3438             i.suffix = 0;
3439           else if (!check_qword_reg ())
3440             return 0;
3441         }
3442       else if (i.suffix == WORD_MNEM_SUFFIX)
3443         {
3444           if (!check_word_reg ())
3445             return 0;
3446         }
3447       else if (i.suffix == XMMWORD_MNEM_SUFFIX)
3448         {
3449           /* Skip if the instruction has x suffix.  match_template
3450              should check if it is a valid suffix.  */
3451         }
3452       else if (intel_syntax && i.tm.opcode_modifier.ignoresize)
3453         /* Do nothing if the instruction is going to ignore the prefix.  */
3454         ;
3455       else
3456         abort ();
3457     }
3458   else if (i.tm.opcode_modifier.defaultsize
3459            && !i.suffix
3460            /* exclude fldenv/frstor/fsave/fstenv */
3461            && i.tm.opcode_modifier.no_ssuf)
3462     {
3463       i.suffix = stackop_size;
3464     }
3465   else if (intel_syntax
3466            && !i.suffix
3467            && (i.tm.operand_types[0].bitfield.jumpabsolute
3468                || i.tm.opcode_modifier.jumpbyte
3469                || i.tm.opcode_modifier.jumpintersegment
3470                || (i.tm.base_opcode == 0x0f01 /* [ls][gi]dt */
3471                    && i.tm.extension_opcode <= 3)))
3472     {
3473       switch (flag_code)
3474         {
3475         case CODE_64BIT:
3476           if (!i.tm.opcode_modifier.no_qsuf)
3477             {
3478               i.suffix = QWORD_MNEM_SUFFIX;
3479               break;
3480             }
3481         case CODE_32BIT:
3482           if (!i.tm.opcode_modifier.no_lsuf)
3483             i.suffix = LONG_MNEM_SUFFIX;
3484           break;
3485         case CODE_16BIT:
3486           if (!i.tm.opcode_modifier.no_wsuf)
3487             i.suffix = WORD_MNEM_SUFFIX;
3488           break;
3489         }
3490     }
3491
3492   if (!i.suffix)
3493     {
3494       if (!intel_syntax)
3495         {
3496           if (i.tm.opcode_modifier.w)
3497             {
3498               as_bad (_("no instruction mnemonic suffix given and "
3499                         "no register operands; can't size instruction"));
3500               return 0;
3501             }
3502         }
3503       else
3504         {
3505           unsigned int suffixes;
3506           
3507           suffixes = !i.tm.opcode_modifier.no_bsuf;
3508           if (!i.tm.opcode_modifier.no_wsuf)
3509             suffixes |= 1 << 1;
3510           if (!i.tm.opcode_modifier.no_lsuf)
3511             suffixes |= 1 << 2;
3512           if (!i.tm.opcode_modifier.no_ldsuf)
3513             suffixes |= 1 << 3;
3514           if (!i.tm.opcode_modifier.no_ssuf)
3515             suffixes |= 1 << 4;
3516           if (!i.tm.opcode_modifier.no_qsuf)
3517             suffixes |= 1 << 5;
3518
3519           /* There are more than suffix matches.  */
3520           if (i.tm.opcode_modifier.w
3521               || ((suffixes & (suffixes - 1))
3522                   && !i.tm.opcode_modifier.defaultsize
3523                   && !i.tm.opcode_modifier.ignoresize))
3524             {
3525               as_bad (_("ambiguous operand size for `%s'"), i.tm.name);
3526               return 0;
3527             }
3528         }
3529     }
3530
3531   /* Change the opcode based on the operand size given by i.suffix;
3532      We don't need to change things for byte insns.  */
3533
3534   if (i.suffix
3535       && i.suffix != BYTE_MNEM_SUFFIX
3536       && i.suffix != XMMWORD_MNEM_SUFFIX)
3537     {
3538       /* It's not a byte, select word/dword operation.  */
3539       if (i.tm.opcode_modifier.w)
3540         {
3541           if (i.tm.opcode_modifier.shortform)
3542             i.tm.base_opcode |= 8;
3543           else
3544             i.tm.base_opcode |= 1;
3545         }
3546
3547       /* Now select between word & dword operations via the operand
3548          size prefix, except for instructions that will ignore this
3549          prefix anyway.  */
3550       if (i.tm.opcode_modifier.addrprefixop0)
3551         {
3552           /* The address size override prefix changes the size of the
3553              first operand.  */
3554           if ((flag_code == CODE_32BIT
3555                && i.op->regs[0].reg_type.bitfield.reg16)
3556               || (flag_code != CODE_32BIT
3557                   && i.op->regs[0].reg_type.bitfield.reg32))
3558             if (!add_prefix (ADDR_PREFIX_OPCODE))
3559               return 0;
3560         }
3561       else if (i.suffix != QWORD_MNEM_SUFFIX
3562                && i.suffix != LONG_DOUBLE_MNEM_SUFFIX
3563                && !i.tm.opcode_modifier.ignoresize
3564                && !i.tm.opcode_modifier.floatmf
3565                && ((i.suffix == LONG_MNEM_SUFFIX) == (flag_code == CODE_16BIT)
3566                    || (flag_code == CODE_64BIT
3567                        && i.tm.opcode_modifier.jumpbyte)))
3568         {
3569           unsigned int prefix = DATA_PREFIX_OPCODE;
3570
3571           if (i.tm.opcode_modifier.jumpbyte) /* jcxz, loop */
3572             prefix = ADDR_PREFIX_OPCODE;
3573
3574           if (!add_prefix (prefix))
3575             return 0;
3576         }
3577
3578       /* Set mode64 for an operand.  */
3579       if (i.suffix == QWORD_MNEM_SUFFIX
3580           && flag_code == CODE_64BIT
3581           && !i.tm.opcode_modifier.norex64)
3582         {
3583           /* Special case for xchg %rax,%rax.  It is NOP and doesn't
3584              need rex64.  cmpxchg8b is also a special case. */
3585           if (! (i.operands == 2
3586                  && i.tm.base_opcode == 0x90
3587                  && i.tm.extension_opcode == None
3588                  && UINTS_EQUAL (i.types [0], acc64)
3589                  && UINTS_EQUAL (i.types [1], acc64))
3590               && ! (i.operands == 1
3591                     && i.tm.base_opcode == 0xfc7
3592                     && i.tm.extension_opcode == 1
3593                     && !operand_type_check (i.types [0], reg)
3594                     && operand_type_check (i.types [0], anymem)))
3595             i.rex |= REX_W;
3596         }
3597
3598       /* Size floating point instruction.  */
3599       if (i.suffix == LONG_MNEM_SUFFIX)
3600         if (i.tm.opcode_modifier.floatmf)
3601           i.tm.base_opcode ^= 4;
3602     }
3603
3604   return 1;
3605 }
3606
3607 static int
3608 check_byte_reg (void)
3609 {
3610   int op;
3611
3612   for (op = i.operands; --op >= 0;)
3613     {
3614       /* If this is an eight bit register, it's OK.  If it's the 16 or
3615          32 bit version of an eight bit register, we will just use the
3616          low portion, and that's OK too.  */
3617       if (i.types[op].bitfield.reg8)
3618         continue;
3619
3620       /* Don't generate this warning if not needed.  */
3621       if (intel_syntax && i.tm.opcode_modifier.byteokintel)
3622         continue;
3623
3624       /* crc32 doesn't generate this warning.  */
3625       if (i.tm.base_opcode == 0xf20f38f0)
3626         continue;
3627
3628       if ((i.types[op].bitfield.reg16
3629            || i.types[op].bitfield.reg32
3630            || i.types[op].bitfield.reg64)
3631           && i.op[op].regs->reg_num < 4)
3632         {
3633           /* Prohibit these changes in the 64bit mode, since the
3634              lowering is more complicated.  */
3635           if (flag_code == CODE_64BIT
3636               && !i.tm.operand_types[op].bitfield.inoutportreg)
3637             {
3638               as_bad (_("Incorrect register `%s%s' used with `%c' suffix"),
3639                       register_prefix, i.op[op].regs->reg_name,
3640                       i.suffix);
3641               return 0;
3642             }
3643 #if REGISTER_WARNINGS
3644           if (!quiet_warnings
3645               && !i.tm.operand_types[op].bitfield.inoutportreg)
3646             as_warn (_("using `%s%s' instead of `%s%s' due to `%c' suffix"),
3647                      register_prefix,
3648                      (i.op[op].regs + (i.types[op].bitfield.reg16
3649                                        ? REGNAM_AL - REGNAM_AX
3650                                        : REGNAM_AL - REGNAM_EAX))->reg_name,
3651                      register_prefix,
3652                      i.op[op].regs->reg_name,
3653                      i.suffix);
3654 #endif
3655           continue;
3656         }
3657       /* Any other register is bad.  */
3658       if (i.types[op].bitfield.reg16
3659           || i.types[op].bitfield.reg32
3660           || i.types[op].bitfield.reg64
3661           || i.types[op].bitfield.regmmx
3662           || i.types[op].bitfield.regxmm
3663           || i.types[op].bitfield.sreg2
3664           || i.types[op].bitfield.sreg3
3665           || i.types[op].bitfield.control
3666           || i.types[op].bitfield.debug
3667           || i.types[op].bitfield.test
3668           || i.types[op].bitfield.floatreg
3669           || i.types[op].bitfield.floatacc)
3670         {
3671           as_bad (_("`%s%s' not allowed with `%s%c'"),
3672                   register_prefix,
3673                   i.op[op].regs->reg_name,
3674                   i.tm.name,
3675                   i.suffix);
3676           return 0;
3677         }
3678     }
3679   return 1;
3680 }
3681
3682 static int
3683 check_long_reg (void)
3684 {
3685   int op;
3686
3687   for (op = i.operands; --op >= 0;)
3688     /* Reject eight bit registers, except where the template requires
3689        them. (eg. movzb)  */
3690     if (i.types[op].bitfield.reg8
3691         && (i.tm.operand_types[op].bitfield.reg16
3692             || i.tm.operand_types[op].bitfield.reg32
3693             || i.tm.operand_types[op].bitfield.acc))
3694       {
3695         as_bad (_("`%s%s' not allowed with `%s%c'"),
3696                 register_prefix,
3697                 i.op[op].regs->reg_name,
3698                 i.tm.name,
3699                 i.suffix);
3700         return 0;
3701       }
3702   /* Warn if the e prefix on a general reg is missing.  */
3703     else if ((!quiet_warnings || flag_code == CODE_64BIT)
3704              && i.types[op].bitfield.reg16
3705              && (i.tm.operand_types[op].bitfield.reg32
3706                  || i.tm.operand_types[op].bitfield.acc))
3707       {
3708         /* Prohibit these changes in the 64bit mode, since the
3709            lowering is more complicated.  */
3710         if (flag_code == CODE_64BIT)
3711           {
3712             as_bad (_("Incorrect register `%s%s' used with `%c' suffix"),
3713                     register_prefix, i.op[op].regs->reg_name,
3714                     i.suffix);
3715             return 0;
3716           }
3717 #if REGISTER_WARNINGS
3718         else
3719           as_warn (_("using `%s%s' instead of `%s%s' due to `%c' suffix"),
3720                    register_prefix,
3721                    (i.op[op].regs + REGNAM_EAX - REGNAM_AX)->reg_name,
3722                    register_prefix,
3723                    i.op[op].regs->reg_name,
3724                    i.suffix);
3725 #endif
3726       }
3727   /* Warn if the r prefix on a general reg is missing.  */
3728     else if (i.types[op].bitfield.reg64
3729              && (i.tm.operand_types[op].bitfield.reg32
3730                  || i.tm.operand_types[op].bitfield.acc))
3731       {
3732         if (intel_syntax
3733             && i.tm.opcode_modifier.toqword
3734             && !i.types[0].bitfield.regxmm)
3735           {
3736             /* Convert to QWORD.  We want REX byte. */
3737             i.suffix = QWORD_MNEM_SUFFIX;
3738           }
3739         else
3740           {
3741             as_bad (_("Incorrect register `%s%s' used with `%c' suffix"),
3742                     register_prefix, i.op[op].regs->reg_name,
3743                     i.suffix);
3744             return 0;
3745           }
3746       }
3747   return 1;
3748 }
3749
3750 static int
3751 check_qword_reg (void)
3752 {
3753   int op;
3754
3755   for (op = i.operands; --op >= 0; )
3756     /* Reject eight bit registers, except where the template requires
3757        them. (eg. movzb)  */
3758     if (i.types[op].bitfield.reg8
3759         && (i.tm.operand_types[op].bitfield.reg16
3760             || i.tm.operand_types[op].bitfield.reg32
3761             || i.tm.operand_types[op].bitfield.acc))
3762       {
3763         as_bad (_("`%s%s' not allowed with `%s%c'"),
3764                 register_prefix,
3765                 i.op[op].regs->reg_name,
3766                 i.tm.name,
3767                 i.suffix);
3768         return 0;
3769       }
3770   /* Warn if the e prefix on a general reg is missing.  */
3771     else if ((i.types[op].bitfield.reg16
3772               || i.types[op].bitfield.reg32)
3773              && (i.tm.operand_types[op].bitfield.reg32
3774                  || i.tm.operand_types[op].bitfield.acc))
3775       {
3776         /* Prohibit these changes in the 64bit mode, since the
3777            lowering is more complicated.  */
3778         if (intel_syntax
3779             && i.tm.opcode_modifier.todword
3780             && !i.types[0].bitfield.regxmm)
3781           {
3782             /* Convert to DWORD.  We don't want REX byte. */
3783             i.suffix = LONG_MNEM_SUFFIX;
3784           }
3785         else
3786           {
3787             as_bad (_("Incorrect register `%s%s' used with `%c' suffix"),
3788                     register_prefix, i.op[op].regs->reg_name,
3789                     i.suffix);
3790             return 0;
3791           }
3792       }
3793   return 1;
3794 }
3795
3796 static int
3797 check_word_reg (void)
3798 {
3799   int op;
3800   for (op = i.operands; --op >= 0;)
3801     /* Reject eight bit registers, except where the template requires
3802        them. (eg. movzb)  */
3803     if (i.types[op].bitfield.reg8
3804         && (i.tm.operand_types[op].bitfield.reg16
3805             || i.tm.operand_types[op].bitfield.reg32
3806             || i.tm.operand_types[op].bitfield.acc))
3807       {
3808         as_bad (_("`%s%s' not allowed with `%s%c'"),
3809                 register_prefix,
3810                 i.op[op].regs->reg_name,
3811                 i.tm.name,
3812                 i.suffix);
3813         return 0;
3814       }
3815   /* Warn if the e prefix on a general reg is present.  */
3816     else if ((!quiet_warnings || flag_code == CODE_64BIT)
3817              && i.types[op].bitfield.reg32
3818              && (i.tm.operand_types[op].bitfield.reg16
3819                  || i.tm.operand_types[op].bitfield.acc))
3820       {
3821         /* Prohibit these changes in the 64bit mode, since the
3822            lowering is more complicated.  */
3823         if (flag_code == CODE_64BIT)
3824           {
3825             as_bad (_("Incorrect register `%s%s' used with `%c' suffix"),
3826                     register_prefix, i.op[op].regs->reg_name,
3827                     i.suffix);
3828             return 0;
3829           }
3830         else
3831 #if REGISTER_WARNINGS
3832           as_warn (_("using `%s%s' instead of `%s%s' due to `%c' suffix"),
3833                    register_prefix,
3834                    (i.op[op].regs + REGNAM_AX - REGNAM_EAX)->reg_name,
3835                    register_prefix,
3836                    i.op[op].regs->reg_name,
3837                    i.suffix);
3838 #endif
3839       }
3840   return 1;
3841 }
3842
3843 static int
3844 update_imm (unsigned int j)
3845 {
3846   i386_operand_type overlap;
3847
3848   overlap = operand_type_and (i.types[j], i.tm.operand_types[j]);
3849   if ((overlap.bitfield.imm8
3850        || overlap.bitfield.imm8s
3851        || overlap.bitfield.imm16
3852        || overlap.bitfield.imm32
3853        || overlap.bitfield.imm32s
3854        || overlap.bitfield.imm64)
3855       && !UINTS_EQUAL (overlap, imm8)
3856       && !UINTS_EQUAL (overlap, imm8s)
3857       && !UINTS_EQUAL (overlap, imm16)
3858       && !UINTS_EQUAL (overlap, imm32)
3859       && !UINTS_EQUAL (overlap, imm32s)
3860       && !UINTS_EQUAL (overlap, imm64))
3861     {
3862       if (i.suffix)
3863         {
3864           i386_operand_type temp;
3865
3866           UINTS_CLEAR (temp);
3867           if (i.suffix == BYTE_MNEM_SUFFIX) 
3868             {
3869               temp.bitfield.imm8 = overlap.bitfield.imm8;
3870               temp.bitfield.imm8s = overlap.bitfield.imm8s;
3871             }
3872           else if (i.suffix == WORD_MNEM_SUFFIX)
3873             temp.bitfield.imm16 = overlap.bitfield.imm16;
3874           else if (i.suffix == QWORD_MNEM_SUFFIX)
3875             {
3876               temp.bitfield.imm64 = overlap.bitfield.imm64;
3877               temp.bitfield.imm32s = overlap.bitfield.imm32s;
3878             }
3879           else
3880             temp.bitfield.imm32 = overlap.bitfield.imm32;
3881           overlap = temp;
3882         }
3883       else if (UINTS_EQUAL (overlap, imm16_32_32s)
3884                || UINTS_EQUAL (overlap, imm16_32)
3885                || UINTS_EQUAL (overlap, imm16_32s))
3886         {
3887           UINTS_CLEAR (overlap);
3888           if ((flag_code == CODE_16BIT) ^ (i.prefix[DATA_PREFIX] != 0))
3889             overlap.bitfield.imm16 = 1;
3890           else
3891             overlap.bitfield.imm32s = 1;
3892         }
3893       if (!UINTS_EQUAL (overlap, imm8)
3894           && !UINTS_EQUAL (overlap, imm8s)
3895           && !UINTS_EQUAL (overlap, imm16)
3896           && !UINTS_EQUAL (overlap, imm32)
3897           && !UINTS_EQUAL (overlap, imm32s)
3898           && !UINTS_EQUAL (overlap, imm64))
3899         {
3900           as_bad (_("no instruction mnemonic suffix given; "
3901                     "can't determine immediate size"));
3902           return 0;
3903         }
3904     }
3905   i.types[j] = overlap;
3906
3907   return 1;
3908 }
3909
3910 static int
3911 finalize_imm (void)
3912 {
3913   unsigned int j;
3914
3915   for (j = 0; j < 2; j++)
3916     if (update_imm (j) == 0)
3917       return 0;
3918
3919   i.types[2] = operand_type_and (i.types[2], i.tm.operand_types[2]);
3920   assert (operand_type_check (i.types[2], imm) == 0);
3921
3922   return 1;
3923 }
3924
3925 static void
3926 process_drex (void)
3927 {
3928   i.drex.modrm_reg = 0;
3929   i.drex.modrm_regmem = 0;
3930
3931   /* SSE5 4 operand instructions must have the destination the same as 
3932      one of the inputs.  Figure out the destination register and cache
3933      it away in the drex field, and remember which fields to use for 
3934      the modrm byte.  */
3935   if (i.tm.opcode_modifier.drex 
3936       && i.tm.opcode_modifier.drexv 
3937       && i.operands == 4)
3938     {
3939       i.tm.extension_opcode = None;
3940
3941       /* Case 1: 4 operand insn, dest = src1, src3 = register.  */
3942       if (i.types[0].bitfield.regxmm != 0
3943           && i.types[1].bitfield.regxmm != 0
3944           && i.types[2].bitfield.regxmm != 0
3945           && i.types[3].bitfield.regxmm != 0
3946           && i.op[0].regs->reg_num == i.op[3].regs->reg_num
3947           && i.op[0].regs->reg_flags == i.op[3].regs->reg_flags)
3948         {
3949           /* Clear the arguments that are stored in drex.  */
3950           UINTS_CLEAR (i.types[0]); 
3951           UINTS_CLEAR (i.types[3]);
3952           i.reg_operands -= 2;
3953
3954           /* There are two different ways to encode a 4 operand 
3955              instruction with all registers that uses OC1 set to 
3956              0 or 1.  Favor setting OC1 to 0 since this mimics the 
3957              actions of other SSE5 assemblers.  Use modrm encoding 2 
3958              for register/register.  Include the high order bit that 
3959              is normally stored in the REX byte in the register
3960              field.  */
3961           i.tm.extension_opcode = DREX_X1_XMEM_X2_X1;
3962           i.drex.modrm_reg = 2;
3963           i.drex.modrm_regmem = 1;
3964           i.drex.reg = (i.op[3].regs->reg_num
3965                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
3966         }
3967
3968       /* Case 2: 4 operand insn, dest = src1, src3 = memory.  */
3969       else if (i.types[0].bitfield.regxmm != 0
3970                && i.types[1].bitfield.regxmm != 0
3971                && (i.types[2].bitfield.regxmm 
3972                    || operand_type_check (i.types[2], anymem))
3973                && i.types[3].bitfield.regxmm != 0
3974                && i.op[0].regs->reg_num == i.op[3].regs->reg_num
3975                && i.op[0].regs->reg_flags == i.op[3].regs->reg_flags)
3976         {
3977           /* clear the arguments that are stored in drex */
3978           UINTS_CLEAR (i.types[0]);
3979           UINTS_CLEAR (i.types[3]);
3980           i.reg_operands -= 2;
3981
3982           /* Specify the modrm encoding for memory addressing.  Include 
3983              the high order bit that is normally stored in the REX byte
3984              in the register field.  */
3985           i.tm.extension_opcode = DREX_X1_X2_XMEM_X1;
3986           i.drex.modrm_reg = 1;
3987           i.drex.modrm_regmem = 2;
3988           i.drex.reg = (i.op[3].regs->reg_num
3989                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
3990         }
3991
3992       /* Case 3: 4 operand insn, dest = src1, src2 = memory.  */
3993       else if (i.types[0].bitfield.regxmm != 0
3994                && operand_type_check (i.types[1], anymem) != 0
3995                && i.types[2].bitfield.regxmm != 0
3996                && i.types[3].bitfield.regxmm != 0
3997                && i.op[0].regs->reg_num == i.op[3].regs->reg_num
3998                && i.op[0].regs->reg_flags == i.op[3].regs->reg_flags)
3999         {
4000           /* Clear the arguments that are stored in drex.  */
4001           UINTS_CLEAR (i.types[0]);
4002           UINTS_CLEAR (i.types[3]);
4003           i.reg_operands -= 2;
4004
4005           /* Specify the modrm encoding for memory addressing.  Include
4006              the high order bit that is normally stored in the REX byte 
4007              in the register field.  */
4008           i.tm.extension_opcode = DREX_X1_XMEM_X2_X1;
4009           i.drex.modrm_reg = 2;
4010           i.drex.modrm_regmem = 1;
4011           i.drex.reg = (i.op[3].regs->reg_num
4012                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4013         }
4014
4015       /* Case 4: 4 operand insn, dest = src3, src2 = register. */
4016       else if (i.types[0].bitfield.regxmm != 0
4017                && i.types[1].bitfield.regxmm != 0
4018                && i.types[2].bitfield.regxmm != 0
4019                && i.types[3].bitfield.regxmm != 0
4020                && i.op[2].regs->reg_num == i.op[3].regs->reg_num
4021                && i.op[2].regs->reg_flags == i.op[3].regs->reg_flags)
4022         {
4023           /* clear the arguments that are stored in drex */
4024           UINTS_CLEAR (i.types[2]);
4025           UINTS_CLEAR (i.types[3]);
4026           i.reg_operands -= 2;
4027
4028           /* There are two different ways to encode a 4 operand 
4029              instruction with all registers that uses OC1 set to 
4030              0 or 1.  Favor setting OC1 to 0 since this mimics the 
4031              actions of other SSE5 assemblers.  Use modrm encoding 
4032              2 for register/register.  Include the high order bit that 
4033              is normally stored in the REX byte in the register 
4034              field.  */
4035           i.tm.extension_opcode = DREX_XMEM_X1_X2_X2;
4036           i.drex.modrm_reg = 1;
4037           i.drex.modrm_regmem = 0;
4038
4039           /* Remember the register, including the upper bits */
4040           i.drex.reg = (i.op[3].regs->reg_num
4041                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4042         }
4043
4044       /* Case 5: 4 operand insn, dest = src3, src2 = memory.  */
4045       else if (i.types[0].bitfield.regxmm != 0
4046                && (i.types[1].bitfield.regxmm 
4047                    || operand_type_check (i.types[1], anymem)) 
4048                && i.types[2].bitfield.regxmm != 0
4049                && i.types[3].bitfield.regxmm != 0
4050                && i.op[2].regs->reg_num == i.op[3].regs->reg_num
4051                && i.op[2].regs->reg_flags == i.op[3].regs->reg_flags)
4052         {
4053           /* Clear the arguments that are stored in drex.  */
4054           UINTS_CLEAR (i.types[2]);
4055           UINTS_CLEAR (i.types[3]);
4056           i.reg_operands -= 2;
4057
4058           /* Specify the modrm encoding and remember the register 
4059              including the bits normally stored in the REX byte. */
4060           i.tm.extension_opcode = DREX_X1_XMEM_X2_X2;
4061           i.drex.modrm_reg = 0;
4062           i.drex.modrm_regmem = 1;
4063           i.drex.reg = (i.op[3].regs->reg_num
4064                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4065         }
4066
4067       /* Case 6: 4 operand insn, dest = src3, src1 = memory.  */
4068       else if (operand_type_check (i.types[0], anymem) != 0
4069                && i.types[1].bitfield.regxmm != 0
4070                && i.types[2].bitfield.regxmm != 0
4071                && i.types[3].bitfield.regxmm != 0
4072                && i.op[2].regs->reg_num == i.op[3].regs->reg_num
4073                && i.op[2].regs->reg_flags == i.op[3].regs->reg_flags)
4074         {
4075           /* clear the arguments that are stored in drex */
4076           UINTS_CLEAR (i.types[2]);
4077           UINTS_CLEAR (i.types[3]);
4078           i.reg_operands -= 2;
4079
4080           /* Specify the modrm encoding and remember the register 
4081              including the bits normally stored in the REX byte. */
4082           i.tm.extension_opcode = DREX_XMEM_X1_X2_X2;
4083           i.drex.modrm_reg = 1;
4084           i.drex.modrm_regmem = 0;
4085           i.drex.reg = (i.op[3].regs->reg_num
4086                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4087         }
4088
4089       else
4090         as_bad (_("Incorrect operands for the '%s' instruction"), 
4091                 i.tm.name);
4092     }
4093
4094   /* SSE5 instructions with the DREX byte where the only memory operand 
4095      is in the 2nd argument, and the first and last xmm register must 
4096      match, and is encoded in the DREX byte. */
4097   else if (i.tm.opcode_modifier.drex 
4098            && !i.tm.opcode_modifier.drexv 
4099            && i.operands == 4)
4100     {
4101       /* Case 1: 4 operand insn, dest = src1, src3 = reg/mem.  */
4102       if (i.types[0].bitfield.regxmm != 0
4103           && (i.types[1].bitfield.regxmm 
4104               || operand_type_check(i.types[1], anymem)) 
4105           && i.types[2].bitfield.regxmm != 0
4106           && i.types[3].bitfield.regxmm != 0
4107           && i.op[0].regs->reg_num == i.op[3].regs->reg_num
4108           && i.op[0].regs->reg_flags == i.op[3].regs->reg_flags)
4109         {
4110           /* clear the arguments that are stored in drex */
4111           UINTS_CLEAR (i.types[0]);
4112           UINTS_CLEAR (i.types[3]);
4113           i.reg_operands -= 2;
4114
4115           /* Specify the modrm encoding and remember the register 
4116              including the high bit normally stored in the REX 
4117              byte.  */
4118           i.drex.modrm_reg = 2;
4119           i.drex.modrm_regmem = 1;
4120           i.drex.reg = (i.op[3].regs->reg_num
4121                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4122         }
4123
4124       else
4125         as_bad (_("Incorrect operands for the '%s' instruction"), 
4126                 i.tm.name);
4127     }
4128
4129   /* SSE5 3 operand instructions that the result is a register, being 
4130      either operand can be a memory operand, using OC0 to note which 
4131      one is the memory.  */
4132   else if (i.tm.opcode_modifier.drex 
4133            && i.tm.opcode_modifier.drexv
4134            && i.operands == 3)
4135     {
4136       i.tm.extension_opcode = None;
4137
4138       /* Case 1: 3 operand insn, src1 = register.  */
4139       if (i.types[0].bitfield.regxmm != 0
4140           && i.types[1].bitfield.regxmm != 0
4141           && i.types[2].bitfield.regxmm != 0)
4142         {
4143           /* Clear the arguments that are stored in drex.  */
4144           UINTS_CLEAR (i.types[2]);
4145           i.reg_operands--;
4146
4147           /* Specify the modrm encoding and remember the register 
4148              including the high bit normally stored in the REX byte.  */
4149           i.tm.extension_opcode = DREX_XMEM_X1_X2;
4150           i.drex.modrm_reg = 1;
4151           i.drex.modrm_regmem = 0;
4152           i.drex.reg = (i.op[2].regs->reg_num
4153                         + ((i.op[2].regs->reg_flags & RegRex) ? 8 : 0));
4154         }
4155
4156       /* Case 2: 3 operand insn, src1 = memory.  */
4157       else if (operand_type_check (i.types[0], anymem) != 0
4158                && i.types[1].bitfield.regxmm != 0
4159                && i.types[2].bitfield.regxmm != 0)
4160         {
4161           /* Clear the arguments that are stored in drex.  */
4162           UINTS_CLEAR (i.types[2]);
4163           i.reg_operands--;
4164
4165           /* Specify the modrm encoding and remember the register 
4166              including the high bit normally stored in the REX 
4167              byte.  */
4168           i.tm.extension_opcode = DREX_XMEM_X1_X2;
4169           i.drex.modrm_reg = 1;
4170           i.drex.modrm_regmem = 0;
4171           i.drex.reg = (i.op[2].regs->reg_num
4172                         + ((i.op[2].regs->reg_flags & RegRex) ? 8 : 0));
4173         }
4174
4175       /* Case 3: 3 operand insn, src2 = memory.  */
4176       else if (i.types[0].bitfield.regxmm != 0
4177                && operand_type_check (i.types[1], anymem) != 0
4178                && i.types[2].bitfield.regxmm != 0)
4179         {
4180           /* Clear the arguments that are stored in drex.  */
4181           UINTS_CLEAR (i.types[2]);
4182           i.reg_operands--;
4183
4184           /* Specify the modrm encoding and remember the register 
4185              including the high bit normally stored in the REX byte.  */
4186           i.tm.extension_opcode = DREX_X1_XMEM_X2;
4187           i.drex.modrm_reg = 0;
4188           i.drex.modrm_regmem = 1;
4189           i.drex.reg = (i.op[2].regs->reg_num
4190                         + ((i.op[2].regs->reg_flags & RegRex) ? 8 : 0));
4191         }
4192
4193       else
4194         as_bad (_("Incorrect operands for the '%s' instruction"), 
4195                 i.tm.name);
4196     }
4197
4198   /* SSE5 4 operand instructions that are the comparison instructions 
4199      where the first operand is the immediate value of the comparison 
4200      to be done.  */
4201   else if (i.tm.opcode_modifier.drexc != 0 && i.operands == 4)
4202     {
4203       /* Case 1: 4 operand insn, src1 = reg/memory. */
4204       if (operand_type_check (i.types[0], imm) != 0
4205           && (i.types[1].bitfield.regxmm 
4206               || operand_type_check (i.types[1], anymem)) 
4207           && i.types[2].bitfield.regxmm != 0
4208           && i.types[3].bitfield.regxmm != 0)
4209         {
4210           /* clear the arguments that are stored in drex */
4211           UINTS_CLEAR (i.types[3]);
4212           i.reg_operands--;
4213
4214           /* Specify the modrm encoding and remember the register 
4215              including the high bit normally stored in the REX byte.  */
4216           i.drex.modrm_reg = 2;
4217           i.drex.modrm_regmem = 1;
4218           i.drex.reg = (i.op[3].regs->reg_num
4219                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4220         }
4221
4222       /* Case 2: 3 operand insn with ImmExt that places the 
4223          opcode_extension as an immediate argument.  This is used for 
4224          all of the varients of comparison that supplies the appropriate
4225          value as part of the instruction.  */
4226       else if ((i.types[0].bitfield.regxmm
4227                 || operand_type_check (i.types[0], anymem)) 
4228                && i.types[1].bitfield.regxmm != 0
4229                && i.types[2].bitfield.regxmm != 0
4230                && operand_type_check (i.types[3], imm) != 0)
4231         {
4232           /* clear the arguments that are stored in drex */
4233           UINTS_CLEAR (i.types[2]);
4234           i.reg_operands--;
4235
4236           /* Specify the modrm encoding and remember the register 
4237              including the high bit normally stored in the REX byte.  */
4238           i.drex.modrm_reg = 1;
4239           i.drex.modrm_regmem = 0;
4240           i.drex.reg = (i.op[2].regs->reg_num
4241                         + ((i.op[2].regs->reg_flags & RegRex) ? 8 : 0));
4242         }
4243
4244       else
4245         as_bad (_("Incorrect operands for the '%s' instruction"), 
4246                 i.tm.name);
4247     }
4248
4249   else if (i.tm.opcode_modifier.drex 
4250            || i.tm.opcode_modifier.drexv 
4251            || i.tm.opcode_modifier.drexc)
4252     as_bad (_("Internal error for the '%s' instruction"), i.tm.name);
4253 }
4254
4255 static int
4256 process_operands (void)
4257 {
4258   /* Default segment register this instruction will use for memory
4259      accesses.  0 means unknown.  This is only for optimizing out
4260      unnecessary segment overrides.  */
4261   const seg_entry *default_seg = 0;
4262
4263   /* Handle all of the DREX munging that SSE5 needs.  */
4264   if (i.tm.opcode_modifier.drex 
4265       || i.tm.opcode_modifier.drexv 
4266       || i.tm.opcode_modifier.drexc)
4267     process_drex ();
4268
4269   if (i.tm.opcode_modifier.firstxmm0)
4270     {
4271       unsigned int j;
4272
4273       /* The first operand is implicit and must be xmm0.  */
4274       assert (i.reg_operands && UINTS_EQUAL (i.types[0], regxmm));
4275       if (i.op[0].regs->reg_num != 0)
4276         {
4277           if (intel_syntax)
4278             as_bad (_("the last operand of `%s' must be `%sxmm0'"),
4279                     i.tm.name, register_prefix);
4280           else
4281             as_bad (_("the first operand of `%s' must be `%sxmm0'"),
4282                     i.tm.name, register_prefix);
4283           return 0;
4284         }
4285
4286       for (j = 1; j < i.operands; j++)
4287         {
4288           i.op[j - 1] = i.op[j];
4289           i.types[j - 1] = i.types[j];
4290
4291           /* We need to adjust fields in i.tm since they are used by
4292              build_modrm_byte.  */
4293           i.tm.operand_types [j - 1] = i.tm.operand_types [j];
4294         }
4295
4296       i.operands--;
4297       i.reg_operands--;
4298       i.tm.operands--;
4299     }
4300   else if (i.tm.opcode_modifier.regkludge)
4301     {
4302       /* The imul $imm, %reg instruction is converted into
4303          imul $imm, %reg, %reg, and the clr %reg instruction
4304          is converted into xor %reg, %reg.  */
4305
4306       unsigned int first_reg_op;
4307
4308       if (operand_type_check (i.types[0], reg))
4309         first_reg_op = 0;
4310       else
4311         first_reg_op = 1;
4312       /* Pretend we saw the extra register operand.  */
4313       assert (i.reg_operands == 1
4314               && i.op[first_reg_op + 1].regs == 0);
4315       i.op[first_reg_op + 1].regs = i.op[first_reg_op].regs;
4316       i.types[first_reg_op + 1] = i.types[first_reg_op];
4317       i.operands++;
4318       i.reg_operands++;
4319     }
4320
4321   if (i.tm.opcode_modifier.shortform)
4322     {
4323       if (i.types[0].bitfield.sreg2
4324           || i.types[0].bitfield.sreg3)
4325         {
4326           if (i.tm.base_opcode == POP_SEG_SHORT
4327               && i.op[0].regs->reg_num == 1)
4328             {
4329               as_bad (_("you can't `pop %%cs'"));
4330               return 0;
4331             }
4332           i.tm.base_opcode |= (i.op[0].regs->reg_num << 3);
4333           if ((i.op[0].regs->reg_flags & RegRex) != 0)
4334             i.rex |= REX_B;
4335         }
4336       else
4337         {
4338           /* The register or float register operand is in operand 
4339              0 or 1.  */
4340           unsigned int op;
4341           
4342            if (i.types[0].bitfield.floatreg
4343                || operand_type_check (i.types[0], reg))
4344              op = 0;
4345            else
4346              op = 1;
4347           /* Register goes in low 3 bits of opcode.  */
4348           i.tm.base_opcode |= i.op[op].regs->reg_num;
4349           if ((i.op[op].regs->reg_flags & RegRex) != 0)
4350             i.rex |= REX_B;
4351           if (!quiet_warnings && i.tm.opcode_modifier.ugh)
4352             {
4353               /* Warn about some common errors, but press on regardless.
4354                  The first case can be generated by gcc (<= 2.8.1).  */
4355               if (i.operands == 2)
4356                 {
4357                   /* Reversed arguments on faddp, fsubp, etc.  */
4358                   as_warn (_("translating to `%s %s%s,%s%s'"), i.tm.name,
4359                            register_prefix, i.op[1].regs->reg_name,
4360                            register_prefix, i.op[0].regs->reg_name);
4361                 }
4362               else
4363                 {
4364                   /* Extraneous `l' suffix on fp insn.  */
4365                   as_warn (_("translating to `%s %s%s'"), i.tm.name,
4366                            register_prefix, i.op[0].regs->reg_name);
4367                 }
4368             }
4369         }
4370     }
4371   else if (i.tm.opcode_modifier.modrm)
4372     {
4373       /* The opcode is completed (modulo i.tm.extension_opcode which
4374          must be put into the modrm byte).  Now, we make the modrm and
4375          index base bytes based on all the info we've collected.  */
4376
4377       default_seg = build_modrm_byte ();
4378     }
4379   else if ((i.tm.base_opcode & ~0x3) == MOV_AX_DISP32)
4380     {
4381       default_seg = &ds;
4382     }
4383   else if (i.tm.opcode_modifier.isstring)
4384     {
4385       /* For the string instructions that allow a segment override
4386          on one of their operands, the default segment is ds.  */
4387       default_seg = &ds;
4388     }
4389
4390   if (i.tm.base_opcode == 0x8d /* lea */
4391       && i.seg[0]
4392       && !quiet_warnings)
4393     as_warn (_("segment override on `%s' is ineffectual"), i.tm.name);
4394
4395   /* If a segment was explicitly specified, and the specified segment
4396      is not the default, use an opcode prefix to select it.  If we
4397      never figured out what the default segment is, then default_seg
4398      will be zero at this point, and the specified segment prefix will
4399      always be used.  */
4400   if ((i.seg[0]) && (i.seg[0] != default_seg))
4401     {
4402       if (!add_prefix (i.seg[0]->seg_prefix))
4403         return 0;
4404     }
4405   return 1;
4406 }
4407
4408 static const seg_entry *
4409 build_modrm_byte (void)
4410 {
4411   const seg_entry *default_seg = 0;
4412
4413   /* SSE5 4 operand instructions are encoded in such a way that one of 
4414      the inputs must match the destination register.  Process_drex hides
4415      the 3rd argument in the drex field, so that by the time we get 
4416      here, it looks to GAS as if this is a 2 operand instruction.  */
4417   if ((i.tm.opcode_modifier.drex 
4418        || i.tm.opcode_modifier.drexv 
4419        || i.tm.opcode_modifier.drexc)
4420       && i.reg_operands == 2)
4421     {
4422       const reg_entry *reg = i.op[i.drex.modrm_reg].regs;
4423       const reg_entry *regmem = i.op[i.drex.modrm_regmem].regs;
4424
4425       i.rm.reg = reg->reg_num;
4426       i.rm.regmem = regmem->reg_num;
4427       i.rm.mode = 3;
4428       if ((reg->reg_flags & RegRex) != 0)
4429         i.rex |= REX_R;
4430       if ((regmem->reg_flags & RegRex) != 0)
4431         i.rex |= REX_B;
4432     }
4433
4434   /* i.reg_operands MUST be the number of real register operands;
4435      implicit registers do not count.  */
4436   else if (i.reg_operands == 2)
4437     {
4438       unsigned int source, dest;
4439
4440       switch (i.operands)
4441         {
4442         case 2:
4443           source = 0;
4444           break;
4445         case 3:
4446           /* When there are 3 operands, one of them may be immediate,
4447              which may be the first or the last operand.  Otherwise,
4448              the first operand must be shift count register (cl). */
4449           assert (i.imm_operands == 1
4450                   || (i.imm_operands == 0
4451                       && i.types[0].bitfield.shiftcount));
4452           if (operand_type_check (i.types[0], imm)
4453               || i.types[0].bitfield.shiftcount)
4454             source = 1;
4455           else
4456             source = 0;
4457           break;
4458         case 4:
4459           /* When there are 4 operands, the first two must be 8bit
4460              immediate operands. The source operand will be the 3rd
4461              one.  */
4462           assert (i.imm_operands == 2
4463                   && i.types[0].bitfield.imm8
4464                   && i.types[1].bitfield.imm8);
4465           source = 2;
4466           break;
4467         default:
4468           abort ();
4469         }
4470
4471       dest = source + 1;
4472
4473       i.rm.mode = 3;
4474       /* One of the register operands will be encoded in the i.tm.reg
4475          field, the other in the combined i.tm.mode and i.tm.regmem
4476          fields.  If no form of this instruction supports a memory
4477          destination operand, then we assume the source operand may
4478          sometimes be a memory operand and so we need to store the
4479          destination in the i.rm.reg field.  */
4480       if (!i.tm.operand_types[dest].bitfield.regmem
4481           && operand_type_check (i.tm.operand_types[dest], anymem) == 0)
4482         {
4483           i.rm.reg = i.op[dest].regs->reg_num;
4484           i.rm.regmem = i.op[source].regs->reg_num;
4485           if ((i.op[dest].regs->reg_flags & RegRex) != 0)
4486             i.rex |= REX_R;
4487           if ((i.op[source].regs->reg_flags & RegRex) != 0)
4488             i.rex |= REX_B;
4489         }
4490       else
4491         {
4492           i.rm.reg = i.op[source].regs->reg_num;
4493           i.rm.regmem = i.op[dest].regs->reg_num;
4494           if ((i.op[dest].regs->reg_flags & RegRex) != 0)
4495             i.rex |= REX_B;
4496           if ((i.op[source].regs->reg_flags & RegRex) != 0)
4497             i.rex |= REX_R;
4498         }
4499       if (flag_code != CODE_64BIT && (i.rex & (REX_R | REX_B)))
4500         {
4501           if (!i.types[0].bitfield.control
4502               && !i.types[1].bitfield.control)
4503             abort ();
4504           i.rex &= ~(REX_R | REX_B);
4505           add_prefix (LOCK_PREFIX_OPCODE);
4506         }
4507     }
4508   else
4509     {                   /* If it's not 2 reg operands...  */
4510       if (i.mem_operands)
4511         {
4512           unsigned int fake_zero_displacement = 0;
4513           unsigned int op;
4514
4515           /* This has been precalculated for SSE5 instructions 
4516              that have a DREX field earlier in process_drex.  */
4517           if (i.tm.opcode_modifier.drex 
4518               || i.tm.opcode_modifier.drexv 
4519               || i.tm.opcode_modifier.drexc)
4520             op = i.drex.modrm_regmem;
4521           else
4522             {
4523               for (op = 0; op < i.operands; op++)
4524                 if (operand_type_check (i.types[op], anymem))
4525                   break;
4526               assert (op < i.operands);
4527             }
4528
4529           default_seg = &ds;
4530
4531           if (i.base_reg == 0)
4532             {
4533               i.rm.mode = 0;
4534               if (!i.disp_operands)
4535                 fake_zero_displacement = 1;
4536               if (i.index_reg == 0)
4537                 {
4538                   /* Operand is just <disp>  */
4539                   if (flag_code == CODE_64BIT)
4540                     {
4541                       /* 64bit mode overwrites the 32bit absolute
4542                          addressing by RIP relative addressing and
4543                          absolute addressing is encoded by one of the
4544                          redundant SIB forms.  */
4545                       i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
4546                       i.sib.base = NO_BASE_REGISTER;
4547                       i.sib.index = NO_INDEX_REGISTER;
4548                       i.types[op] = ((i.prefix[ADDR_PREFIX] == 0)
4549                                      ? disp32s : disp32);
4550                     }
4551                   else if ((flag_code == CODE_16BIT)
4552                            ^ (i.prefix[ADDR_PREFIX] != 0))
4553                     {
4554                       i.rm.regmem = NO_BASE_REGISTER_16;
4555                       i.types[op] = disp16;
4556                     }
4557                   else
4558                     {
4559                       i.rm.regmem = NO_BASE_REGISTER;
4560                       i.types[op] = disp32;
4561                     }
4562                 }
4563               else /* !i.base_reg && i.index_reg  */
4564                 {
4565                   if (i.index_reg->reg_num == RegEiz
4566                       || i.index_reg->reg_num == RegRiz)
4567                     i.sib.index = NO_INDEX_REGISTER;
4568                   else
4569                     i.sib.index = i.index_reg->reg_num;
4570                   i.sib.base = NO_BASE_REGISTER;
4571                   i.sib.scale = i.log2_scale_factor;
4572                   i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
4573                   i.types[op].bitfield.disp8 = 0;
4574                   i.types[op].bitfield.disp16 = 0;
4575                   i.types[op].bitfield.disp64 = 0;
4576                   if (flag_code != CODE_64BIT)
4577                     {
4578                       /* Must be 32 bit */
4579                       i.types[op].bitfield.disp32 = 1;
4580                       i.types[op].bitfield.disp32s = 0;
4581                     }
4582                   else
4583                     {
4584                       i.types[op].bitfield.disp32 = 0;
4585                       i.types[op].bitfield.disp32s = 1;
4586                     }
4587                   if ((i.index_reg->reg_flags & RegRex) != 0)
4588                     i.rex |= REX_X;
4589                 }
4590             }
4591           /* RIP addressing for 64bit mode.  */
4592           else if (i.base_reg->reg_num == RegRip ||
4593                    i.base_reg->reg_num == RegEip)
4594             {
4595               i.rm.regmem = NO_BASE_REGISTER;
4596               i.types[op].bitfield.disp8 = 0;
4597               i.types[op].bitfield.disp16 = 0;
4598               i.types[op].bitfield.disp32 = 0;
4599               i.types[op].bitfield.disp32s = 1;
4600               i.types[op].bitfield.disp64 = 0;
4601               i.flags[op] |= Operand_PCrel;
4602               if (! i.disp_operands)
4603                 fake_zero_displacement = 1;
4604             }
4605           else if (i.base_reg->reg_type.bitfield.reg16)
4606             {
4607               switch (i.base_reg->reg_num)
4608                 {
4609                 case 3: /* (%bx)  */
4610                   if (i.index_reg == 0)
4611                     i.rm.regmem = 7;
4612                   else /* (%bx,%si) -> 0, or (%bx,%di) -> 1  */
4613                     i.rm.regmem = i.index_reg->reg_num - 6;
4614                   break;
4615                 case 5: /* (%bp)  */
4616                   default_seg = &ss;
4617                   if (i.index_reg == 0)
4618                     {
4619                       i.rm.regmem = 6;
4620                       if (operand_type_check (i.types[op], disp) == 0)
4621                         {
4622                           /* fake (%bp) into 0(%bp)  */
4623                           i.types[op].bitfield.disp8 = 1;
4624                           fake_zero_displacement = 1;
4625                         }
4626                     }
4627                   else /* (%bp,%si) -> 2, or (%bp,%di) -> 3  */
4628                     i.rm.regmem = i.index_reg->reg_num - 6 + 2;
4629                   break;
4630                 default: /* (%si) -> 4 or (%di) -> 5  */
4631                   i.rm.regmem = i.base_reg->reg_num - 6 + 4;
4632                 }
4633               i.rm.mode = mode_from_disp_size (i.types[op]);
4634             }
4635           else /* i.base_reg and 32/64 bit mode  */
4636             {
4637               if (flag_code == CODE_64BIT
4638                   && operand_type_check (i.types[op], disp))
4639                 {
4640                   i386_operand_type temp;
4641                   UINTS_CLEAR (temp);
4642                   temp.bitfield.disp8 = i.types[op].bitfield.disp8;
4643                   i.types[op] = temp;
4644                   if (i.prefix[ADDR_PREFIX] == 0)
4645                     i.types[op].bitfield.disp32s = 1;
4646                   else
4647                     i.types[op].bitfield.disp32 = 1;
4648                 }
4649
4650               i.rm.regmem = i.base_reg->reg_num;
4651               if ((i.base_reg->reg_flags & RegRex) != 0)
4652                 i.rex |= REX_B;
4653               i.sib.base = i.base_reg->reg_num;
4654               /* x86-64 ignores REX prefix bit here to avoid decoder
4655                  complications.  */
4656               if ((i.base_reg->reg_num & 7) == EBP_REG_NUM)
4657                 {
4658                   default_seg = &ss;
4659                   if (i.disp_operands == 0)
4660                     {
4661                       fake_zero_displacement = 1;
4662                       i.types[op].bitfield.disp8 = 1;
4663                     }
4664                 }
4665               else if (i.base_reg->reg_num == ESP_REG_NUM)
4666                 {
4667                   default_seg = &ss;
4668                 }
4669               i.sib.scale = i.log2_scale_factor;
4670               if (i.index_reg == 0)
4671                 {
4672                   /* <disp>(%esp) becomes two byte modrm with no index
4673                      register.  We've already stored the code for esp
4674                      in i.rm.regmem ie. ESCAPE_TO_TWO_BYTE_ADDRESSING.
4675                      Any base register besides %esp will not use the
4676                      extra modrm byte.  */
4677                   i.sib.index = NO_INDEX_REGISTER;
4678                 }
4679               else
4680                 {
4681                   if (i.index_reg->reg_num == RegEiz
4682                       || i.index_reg->reg_num == RegRiz)
4683                     i.sib.index = NO_INDEX_REGISTER;
4684                   else
4685                     i.sib.index = i.index_reg->reg_num;
4686                   i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
4687                   if ((i.index_reg->reg_flags & RegRex) != 0)
4688                     i.rex |= REX_X;
4689                 }
4690
4691               if (i.disp_operands
4692                   && (i.reloc[op] == BFD_RELOC_386_TLS_DESC_CALL
4693                       || i.reloc[op] == BFD_RELOC_X86_64_TLSDESC_CALL))
4694                 i.rm.mode = 0;
4695               else
4696                 i.rm.mode = mode_from_disp_size (i.types[op]);
4697             }
4698
4699           if (fake_zero_displacement)
4700             {
4701               /* Fakes a zero displacement assuming that i.types[op]
4702                  holds the correct displacement size.  */
4703               expressionS *exp;
4704
4705               assert (i.op[op].disps == 0);
4706               exp = &disp_expressions[i.disp_operands++];
4707               i.op[op].disps = exp;
4708               exp->X_op = O_constant;
4709               exp->X_add_number = 0;
4710               exp->X_add_symbol = (symbolS *) 0;
4711               exp->X_op_symbol = (symbolS *) 0;
4712             }
4713         }
4714
4715       /* Fill in i.rm.reg or i.rm.regmem field with register operand
4716          (if any) based on i.tm.extension_opcode.  Again, we must be
4717          careful to make sure that segment/control/debug/test/MMX
4718          registers are coded into the i.rm.reg field.  */
4719       if (i.reg_operands)
4720         {
4721           unsigned int op;
4722
4723           /* This has been precalculated for SSE5 instructions 
4724              that have a DREX field earlier in process_drex.  */
4725           if (i.tm.opcode_modifier.drex 
4726               || i.tm.opcode_modifier.drexv 
4727               || i.tm.opcode_modifier.drexc)
4728             {
4729               op = i.drex.modrm_reg;
4730               i.rm.reg = i.op[op].regs->reg_num;
4731               if ((i.op[op].regs->reg_flags & RegRex) != 0)
4732                 i.rex |= REX_R;
4733             }
4734           else
4735             {
4736               for (op = 0; op < i.operands; op++)
4737                 if (i.types[op].bitfield.reg8
4738                     || i.types[op].bitfield.reg16
4739                     || i.types[op].bitfield.reg32
4740                     || i.types[op].bitfield.reg64
4741                     || i.types[op].bitfield.regmmx
4742                     || i.types[op].bitfield.regxmm
4743                     || i.types[op].bitfield.sreg2
4744                     || i.types[op].bitfield.sreg3
4745                     || i.types[op].bitfield.control
4746                     || i.types[op].bitfield.debug
4747                     || i.types[op].bitfield.test)
4748                   break;
4749
4750               assert (op < i.operands);
4751
4752               /* If there is an extension opcode to put here, the 
4753                  register number must be put into the regmem field.  */
4754               if (i.tm.extension_opcode != None)
4755                 {
4756                   i.rm.regmem = i.op[op].regs->reg_num;
4757                   if ((i.op[op].regs->reg_flags & RegRex) != 0)
4758                     i.rex |= REX_B;
4759                 }
4760               else
4761                 {
4762                   i.rm.reg = i.op[op].regs->reg_num;
4763                   if ((i.op[op].regs->reg_flags & RegRex) != 0)
4764                     i.rex |= REX_R;
4765                 }
4766             }
4767
4768           /* Now, if no memory operand has set i.rm.mode = 0, 1, 2 we
4769              must set it to 3 to indicate this is a register operand
4770              in the regmem field.  */
4771           if (!i.mem_operands)
4772             i.rm.mode = 3;
4773         }
4774
4775       /* Fill in i.rm.reg field with extension opcode (if any).  */
4776       if (i.tm.extension_opcode != None
4777           && !(i.tm.opcode_modifier.drex 
4778               || i.tm.opcode_modifier.drexv 
4779               || i.tm.opcode_modifier.drexc))
4780         i.rm.reg = i.tm.extension_opcode;
4781     }
4782   return default_seg;
4783 }
4784
4785 static void
4786 output_branch (void)
4787 {
4788   char *p;
4789   int code16;
4790   int prefix;
4791   relax_substateT subtype;
4792   symbolS *sym;
4793   offsetT off;
4794
4795   code16 = 0;
4796   if (flag_code == CODE_16BIT)
4797     code16 = CODE16;
4798
4799   prefix = 0;
4800   if (i.prefix[DATA_PREFIX] != 0)
4801     {
4802       prefix = 1;
4803       i.prefixes -= 1;
4804       code16 ^= CODE16;
4805     }
4806   /* Pentium4 branch hints.  */
4807   if (i.prefix[SEG_PREFIX] == CS_PREFIX_OPCODE /* not taken */
4808       || i.prefix[SEG_PREFIX] == DS_PREFIX_OPCODE /* taken */)
4809     {
4810       prefix++;
4811       i.prefixes--;
4812     }
4813   if (i.prefix[REX_PREFIX] != 0)
4814     {
4815       prefix++;
4816       i.prefixes--;
4817     }
4818
4819   if (i.prefixes != 0 && !intel_syntax)
4820     as_warn (_("skipping prefixes on this instruction"));
4821
4822   /* It's always a symbol;  End frag & setup for relax.
4823      Make sure there is enough room in this frag for the largest
4824      instruction we may generate in md_convert_frag.  This is 2
4825      bytes for the opcode and room for the prefix and largest
4826      displacement.  */
4827   frag_grow (prefix + 2 + 4);
4828   /* Prefix and 1 opcode byte go in fr_fix.  */
4829   p = frag_more (prefix + 1);
4830   if (i.prefix[DATA_PREFIX] != 0)
4831     *p++ = DATA_PREFIX_OPCODE;
4832   if (i.prefix[SEG_PREFIX] == CS_PREFIX_OPCODE
4833       || i.prefix[SEG_PREFIX] == DS_PREFIX_OPCODE)
4834     *p++ = i.prefix[SEG_PREFIX];
4835   if (i.prefix[REX_PREFIX] != 0)
4836     *p++ = i.prefix[REX_PREFIX];
4837   *p = i.tm.base_opcode;
4838
4839   if ((unsigned char) *p == JUMP_PC_RELATIVE)
4840     subtype = ENCODE_RELAX_STATE (UNCOND_JUMP, SMALL);
4841   else if (cpu_arch_flags.bitfield.cpui386)
4842     subtype = ENCODE_RELAX_STATE (COND_JUMP, SMALL);
4843   else
4844     subtype = ENCODE_RELAX_STATE (COND_JUMP86, SMALL);
4845   subtype |= code16;
4846
4847   sym = i.op[0].disps->X_add_symbol;
4848   off = i.op[0].disps->X_add_number;
4849
4850   if (i.op[0].disps->X_op != O_constant
4851       && i.op[0].disps->X_op != O_symbol)
4852     {
4853       /* Handle complex expressions.  */
4854       sym = make_expr_symbol (i.op[0].disps);
4855       off = 0;
4856     }
4857
4858   /* 1 possible extra opcode + 4 byte displacement go in var part.
4859      Pass reloc in fr_var.  */
4860   frag_var (rs_machine_dependent, 5, i.reloc[0], subtype, sym, off, p);
4861 }
4862
4863 static void
4864 output_jump (void)
4865 {
4866   char *p;
4867   int size;
4868   fixS *fixP;
4869
4870   if (i.tm.opcode_modifier.jumpbyte)
4871     {
4872       /* This is a loop or jecxz type instruction.  */
4873       size = 1;
4874       if (i.prefix[ADDR_PREFIX] != 0)
4875         {
4876           FRAG_APPEND_1_CHAR (ADDR_PREFIX_OPCODE);
4877           i.prefixes -= 1;
4878         }
4879       /* Pentium4 branch hints.  */
4880       if (i.prefix[SEG_PREFIX] == CS_PREFIX_OPCODE /* not taken */
4881           || i.prefix[SEG_PREFIX] == DS_PREFIX_OPCODE /* taken */)
4882         {
4883           FRAG_APPEND_1_CHAR (i.prefix[SEG_PREFIX]);
4884           i.prefixes--;
4885         }
4886     }
4887   else
4888     {
4889       int code16;
4890
4891       code16 = 0;
4892       if (flag_code == CODE_16BIT)
4893         code16 = CODE16;
4894
4895       if (i.prefix[DATA_PREFIX] != 0)
4896         {
4897           FRAG_APPEND_1_CHAR (DATA_PREFIX_OPCODE);
4898           i.prefixes -= 1;
4899           code16 ^= CODE16;
4900         }
4901
4902       size = 4;
4903       if (code16)
4904         size = 2;
4905     }
4906
4907   if (i.prefix[REX_PREFIX] != 0)
4908     {
4909       FRAG_APPEND_1_CHAR (i.prefix[REX_PREFIX]);
4910       i.prefixes -= 1;
4911     }
4912
4913   if (i.prefixes != 0 && !intel_syntax)
4914     as_warn (_("skipping prefixes on this instruction"));
4915
4916   p = frag_more (1 + size);
4917   *p++ = i.tm.base_opcode;
4918
4919   fixP = fix_new_exp (frag_now, p - frag_now->fr_literal, size,
4920                       i.op[0].disps, 1, reloc (size, 1, 1, i.reloc[0]));
4921
4922   /* All jumps handled here are signed, but don't use a signed limit
4923      check for 32 and 16 bit jumps as we want to allow wrap around at
4924      4G and 64k respectively.  */
4925   if (size == 1)
4926     fixP->fx_signed = 1;
4927 }
4928
4929 static void
4930 output_interseg_jump (void)
4931 {
4932   char *p;
4933   int size;
4934   int prefix;
4935   int code16;
4936
4937   code16 = 0;
4938   if (flag_code == CODE_16BIT)
4939     code16 = CODE16;
4940
4941   prefix = 0;
4942   if (i.prefix[DATA_PREFIX] != 0)
4943     {
4944       prefix = 1;
4945       i.prefixes -= 1;
4946       code16 ^= CODE16;
4947     }
4948   if (i.prefix[REX_PREFIX] != 0)
4949     {
4950       prefix++;
4951       i.prefixes -= 1;
4952     }
4953
4954   size = 4;
4955   if (code16)
4956     size = 2;
4957
4958   if (i.prefixes != 0 && !intel_syntax)
4959     as_warn (_("skipping prefixes on this instruction"));
4960
4961   /* 1 opcode; 2 segment; offset  */
4962   p = frag_more (prefix + 1 + 2 + size);
4963
4964   if (i.prefix[DATA_PREFIX] != 0)
4965     *p++ = DATA_PREFIX_OPCODE;
4966
4967   if (i.prefix[REX_PREFIX] != 0)
4968     *p++ = i.prefix[REX_PREFIX];
4969
4970   *p++ = i.tm.base_opcode;
4971   if (i.op[1].imms->X_op == O_constant)
4972     {
4973       offsetT n = i.op[1].imms->X_add_number;
4974
4975       if (size == 2
4976           && !fits_in_unsigned_word (n)
4977           && !fits_in_signed_word (n))
4978         {
4979           as_bad (_("16-bit jump out of range"));
4980           return;
4981         }
4982       md_number_to_chars (p, n, size);
4983     }
4984   else
4985     fix_new_exp (frag_now, p - frag_now->fr_literal, size,
4986                  i.op[1].imms, 0, reloc (size, 0, 0, i.reloc[1]));
4987   if (i.op[0].imms->X_op != O_constant)
4988     as_bad (_("can't handle non absolute segment in `%s'"),
4989             i.tm.name);
4990   md_number_to_chars (p + size, (valueT) i.op[0].imms->X_add_number, 2);
4991 }
4992
4993 static void
4994 output_insn (void)
4995 {
4996   fragS *insn_start_frag;
4997   offsetT insn_start_off;
4998
4999   /* Tie dwarf2 debug info to the address at the start of the insn.
5000      We can't do this after the insn has been output as the current
5001      frag may have been closed off.  eg. by frag_var.  */
5002   dwarf2_emit_insn (0);
5003
5004   insn_start_frag = frag_now;
5005   insn_start_off = frag_now_fix ();
5006
5007   /* Output jumps.  */
5008   if (i.tm.opcode_modifier.jump)
5009     output_branch ();
5010   else if (i.tm.opcode_modifier.jumpbyte
5011            || i.tm.opcode_modifier.jumpdword)
5012     output_jump ();
5013   else if (i.tm.opcode_modifier.jumpintersegment)
5014     output_interseg_jump ();
5015   else
5016     {
5017       /* Output normal instructions here.  */
5018       char *p;
5019       unsigned char *q;
5020       unsigned int j;
5021       unsigned int prefix;
5022
5023       switch (i.tm.opcode_length)
5024         {
5025         case 3:
5026           if (i.tm.base_opcode & 0xff000000)
5027             {
5028               prefix = (i.tm.base_opcode >> 24) & 0xff;
5029               goto check_prefix;
5030             }
5031           break;
5032         case 2:
5033           if ((i.tm.base_opcode & 0xff0000) != 0)
5034             {
5035               prefix = (i.tm.base_opcode >> 16) & 0xff;
5036               if (i.tm.cpu_flags.bitfield.cpupadlock)
5037                 {
5038 check_prefix:
5039                   if (prefix != REPE_PREFIX_OPCODE
5040                       || i.prefix[LOCKREP_PREFIX] != REPE_PREFIX_OPCODE)
5041                     add_prefix (prefix);
5042                 }
5043               else
5044                 add_prefix (prefix);
5045             }
5046           break;
5047         case 1:
5048           break;
5049         default:
5050           abort ();
5051         }
5052
5053       /* The prefix bytes.  */
5054       for (j = ARRAY_SIZE (i.prefix), q = i.prefix; j > 0; j--, q++)
5055         if (*q)
5056           FRAG_APPEND_1_CHAR (*q);
5057
5058       /* Now the opcode; be careful about word order here!  */
5059       if (i.tm.opcode_length == 1)
5060         {
5061           FRAG_APPEND_1_CHAR (i.tm.base_opcode);
5062         }
5063       else
5064         {
5065           switch (i.tm.opcode_length)
5066             {
5067             case 3:
5068               p = frag_more (3);
5069               *p++ = (i.tm.base_opcode >> 16) & 0xff;
5070               break;
5071             case 2:
5072               p = frag_more (2);
5073               break;
5074             default:
5075               abort ();
5076               break;
5077             }
5078
5079           /* Put out high byte first: can't use md_number_to_chars!  */
5080           *p++ = (i.tm.base_opcode >> 8) & 0xff;
5081           *p = i.tm.base_opcode & 0xff;
5082
5083           /* On SSE5, encode the OC1 bit in the DREX field if this 
5084              encoding has multiple formats.  */
5085           if (i.tm.opcode_modifier.drex 
5086               && i.tm.opcode_modifier.drexv 
5087               && DREX_OC1 (i.tm.extension_opcode))
5088             *p |= DREX_OC1_MASK;
5089         }
5090
5091       /* Now the modrm byte and sib byte (if present).  */
5092       if (i.tm.opcode_modifier.modrm)
5093         {
5094           FRAG_APPEND_1_CHAR ((i.rm.regmem << 0
5095                                | i.rm.reg << 3
5096                                | i.rm.mode << 6));
5097           /* If i.rm.regmem == ESP (4)
5098              && i.rm.mode != (Register mode)
5099              && not 16 bit
5100              ==> need second modrm byte.  */
5101           if (i.rm.regmem == ESCAPE_TO_TWO_BYTE_ADDRESSING
5102               && i.rm.mode != 3
5103               && !(i.base_reg && i.base_reg->reg_type.bitfield.reg16))
5104             FRAG_APPEND_1_CHAR ((i.sib.base << 0
5105                                  | i.sib.index << 3
5106                                  | i.sib.scale << 6));
5107         }
5108
5109       /* Write the DREX byte if needed.  */
5110       if (i.tm.opcode_modifier.drex || i.tm.opcode_modifier.drexc)
5111         {
5112           p = frag_more (1);
5113           *p = (((i.drex.reg & 0xf) << 4) | (i.drex.rex & 0x7));
5114
5115           /* Encode the OC0 bit if this encoding has multiple 
5116              formats.  */
5117           if ((i.tm.opcode_modifier.drex 
5118                || i.tm.opcode_modifier.drexv) 
5119               && DREX_OC0 (i.tm.extension_opcode))
5120             *p |= DREX_OC0_MASK;
5121         }
5122
5123       if (i.disp_operands)
5124         output_disp (insn_start_frag, insn_start_off);
5125
5126       if (i.imm_operands)
5127         output_imm (insn_start_frag, insn_start_off);
5128     }
5129
5130 #ifdef DEBUG386
5131   if (flag_debug)
5132     {
5133       pi ("" /*line*/, &i);
5134     }
5135 #endif /* DEBUG386  */
5136 }
5137
5138 /* Return the size of the displacement operand N.  */
5139
5140 static int
5141 disp_size (unsigned int n)
5142 {
5143   int size = 4;
5144   if (i.types[n].bitfield.disp64)
5145     size = 8;
5146   else if (i.types[n].bitfield.disp8)
5147     size = 1;
5148   else if (i.types[n].bitfield.disp16)
5149     size = 2;
5150   return size;
5151 }
5152
5153 /* Return the size of the immediate operand N.  */
5154
5155 static int
5156 imm_size (unsigned int n)
5157 {
5158   int size = 4;
5159   if (i.types[n].bitfield.imm64)
5160     size = 8;
5161   else if (i.types[n].bitfield.imm8 || i.types[n].bitfield.imm8s)
5162     size = 1;
5163   else if (i.types[n].bitfield.imm16)
5164     size = 2;
5165   return size;
5166 }
5167
5168 static void
5169 output_disp (fragS *insn_start_frag, offsetT insn_start_off)
5170 {
5171   char *p;
5172   unsigned int n;
5173
5174   for (n = 0; n < i.operands; n++)
5175     {
5176       if (operand_type_check (i.types[n], disp))
5177         {
5178           if (i.op[n].disps->X_op == O_constant)
5179             {
5180               int size = disp_size (n);
5181               offsetT val;
5182
5183               val = offset_in_range (i.op[n].disps->X_add_number,
5184                                      size);
5185               p = frag_more (size);
5186               md_number_to_chars (p, val, size);
5187             }
5188           else
5189             {
5190               enum bfd_reloc_code_real reloc_type;
5191               int size = disp_size (n);
5192               int sign = i.types[n].bitfield.disp32s;
5193               int pcrel = (i.flags[n] & Operand_PCrel) != 0;
5194
5195               /* We can't have 8 bit displacement here.  */
5196               assert (!i.types[n].bitfield.disp8);
5197
5198               /* The PC relative address is computed relative
5199                  to the instruction boundary, so in case immediate
5200                  fields follows, we need to adjust the value.  */
5201               if (pcrel && i.imm_operands)
5202                 {
5203                   unsigned int n1;
5204                   int sz = 0;
5205
5206                   for (n1 = 0; n1 < i.operands; n1++)
5207                     if (operand_type_check (i.types[n1], imm))
5208                       {
5209                         /* Only one immediate is allowed for PC
5210                            relative address.  */
5211                         assert (sz == 0);
5212                         sz = imm_size (n1);
5213                         i.op[n].disps->X_add_number -= sz;
5214                       }
5215                   /* We should find the immediate.  */
5216                   assert (sz != 0);
5217                 }
5218
5219               p = frag_more (size);
5220               reloc_type = reloc (size, pcrel, sign, i.reloc[n]);
5221               if (GOT_symbol
5222                   && GOT_symbol == i.op[n].disps->X_add_symbol
5223                   && (((reloc_type == BFD_RELOC_32
5224                         || reloc_type == BFD_RELOC_X86_64_32S
5225                         || (reloc_type == BFD_RELOC_64
5226                             && object_64bit))
5227                        && (i.op[n].disps->X_op == O_symbol
5228                            || (i.op[n].disps->X_op == O_add
5229                                && ((symbol_get_value_expression
5230                                     (i.op[n].disps->X_op_symbol)->X_op)
5231                                    == O_subtract))))
5232                       || reloc_type == BFD_RELOC_32_PCREL))
5233                 {
5234                   offsetT add;
5235
5236                   if (insn_start_frag == frag_now)
5237                     add = (p - frag_now->fr_literal) - insn_start_off;
5238                   else
5239                     {
5240                       fragS *fr;
5241
5242                       add = insn_start_frag->fr_fix - insn_start_off;
5243                       for (fr = insn_start_frag->fr_next;
5244                            fr && fr != frag_now; fr = fr->fr_next)
5245                         add += fr->fr_fix;
5246                       add += p - frag_now->fr_literal;
5247                     }
5248
5249                   if (!object_64bit)
5250                     {
5251                       reloc_type = BFD_RELOC_386_GOTPC;
5252                       i.op[n].imms->X_add_number += add;
5253                     }
5254                   else if (reloc_type == BFD_RELOC_64)
5255                     reloc_type = BFD_RELOC_X86_64_GOTPC64;
5256                   else
5257                     /* Don't do the adjustment for x86-64, as there
5258                        the pcrel addressing is relative to the _next_
5259                        insn, and that is taken care of in other code.  */
5260                     reloc_type = BFD_RELOC_X86_64_GOTPC32;
5261                 }
5262               fix_new_exp (frag_now, p - frag_now->fr_literal, size,
5263                            i.op[n].disps, pcrel, reloc_type);
5264             }
5265         }
5266     }
5267 }
5268
5269 static void
5270 output_imm (fragS *insn_start_frag, offsetT insn_start_off)
5271 {
5272   char *p;
5273   unsigned int n;
5274
5275   for (n = 0; n < i.operands; n++)
5276     {
5277       if (operand_type_check (i.types[n], imm))
5278         {
5279           if (i.op[n].imms->X_op == O_constant)
5280             {
5281               int size = imm_size (n);
5282               offsetT val;
5283
5284               val = offset_in_range (i.op[n].imms->X_add_number,
5285                                      size);
5286               p = frag_more (size);
5287               md_number_to_chars (p, val, size);
5288             }
5289           else
5290             {
5291               /* Not absolute_section.
5292                  Need a 32-bit fixup (don't support 8bit
5293                  non-absolute imms).  Try to support other
5294                  sizes ...  */
5295               enum bfd_reloc_code_real reloc_type;
5296               int size = imm_size (n);
5297               int sign;
5298
5299               if (i.types[n].bitfield.imm32s
5300                   && (i.suffix == QWORD_MNEM_SUFFIX
5301                       || (!i.suffix && i.tm.opcode_modifier.no_lsuf)))
5302                 sign = 1;
5303               else
5304                 sign = 0;
5305
5306               p = frag_more (size);
5307               reloc_type = reloc (size, 0, sign, i.reloc[n]);
5308
5309               /*   This is tough to explain.  We end up with this one if we
5310                * have operands that look like
5311                * "_GLOBAL_OFFSET_TABLE_+[.-.L284]".  The goal here is to
5312                * obtain the absolute address of the GOT, and it is strongly
5313                * preferable from a performance point of view to avoid using
5314                * a runtime relocation for this.  The actual sequence of
5315                * instructions often look something like:
5316                *
5317                *        call    .L66
5318                * .L66:
5319                *        popl    %ebx
5320                *        addl    $_GLOBAL_OFFSET_TABLE_+[.-.L66],%ebx
5321                *
5322                *   The call and pop essentially return the absolute address
5323                * of the label .L66 and store it in %ebx.  The linker itself
5324                * will ultimately change the first operand of the addl so
5325                * that %ebx points to the GOT, but to keep things simple, the
5326                * .o file must have this operand set so that it generates not
5327                * the absolute address of .L66, but the absolute address of
5328                * itself.  This allows the linker itself simply treat a GOTPC
5329                * relocation as asking for a pcrel offset to the GOT to be
5330                * added in, and the addend of the relocation is stored in the
5331                * operand field for the instruction itself.
5332                *
5333                *   Our job here is to fix the operand so that it would add
5334                * the correct offset so that %ebx would point to itself.  The
5335                * thing that is tricky is that .-.L66 will point to the
5336                * beginning of the instruction, so we need to further modify
5337                * the operand so that it will point to itself.  There are
5338                * other cases where you have something like:
5339                *
5340                *        .long   $_GLOBAL_OFFSET_TABLE_+[.-.L66]
5341                *
5342                * and here no correction would be required.  Internally in
5343                * the assembler we treat operands of this form as not being
5344                * pcrel since the '.' is explicitly mentioned, and I wonder
5345                * whether it would simplify matters to do it this way.  Who
5346                * knows.  In earlier versions of the PIC patches, the
5347                * pcrel_adjust field was used to store the correction, but
5348                * since the expression is not pcrel, I felt it would be
5349                * confusing to do it this way.  */
5350
5351               if ((reloc_type == BFD_RELOC_32
5352                    || reloc_type == BFD_RELOC_X86_64_32S
5353                    || reloc_type == BFD_RELOC_64)
5354                   && GOT_symbol
5355                   && GOT_symbol == i.op[n].imms->X_add_symbol
5356                   && (i.op[n].imms->X_op == O_symbol
5357                       || (i.op[n].imms->X_op == O_add
5358                           && ((symbol_get_value_expression
5359                                (i.op[n].imms->X_op_symbol)->X_op)
5360                               == O_subtract))))
5361                 {
5362                   offsetT add;
5363
5364                   if (insn_start_frag == frag_now)
5365                     add = (p - frag_now->fr_literal) - insn_start_off;
5366                   else
5367                     {
5368                       fragS *fr;
5369
5370                       add = insn_start_frag->fr_fix - insn_start_off;
5371                       for (fr = insn_start_frag->fr_next;
5372                            fr && fr != frag_now; fr = fr->fr_next)
5373                         add += fr->fr_fix;
5374                       add += p - frag_now->fr_literal;
5375                     }
5376
5377                   if (!object_64bit)
5378                     reloc_type = BFD_RELOC_386_GOTPC;
5379                   else if (size == 4)
5380                     reloc_type = BFD_RELOC_X86_64_GOTPC32;
5381                   else if (size == 8)
5382                     reloc_type = BFD_RELOC_X86_64_GOTPC64;
5383                   i.op[n].imms->X_add_number += add;
5384                 }
5385               fix_new_exp (frag_now, p - frag_now->fr_literal, size,
5386                            i.op[n].imms, 0, reloc_type);
5387             }
5388         }
5389     }
5390 }
5391 \f
5392 /* x86_cons_fix_new is called via the expression parsing code when a
5393    reloc is needed.  We use this hook to get the correct .got reloc.  */
5394 static enum bfd_reloc_code_real got_reloc = NO_RELOC;
5395 static int cons_sign = -1;
5396
5397 void
5398 x86_cons_fix_new (fragS *frag, unsigned int off, unsigned int len,
5399                   expressionS *exp)
5400 {
5401   enum bfd_reloc_code_real r = reloc (len, 0, cons_sign, got_reloc);
5402
5403   got_reloc = NO_RELOC;
5404
5405 #ifdef TE_PE
5406   if (exp->X_op == O_secrel)
5407     {
5408       exp->X_op = O_symbol;
5409       r = BFD_RELOC_32_SECREL;
5410     }
5411 #endif
5412
5413   fix_new_exp (frag, off, len, exp, 0, r);
5414 }
5415
5416 #if (!defined (OBJ_ELF) && !defined (OBJ_MAYBE_ELF)) || defined (LEX_AT)
5417 # define lex_got(reloc, adjust, types) NULL
5418 #else
5419 /* Parse operands of the form
5420    <symbol>@GOTOFF+<nnn>
5421    and similar .plt or .got references.
5422
5423    If we find one, set up the correct relocation in RELOC and copy the
5424    input string, minus the `@GOTOFF' into a malloc'd buffer for
5425    parsing by the calling routine.  Return this buffer, and if ADJUST
5426    is non-null set it to the length of the string we removed from the
5427    input line.  Otherwise return NULL.  */
5428 static char *
5429 lex_got (enum bfd_reloc_code_real *reloc,
5430          int *adjust,
5431          i386_operand_type *types)
5432 {
5433   /* Some of the relocations depend on the size of what field is to
5434      be relocated.  But in our callers i386_immediate and i386_displacement
5435      we don't yet know the operand size (this will be set by insn
5436      matching).  Hence we record the word32 relocation here,
5437      and adjust the reloc according to the real size in reloc().  */
5438   static const struct {
5439     const char *str;
5440     const enum bfd_reloc_code_real rel[2];
5441     const i386_operand_type types64;
5442   } gotrel[] = {
5443     { "PLTOFF",   { 0,
5444                     BFD_RELOC_X86_64_PLTOFF64 },
5445       OPERAND_TYPE_IMM64 },
5446     { "PLT",      { BFD_RELOC_386_PLT32,
5447                     BFD_RELOC_X86_64_PLT32    },
5448       OPERAND_TYPE_IMM32_32S_DISP32 },
5449     { "GOTPLT",   { 0,
5450                     BFD_RELOC_X86_64_GOTPLT64 },
5451       OPERAND_TYPE_IMM64_DISP64 },
5452     { "GOTOFF",   { BFD_RELOC_386_GOTOFF,
5453                     BFD_RELOC_X86_64_GOTOFF64 },
5454       OPERAND_TYPE_IMM64_DISP64 },
5455     { "GOTPCREL", { 0,
5456                     BFD_RELOC_X86_64_GOTPCREL },
5457       OPERAND_TYPE_IMM32_32S_DISP32 },
5458     { "TLSGD",    { BFD_RELOC_386_TLS_GD,
5459                     BFD_RELOC_X86_64_TLSGD    },
5460       OPERAND_TYPE_IMM32_32S_DISP32 },
5461     { "TLSLDM",   { BFD_RELOC_386_TLS_LDM,
5462                     0                         },
5463       OPERAND_TYPE_NONE },
5464     { "TLSLD",    { 0,
5465                     BFD_RELOC_X86_64_TLSLD    },
5466       OPERAND_TYPE_IMM32_32S_DISP32 },
5467     { "GOTTPOFF", { BFD_RELOC_386_TLS_IE_32,
5468                     BFD_RELOC_X86_64_GOTTPOFF },
5469       OPERAND_TYPE_IMM32_32S_DISP32 },
5470     { "TPOFF",    { BFD_RELOC_386_TLS_LE_32,
5471                     BFD_RELOC_X86_64_TPOFF32  },
5472       OPERAND_TYPE_IMM32_32S_64_DISP32_64 },
5473     { "NTPOFF",   { BFD_RELOC_386_TLS_LE,
5474                     0                         },
5475       OPERAND_TYPE_NONE },
5476     { "DTPOFF",   { BFD_RELOC_386_TLS_LDO_32,
5477                     BFD_RELOC_X86_64_DTPOFF32 },
5478       
5479       OPERAND_TYPE_IMM32_32S_64_DISP32_64 },
5480     { "GOTNTPOFF",{ BFD_RELOC_386_TLS_GOTIE,
5481                     0                         },
5482       OPERAND_TYPE_NONE },
5483     { "INDNTPOFF",{ BFD_RELOC_386_TLS_IE,
5484                     0                         },
5485       OPERAND_TYPE_NONE },
5486     { "GOT",      { BFD_RELOC_386_GOT32,
5487                     BFD_RELOC_X86_64_GOT32    },
5488       OPERAND_TYPE_IMM32_32S_64_DISP32 },
5489     { "TLSDESC",  { BFD_RELOC_386_TLS_GOTDESC,
5490                     BFD_RELOC_X86_64_GOTPC32_TLSDESC },
5491       OPERAND_TYPE_IMM32_32S_DISP32 },
5492     { "TLSCALL",  { BFD_RELOC_386_TLS_DESC_CALL,
5493                     BFD_RELOC_X86_64_TLSDESC_CALL },
5494       OPERAND_TYPE_IMM32_32S_DISP32 },
5495   };
5496   char *cp;
5497   unsigned int j;
5498
5499   if (!IS_ELF)
5500     return NULL;
5501
5502   for (cp = input_line_pointer; *cp != '@'; cp++)
5503     if (is_end_of_line[(unsigned char) *cp] || *cp == ',')
5504       return NULL;
5505
5506   for (j = 0; j < ARRAY_SIZE (gotrel); j++)
5507     {
5508       int len;
5509
5510       len = strlen (gotrel[j].str);
5511       if (strncasecmp (cp + 1, gotrel[j].str, len) == 0)
5512         {
5513           if (gotrel[j].rel[object_64bit] != 0)
5514             {
5515               int first, second;
5516               char *tmpbuf, *past_reloc;
5517
5518               *reloc = gotrel[j].rel[object_64bit];
5519               if (adjust)
5520                 *adjust = len;
5521
5522               if (types)
5523                 {
5524                   if (flag_code != CODE_64BIT)
5525                     {
5526                       types->bitfield.imm32 = 1;
5527                       types->bitfield.disp32 = 1;
5528                     }
5529                   else
5530                     *types = gotrel[j].types64;
5531                 }
5532
5533               if (GOT_symbol == NULL)
5534                 GOT_symbol = symbol_find_or_make (GLOBAL_OFFSET_TABLE_NAME);
5535
5536               /* The length of the first part of our input line.  */
5537               first = cp - input_line_pointer;
5538
5539               /* The second part goes from after the reloc token until
5540                  (and including) an end_of_line char or comma.  */
5541               past_reloc = cp + 1 + len;
5542               cp = past_reloc;
5543               while (!is_end_of_line[(unsigned char) *cp] && *cp != ',')
5544                 ++cp;
5545               second = cp + 1 - past_reloc;
5546
5547               /* Allocate and copy string.  The trailing NUL shouldn't
5548                  be necessary, but be safe.  */
5549               tmpbuf = xmalloc (first + second + 2);
5550               memcpy (tmpbuf, input_line_pointer, first);
5551               if (second != 0 && *past_reloc != ' ')
5552                 /* Replace the relocation token with ' ', so that
5553                    errors like foo@GOTOFF1 will be detected.  */
5554                 tmpbuf[first++] = ' ';
5555               memcpy (tmpbuf + first, past_reloc, second);
5556               tmpbuf[first + second] = '\0';
5557               return tmpbuf;
5558             }
5559
5560           as_bad (_("@%s reloc is not supported with %d-bit output format"),
5561                   gotrel[j].str, 1 << (5 + object_64bit));
5562           return NULL;
5563         }
5564     }
5565
5566   /* Might be a symbol version string.  Don't as_bad here.  */
5567   return NULL;
5568 }
5569
5570 void
5571 x86_cons (expressionS *exp, int size)
5572 {
5573   if (size == 4 || (object_64bit && size == 8))
5574     {
5575       /* Handle @GOTOFF and the like in an expression.  */
5576       char *save;
5577       char *gotfree_input_line;
5578       int adjust;
5579
5580       save = input_line_pointer;
5581       gotfree_input_line = lex_got (&got_reloc, &adjust, NULL);
5582       if (gotfree_input_line)
5583         input_line_pointer = gotfree_input_line;
5584
5585       expression (exp);
5586
5587       if (gotfree_input_line)
5588         {
5589           /* expression () has merrily parsed up to the end of line,
5590              or a comma - in the wrong buffer.  Transfer how far
5591              input_line_pointer has moved to the right buffer.  */
5592           input_line_pointer = (save
5593                                 + (input_line_pointer - gotfree_input_line)
5594                                 + adjust);
5595           free (gotfree_input_line);
5596           if (exp->X_op == O_constant
5597               || exp->X_op == O_absent
5598               || exp->X_op == O_illegal
5599               || exp->X_op == O_register
5600               || exp->X_op == O_big)
5601             {
5602               char c = *input_line_pointer;
5603               *input_line_pointer = 0;
5604               as_bad (_("missing or invalid expression `%s'"), save);
5605               *input_line_pointer = c;
5606             }
5607         }
5608     }
5609   else
5610     expression (exp);
5611 }
5612 #endif
5613
5614 static void signed_cons (int size)
5615 {
5616   if (flag_code == CODE_64BIT)
5617     cons_sign = 1;
5618   cons (size);
5619   cons_sign = -1;
5620 }
5621
5622 #ifdef TE_PE
5623 static void
5624 pe_directive_secrel (dummy)
5625      int dummy ATTRIBUTE_UNUSED;
5626 {
5627   expressionS exp;
5628
5629   do
5630     {
5631       expression (&exp);
5632       if (exp.X_op == O_symbol)
5633         exp.X_op = O_secrel;
5634
5635       emit_expr (&exp, 4);
5636     }
5637   while (*input_line_pointer++ == ',');
5638
5639   input_line_pointer--;
5640   demand_empty_rest_of_line ();
5641 }
5642 #endif
5643
5644 static int
5645 i386_immediate (char *imm_start)
5646 {
5647   char *save_input_line_pointer;
5648   char *gotfree_input_line;
5649   segT exp_seg = 0;
5650   expressionS *exp;
5651   i386_operand_type types;
5652
5653   UINTS_SET (types, ~0);
5654
5655   if (i.imm_operands == MAX_IMMEDIATE_OPERANDS)
5656     {
5657       as_bad (_("at most %d immediate operands are allowed"),
5658               MAX_IMMEDIATE_OPERANDS);
5659       return 0;
5660     }
5661
5662   exp = &im_expressions[i.imm_operands++];
5663   i.op[this_operand].imms = exp;
5664
5665   if (is_space_char (*imm_start))
5666     ++imm_start;
5667
5668   save_input_line_pointer = input_line_pointer;
5669   input_line_pointer = imm_start;
5670
5671   gotfree_input_line = lex_got (&i.reloc[this_operand], NULL, &types);
5672   if (gotfree_input_line)
5673     input_line_pointer = gotfree_input_line;
5674
5675   exp_seg = expression (exp);
5676
5677   SKIP_WHITESPACE ();
5678   if (*input_line_pointer)
5679     as_bad (_("junk `%s' after expression"), input_line_pointer);
5680
5681   input_line_pointer = save_input_line_pointer;
5682   if (gotfree_input_line)
5683     free (gotfree_input_line);
5684
5685   if (exp->X_op == O_absent
5686       || exp->X_op == O_illegal
5687       || exp->X_op == O_big
5688       || (gotfree_input_line
5689           && (exp->X_op == O_constant
5690               || exp->X_op == O_register)))
5691     {
5692       as_bad (_("missing or invalid immediate expression `%s'"),
5693               imm_start);
5694       return 0;
5695     }
5696   else if (exp->X_op == O_constant)
5697     {
5698       /* Size it properly later.  */
5699       i.types[this_operand].bitfield.imm64 = 1;
5700       /* If BFD64, sign extend val.  */
5701       if (!use_rela_relocations
5702           && (exp->X_add_number & ~(((addressT) 2 << 31) - 1)) == 0)
5703         exp->X_add_number
5704           = (exp->X_add_number ^ ((addressT) 1 << 31)) - ((addressT) 1 << 31);
5705     }
5706 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
5707   else if (OUTPUT_FLAVOR == bfd_target_aout_flavour
5708            && exp_seg != absolute_section
5709            && exp_seg != text_section
5710            && exp_seg != data_section
5711            && exp_seg != bss_section
5712            && exp_seg != undefined_section
5713            && !bfd_is_com_section (exp_seg))
5714     {
5715       as_bad (_("unimplemented segment %s in operand"), exp_seg->name);
5716       return 0;
5717     }
5718 #endif
5719   else if (!intel_syntax && exp->X_op == O_register)
5720     {
5721       as_bad (_("illegal immediate register operand %s"), imm_start);
5722       return 0;
5723     }
5724   else
5725     {
5726       /* This is an address.  The size of the address will be
5727          determined later, depending on destination register,
5728          suffix, or the default for the section.  */
5729       i.types[this_operand].bitfield.imm8 = 1;
5730       i.types[this_operand].bitfield.imm16 = 1;
5731       i.types[this_operand].bitfield.imm32 = 1;
5732       i.types[this_operand].bitfield.imm32s = 1;
5733       i.types[this_operand].bitfield.imm64 = 1;
5734       i.types[this_operand] = operand_type_and (i.types[this_operand],
5735                                                 types);
5736     }
5737
5738   return 1;
5739 }
5740
5741 static char *
5742 i386_scale (char *scale)
5743 {
5744   offsetT val;
5745   char *save = input_line_pointer;
5746
5747   input_line_pointer = scale;
5748   val = get_absolute_expression ();
5749
5750   switch (val)
5751     {
5752     case 1:
5753       i.log2_scale_factor = 0;
5754       break;
5755     case 2:
5756       i.log2_scale_factor = 1;
5757       break;
5758     case 4:
5759       i.log2_scale_factor = 2;
5760       break;
5761     case 8:
5762       i.log2_scale_factor = 3;
5763       break;
5764     default:
5765       {
5766         char sep = *input_line_pointer;
5767
5768         *input_line_pointer = '\0';
5769         as_bad (_("expecting scale factor of 1, 2, 4, or 8: got `%s'"),
5770                 scale);
5771         *input_line_pointer = sep;
5772         input_line_pointer = save;
5773         return NULL;
5774       }
5775     }
5776   if (i.log2_scale_factor != 0 && i.index_reg == 0)
5777     {
5778       as_warn (_("scale factor of %d without an index register"),
5779                1 << i.log2_scale_factor);
5780       i.log2_scale_factor = 0;
5781     }
5782   scale = input_line_pointer;
5783   input_line_pointer = save;
5784   return scale;
5785 }
5786
5787 static int
5788 i386_displacement (char *disp_start, char *disp_end)
5789 {
5790   expressionS *exp;
5791   segT exp_seg = 0;
5792   char *save_input_line_pointer;
5793   char *gotfree_input_line;
5794   int override;
5795   i386_operand_type bigdisp, types = anydisp;
5796   int ret;
5797
5798   if (i.disp_operands == MAX_MEMORY_OPERANDS)
5799     {
5800       as_bad (_("at most %d displacement operands are allowed"),
5801               MAX_MEMORY_OPERANDS);
5802       return 0;
5803     }
5804
5805   UINTS_CLEAR (bigdisp);
5806   if ((i.types[this_operand].bitfield.jumpabsolute)
5807       || (!current_templates->start->opcode_modifier.jump
5808           && !current_templates->start->opcode_modifier.jumpdword))
5809     {
5810       bigdisp.bitfield.disp32 = 1;
5811       override = (i.prefix[ADDR_PREFIX] != 0);
5812       if (flag_code == CODE_64BIT)
5813         {
5814           if (!override)
5815             {
5816               bigdisp.bitfield.disp32s = 1;
5817               bigdisp.bitfield.disp64 = 1;
5818             }
5819         }
5820       else if ((flag_code == CODE_16BIT) ^ override)
5821         {
5822           bigdisp.bitfield.disp32 = 0;
5823           bigdisp.bitfield.disp16 = 1;
5824         }
5825     }
5826   else
5827     {
5828       /* For PC-relative branches, the width of the displacement
5829          is dependent upon data size, not address size.  */
5830       override = (i.prefix[DATA_PREFIX] != 0);
5831       if (flag_code == CODE_64BIT)
5832         {
5833           if (override || i.suffix == WORD_MNEM_SUFFIX)
5834             bigdisp.bitfield.disp16 = 1;
5835           else
5836             {
5837               bigdisp.bitfield.disp32 = 1;
5838               bigdisp.bitfield.disp32s = 1;
5839             }
5840         }
5841       else
5842         {
5843           if (!override)
5844             override = (i.suffix == (flag_code != CODE_16BIT
5845                                      ? WORD_MNEM_SUFFIX
5846                                      : LONG_MNEM_SUFFIX));
5847           bigdisp.bitfield.disp32 = 1;
5848           if ((flag_code == CODE_16BIT) ^ override)
5849             {
5850               bigdisp.bitfield.disp32 = 0;
5851               bigdisp.bitfield.disp16 = 1;
5852             }
5853         }
5854     }
5855   i.types[this_operand] = operand_type_or (i.types[this_operand],
5856                                            bigdisp);
5857
5858   exp = &disp_expressions[i.disp_operands];
5859   i.op[this_operand].disps = exp;
5860   i.disp_operands++;
5861   save_input_line_pointer = input_line_pointer;
5862   input_line_pointer = disp_start;
5863   END_STRING_AND_SAVE (disp_end);
5864
5865 #ifndef GCC_ASM_O_HACK
5866 #define GCC_ASM_O_HACK 0
5867 #endif
5868 #if GCC_ASM_O_HACK
5869   END_STRING_AND_SAVE (disp_end + 1);
5870   if (i.types[this_operand].bitfield.baseIndex
5871       && displacement_string_end[-1] == '+')
5872     {
5873       /* This hack is to avoid a warning when using the "o"
5874          constraint within gcc asm statements.
5875          For instance:
5876
5877          #define _set_tssldt_desc(n,addr,limit,type) \
5878          __asm__ __volatile__ ( \
5879          "movw %w2,%0\n\t" \
5880          "movw %w1,2+%0\n\t" \
5881          "rorl $16,%1\n\t" \
5882          "movb %b1,4+%0\n\t" \
5883          "movb %4,5+%0\n\t" \
5884          "movb $0,6+%0\n\t" \
5885          "movb %h1,7+%0\n\t" \
5886          "rorl $16,%1" \
5887          : "=o"(*(n)) : "q" (addr), "ri"(limit), "i"(type))
5888
5889          This works great except that the output assembler ends
5890          up looking a bit weird if it turns out that there is
5891          no offset.  You end up producing code that looks like:
5892
5893          #APP
5894          movw $235,(%eax)
5895          movw %dx,2+(%eax)
5896          rorl $16,%edx
5897          movb %dl,4+(%eax)
5898          movb $137,5+(%eax)
5899          movb $0,6+(%eax)
5900          movb %dh,7+(%eax)
5901          rorl $16,%edx
5902          #NO_APP
5903
5904          So here we provide the missing zero.  */
5905
5906       *displacement_string_end = '0';
5907     }
5908 #endif
5909   gotfree_input_line = lex_got (&i.reloc[this_operand], NULL, &types);
5910   if (gotfree_input_line)
5911     input_line_pointer = gotfree_input_line;
5912
5913   exp_seg = expression (exp);
5914
5915   SKIP_WHITESPACE ();
5916   if (*input_line_pointer)
5917     as_bad (_("junk `%s' after expression"), input_line_pointer);
5918 #if GCC_ASM_O_HACK
5919   RESTORE_END_STRING (disp_end + 1);
5920 #endif
5921   input_line_pointer = save_input_line_pointer;
5922   if (gotfree_input_line)
5923     free (gotfree_input_line);
5924   ret = 1;
5925
5926   /* We do this to make sure that the section symbol is in
5927      the symbol table.  We will ultimately change the relocation
5928      to be relative to the beginning of the section.  */
5929   if (i.reloc[this_operand] == BFD_RELOC_386_GOTOFF
5930       || i.reloc[this_operand] == BFD_RELOC_X86_64_GOTPCREL
5931       || i.reloc[this_operand] == BFD_RELOC_X86_64_GOTOFF64)
5932     {
5933       if (exp->X_op != O_symbol)
5934         goto inv_disp;
5935
5936       if (S_IS_LOCAL (exp->X_add_symbol)
5937           && S_GET_SEGMENT (exp->X_add_symbol) != undefined_section)
5938         section_symbol (S_GET_SEGMENT (exp->X_add_symbol));
5939       exp->X_op = O_subtract;
5940       exp->X_op_symbol = GOT_symbol;
5941       if (i.reloc[this_operand] == BFD_RELOC_X86_64_GOTPCREL)
5942         i.reloc[this_operand] = BFD_RELOC_32_PCREL;
5943       else if (i.reloc[this_operand] == BFD_RELOC_X86_64_GOTOFF64)
5944         i.reloc[this_operand] = BFD_RELOC_64;
5945       else
5946         i.reloc[this_operand] = BFD_RELOC_32;
5947     }
5948
5949   else if (exp->X_op == O_absent
5950            || exp->X_op == O_illegal
5951            || exp->X_op == O_big
5952            || (gotfree_input_line
5953                && (exp->X_op == O_constant
5954                    || exp->X_op == O_register)))
5955     {
5956     inv_disp:
5957       as_bad (_("missing or invalid displacement expression `%s'"),
5958               disp_start);
5959       ret = 0;
5960     }
5961
5962 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
5963   else if (exp->X_op != O_constant
5964            && OUTPUT_FLAVOR == bfd_target_aout_flavour
5965            && exp_seg != absolute_section
5966            && exp_seg != text_section
5967            && exp_seg != data_section
5968            && exp_seg != bss_section
5969            && exp_seg != undefined_section
5970            && !bfd_is_com_section (exp_seg))
5971     {
5972       as_bad (_("unimplemented segment %s in operand"), exp_seg->name);
5973       ret = 0;
5974     }
5975 #endif
5976
5977   RESTORE_END_STRING (disp_end);
5978
5979   /* Check if this is a displacement only operand.  */
5980   bigdisp = i.types[this_operand];
5981   bigdisp.bitfield.disp8 = 0;
5982   bigdisp.bitfield.disp16 = 0;
5983   bigdisp.bitfield.disp32 = 0;
5984   bigdisp.bitfield.disp32s = 0;
5985   bigdisp.bitfield.disp64 = 0;
5986   if (UINTS_ALL_ZERO (bigdisp))
5987     i.types[this_operand] = operand_type_and (i.types[this_operand],
5988                                               types);
5989
5990   return ret;
5991 }
5992
5993 /* Make sure the memory operand we've been dealt is valid.
5994    Return 1 on success, 0 on a failure.  */
5995
5996 static int
5997 i386_index_check (const char *operand_string)
5998 {
5999   int ok;
6000 #if INFER_ADDR_PREFIX
6001   int fudged = 0;
6002
6003  tryprefix:
6004 #endif
6005   ok = 1;
6006   if (flag_code == CODE_64BIT)
6007     {
6008       if ((i.base_reg
6009            && ((i.prefix[ADDR_PREFIX] == 0
6010                 && !i.base_reg->reg_type.bitfield.reg64)
6011                || (i.prefix[ADDR_PREFIX]
6012                    && !i.base_reg->reg_type.bitfield.reg32))
6013            && (i.index_reg
6014                || i.base_reg->reg_num !=
6015                   (i.prefix[ADDR_PREFIX] == 0 ? RegRip : RegEip)))
6016           || (i.index_reg
6017               && (!i.index_reg->reg_type.bitfield.baseindex
6018                   || (i.prefix[ADDR_PREFIX] == 0
6019                       && i.index_reg->reg_num != RegRiz
6020                       && !i.index_reg->reg_type.bitfield.reg64
6021                       )
6022                   || (i.prefix[ADDR_PREFIX]
6023                       && i.index_reg->reg_num != RegEiz
6024                       && !i.index_reg->reg_type.bitfield.reg32))))
6025         ok = 0;
6026     }
6027   else
6028     {
6029       if ((flag_code == CODE_16BIT) ^ (i.prefix[ADDR_PREFIX] != 0))
6030         {
6031           /* 16bit checks.  */
6032           if ((i.base_reg
6033                && (!i.base_reg->reg_type.bitfield.reg16
6034                    || !i.base_reg->reg_type.bitfield.baseindex))
6035               || (i.index_reg
6036                   && (!i.index_reg->reg_type.bitfield.reg16
6037                       || !i.index_reg->reg_type.bitfield.baseindex
6038                       || !(i.base_reg
6039                            && i.base_reg->reg_num < 6
6040                            && i.index_reg->reg_num >= 6
6041                            && i.log2_scale_factor == 0))))
6042             ok = 0;
6043         }
6044       else
6045         {
6046           /* 32bit checks.  */
6047           if ((i.base_reg
6048                && !i.base_reg->reg_type.bitfield.reg32)
6049               || (i.index_reg
6050                   && ((!i.index_reg->reg_type.bitfield.reg32
6051                        && i.index_reg->reg_num != RegEiz)
6052                       || !i.index_reg->reg_type.bitfield.baseindex)))
6053             ok = 0;
6054         }
6055     }
6056   if (!ok)
6057     {
6058 #if INFER_ADDR_PREFIX
6059       if (i.prefix[ADDR_PREFIX] == 0)
6060         {
6061           i.prefix[ADDR_PREFIX] = ADDR_PREFIX_OPCODE;
6062           i.prefixes += 1;
6063           /* Change the size of any displacement too.  At most one of
6064              Disp16 or Disp32 is set.
6065              FIXME.  There doesn't seem to be any real need for separate
6066              Disp16 and Disp32 flags.  The same goes for Imm16 and Imm32.
6067              Removing them would probably clean up the code quite a lot.  */
6068           if (flag_code != CODE_64BIT
6069               && (i.types[this_operand].bitfield.disp16
6070                   || i.types[this_operand].bitfield.disp32))
6071             i.types[this_operand]
6072               = operand_type_xor (i.types[this_operand], disp16_32);
6073           fudged = 1;
6074           goto tryprefix;
6075         }
6076       if (fudged)
6077         as_bad (_("`%s' is not a valid base/index expression"),
6078                 operand_string);
6079       else
6080 #endif
6081         as_bad (_("`%s' is not a valid %s bit base/index expression"),
6082                 operand_string,
6083                 flag_code_names[flag_code]);
6084     }
6085   return ok;
6086 }
6087
6088 /* Parse OPERAND_STRING into the i386_insn structure I.  Returns non-zero
6089    on error.  */
6090
6091 static int
6092 i386_operand (char *operand_string)
6093 {
6094   const reg_entry *r;
6095   char *end_op;
6096   char *op_string = operand_string;
6097
6098   if (is_space_char (*op_string))
6099     ++op_string;
6100
6101   /* We check for an absolute prefix (differentiating,
6102      for example, 'jmp pc_relative_label' from 'jmp *absolute_label'.  */
6103   if (*op_string == ABSOLUTE_PREFIX)
6104     {
6105       ++op_string;
6106       if (is_space_char (*op_string))
6107         ++op_string;
6108       i.types[this_operand].bitfield.jumpabsolute = 1;
6109     }
6110
6111   /* Check if operand is a register.  */
6112   if ((r = parse_register (op_string, &end_op)) != NULL)
6113     {
6114       i386_operand_type temp;
6115
6116       /* Check for a segment override by searching for ':' after a
6117          segment register.  */
6118       op_string = end_op;
6119       if (is_space_char (*op_string))
6120         ++op_string;
6121       if (*op_string == ':'
6122           && (r->reg_type.bitfield.sreg2
6123               || r->reg_type.bitfield.sreg3))
6124         {
6125           switch (r->reg_num)
6126             {
6127             case 0:
6128               i.seg[i.mem_operands] = &es;
6129               break;
6130             case 1:
6131               i.seg[i.mem_operands] = &cs;
6132               break;
6133             case 2:
6134               i.seg[i.mem_operands] = &ss;
6135               break;
6136             case 3:
6137               i.seg[i.mem_operands] = &ds;
6138               break;
6139             case 4:
6140               i.seg[i.mem_operands] = &fs;
6141               break;
6142             case 5:
6143               i.seg[i.mem_operands] = &gs;
6144               break;
6145             }
6146
6147           /* Skip the ':' and whitespace.  */
6148           ++op_string;
6149           if (is_space_char (*op_string))
6150             ++op_string;
6151
6152           if (!is_digit_char (*op_string)
6153               && !is_identifier_char (*op_string)
6154               && *op_string != '('
6155               && *op_string != ABSOLUTE_PREFIX)
6156             {
6157               as_bad (_("bad memory operand `%s'"), op_string);
6158               return 0;
6159             }
6160           /* Handle case of %es:*foo.  */
6161           if (*op_string == ABSOLUTE_PREFIX)
6162             {
6163               ++op_string;
6164               if (is_space_char (*op_string))
6165                 ++op_string;
6166               i.types[this_operand].bitfield.jumpabsolute = 1;
6167             }
6168           goto do_memory_reference;
6169         }
6170       if (*op_string)
6171         {
6172           as_bad (_("junk `%s' after register"), op_string);
6173           return 0;
6174         }
6175       temp = r->reg_type;
6176       temp.bitfield.baseindex = 0;
6177       i.types[this_operand] = operand_type_or (i.types[this_operand],
6178                                                temp);
6179       i.op[this_operand].regs = r;
6180       i.reg_operands++;
6181     }
6182   else if (*op_string == REGISTER_PREFIX)
6183     {
6184       as_bad (_("bad register name `%s'"), op_string);
6185       return 0;
6186     }
6187   else if (*op_string == IMMEDIATE_PREFIX)
6188     {
6189       ++op_string;
6190       if (i.types[this_operand].bitfield.jumpabsolute)
6191         {
6192           as_bad (_("immediate operand illegal with absolute jump"));
6193           return 0;
6194         }
6195       if (!i386_immediate (op_string))
6196         return 0;
6197     }
6198   else if (is_digit_char (*op_string)
6199            || is_identifier_char (*op_string)
6200            || *op_string == '(')
6201     {
6202       /* This is a memory reference of some sort.  */
6203       char *base_string;
6204
6205       /* Start and end of displacement string expression (if found).  */
6206       char *displacement_string_start;
6207       char *displacement_string_end;
6208
6209     do_memory_reference:
6210       if ((i.mem_operands == 1
6211            && !current_templates->start->opcode_modifier.isstring)
6212           || i.mem_operands == 2)
6213         {
6214           as_bad (_("too many memory references for `%s'"),
6215                   current_templates->start->name);
6216           return 0;
6217         }
6218
6219       /* Check for base index form.  We detect the base index form by
6220          looking for an ')' at the end of the operand, searching
6221          for the '(' matching it, and finding a REGISTER_PREFIX or ','
6222          after the '('.  */
6223       base_string = op_string + strlen (op_string);
6224
6225       --base_string;
6226       if (is_space_char (*base_string))
6227         --base_string;
6228
6229       /* If we only have a displacement, set-up for it to be parsed later.  */
6230       displacement_string_start = op_string;
6231       displacement_string_end = base_string + 1;
6232
6233       if (*base_string == ')')
6234         {
6235           char *temp_string;
6236           unsigned int parens_balanced = 1;
6237           /* We've already checked that the number of left & right ()'s are
6238              equal, so this loop will not be infinite.  */
6239           do
6240             {
6241               base_string--;
6242               if (*base_string == ')')
6243                 parens_balanced++;
6244               if (*base_string == '(')
6245                 parens_balanced--;
6246             }
6247           while (parens_balanced);
6248
6249           temp_string = base_string;
6250
6251           /* Skip past '(' and whitespace.  */
6252           ++base_string;
6253           if (is_space_char (*base_string))
6254             ++base_string;
6255
6256           if (*base_string == ','
6257               || ((i.base_reg = parse_register (base_string, &end_op))
6258                   != NULL))
6259             {
6260               displacement_string_end = temp_string;
6261
6262               i.types[this_operand].bitfield.baseindex = 1;
6263
6264               if (i.base_reg)
6265                 {
6266                   base_string = end_op;
6267                   if (is_space_char (*base_string))
6268                     ++base_string;
6269                 }
6270
6271               /* There may be an index reg or scale factor here.  */
6272               if (*base_string == ',')
6273                 {
6274                   ++base_string;
6275                   if (is_space_char (*base_string))
6276                     ++base_string;
6277
6278                   if ((i.index_reg = parse_register (base_string, &end_op))
6279                       != NULL)
6280                     {
6281                       base_string = end_op;
6282                       if (is_space_char (*base_string))
6283                         ++base_string;
6284                       if (*base_string == ',')
6285                         {
6286                           ++base_string;
6287                           if (is_space_char (*base_string))
6288                             ++base_string;
6289                         }
6290                       else if (*base_string != ')')
6291                         {
6292                           as_bad (_("expecting `,' or `)' "
6293                                     "after index register in `%s'"),
6294                                   operand_string);
6295                           return 0;
6296                         }
6297                     }
6298                   else if (*base_string == REGISTER_PREFIX)
6299                     {
6300                       as_bad (_("bad register name `%s'"), base_string);
6301                       return 0;
6302                     }
6303
6304                   /* Check for scale factor.  */
6305                   if (*base_string != ')')
6306                     {
6307                       char *end_scale = i386_scale (base_string);
6308
6309                       if (!end_scale)
6310                         return 0;
6311
6312                       base_string = end_scale;
6313                       if (is_space_char (*base_string))
6314                         ++base_string;
6315                       if (*base_string != ')')
6316                         {
6317                           as_bad (_("expecting `)' "
6318                                     "after scale factor in `%s'"),
6319                                   operand_string);
6320                           return 0;
6321                         }
6322                     }
6323                   else if (!i.index_reg)
6324                     {
6325                       as_bad (_("expecting index register or scale factor "
6326                                 "after `,'; got '%c'"),
6327                               *base_string);
6328                       return 0;
6329                     }
6330                 }
6331               else if (*base_string != ')')
6332                 {
6333                   as_bad (_("expecting `,' or `)' "
6334                             "after base register in `%s'"),
6335                           operand_string);
6336                   return 0;
6337                 }
6338             }
6339           else if (*base_string == REGISTER_PREFIX)
6340             {
6341               as_bad (_("bad register name `%s'"), base_string);
6342               return 0;
6343             }
6344         }
6345
6346       /* If there's an expression beginning the operand, parse it,
6347          assuming displacement_string_start and
6348          displacement_string_end are meaningful.  */
6349       if (displacement_string_start != displacement_string_end)
6350         {
6351           if (!i386_displacement (displacement_string_start,
6352                                   displacement_string_end))
6353             return 0;
6354         }
6355
6356       /* Special case for (%dx) while doing input/output op.  */
6357       if (i.base_reg
6358           && UINTS_EQUAL (i.base_reg->reg_type, reg16_inoutportreg)
6359           && i.index_reg == 0
6360           && i.log2_scale_factor == 0
6361           && i.seg[i.mem_operands] == 0
6362           && !operand_type_check (i.types[this_operand], disp))
6363         {
6364           UINTS_CLEAR (i.types[this_operand]);
6365           i.types[this_operand].bitfield.inoutportreg = 1;
6366           return 1;
6367         }
6368
6369       if (i386_index_check (operand_string) == 0)
6370         return 0;
6371       i.mem_operands++;
6372     }
6373   else
6374     {
6375       /* It's not a memory operand; argh!  */
6376       as_bad (_("invalid char %s beginning operand %d `%s'"),
6377               output_invalid (*op_string),
6378               this_operand + 1,
6379               op_string);
6380       return 0;
6381     }
6382   return 1;                     /* Normal return.  */
6383 }
6384 \f
6385 /* md_estimate_size_before_relax()
6386
6387    Called just before relax() for rs_machine_dependent frags.  The x86
6388    assembler uses these frags to handle variable size jump
6389    instructions.
6390
6391    Any symbol that is now undefined will not become defined.
6392    Return the correct fr_subtype in the frag.
6393    Return the initial "guess for variable size of frag" to caller.
6394    The guess is actually the growth beyond the fixed part.  Whatever
6395    we do to grow the fixed or variable part contributes to our
6396    returned value.  */
6397
6398 int
6399 md_estimate_size_before_relax (fragP, segment)
6400      fragS *fragP;
6401      segT segment;
6402 {
6403   /* We've already got fragP->fr_subtype right;  all we have to do is
6404      check for un-relaxable symbols.  On an ELF system, we can't relax
6405      an externally visible symbol, because it may be overridden by a
6406      shared library.  */
6407   if (S_GET_SEGMENT (fragP->fr_symbol) != segment
6408 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
6409       || (IS_ELF
6410           && (S_IS_EXTERNAL (fragP->fr_symbol)
6411               || S_IS_WEAK (fragP->fr_symbol)))
6412 #endif
6413       )
6414     {
6415       /* Symbol is undefined in this segment, or we need to keep a
6416          reloc so that weak symbols can be overridden.  */
6417       int size = (fragP->fr_subtype & CODE16) ? 2 : 4;
6418       enum bfd_reloc_code_real reloc_type;
6419       unsigned char *opcode;
6420       int old_fr_fix;
6421
6422       if (fragP->fr_var != NO_RELOC)
6423         reloc_type = fragP->fr_var;
6424       else if (size == 2)
6425         reloc_type = BFD_RELOC_16_PCREL;
6426       else
6427         reloc_type = BFD_RELOC_32_PCREL;
6428
6429       old_fr_fix = fragP->fr_fix;
6430       opcode = (unsigned char *) fragP->fr_opcode;
6431
6432       switch (TYPE_FROM_RELAX_STATE (fragP->fr_subtype))
6433         {
6434         case UNCOND_JUMP:
6435           /* Make jmp (0xeb) a (d)word displacement jump.  */
6436           opcode[0] = 0xe9;
6437           fragP->fr_fix += size;
6438           fix_new (fragP, old_fr_fix, size,
6439                    fragP->fr_symbol,
6440                    fragP->fr_offset, 1,
6441                    reloc_type);
6442           break;
6443
6444         case COND_JUMP86:
6445           if (size == 2
6446               && (!no_cond_jump_promotion || fragP->fr_var != NO_RELOC))
6447             {
6448               /* Negate the condition, and branch past an
6449                  unconditional jump.  */
6450               opcode[0] ^= 1;
6451               opcode[1] = 3;
6452               /* Insert an unconditional jump.  */
6453               opcode[2] = 0xe9;
6454               /* We added two extra opcode bytes, and have a two byte
6455                  offset.  */
6456               fragP->fr_fix += 2 + 2;
6457               fix_new (fragP, old_fr_fix + 2, 2,
6458                        fragP->fr_symbol,
6459                        fragP->fr_offset, 1,
6460                        reloc_type);
6461               break;
6462             }
6463           /* Fall through.  */
6464
6465         case COND_JUMP:
6466           if (no_cond_jump_promotion && fragP->fr_var == NO_RELOC)
6467             {
6468               fixS *fixP;
6469
6470               fragP->fr_fix += 1;
6471               fixP = fix_new (fragP, old_fr_fix, 1,
6472                               fragP->fr_symbol,
6473                               fragP->fr_offset, 1,
6474                               BFD_RELOC_8_PCREL);
6475               fixP->fx_signed = 1;
6476               break;
6477             }
6478
6479           /* This changes the byte-displacement jump 0x7N
6480              to the (d)word-displacement jump 0x0f,0x8N.  */
6481           opcode[1] = opcode[0] + 0x10;
6482           opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
6483           /* We've added an opcode byte.  */
6484           fragP->fr_fix += 1 + size;
6485           fix_new (fragP, old_fr_fix + 1, size,
6486                    fragP->fr_symbol,
6487                    fragP->fr_offset, 1,
6488                    reloc_type);
6489           break;
6490
6491         default:
6492           BAD_CASE (fragP->fr_subtype);
6493           break;
6494         }
6495       frag_wane (fragP);
6496       return fragP->fr_fix - old_fr_fix;
6497     }
6498
6499   /* Guess size depending on current relax state.  Initially the relax
6500      state will correspond to a short jump and we return 1, because
6501      the variable part of the frag (the branch offset) is one byte
6502      long.  However, we can relax a section more than once and in that
6503      case we must either set fr_subtype back to the unrelaxed state,
6504      or return the value for the appropriate branch.  */
6505   return md_relax_table[fragP->fr_subtype].rlx_length;
6506 }
6507
6508 /* Called after relax() is finished.
6509
6510    In:  Address of frag.
6511         fr_type == rs_machine_dependent.
6512         fr_subtype is what the address relaxed to.
6513
6514    Out: Any fixSs and constants are set up.
6515         Caller will turn frag into a ".space 0".  */
6516
6517 void
6518 md_convert_frag (abfd, sec, fragP)
6519      bfd *abfd ATTRIBUTE_UNUSED;
6520      segT sec ATTRIBUTE_UNUSED;
6521      fragS *fragP;
6522 {
6523   unsigned char *opcode;
6524   unsigned char *where_to_put_displacement = NULL;
6525   offsetT target_address;
6526   offsetT opcode_address;
6527   unsigned int extension = 0;
6528   offsetT displacement_from_opcode_start;
6529
6530   opcode = (unsigned char *) fragP->fr_opcode;
6531
6532   /* Address we want to reach in file space.  */
6533   target_address = S_GET_VALUE (fragP->fr_symbol) + fragP->fr_offset;
6534
6535   /* Address opcode resides at in file space.  */
6536   opcode_address = fragP->fr_address + fragP->fr_fix;
6537
6538   /* Displacement from opcode start to fill into instruction.  */
6539   displacement_from_opcode_start = target_address - opcode_address;
6540
6541   if ((fragP->fr_subtype & BIG) == 0)
6542     {
6543       /* Don't have to change opcode.  */
6544       extension = 1;            /* 1 opcode + 1 displacement  */
6545       where_to_put_displacement = &opcode[1];
6546     }
6547   else
6548     {
6549       if (no_cond_jump_promotion
6550           && TYPE_FROM_RELAX_STATE (fragP->fr_subtype) != UNCOND_JUMP)
6551         as_warn_where (fragP->fr_file, fragP->fr_line,
6552                        _("long jump required"));
6553
6554       switch (fragP->fr_subtype)
6555         {
6556         case ENCODE_RELAX_STATE (UNCOND_JUMP, BIG):
6557           extension = 4;                /* 1 opcode + 4 displacement  */
6558           opcode[0] = 0xe9;
6559           where_to_put_displacement = &opcode[1];
6560           break;
6561
6562         case ENCODE_RELAX_STATE (UNCOND_JUMP, BIG16):
6563           extension = 2;                /* 1 opcode + 2 displacement  */
6564           opcode[0] = 0xe9;
6565           where_to_put_displacement = &opcode[1];
6566           break;
6567
6568         case ENCODE_RELAX_STATE (COND_JUMP, BIG):
6569         case ENCODE_RELAX_STATE (COND_JUMP86, BIG):
6570           extension = 5;                /* 2 opcode + 4 displacement  */
6571           opcode[1] = opcode[0] + 0x10;
6572           opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
6573           where_to_put_displacement = &opcode[2];
6574           break;
6575
6576         case ENCODE_RELAX_STATE (COND_JUMP, BIG16):
6577           extension = 3;                /* 2 opcode + 2 displacement  */
6578           opcode[1] = opcode[0] + 0x10;
6579           opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
6580           where_to_put_displacement = &opcode[2];
6581           break;
6582
6583         case ENCODE_RELAX_STATE (COND_JUMP86, BIG16):
6584           extension = 4;
6585           opcode[0] ^= 1;
6586           opcode[1] = 3;
6587           opcode[2] = 0xe9;
6588           where_to_put_displacement = &opcode[3];
6589           break;
6590
6591         default:
6592           BAD_CASE (fragP->fr_subtype);
6593           break;
6594         }
6595     }
6596
6597   /* If size if less then four we are sure that the operand fits,
6598      but if it's 4, then it could be that the displacement is larger
6599      then -/+ 2GB.  */
6600   if (DISP_SIZE_FROM_RELAX_STATE (fragP->fr_subtype) == 4
6601       && object_64bit
6602       && ((addressT) (displacement_from_opcode_start - extension
6603                       + ((addressT) 1 << 31))
6604           > (((addressT) 2 << 31) - 1)))
6605     {
6606       as_bad_where (fragP->fr_file, fragP->fr_line,
6607                     _("jump target out of range"));
6608       /* Make us emit 0.  */
6609       displacement_from_opcode_start = extension;
6610     }
6611   /* Now put displacement after opcode.  */
6612   md_number_to_chars ((char *) where_to_put_displacement,
6613                       (valueT) (displacement_from_opcode_start - extension),
6614                       DISP_SIZE_FROM_RELAX_STATE (fragP->fr_subtype));
6615   fragP->fr_fix += extension;
6616 }
6617 \f
6618 /* Apply a fixup (fixS) to segment data, once it has been determined
6619    by our caller that we have all the info we need to fix it up.
6620
6621    On the 386, immediates, displacements, and data pointers are all in
6622    the same (little-endian) format, so we don't need to care about which
6623    we are handling.  */
6624
6625 void
6626 md_apply_fix (fixP, valP, seg)
6627      /* The fix we're to put in.  */
6628      fixS *fixP;
6629      /* Pointer to the value of the bits.  */
6630      valueT *valP;
6631      /* Segment fix is from.  */
6632      segT seg ATTRIBUTE_UNUSED;
6633 {
6634   char *p = fixP->fx_where + fixP->fx_frag->fr_literal;
6635   valueT value = *valP;
6636
6637 #if !defined (TE_Mach)
6638   if (fixP->fx_pcrel)
6639     {
6640       switch (fixP->fx_r_type)
6641         {
6642         default:
6643           break;
6644
6645         case BFD_RELOC_64:
6646           fixP->fx_r_type = BFD_RELOC_64_PCREL;
6647           break;
6648         case BFD_RELOC_32:
6649         case BFD_RELOC_X86_64_32S:
6650           fixP->fx_r_type = BFD_RELOC_32_PCREL;
6651           break;
6652         case BFD_RELOC_16:
6653           fixP->fx_r_type = BFD_RELOC_16_PCREL;
6654           break;
6655         case BFD_RELOC_8:
6656           fixP->fx_r_type = BFD_RELOC_8_PCREL;
6657           break;
6658         }
6659     }
6660
6661   if (fixP->fx_addsy != NULL
6662       && (fixP->fx_r_type == BFD_RELOC_32_PCREL
6663           || fixP->fx_r_type == BFD_RELOC_64_PCREL
6664           || fixP->fx_r_type == BFD_RELOC_16_PCREL
6665           || fixP->fx_r_type == BFD_RELOC_8_PCREL)
6666       && !use_rela_relocations)
6667     {
6668       /* This is a hack.  There should be a better way to handle this.
6669          This covers for the fact that bfd_install_relocation will
6670          subtract the current location (for partial_inplace, PC relative
6671          relocations); see more below.  */
6672 #ifndef OBJ_AOUT
6673       if (IS_ELF
6674 #ifdef TE_PE
6675           || OUTPUT_FLAVOR == bfd_target_coff_flavour
6676 #endif
6677           )
6678         value += fixP->fx_where + fixP->fx_frag->fr_address;
6679 #endif
6680 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
6681       if (IS_ELF)
6682         {
6683           segT sym_seg = S_GET_SEGMENT (fixP->fx_addsy);
6684
6685           if ((sym_seg == seg
6686                || (symbol_section_p (fixP->fx_addsy)
6687                    && sym_seg != absolute_section))
6688               && !generic_force_reloc (fixP))
6689             {
6690               /* Yes, we add the values in twice.  This is because
6691                  bfd_install_relocation subtracts them out again.  I think
6692                  bfd_install_relocation is broken, but I don't dare change
6693                  it.  FIXME.  */
6694               value += fixP->fx_where + fixP->fx_frag->fr_address;
6695             }
6696         }
6697 #endif
6698 #if defined (OBJ_COFF) && defined (TE_PE)
6699       /* For some reason, the PE format does not store a
6700          section address offset for a PC relative symbol.  */
6701       if (S_GET_SEGMENT (fixP->fx_addsy) != seg
6702           || S_IS_WEAK (fixP->fx_addsy))
6703         value += md_pcrel_from (fixP);
6704 #endif
6705     }
6706
6707   /* Fix a few things - the dynamic linker expects certain values here,
6708      and we must not disappoint it.  */
6709 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
6710   if (IS_ELF && fixP->fx_addsy)
6711     switch (fixP->fx_r_type)
6712       {
6713       case BFD_RELOC_386_PLT32:
6714       case BFD_RELOC_X86_64_PLT32:
6715         /* Make the jump instruction point to the address of the operand.  At
6716            runtime we merely add the offset to the actual PLT entry.  */
6717         value = -4;
6718         break;
6719
6720       case BFD_RELOC_386_TLS_GD:
6721       case BFD_RELOC_386_TLS_LDM:
6722       case BFD_RELOC_386_TLS_IE_32:
6723       case BFD_RELOC_386_TLS_IE:
6724       case BFD_RELOC_386_TLS_GOTIE:
6725       case BFD_RELOC_386_TLS_GOTDESC:
6726       case BFD_RELOC_X86_64_TLSGD:
6727       case BFD_RELOC_X86_64_TLSLD:
6728       case BFD_RELOC_X86_64_GOTTPOFF:
6729       case BFD_RELOC_X86_64_GOTPC32_TLSDESC:
6730         value = 0; /* Fully resolved at runtime.  No addend.  */
6731         /* Fallthrough */
6732       case BFD_RELOC_386_TLS_LE:
6733       case BFD_RELOC_386_TLS_LDO_32:
6734       case BFD_RELOC_386_TLS_LE_32:
6735       case BFD_RELOC_X86_64_DTPOFF32:
6736       case BFD_RELOC_X86_64_DTPOFF64:
6737       case BFD_RELOC_X86_64_TPOFF32:
6738       case BFD_RELOC_X86_64_TPOFF64:
6739         S_SET_THREAD_LOCAL (fixP->fx_addsy);
6740         break;
6741
6742       case BFD_RELOC_386_TLS_DESC_CALL:
6743       case BFD_RELOC_X86_64_TLSDESC_CALL:
6744         value = 0; /* Fully resolved at runtime.  No addend.  */
6745         S_SET_THREAD_LOCAL (fixP->fx_addsy);
6746         fixP->fx_done = 0;
6747         return;
6748
6749       case BFD_RELOC_386_GOT32:
6750       case BFD_RELOC_X86_64_GOT32:
6751         value = 0; /* Fully resolved at runtime.  No addend.  */
6752         break;
6753
6754       case BFD_RELOC_VTABLE_INHERIT:
6755       case BFD_RELOC_VTABLE_ENTRY:
6756         fixP->fx_done = 0;
6757         return;
6758
6759       default:
6760         break;
6761       }
6762 #endif /* defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)  */
6763   *valP = value;
6764 #endif /* !defined (TE_Mach)  */
6765
6766   /* Are we finished with this relocation now?  */
6767   if (fixP->fx_addsy == NULL)
6768     fixP->fx_done = 1;
6769   else if (use_rela_relocations)
6770     {
6771       fixP->fx_no_overflow = 1;
6772       /* Remember value for tc_gen_reloc.  */
6773       fixP->fx_addnumber = value;
6774       value = 0;
6775     }
6776
6777   md_number_to_chars (p, value, fixP->fx_size);
6778 }
6779 \f
6780 char *
6781 md_atof (int type, char *litP, int *sizeP)
6782 {
6783   /* This outputs the LITTLENUMs in REVERSE order;
6784      in accord with the bigendian 386.  */
6785   return ieee_md_atof (type, litP, sizeP, FALSE);
6786 }
6787 \f
6788 static char output_invalid_buf[sizeof (unsigned char) * 2 + 6];
6789
6790 static char *
6791 output_invalid (int c)
6792 {
6793   if (ISPRINT (c))
6794     snprintf (output_invalid_buf, sizeof (output_invalid_buf),
6795               "'%c'", c);
6796   else
6797     snprintf (output_invalid_buf, sizeof (output_invalid_buf),
6798               "(0x%x)", (unsigned char) c);
6799   return output_invalid_buf;
6800 }
6801
6802 /* REG_STRING starts *before* REGISTER_PREFIX.  */
6803
6804 static const reg_entry *
6805 parse_real_register (char *reg_string, char **end_op)
6806 {
6807   char *s = reg_string;
6808   char *p;
6809   char reg_name_given[MAX_REG_NAME_SIZE + 1];
6810   const reg_entry *r;
6811
6812   /* Skip possible REGISTER_PREFIX and possible whitespace.  */
6813   if (*s == REGISTER_PREFIX)
6814     ++s;
6815
6816   if (is_space_char (*s))
6817     ++s;
6818
6819   p = reg_name_given;
6820   while ((*p++ = register_chars[(unsigned char) *s]) != '\0')
6821     {
6822       if (p >= reg_name_given + MAX_REG_NAME_SIZE)
6823         return (const reg_entry *) NULL;
6824       s++;
6825     }
6826
6827   /* For naked regs, make sure that we are not dealing with an identifier.
6828      This prevents confusing an identifier like `eax_var' with register
6829      `eax'.  */
6830   if (allow_naked_reg && identifier_chars[(unsigned char) *s])
6831     return (const reg_entry *) NULL;
6832
6833   *end_op = s;
6834
6835   r = (const reg_entry *) hash_find (reg_hash, reg_name_given);
6836
6837   /* Handle floating point regs, allowing spaces in the (i) part.  */
6838   if (r == i386_regtab /* %st is first entry of table  */)
6839     {
6840       if (is_space_char (*s))
6841         ++s;
6842       if (*s == '(')
6843         {
6844           ++s;
6845           if (is_space_char (*s))
6846             ++s;
6847           if (*s >= '0' && *s <= '7')
6848             {
6849               int fpr = *s - '0';
6850               ++s;
6851               if (is_space_char (*s))
6852                 ++s;
6853               if (*s == ')')
6854                 {
6855                   *end_op = s + 1;
6856                   r = hash_find (reg_hash, "st(0)");
6857                   know (r);
6858                   return r + fpr;
6859                 }
6860             }
6861           /* We have "%st(" then garbage.  */
6862           return (const reg_entry *) NULL;
6863         }
6864     }
6865
6866   /* Don't allow fake index register unless allow_index_reg isn't 0. */
6867   if (r != NULL
6868       && !allow_index_reg
6869       && (r->reg_num == RegEiz || r->reg_num == RegRiz))
6870     return (const reg_entry *) NULL;
6871
6872   if (r != NULL
6873       && ((r->reg_flags & (RegRex64 | RegRex))
6874           || r->reg_type.bitfield.reg64)
6875       && (!cpu_arch_flags.bitfield.cpulm
6876           || !UINTS_EQUAL (r->reg_type, control))
6877       && flag_code != CODE_64BIT)
6878     return (const reg_entry *) NULL;
6879
6880   return r;
6881 }
6882
6883 /* REG_STRING starts *before* REGISTER_PREFIX.  */
6884
6885 static const reg_entry *
6886 parse_register (char *reg_string, char **end_op)
6887 {
6888   const reg_entry *r;
6889
6890   if (*reg_string == REGISTER_PREFIX || allow_naked_reg)
6891     r = parse_real_register (reg_string, end_op);
6892   else
6893     r = NULL;
6894   if (!r)
6895     {
6896       char *save = input_line_pointer;
6897       char c;
6898       symbolS *symbolP;
6899
6900       input_line_pointer = reg_string;
6901       c = get_symbol_end ();
6902       symbolP = symbol_find (reg_string);
6903       if (symbolP && S_GET_SEGMENT (symbolP) == reg_section)
6904         {
6905           const expressionS *e = symbol_get_value_expression (symbolP);
6906
6907           know (e->X_op == O_register);
6908           know (e->X_add_number >= 0
6909                 && (valueT) e->X_add_number < i386_regtab_size);
6910           r = i386_regtab + e->X_add_number;
6911           *end_op = input_line_pointer;
6912         }
6913       *input_line_pointer = c;
6914       input_line_pointer = save;
6915     }
6916   return r;
6917 }
6918
6919 int
6920 i386_parse_name (char *name, expressionS *e, char *nextcharP)
6921 {
6922   const reg_entry *r;
6923   char *end = input_line_pointer;
6924
6925   *end = *nextcharP;
6926   r = parse_register (name, &input_line_pointer);
6927   if (r && end <= input_line_pointer)
6928     {
6929       *nextcharP = *input_line_pointer;
6930       *input_line_pointer = 0;
6931       e->X_op = O_register;
6932       e->X_add_number = r - i386_regtab;
6933       return 1;
6934     }
6935   input_line_pointer = end;
6936   *end = 0;
6937   return 0;
6938 }
6939
6940 void
6941 md_operand (expressionS *e)
6942 {
6943   if (*input_line_pointer == REGISTER_PREFIX)
6944     {
6945       char *end;
6946       const reg_entry *r = parse_real_register (input_line_pointer, &end);
6947
6948       if (r)
6949         {
6950           e->X_op = O_register;
6951           e->X_add_number = r - i386_regtab;
6952           input_line_pointer = end;
6953         }
6954     }
6955 }
6956
6957 \f
6958 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
6959 const char *md_shortopts = "kVQ:sqn";
6960 #else
6961 const char *md_shortopts = "qn";
6962 #endif
6963
6964 #define OPTION_32 (OPTION_MD_BASE + 0)
6965 #define OPTION_64 (OPTION_MD_BASE + 1)
6966 #define OPTION_DIVIDE (OPTION_MD_BASE + 2)
6967 #define OPTION_MARCH (OPTION_MD_BASE + 3)
6968 #define OPTION_MTUNE (OPTION_MD_BASE + 4)
6969 #define OPTION_MMNEMONIC (OPTION_MD_BASE + 5)
6970 #define OPTION_MSYNTAX (OPTION_MD_BASE + 6)
6971 #define OPTION_MINDEX_REG (OPTION_MD_BASE + 7)
6972 #define OPTION_MNAKED_REG (OPTION_MD_BASE + 8)
6973 #define OPTION_MOLD_GCC (OPTION_MD_BASE + 9)
6974
6975 struct option md_longopts[] =
6976 {
6977   {"32", no_argument, NULL, OPTION_32},
6978 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) || defined(TE_PEP)
6979   {"64", no_argument, NULL, OPTION_64},
6980 #endif
6981   {"divide", no_argument, NULL, OPTION_DIVIDE},
6982   {"march", required_argument, NULL, OPTION_MARCH},
6983   {"mtune", required_argument, NULL, OPTION_MTUNE},
6984   {"mmnemonic", required_argument, NULL, OPTION_MMNEMONIC},
6985   {"msyntax", required_argument, NULL, OPTION_MSYNTAX},
6986   {"mindex-reg", no_argument, NULL, OPTION_MINDEX_REG},
6987   {"mnaked-reg", no_argument, NULL, OPTION_MNAKED_REG},
6988   {"mold-gcc", no_argument, NULL, OPTION_MOLD_GCC},
6989   {NULL, no_argument, NULL, 0}
6990 };
6991 size_t md_longopts_size = sizeof (md_longopts);
6992
6993 int
6994 md_parse_option (int c, char *arg)
6995 {
6996   unsigned int i;
6997
6998   switch (c)
6999     {
7000     case 'n':
7001       optimize_align_code = 0;
7002       break;
7003
7004     case 'q':
7005       quiet_warnings = 1;
7006       break;
7007
7008 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7009       /* -Qy, -Qn: SVR4 arguments controlling whether a .comment section
7010          should be emitted or not.  FIXME: Not implemented.  */
7011     case 'Q':
7012       break;
7013
7014       /* -V: SVR4 argument to print version ID.  */
7015     case 'V':
7016       print_version_id ();
7017       break;
7018
7019       /* -k: Ignore for FreeBSD compatibility.  */
7020     case 'k':
7021       break;
7022
7023     case 's':
7024       /* -s: On i386 Solaris, this tells the native assembler to use
7025          .stab instead of .stab.excl.  We always use .stab anyhow.  */
7026       break;
7027 #endif
7028 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) || defined(TE_PEP)
7029     case OPTION_64:
7030       {
7031         const char **list, **l;
7032
7033         list = bfd_target_list ();
7034         for (l = list; *l != NULL; l++)
7035           if (CONST_STRNEQ (*l, "elf64-x86-64")
7036               || strcmp (*l, "coff-x86-64") == 0
7037               || strcmp (*l, "pe-x86-64") == 0
7038               || strcmp (*l, "pei-x86-64") == 0)
7039             {
7040               default_arch = "x86_64";
7041               break;
7042             }
7043         if (*l == NULL)
7044           as_fatal (_("No compiled in support for x86_64"));
7045         free (list);
7046       }
7047       break;
7048 #endif
7049
7050     case OPTION_32:
7051       default_arch = "i386";
7052       break;
7053
7054     case OPTION_DIVIDE:
7055 #ifdef SVR4_COMMENT_CHARS
7056       {
7057         char *n, *t;
7058         const char *s;
7059
7060         n = (char *) xmalloc (strlen (i386_comment_chars) + 1);
7061         t = n;
7062         for (s = i386_comment_chars; *s != '\0'; s++)
7063           if (*s != '/')
7064             *t++ = *s;
7065         *t = '\0';
7066         i386_comment_chars = n;
7067       }
7068 #endif
7069       break;
7070
7071     case OPTION_MARCH:
7072       if (*arg == '.')
7073         as_fatal (_("Invalid -march= option: `%s'"), arg);
7074       for (i = 0; i < ARRAY_SIZE (cpu_arch); i++)
7075         {
7076           if (strcmp (arg, cpu_arch [i].name) == 0)
7077             {
7078               cpu_arch_isa = cpu_arch[i].type;
7079               cpu_arch_isa_flags = cpu_arch[i].flags;
7080               if (!cpu_arch_tune_set)
7081                 {
7082                   cpu_arch_tune = cpu_arch_isa;
7083                   cpu_arch_tune_flags = cpu_arch_isa_flags;
7084                 }
7085               break;
7086             }
7087         }
7088       if (i >= ARRAY_SIZE (cpu_arch))
7089         as_fatal (_("Invalid -march= option: `%s'"), arg);
7090       break;
7091
7092     case OPTION_MTUNE:
7093       if (*arg == '.')
7094         as_fatal (_("Invalid -mtune= option: `%s'"), arg);
7095       for (i = 0; i < ARRAY_SIZE (cpu_arch); i++)
7096         {
7097           if (strcmp (arg, cpu_arch [i].name) == 0)
7098             {
7099               cpu_arch_tune_set = 1;
7100               cpu_arch_tune = cpu_arch [i].type;
7101               cpu_arch_tune_flags = cpu_arch[i].flags;
7102               break;
7103             }
7104         }
7105       if (i >= ARRAY_SIZE (cpu_arch))
7106         as_fatal (_("Invalid -mtune= option: `%s'"), arg);
7107       break;
7108
7109     case OPTION_MMNEMONIC:
7110       if (strcasecmp (arg, "att") == 0)
7111         intel_mnemonic = 0;
7112       else if (strcasecmp (arg, "intel") == 0)
7113         intel_mnemonic = 1;
7114       else
7115         as_fatal (_("Invalid -mmnemonic= option: `%s'"), arg);
7116       break;
7117
7118     case OPTION_MSYNTAX:
7119       if (strcasecmp (arg, "att") == 0)
7120         intel_syntax = 0;
7121       else if (strcasecmp (arg, "intel") == 0)
7122         intel_syntax = 1;
7123       else
7124         as_fatal (_("Invalid -msyntax= option: `%s'"), arg);
7125       break;
7126
7127     case OPTION_MINDEX_REG:
7128       allow_index_reg = 1;
7129       break;
7130
7131     case OPTION_MNAKED_REG:
7132       allow_naked_reg = 1;
7133       break;
7134
7135     case OPTION_MOLD_GCC:
7136       old_gcc = 1;
7137       intel_mnemonic = 0;
7138       break;
7139
7140     default:
7141       return 0;
7142     }
7143   return 1;
7144 }
7145
7146 void
7147 md_show_usage (stream)
7148      FILE *stream;
7149 {
7150 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7151   fprintf (stream, _("\
7152   -Q                      ignored\n\
7153   -V                      print assembler version number\n\
7154   -k                      ignored\n"));
7155 #endif
7156   fprintf (stream, _("\
7157   -n                      Do not optimize code alignment\n\
7158   -q                      quieten some warnings\n"));
7159 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7160   fprintf (stream, _("\
7161   -s                      ignored\n"));
7162 #endif
7163 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) || defined(TE_PEP)
7164   fprintf (stream, _("\
7165   --32/--64               generate 32bit/64bit code\n"));
7166 #endif
7167 #ifdef SVR4_COMMENT_CHARS
7168   fprintf (stream, _("\
7169   --divide                do not treat `/' as a comment character\n"));
7170 #else
7171   fprintf (stream, _("\
7172   --divide                ignored\n"));
7173 #endif
7174   fprintf (stream, _("\
7175   -march=CPU/-mtune=CPU   generate code/optimize for CPU, where CPU is one of:\n\
7176                            i386, i486, pentium, pentiumpro, pentium4, nocona,\n\
7177                            core, core2, k6, athlon, k8, generic32, generic64\n"));
7178   fprintf (stream, _("\
7179   -mmnemonic=[att|intel]  use AT&T/Intel mnemonic\n"));
7180   fprintf (stream, _("\
7181   -msyntax=[att|intel]    use AT&T/Intel syntax\n"));
7182   fprintf (stream, _("\
7183   -mindex-reg             support pseudo index registers\n"));
7184   fprintf (stream, _("\
7185   -mnaked-reg             don't require `%%' prefix for registers\n"));
7186   fprintf (stream, _("\
7187   -mold-gcc               support old (<= 2.8.1) versions of gcc\n"));
7188 }
7189
7190 #if ((defined (OBJ_MAYBE_COFF) && defined (OBJ_MAYBE_AOUT)) \
7191      || defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) || defined (TE_PEP))
7192
7193 /* Pick the target format to use.  */
7194
7195 const char *
7196 i386_target_format (void)
7197 {
7198   if (!strcmp (default_arch, "x86_64"))
7199     {
7200       set_code_flag (CODE_64BIT);
7201       if (UINTS_ALL_ZERO (cpu_arch_isa_flags))
7202         {
7203           cpu_arch_isa_flags.bitfield.cpui186 = 1;
7204           cpu_arch_isa_flags.bitfield.cpui286 = 1;
7205           cpu_arch_isa_flags.bitfield.cpui386 = 1;
7206           cpu_arch_isa_flags.bitfield.cpui486 = 1;
7207           cpu_arch_isa_flags.bitfield.cpui586 = 1;
7208           cpu_arch_isa_flags.bitfield.cpui686 = 1;
7209           cpu_arch_isa_flags.bitfield.cpup4 = 1;
7210           cpu_arch_isa_flags.bitfield.cpummx= 1;
7211           cpu_arch_isa_flags.bitfield.cpummx2 = 1;
7212           cpu_arch_isa_flags.bitfield.cpusse = 1;
7213           cpu_arch_isa_flags.bitfield.cpusse2 = 1;
7214         }
7215       if (UINTS_ALL_ZERO (cpu_arch_tune_flags))
7216         {
7217           cpu_arch_tune_flags.bitfield.cpui186 = 1;
7218           cpu_arch_tune_flags.bitfield.cpui286 = 1;
7219           cpu_arch_tune_flags.bitfield.cpui386 = 1;
7220           cpu_arch_tune_flags.bitfield.cpui486 = 1;
7221           cpu_arch_tune_flags.bitfield.cpui586 = 1;
7222           cpu_arch_tune_flags.bitfield.cpui686 = 1;
7223           cpu_arch_tune_flags.bitfield.cpup4 = 1;
7224           cpu_arch_tune_flags.bitfield.cpummx= 1;
7225           cpu_arch_tune_flags.bitfield.cpummx2 = 1;
7226           cpu_arch_tune_flags.bitfield.cpusse = 1;
7227           cpu_arch_tune_flags.bitfield.cpusse2 = 1;
7228         }
7229     }
7230   else if (!strcmp (default_arch, "i386"))
7231     {
7232       set_code_flag (CODE_32BIT);
7233       if (UINTS_ALL_ZERO (cpu_arch_isa_flags))
7234         {
7235           cpu_arch_isa_flags.bitfield.cpui186 = 1;
7236           cpu_arch_isa_flags.bitfield.cpui286 = 1;
7237           cpu_arch_isa_flags.bitfield.cpui386 = 1;
7238         }
7239       if (UINTS_ALL_ZERO (cpu_arch_tune_flags))
7240         {
7241           cpu_arch_tune_flags.bitfield.cpui186 = 1;
7242           cpu_arch_tune_flags.bitfield.cpui286 = 1;
7243           cpu_arch_tune_flags.bitfield.cpui386 = 1;
7244         }
7245     }
7246   else
7247     as_fatal (_("Unknown architecture"));
7248   switch (OUTPUT_FLAVOR)
7249     {
7250 #ifdef TE_PEP
7251     case bfd_target_coff_flavour:
7252       return flag_code == CODE_64BIT ? COFF_TARGET_FORMAT : "coff-i386";
7253       break;
7254 #endif
7255 #ifdef OBJ_MAYBE_AOUT
7256     case bfd_target_aout_flavour:
7257       return AOUT_TARGET_FORMAT;
7258 #endif
7259 #ifdef OBJ_MAYBE_COFF
7260     case bfd_target_coff_flavour:
7261       return "coff-i386";
7262 #endif
7263 #if defined (OBJ_MAYBE_ELF) || defined (OBJ_ELF)
7264     case bfd_target_elf_flavour:
7265       {
7266         if (flag_code == CODE_64BIT)
7267           {
7268             object_64bit = 1;
7269             use_rela_relocations = 1;
7270           }
7271         return flag_code == CODE_64BIT ? ELF_TARGET_FORMAT64 : ELF_TARGET_FORMAT;
7272       }
7273 #endif
7274     default:
7275       abort ();
7276       return NULL;
7277     }
7278 }
7279
7280 #endif /* OBJ_MAYBE_ more than one  */
7281
7282 #if (defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF))
7283 void
7284 i386_elf_emit_arch_note (void)
7285 {
7286   if (IS_ELF && cpu_arch_name != NULL)
7287     {
7288       char *p;
7289       asection *seg = now_seg;
7290       subsegT subseg = now_subseg;
7291       Elf_Internal_Note i_note;
7292       Elf_External_Note e_note;
7293       asection *note_secp;
7294       int len;
7295
7296       /* Create the .note section.  */
7297       note_secp = subseg_new (".note", 0);
7298       bfd_set_section_flags (stdoutput,
7299                              note_secp,
7300                              SEC_HAS_CONTENTS | SEC_READONLY);
7301
7302       /* Process the arch string.  */
7303       len = strlen (cpu_arch_name);
7304
7305       i_note.namesz = len + 1;
7306       i_note.descsz = 0;
7307       i_note.type = NT_ARCH;
7308       p = frag_more (sizeof (e_note.namesz));
7309       md_number_to_chars (p, (valueT) i_note.namesz, sizeof (e_note.namesz));
7310       p = frag_more (sizeof (e_note.descsz));
7311       md_number_to_chars (p, (valueT) i_note.descsz, sizeof (e_note.descsz));
7312       p = frag_more (sizeof (e_note.type));
7313       md_number_to_chars (p, (valueT) i_note.type, sizeof (e_note.type));
7314       p = frag_more (len + 1);
7315       strcpy (p, cpu_arch_name);
7316
7317       frag_align (2, 0, 0);
7318
7319       subseg_set (seg, subseg);
7320     }
7321 }
7322 #endif
7323 \f
7324 symbolS *
7325 md_undefined_symbol (name)
7326      char *name;
7327 {
7328   if (name[0] == GLOBAL_OFFSET_TABLE_NAME[0]
7329       && name[1] == GLOBAL_OFFSET_TABLE_NAME[1]
7330       && name[2] == GLOBAL_OFFSET_TABLE_NAME[2]
7331       && strcmp (name, GLOBAL_OFFSET_TABLE_NAME) == 0)
7332     {
7333       if (!GOT_symbol)
7334         {
7335           if (symbol_find (name))
7336             as_bad (_("GOT already in symbol table"));
7337           GOT_symbol = symbol_new (name, undefined_section,
7338                                    (valueT) 0, &zero_address_frag);
7339         };
7340       return GOT_symbol;
7341     }
7342   return 0;
7343 }
7344
7345 /* Round up a section size to the appropriate boundary.  */
7346
7347 valueT
7348 md_section_align (segment, size)
7349      segT segment ATTRIBUTE_UNUSED;
7350      valueT size;
7351 {
7352 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
7353   if (OUTPUT_FLAVOR == bfd_target_aout_flavour)
7354     {
7355       /* For a.out, force the section size to be aligned.  If we don't do
7356          this, BFD will align it for us, but it will not write out the
7357          final bytes of the section.  This may be a bug in BFD, but it is
7358          easier to fix it here since that is how the other a.out targets
7359          work.  */
7360       int align;
7361
7362       align = bfd_get_section_alignment (stdoutput, segment);
7363       size = ((size + (1 << align) - 1) & ((valueT) -1 << align));
7364     }
7365 #endif
7366
7367   return size;
7368 }
7369
7370 /* On the i386, PC-relative offsets are relative to the start of the
7371    next instruction.  That is, the address of the offset, plus its
7372    size, since the offset is always the last part of the insn.  */
7373
7374 long
7375 md_pcrel_from (fixS *fixP)
7376 {
7377   return fixP->fx_size + fixP->fx_where + fixP->fx_frag->fr_address;
7378 }
7379
7380 #ifndef I386COFF
7381
7382 static void
7383 s_bss (int ignore ATTRIBUTE_UNUSED)
7384 {
7385   int temp;
7386
7387 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7388   if (IS_ELF)
7389     obj_elf_section_change_hook ();
7390 #endif
7391   temp = get_absolute_expression ();
7392   subseg_set (bss_section, (subsegT) temp);
7393   demand_empty_rest_of_line ();
7394 }
7395
7396 #endif
7397
7398 void
7399 i386_validate_fix (fixS *fixp)
7400 {
7401   if (fixp->fx_subsy && fixp->fx_subsy == GOT_symbol)
7402     {
7403       if (fixp->fx_r_type == BFD_RELOC_32_PCREL)
7404         {
7405           if (!object_64bit)
7406             abort ();
7407           fixp->fx_r_type = BFD_RELOC_X86_64_GOTPCREL;
7408         }
7409       else
7410         {
7411           if (!object_64bit)
7412             fixp->fx_r_type = BFD_RELOC_386_GOTOFF;
7413           else
7414             fixp->fx_r_type = BFD_RELOC_X86_64_GOTOFF64;
7415         }
7416       fixp->fx_subsy = 0;
7417     }
7418 }
7419
7420 arelent *
7421 tc_gen_reloc (section, fixp)
7422      asection *section ATTRIBUTE_UNUSED;
7423      fixS *fixp;
7424 {
7425   arelent *rel;
7426   bfd_reloc_code_real_type code;
7427
7428   switch (fixp->fx_r_type)
7429     {
7430     case BFD_RELOC_X86_64_PLT32:
7431     case BFD_RELOC_X86_64_GOT32:
7432     case BFD_RELOC_X86_64_GOTPCREL:
7433     case BFD_RELOC_386_PLT32:
7434     case BFD_RELOC_386_GOT32:
7435     case BFD_RELOC_386_GOTOFF:
7436     case BFD_RELOC_386_GOTPC:
7437     case BFD_RELOC_386_TLS_GD:
7438     case BFD_RELOC_386_TLS_LDM:
7439     case BFD_RELOC_386_TLS_LDO_32:
7440     case BFD_RELOC_386_TLS_IE_32:
7441     case BFD_RELOC_386_TLS_IE:
7442     case BFD_RELOC_386_TLS_GOTIE:
7443     case BFD_RELOC_386_TLS_LE_32:
7444     case BFD_RELOC_386_TLS_LE:
7445     case BFD_RELOC_386_TLS_GOTDESC:
7446     case BFD_RELOC_386_TLS_DESC_CALL:
7447     case BFD_RELOC_X86_64_TLSGD:
7448     case BFD_RELOC_X86_64_TLSLD:
7449     case BFD_RELOC_X86_64_DTPOFF32:
7450     case BFD_RELOC_X86_64_DTPOFF64:
7451     case BFD_RELOC_X86_64_GOTTPOFF:
7452     case BFD_RELOC_X86_64_TPOFF32:
7453     case BFD_RELOC_X86_64_TPOFF64:
7454     case BFD_RELOC_X86_64_GOTOFF64:
7455     case BFD_RELOC_X86_64_GOTPC32:
7456     case BFD_RELOC_X86_64_GOT64:
7457     case BFD_RELOC_X86_64_GOTPCREL64:
7458     case BFD_RELOC_X86_64_GOTPC64:
7459     case BFD_RELOC_X86_64_GOTPLT64:
7460     case BFD_RELOC_X86_64_PLTOFF64:
7461     case BFD_RELOC_X86_64_GOTPC32_TLSDESC:
7462     case BFD_RELOC_X86_64_TLSDESC_CALL:
7463     case BFD_RELOC_RVA:
7464     case BFD_RELOC_VTABLE_ENTRY:
7465     case BFD_RELOC_VTABLE_INHERIT:
7466 #ifdef TE_PE
7467     case BFD_RELOC_32_SECREL:
7468 #endif
7469       code = fixp->fx_r_type;
7470       break;
7471     case BFD_RELOC_X86_64_32S:
7472       if (!fixp->fx_pcrel)
7473         {
7474           /* Don't turn BFD_RELOC_X86_64_32S into BFD_RELOC_32.  */
7475           code = fixp->fx_r_type;
7476           break;
7477         }
7478     default:
7479       if (fixp->fx_pcrel)
7480         {
7481           switch (fixp->fx_size)
7482             {
7483             default:
7484               as_bad_where (fixp->fx_file, fixp->fx_line,
7485                             _("can not do %d byte pc-relative relocation"),
7486                             fixp->fx_size);
7487               code = BFD_RELOC_32_PCREL;
7488               break;
7489             case 1: code = BFD_RELOC_8_PCREL;  break;
7490             case 2: code = BFD_RELOC_16_PCREL; break;
7491             case 4: code = BFD_RELOC_32_PCREL; break;
7492 #ifdef BFD64
7493             case 8: code = BFD_RELOC_64_PCREL; break;
7494 #endif
7495             }
7496         }
7497       else
7498         {
7499           switch (fixp->fx_size)
7500             {
7501             default:
7502               as_bad_where (fixp->fx_file, fixp->fx_line,
7503                             _("can not do %d byte relocation"),
7504                             fixp->fx_size);
7505               code = BFD_RELOC_32;
7506               break;
7507             case 1: code = BFD_RELOC_8;  break;
7508             case 2: code = BFD_RELOC_16; break;
7509             case 4: code = BFD_RELOC_32; break;
7510 #ifdef BFD64
7511             case 8: code = BFD_RELOC_64; break;
7512 #endif
7513             }
7514         }
7515       break;
7516     }
7517
7518   if ((code == BFD_RELOC_32
7519        || code == BFD_RELOC_32_PCREL
7520        || code == BFD_RELOC_X86_64_32S)
7521       && GOT_symbol
7522       && fixp->fx_addsy == GOT_symbol)
7523     {
7524       if (!object_64bit)
7525         code = BFD_RELOC_386_GOTPC;
7526       else
7527         code = BFD_RELOC_X86_64_GOTPC32;
7528     }
7529   if ((code == BFD_RELOC_64 || code == BFD_RELOC_64_PCREL)
7530       && GOT_symbol
7531       && fixp->fx_addsy == GOT_symbol)
7532     {
7533       code = BFD_RELOC_X86_64_GOTPC64;
7534     }
7535
7536   rel = (arelent *) xmalloc (sizeof (arelent));
7537   rel->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
7538   *rel->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
7539
7540   rel->address = fixp->fx_frag->fr_address + fixp->fx_where;
7541
7542   if (!use_rela_relocations)
7543     {
7544       /* HACK: Since i386 ELF uses Rel instead of Rela, encode the
7545          vtable entry to be used in the relocation's section offset.  */
7546       if (fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
7547         rel->address = fixp->fx_offset;
7548
7549       rel->addend = 0;
7550     }
7551   /* Use the rela in 64bit mode.  */
7552   else
7553     {
7554       if (!fixp->fx_pcrel)
7555         rel->addend = fixp->fx_offset;
7556       else
7557         switch (code)
7558           {
7559           case BFD_RELOC_X86_64_PLT32:
7560           case BFD_RELOC_X86_64_GOT32:
7561           case BFD_RELOC_X86_64_GOTPCREL:
7562           case BFD_RELOC_X86_64_TLSGD:
7563           case BFD_RELOC_X86_64_TLSLD:
7564           case BFD_RELOC_X86_64_GOTTPOFF:
7565           case BFD_RELOC_X86_64_GOTPC32_TLSDESC:
7566           case BFD_RELOC_X86_64_TLSDESC_CALL:
7567             rel->addend = fixp->fx_offset - fixp->fx_size;
7568             break;
7569           default:
7570             rel->addend = (section->vma
7571                            - fixp->fx_size
7572                            + fixp->fx_addnumber
7573                            + md_pcrel_from (fixp));
7574             break;
7575           }
7576     }
7577
7578   rel->howto = bfd_reloc_type_lookup (stdoutput, code);
7579   if (rel->howto == NULL)
7580     {
7581       as_bad_where (fixp->fx_file, fixp->fx_line,
7582                     _("cannot represent relocation type %s"),
7583                     bfd_get_reloc_code_name (code));
7584       /* Set howto to a garbage value so that we can keep going.  */
7585       rel->howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_32);
7586       assert (rel->howto != NULL);
7587     }
7588
7589   return rel;
7590 }
7591
7592 \f
7593 /* Parse operands using Intel syntax. This implements a recursive descent
7594    parser based on the BNF grammar published in Appendix B of the MASM 6.1
7595    Programmer's Guide.
7596
7597    FIXME: We do not recognize the full operand grammar defined in the MASM
7598           documentation.  In particular, all the structure/union and
7599           high-level macro operands are missing.
7600
7601    Uppercase words are terminals, lower case words are non-terminals.
7602    Objects surrounded by double brackets '[[' ']]' are optional. Vertical
7603    bars '|' denote choices. Most grammar productions are implemented in
7604    functions called 'intel_<production>'.
7605
7606    Initial production is 'expr'.
7607
7608     addOp               + | -
7609
7610     alpha               [a-zA-Z]
7611
7612     binOp               & | AND | \| | OR | ^ | XOR
7613
7614     byteRegister        AL | AH | BL | BH | CL | CH | DL | DH
7615
7616     constant            digits [[ radixOverride ]]
7617
7618     dataType            BYTE | WORD | DWORD | FWORD | QWORD | TBYTE | OWORD | XMMWORD
7619
7620     digits              decdigit
7621                         | digits decdigit
7622                         | digits hexdigit
7623
7624     decdigit            [0-9]
7625
7626     e04                 e04 addOp e05
7627                         | e05
7628
7629     e05                 e05 binOp e06
7630                         | e06
7631
7632     e06                 e06 mulOp e09
7633                         | e09
7634
7635     e09                 OFFSET e10
7636                         | SHORT e10
7637                         | + e10
7638                         | - e10
7639                         | ~ e10
7640                         | NOT e10
7641                         | e09 PTR e10
7642                         | e09 : e10
7643                         | e10
7644
7645     e10                 e10 [ expr ]
7646                         | e11
7647
7648     e11                 ( expr )
7649                         | [ expr ]
7650                         | constant
7651                         | dataType
7652                         | id
7653                         | $
7654                         | register
7655
7656  => expr                expr cmpOp e04
7657                         | e04
7658
7659     gpRegister          AX | EAX | BX | EBX | CX | ECX | DX | EDX
7660                         | BP | EBP | SP | ESP | DI | EDI | SI | ESI
7661
7662     hexdigit            a | b | c | d | e | f
7663                         | A | B | C | D | E | F
7664
7665     id                  alpha
7666                         | id alpha
7667                         | id decdigit
7668
7669     mulOp               * | / | % | MOD | << | SHL | >> | SHR
7670
7671     quote               " | '
7672
7673     register            specialRegister
7674                         | gpRegister
7675                         | byteRegister
7676
7677     segmentRegister     CS | DS | ES | FS | GS | SS
7678
7679     specialRegister     CR0 | CR2 | CR3 | CR4
7680                         | DR0 | DR1 | DR2 | DR3 | DR6 | DR7
7681                         | TR3 | TR4 | TR5 | TR6 | TR7
7682
7683     We simplify the grammar in obvious places (e.g., register parsing is
7684     done by calling parse_register) and eliminate immediate left recursion
7685     to implement a recursive-descent parser.
7686
7687     expr        e04 expr'
7688
7689     expr'       cmpOp e04 expr'
7690                 | Empty
7691
7692     e04         e05 e04'
7693
7694     e04'        addOp e05 e04'
7695                 | Empty
7696
7697     e05         e06 e05'
7698
7699     e05'        binOp e06 e05'
7700                 | Empty
7701
7702     e06         e09 e06'
7703
7704     e06'        mulOp e09 e06'
7705                 | Empty
7706
7707     e09         OFFSET e10 e09'
7708                 | SHORT e10'
7709                 | + e10'
7710                 | - e10'
7711                 | ~ e10'
7712                 | NOT e10'
7713                 | e10 e09'
7714
7715     e09'        PTR e10 e09'
7716                 | : e10 e09'
7717                 | Empty
7718
7719     e10         e11 e10'
7720
7721     e10'        [ expr ] e10'
7722                 | Empty
7723
7724     e11         ( expr )
7725                 | [ expr ]
7726                 | BYTE
7727                 | WORD
7728                 | DWORD
7729                 | FWORD
7730                 | QWORD
7731                 | TBYTE
7732                 | OWORD
7733                 | XMMWORD
7734                 | .
7735                 | $
7736                 | register
7737                 | id
7738                 | constant  */
7739
7740 /* Parsing structure for the intel syntax parser. Used to implement the
7741    semantic actions for the operand grammar.  */
7742 struct intel_parser_s
7743   {
7744     char *op_string;            /* The string being parsed.  */
7745     int got_a_float;            /* Whether the operand is a float.  */
7746     int op_modifier;            /* Operand modifier.  */
7747     int is_mem;                 /* 1 if operand is memory reference.  */
7748     int in_offset;              /* >=1 if parsing operand of offset.  */
7749     int in_bracket;             /* >=1 if parsing operand in brackets.  */
7750     const reg_entry *reg;       /* Last register reference found.  */
7751     char *disp;                 /* Displacement string being built.  */
7752     char *next_operand;         /* Resume point when splitting operands.  */
7753   };
7754
7755 static struct intel_parser_s intel_parser;
7756
7757 /* Token structure for parsing intel syntax.  */
7758 struct intel_token
7759   {
7760     int code;                   /* Token code.  */
7761     const reg_entry *reg;       /* Register entry for register tokens.  */
7762     char *str;                  /* String representation.  */
7763   };
7764
7765 static struct intel_token cur_token, prev_token;
7766
7767 /* Token codes for the intel parser. Since T_SHORT is already used
7768    by COFF, undefine it first to prevent a warning.  */
7769 #define T_NIL           -1
7770 #define T_CONST         1
7771 #define T_REG           2
7772 #define T_BYTE          3
7773 #define T_WORD          4
7774 #define T_DWORD         5
7775 #define T_FWORD         6
7776 #define T_QWORD         7
7777 #define T_TBYTE         8
7778 #define T_XMMWORD       9
7779 #undef  T_SHORT
7780 #define T_SHORT         10
7781 #define T_OFFSET        11
7782 #define T_PTR           12
7783 #define T_ID            13
7784 #define T_SHL           14
7785 #define T_SHR           15
7786
7787 /* Prototypes for intel parser functions.  */
7788 static int intel_match_token (int);
7789 static void intel_putback_token (void);
7790 static void intel_get_token (void);
7791 static int intel_expr (void);
7792 static int intel_e04 (void);
7793 static int intel_e05 (void);
7794 static int intel_e06 (void);
7795 static int intel_e09 (void);
7796 static int intel_e10 (void);
7797 static int intel_e11 (void);
7798
7799 static int
7800 i386_intel_operand (char *operand_string, int got_a_float)
7801 {
7802   int ret;
7803   char *p;
7804
7805   p = intel_parser.op_string = xstrdup (operand_string);
7806   intel_parser.disp = (char *) xmalloc (strlen (operand_string) + 1);
7807
7808   for (;;)
7809     {
7810       /* Initialize token holders.  */
7811       cur_token.code = prev_token.code = T_NIL;
7812       cur_token.reg = prev_token.reg = NULL;
7813       cur_token.str = prev_token.str = NULL;
7814
7815       /* Initialize parser structure.  */
7816       intel_parser.got_a_float = got_a_float;
7817       intel_parser.op_modifier = 0;
7818       intel_parser.is_mem = 0;
7819       intel_parser.in_offset = 0;
7820       intel_parser.in_bracket = 0;
7821       intel_parser.reg = NULL;
7822       intel_parser.disp[0] = '\0';
7823       intel_parser.next_operand = NULL;
7824
7825       /* Read the first token and start the parser.  */
7826       intel_get_token ();
7827       ret = intel_expr ();
7828
7829       if (!ret)
7830         break;
7831
7832       if (cur_token.code != T_NIL)
7833         {
7834           as_bad (_("invalid operand for '%s' ('%s' unexpected)"),
7835                   current_templates->start->name, cur_token.str);
7836           ret = 0;
7837         }
7838       /* If we found a memory reference, hand it over to i386_displacement
7839          to fill in the rest of the operand fields.  */
7840       else if (intel_parser.is_mem)
7841         {
7842           if ((i.mem_operands == 1
7843                && !current_templates->start->opcode_modifier.isstring)
7844               || i.mem_operands == 2)
7845             {
7846               as_bad (_("too many memory references for '%s'"),
7847                       current_templates->start->name);
7848               ret = 0;
7849             }
7850           else
7851             {
7852               char *s = intel_parser.disp;
7853               i.mem_operands++;
7854
7855               if (!quiet_warnings && intel_parser.is_mem < 0)
7856                 /* See the comments in intel_bracket_expr.  */
7857                 as_warn (_("Treating `%s' as memory reference"), operand_string);
7858
7859               /* Add the displacement expression.  */
7860               if (*s != '\0')
7861                 ret = i386_displacement (s, s + strlen (s));
7862               if (ret)
7863                 {
7864                   /* Swap base and index in 16-bit memory operands like
7865                      [si+bx]. Since i386_index_check is also used in AT&T
7866                      mode we have to do that here.  */
7867                   if (i.base_reg
7868                       && i.index_reg
7869                       && i.base_reg->reg_type.bitfield.reg16
7870                       && i.index_reg->reg_type.bitfield.reg16
7871                       && i.base_reg->reg_num >= 6
7872                       && i.index_reg->reg_num < 6)
7873                     {
7874                       const reg_entry *base = i.index_reg;
7875
7876                       i.index_reg = i.base_reg;
7877                       i.base_reg = base;
7878                     }
7879                   ret = i386_index_check (operand_string);
7880                 }
7881             }
7882         }
7883
7884       /* Constant and OFFSET expressions are handled by i386_immediate.  */
7885       else if ((intel_parser.op_modifier & (1 << T_OFFSET))
7886                || intel_parser.reg == NULL)
7887         ret = i386_immediate (intel_parser.disp);
7888
7889       if (intel_parser.next_operand && this_operand >= MAX_OPERANDS - 1)
7890         ret = 0;
7891       if (!ret || !intel_parser.next_operand)
7892         break;
7893       intel_parser.op_string = intel_parser.next_operand;
7894       this_operand = i.operands++;
7895     }
7896
7897   free (p);
7898   free (intel_parser.disp);
7899
7900   return ret;
7901 }
7902
7903 #define NUM_ADDRESS_REGS (!!i.base_reg + !!i.index_reg)
7904
7905 /* expr e04 expr'
7906
7907    expr'  cmpOp e04 expr'
7908         | Empty  */
7909 static int
7910 intel_expr (void)
7911 {
7912   /* XXX Implement the comparison operators.  */
7913   return intel_e04 ();
7914 }
7915
7916 /* e04  e05 e04'
7917
7918    e04' addOp e05 e04'
7919         | Empty  */
7920 static int
7921 intel_e04 (void)
7922 {
7923   int nregs = -1;
7924
7925   for (;;)
7926     {
7927       if (!intel_e05())
7928         return 0;
7929
7930       if (nregs >= 0 && NUM_ADDRESS_REGS > nregs)
7931         i.base_reg = i386_regtab + REGNAM_AL; /* al is invalid as base */
7932
7933       if (cur_token.code == '+')
7934         nregs = -1;
7935       else if (cur_token.code == '-')
7936         nregs = NUM_ADDRESS_REGS;
7937       else
7938         return 1;
7939
7940       strcat (intel_parser.disp, cur_token.str);
7941       intel_match_token (cur_token.code);
7942     }
7943 }
7944
7945 /* e05  e06 e05'
7946
7947    e05' binOp e06 e05'
7948         | Empty  */
7949 static int
7950 intel_e05 (void)
7951 {
7952   int nregs = ~NUM_ADDRESS_REGS;
7953
7954   for (;;)
7955     {
7956       if (!intel_e06())
7957         return 0;
7958
7959       if (cur_token.code == '&'
7960           || cur_token.code == '|'
7961           || cur_token.code == '^')
7962         {
7963           char str[2];
7964
7965           str[0] = cur_token.code;
7966           str[1] = 0;
7967           strcat (intel_parser.disp, str);
7968         }
7969       else
7970         break;
7971
7972       intel_match_token (cur_token.code);
7973
7974       if (nregs < 0)
7975         nregs = ~nregs;
7976     }
7977   if (nregs >= 0 && NUM_ADDRESS_REGS > nregs)
7978     i.base_reg = i386_regtab + REGNAM_AL + 1; /* cl is invalid as base */
7979   return 1;
7980 }
7981
7982 /* e06  e09 e06'
7983
7984    e06' mulOp e09 e06'
7985         | Empty  */
7986 static int
7987 intel_e06 (void)
7988 {
7989   int nregs = ~NUM_ADDRESS_REGS;
7990
7991   for (;;)
7992     {
7993       if (!intel_e09())
7994         return 0;
7995
7996       if (cur_token.code == '*'
7997           || cur_token.code == '/'
7998           || cur_token.code == '%')
7999         {
8000           char str[2];
8001
8002           str[0] = cur_token.code;
8003           str[1] = 0;
8004           strcat (intel_parser.disp, str);
8005         }
8006       else if (cur_token.code == T_SHL)
8007         strcat (intel_parser.disp, "<<");
8008       else if (cur_token.code == T_SHR)
8009         strcat (intel_parser.disp, ">>");
8010       else
8011         break;
8012
8013       intel_match_token (cur_token.code);
8014
8015       if (nregs < 0)
8016         nregs = ~nregs;
8017     }
8018   if (nregs >= 0 && NUM_ADDRESS_REGS > nregs)
8019     i.base_reg = i386_regtab + REGNAM_AL + 2; /* dl is invalid as base */
8020   return 1;
8021 }
8022
8023 /* e09  OFFSET e09
8024         | SHORT e09
8025         | + e09
8026         | - e09
8027         | ~ e09
8028         | NOT e09
8029         | e10 e09'
8030
8031    e09' PTR e10 e09'
8032         | : e10 e09'
8033         | Empty */
8034 static int
8035 intel_e09 (void)
8036 {
8037   int nregs = ~NUM_ADDRESS_REGS;
8038   int in_offset = 0;
8039
8040   for (;;)
8041     {
8042       /* Don't consume constants here.  */
8043       if (cur_token.code == '+' || cur_token.code == '-')
8044         {
8045           /* Need to look one token ahead - if the next token
8046              is a constant, the current token is its sign.  */
8047           int next_code;
8048
8049           intel_match_token (cur_token.code);
8050           next_code = cur_token.code;
8051           intel_putback_token ();
8052           if (next_code == T_CONST)
8053             break;
8054         }
8055
8056       /* e09  OFFSET e09  */
8057       if (cur_token.code == T_OFFSET)
8058         {
8059           if (!in_offset++)
8060             ++intel_parser.in_offset;
8061         }
8062
8063       /* e09  SHORT e09  */
8064       else if (cur_token.code == T_SHORT)
8065         intel_parser.op_modifier |= 1 << T_SHORT;
8066
8067       /* e09  + e09  */
8068       else if (cur_token.code == '+')
8069         strcat (intel_parser.disp, "+");
8070
8071       /* e09  - e09
8072               | ~ e09
8073               | NOT e09  */
8074       else if (cur_token.code == '-' || cur_token.code == '~')
8075         {
8076           char str[2];
8077
8078           if (nregs < 0)
8079             nregs = ~nregs;
8080           str[0] = cur_token.code;
8081           str[1] = 0;
8082           strcat (intel_parser.disp, str);
8083         }
8084
8085       /* e09  e10 e09'  */
8086       else
8087         break;
8088
8089       intel_match_token (cur_token.code);
8090     }
8091
8092   for (;;)
8093     {
8094       if (!intel_e10 ())
8095         return 0;
8096
8097       /* e09'  PTR e10 e09' */
8098       if (cur_token.code == T_PTR)
8099         {
8100           char suffix;
8101
8102           if (prev_token.code == T_BYTE)
8103             suffix = BYTE_MNEM_SUFFIX;
8104
8105           else if (prev_token.code == T_WORD)
8106             {
8107               if (current_templates->start->name[0] == 'l'
8108                   && current_templates->start->name[2] == 's'
8109                   && current_templates->start->name[3] == 0)
8110                 suffix = BYTE_MNEM_SUFFIX; /* so it will cause an error */
8111               else if (intel_parser.got_a_float == 2)   /* "fi..." */
8112                 suffix = SHORT_MNEM_SUFFIX;
8113               else
8114                 suffix = WORD_MNEM_SUFFIX;
8115             }
8116
8117           else if (prev_token.code == T_DWORD)
8118             {
8119               if (current_templates->start->name[0] == 'l'
8120                   && current_templates->start->name[2] == 's'
8121                   && current_templates->start->name[3] == 0)
8122                 suffix = WORD_MNEM_SUFFIX;
8123               else if (flag_code == CODE_16BIT
8124                        && (current_templates->start->opcode_modifier.jump
8125                            || current_templates->start->opcode_modifier.jumpdword))
8126                 suffix = LONG_DOUBLE_MNEM_SUFFIX;
8127               else if (intel_parser.got_a_float == 1)   /* "f..." */
8128                 suffix = SHORT_MNEM_SUFFIX;
8129               else
8130                 suffix = LONG_MNEM_SUFFIX;
8131             }
8132
8133           else if (prev_token.code == T_FWORD)
8134             {
8135               if (current_templates->start->name[0] == 'l'
8136                   && current_templates->start->name[2] == 's'
8137                   && current_templates->start->name[3] == 0)
8138                 suffix = LONG_MNEM_SUFFIX;
8139               else if (!intel_parser.got_a_float)
8140                 {
8141                   if (flag_code == CODE_16BIT)
8142                     add_prefix (DATA_PREFIX_OPCODE);
8143                   suffix = LONG_DOUBLE_MNEM_SUFFIX;
8144                 }
8145               else
8146                 suffix = BYTE_MNEM_SUFFIX; /* so it will cause an error */
8147             }
8148
8149           else if (prev_token.code == T_QWORD)
8150             {
8151               if (intel_parser.got_a_float == 1)        /* "f..." */
8152                 suffix = LONG_MNEM_SUFFIX;
8153               else
8154                 suffix = QWORD_MNEM_SUFFIX;
8155             }
8156
8157           else if (prev_token.code == T_TBYTE)
8158             {
8159               if (intel_parser.got_a_float == 1)
8160                 suffix = LONG_DOUBLE_MNEM_SUFFIX;
8161               else
8162                 suffix = BYTE_MNEM_SUFFIX; /* so it will cause an error */
8163             }
8164
8165           else if (prev_token.code == T_XMMWORD)
8166             {
8167               suffix = XMMWORD_MNEM_SUFFIX;
8168             }
8169
8170           else
8171             {
8172               as_bad (_("Unknown operand modifier `%s'"), prev_token.str);
8173               return 0;
8174             }
8175
8176           /* Operands for jump/call using 'ptr' notation denote absolute
8177              addresses.  */
8178           if (current_templates->start->opcode_modifier.jump
8179               || current_templates->start->opcode_modifier.jumpdword)
8180             i.types[this_operand].bitfield.jumpabsolute = 1;
8181
8182           if (current_templates->start->base_opcode == 0x8d /* lea */)
8183             ;
8184           else if (!i.suffix)
8185             i.suffix = suffix;
8186           else if (i.suffix != suffix)
8187             {
8188               as_bad (_("Conflicting operand modifiers"));
8189               return 0;
8190             }
8191
8192         }
8193
8194       /* e09'  : e10 e09'  */
8195       else if (cur_token.code == ':')
8196         {
8197           if (prev_token.code != T_REG)
8198             {
8199               /* While {call,jmp} SSSS:OOOO is MASM syntax only when SSSS is a
8200                  segment/group identifier (which we don't have), using comma
8201                  as the operand separator there is even less consistent, since
8202                  there all branches only have a single operand.  */
8203               if (this_operand != 0
8204                   || intel_parser.in_offset
8205                   || intel_parser.in_bracket
8206                   || (!current_templates->start->opcode_modifier.jump
8207                       && !current_templates->start->opcode_modifier.jumpdword
8208                       && !current_templates->start->opcode_modifier.jumpintersegment
8209                       && !current_templates->start->operand_types[0].bitfield.jumpabsolute))
8210                 return intel_match_token (T_NIL);
8211               /* Remember the start of the 2nd operand and terminate 1st
8212                  operand here.
8213                  XXX This isn't right, yet (when SSSS:OOOO is right operand of
8214                  another expression), but it gets at least the simplest case
8215                  (a plain number or symbol on the left side) right.  */
8216               intel_parser.next_operand = intel_parser.op_string;
8217               *--intel_parser.op_string = '\0';
8218               return intel_match_token (':');
8219             }
8220         }
8221
8222       /* e09'  Empty  */
8223       else
8224         break;
8225
8226       intel_match_token (cur_token.code);
8227
8228     }
8229
8230   if (in_offset)
8231     {
8232       --intel_parser.in_offset;
8233       if (nregs < 0)
8234         nregs = ~nregs;
8235       if (NUM_ADDRESS_REGS > nregs)
8236         {
8237           as_bad (_("Invalid operand to `OFFSET'"));
8238           return 0;
8239         }
8240       intel_parser.op_modifier |= 1 << T_OFFSET;
8241     }
8242
8243   if (nregs >= 0 && NUM_ADDRESS_REGS > nregs)
8244     i.base_reg = i386_regtab + REGNAM_AL + 3; /* bl is invalid as base */
8245   return 1;
8246 }
8247
8248 static int
8249 intel_bracket_expr (void)
8250 {
8251   int was_offset = intel_parser.op_modifier & (1 << T_OFFSET);
8252   const char *start = intel_parser.op_string;
8253   int len;
8254
8255   if (i.op[this_operand].regs)
8256     return intel_match_token (T_NIL);
8257
8258   intel_match_token ('[');
8259
8260   /* Mark as a memory operand only if it's not already known to be an
8261      offset expression.  If it's an offset expression, we need to keep
8262      the brace in.  */
8263   if (!intel_parser.in_offset)
8264     {
8265       ++intel_parser.in_bracket;
8266
8267       /* Operands for jump/call inside brackets denote absolute addresses.  */
8268       if (current_templates->start->opcode_modifier.jump
8269           || current_templates->start->opcode_modifier.jumpdword)
8270         i.types[this_operand].bitfield.jumpabsolute = 1;
8271
8272       /* Unfortunately gas always diverged from MASM in a respect that can't
8273          be easily fixed without risking to break code sequences likely to be
8274          encountered (the testsuite even check for this): MASM doesn't consider
8275          an expression inside brackets unconditionally as a memory reference.
8276          When that is e.g. a constant, an offset expression, or the sum of the
8277          two, this is still taken as a constant load. gas, however, always
8278          treated these as memory references. As a compromise, we'll try to make
8279          offset expressions inside brackets work the MASM way (since that's
8280          less likely to be found in real world code), but make constants alone
8281          continue to work the traditional gas way. In either case, issue a
8282          warning.  */
8283       intel_parser.op_modifier &= ~was_offset;
8284     }
8285   else
8286     strcat (intel_parser.disp, "[");
8287
8288   /* Add a '+' to the displacement string if necessary.  */
8289   if (*intel_parser.disp != '\0'
8290       && *(intel_parser.disp + strlen (intel_parser.disp) - 1) != '+')
8291     strcat (intel_parser.disp, "+");
8292
8293   if (intel_expr ()
8294       && (len = intel_parser.op_string - start - 1,
8295           intel_match_token (']')))
8296     {
8297       /* Preserve brackets when the operand is an offset expression.  */
8298       if (intel_parser.in_offset)
8299         strcat (intel_parser.disp, "]");
8300       else
8301         {
8302           --intel_parser.in_bracket;
8303           if (i.base_reg || i.index_reg)
8304             intel_parser.is_mem = 1;
8305           if (!intel_parser.is_mem)
8306             {
8307               if (!(intel_parser.op_modifier & (1 << T_OFFSET)))
8308                 /* Defer the warning until all of the operand was parsed.  */
8309                 intel_parser.is_mem = -1;
8310               else if (!quiet_warnings)
8311                 as_warn (_("`[%.*s]' taken to mean just `%.*s'"),
8312                          len, start, len, start);
8313             }
8314         }
8315       intel_parser.op_modifier |= was_offset;
8316
8317       return 1;
8318     }
8319   return 0;
8320 }
8321
8322 /* e10  e11 e10'
8323
8324    e10' [ expr ] e10'
8325         | Empty  */
8326 static int
8327 intel_e10 (void)
8328 {
8329   if (!intel_e11 ())
8330     return 0;
8331
8332   while (cur_token.code == '[')
8333     {
8334       if (!intel_bracket_expr ())
8335         return 0;
8336     }
8337
8338   return 1;
8339 }
8340
8341 /* e11  ( expr )
8342         | [ expr ]
8343         | BYTE
8344         | WORD
8345         | DWORD
8346         | FWORD
8347         | QWORD
8348         | TBYTE
8349         | OWORD
8350         | XMMWORD
8351         | $
8352         | .
8353         | register
8354         | id
8355         | constant  */
8356 static int
8357 intel_e11 (void)
8358 {
8359   switch (cur_token.code)
8360     {
8361     /* e11  ( expr ) */
8362     case '(':
8363       intel_match_token ('(');
8364       strcat (intel_parser.disp, "(");
8365
8366       if (intel_expr () && intel_match_token (')'))
8367         {
8368           strcat (intel_parser.disp, ")");
8369           return 1;
8370         }
8371       return 0;
8372
8373     /* e11  [ expr ] */
8374     case '[':
8375       return intel_bracket_expr ();
8376
8377     /* e11  $
8378             | .  */
8379     case '.':
8380       strcat (intel_parser.disp, cur_token.str);
8381       intel_match_token (cur_token.code);
8382
8383       /* Mark as a memory operand only if it's not already known to be an
8384          offset expression.  */
8385       if (!intel_parser.in_offset)
8386         intel_parser.is_mem = 1;
8387
8388       return 1;
8389
8390     /* e11  register  */
8391     case T_REG:
8392       {
8393         const reg_entry *reg = intel_parser.reg = cur_token.reg;
8394
8395         intel_match_token (T_REG);
8396
8397         /* Check for segment change.  */
8398         if (cur_token.code == ':')
8399           {
8400             if (!reg->reg_type.bitfield.sreg2
8401                 && !reg->reg_type.bitfield.sreg3)
8402               {
8403                 as_bad (_("`%s' is not a valid segment register"),
8404                         reg->reg_name);
8405                 return 0;
8406               }
8407             else if (i.seg[i.mem_operands])
8408               as_warn (_("Extra segment override ignored"));
8409             else
8410               {
8411                 if (!intel_parser.in_offset)
8412                   intel_parser.is_mem = 1;
8413                 switch (reg->reg_num)
8414                   {
8415                   case 0:
8416                     i.seg[i.mem_operands] = &es;
8417                     break;
8418                   case 1:
8419                     i.seg[i.mem_operands] = &cs;
8420                     break;
8421                   case 2:
8422                     i.seg[i.mem_operands] = &ss;
8423                     break;
8424                   case 3:
8425                     i.seg[i.mem_operands] = &ds;
8426                     break;
8427                   case 4:
8428                     i.seg[i.mem_operands] = &fs;
8429                     break;
8430                   case 5:
8431                     i.seg[i.mem_operands] = &gs;
8432                     break;
8433                   }
8434               }
8435           }
8436
8437         /* Not a segment register. Check for register scaling.  */
8438         else if (cur_token.code == '*')
8439           {
8440             if (!intel_parser.in_bracket)
8441               {
8442                 as_bad (_("Register scaling only allowed in memory operands"));
8443                 return 0;
8444               }
8445
8446             if (reg->reg_type.bitfield.reg16) /* Disallow things like [si*1]. */
8447               reg = i386_regtab + REGNAM_AX + 4; /* sp is invalid as index */
8448             else if (i.index_reg)
8449               reg = i386_regtab + REGNAM_EAX + 4; /* esp is invalid as index */
8450
8451             /* What follows must be a valid scale.  */
8452             intel_match_token ('*');
8453             i.index_reg = reg;
8454             i.types[this_operand].bitfield.baseindex = 1;
8455
8456             /* Set the scale after setting the register (otherwise,
8457                i386_scale will complain)  */
8458             if (cur_token.code == '+' || cur_token.code == '-')
8459               {
8460                 char *str, sign = cur_token.code;
8461                 intel_match_token (cur_token.code);
8462                 if (cur_token.code != T_CONST)
8463                   {
8464                     as_bad (_("Syntax error: Expecting a constant, got `%s'"),
8465                             cur_token.str);
8466                     return 0;
8467                   }
8468                 str = (char *) xmalloc (strlen (cur_token.str) + 2);
8469                 strcpy (str + 1, cur_token.str);
8470                 *str = sign;
8471                 if (!i386_scale (str))
8472                   return 0;
8473                 free (str);
8474               }
8475             else if (!i386_scale (cur_token.str))
8476               return 0;
8477             intel_match_token (cur_token.code);
8478           }
8479
8480         /* No scaling. If this is a memory operand, the register is either a
8481            base register (first occurrence) or an index register (second
8482            occurrence).  */
8483         else if (intel_parser.in_bracket)
8484           {
8485
8486             if (!i.base_reg)
8487               i.base_reg = reg;
8488             else if (!i.index_reg)
8489               i.index_reg = reg;
8490             else
8491               {
8492                 as_bad (_("Too many register references in memory operand"));
8493                 return 0;
8494               }
8495
8496             i.types[this_operand].bitfield.baseindex = 1;
8497           }
8498
8499         /* It's neither base nor index.  */
8500         else if (!intel_parser.in_offset && !intel_parser.is_mem)
8501           {
8502             i386_operand_type temp = reg->reg_type;
8503             temp.bitfield.baseindex = 0;
8504             i.types[this_operand] = operand_type_or (i.types[this_operand],
8505                                                      temp);
8506             i.op[this_operand].regs = reg;
8507             i.reg_operands++;
8508           }
8509         else
8510           {
8511             as_bad (_("Invalid use of register"));
8512             return 0;
8513           }
8514
8515         /* Since registers are not part of the displacement string (except
8516            when we're parsing offset operands), we may need to remove any
8517            preceding '+' from the displacement string.  */
8518         if (*intel_parser.disp != '\0'
8519             && !intel_parser.in_offset)
8520           {
8521             char *s = intel_parser.disp;
8522             s += strlen (s) - 1;
8523             if (*s == '+')
8524               *s = '\0';
8525           }
8526
8527         return 1;
8528       }
8529
8530     /* e11  BYTE
8531             | WORD
8532             | DWORD
8533             | FWORD
8534             | QWORD
8535             | TBYTE
8536             | OWORD
8537             | XMMWORD  */
8538     case T_BYTE:
8539     case T_WORD:
8540     case T_DWORD:
8541     case T_FWORD:
8542     case T_QWORD:
8543     case T_TBYTE:
8544     case T_XMMWORD:
8545       intel_match_token (cur_token.code);
8546
8547       if (cur_token.code == T_PTR)
8548         return 1;
8549
8550       /* It must have been an identifier.  */
8551       intel_putback_token ();
8552       cur_token.code = T_ID;
8553       /* FALLTHRU */
8554
8555     /* e11  id
8556             | constant  */
8557     case T_ID:
8558       if (!intel_parser.in_offset && intel_parser.is_mem <= 0)
8559         {
8560           symbolS *symbolP;
8561
8562           /* The identifier represents a memory reference only if it's not
8563              preceded by an offset modifier and if it's not an equate.  */
8564           symbolP = symbol_find(cur_token.str);
8565           if (!symbolP || S_GET_SEGMENT(symbolP) != absolute_section)
8566             intel_parser.is_mem = 1;
8567         }
8568         /* FALLTHRU */
8569
8570     case T_CONST:
8571     case '-':
8572     case '+':
8573       {
8574         char *save_str, sign = 0;
8575
8576         /* Allow constants that start with `+' or `-'.  */
8577         if (cur_token.code == '-' || cur_token.code == '+')
8578           {
8579             sign = cur_token.code;
8580             intel_match_token (cur_token.code);
8581             if (cur_token.code != T_CONST)
8582               {
8583                 as_bad (_("Syntax error: Expecting a constant, got `%s'"),
8584                         cur_token.str);
8585                 return 0;
8586               }
8587           }
8588
8589         save_str = (char *) xmalloc (strlen (cur_token.str) + 2);
8590         strcpy (save_str + !!sign, cur_token.str);
8591         if (sign)
8592           *save_str = sign;
8593
8594         /* Get the next token to check for register scaling.  */
8595         intel_match_token (cur_token.code);
8596
8597         /* Check if this constant is a scaling factor for an
8598            index register.  */
8599         if (cur_token.code == '*')
8600           {
8601             if (intel_match_token ('*') && cur_token.code == T_REG)
8602               {
8603                 const reg_entry *reg = cur_token.reg;
8604
8605                 if (!intel_parser.in_bracket)
8606                   {
8607                     as_bad (_("Register scaling only allowed "
8608                               "in memory operands"));
8609                     return 0;
8610                   }
8611
8612                  /* Disallow things like [1*si].
8613                     sp and esp are invalid as index.  */
8614                 if (reg->reg_type.bitfield.reg16)
8615                   reg = i386_regtab + REGNAM_AX + 4;
8616                 else if (i.index_reg)
8617                   reg = i386_regtab + REGNAM_EAX + 4;
8618
8619                 /* The constant is followed by `* reg', so it must be
8620                    a valid scale.  */
8621                 i.index_reg = reg;
8622                 i.types[this_operand].bitfield.baseindex = 1;
8623
8624                 /* Set the scale after setting the register (otherwise,
8625                    i386_scale will complain)  */
8626                 if (!i386_scale (save_str))
8627                   return 0;
8628                 intel_match_token (T_REG);
8629
8630                 /* Since registers are not part of the displacement
8631                    string, we may need to remove any preceding '+' from
8632                    the displacement string.  */
8633                 if (*intel_parser.disp != '\0')
8634                   {
8635                     char *s = intel_parser.disp;
8636                     s += strlen (s) - 1;
8637                     if (*s == '+')
8638                       *s = '\0';
8639                   }
8640
8641                 free (save_str);
8642
8643                 return 1;
8644               }
8645
8646             /* The constant was not used for register scaling. Since we have
8647                already consumed the token following `*' we now need to put it
8648                back in the stream.  */
8649             intel_putback_token ();
8650           }
8651
8652         /* Add the constant to the displacement string.  */
8653         strcat (intel_parser.disp, save_str);
8654         free (save_str);
8655
8656         return 1;
8657       }
8658     }
8659
8660   as_bad (_("Unrecognized token '%s'"), cur_token.str);
8661   return 0;
8662 }
8663
8664 /* Match the given token against cur_token. If they match, read the next
8665    token from the operand string.  */
8666 static int
8667 intel_match_token (int code)
8668 {
8669   if (cur_token.code == code)
8670     {
8671       intel_get_token ();
8672       return 1;
8673     }
8674   else
8675     {
8676       as_bad (_("Unexpected token `%s'"), cur_token.str);
8677       return 0;
8678     }
8679 }
8680
8681 /* Read a new token from intel_parser.op_string and store it in cur_token.  */
8682 static void
8683 intel_get_token (void)
8684 {
8685   char *end_op;
8686   const reg_entry *reg;
8687   struct intel_token new_token;
8688
8689   new_token.code = T_NIL;
8690   new_token.reg = NULL;
8691   new_token.str = NULL;
8692
8693   /* Free the memory allocated to the previous token and move
8694      cur_token to prev_token.  */
8695   if (prev_token.str)
8696     free (prev_token.str);
8697
8698   prev_token = cur_token;
8699
8700   /* Skip whitespace.  */
8701   while (is_space_char (*intel_parser.op_string))
8702     intel_parser.op_string++;
8703
8704   /* Return an empty token if we find nothing else on the line.  */
8705   if (*intel_parser.op_string == '\0')
8706     {
8707       cur_token = new_token;
8708       return;
8709     }
8710
8711   /* The new token cannot be larger than the remainder of the operand
8712      string.  */
8713   new_token.str = (char *) xmalloc (strlen (intel_parser.op_string) + 1);
8714   new_token.str[0] = '\0';
8715
8716   if (strchr ("0123456789", *intel_parser.op_string))
8717     {
8718       char *p = new_token.str;
8719       char *q = intel_parser.op_string;
8720       new_token.code = T_CONST;
8721
8722       /* Allow any kind of identifier char to encompass floating point and
8723          hexadecimal numbers.  */
8724       while (is_identifier_char (*q))
8725         *p++ = *q++;
8726       *p = '\0';
8727
8728       /* Recognize special symbol names [0-9][bf].  */
8729       if (strlen (intel_parser.op_string) == 2
8730           && (intel_parser.op_string[1] == 'b'
8731               || intel_parser.op_string[1] == 'f'))
8732         new_token.code = T_ID;
8733     }
8734
8735   else if ((reg = parse_register (intel_parser.op_string, &end_op)) != NULL)
8736     {
8737       size_t len = end_op - intel_parser.op_string;
8738
8739       new_token.code = T_REG;
8740       new_token.reg = reg;
8741
8742       memcpy (new_token.str, intel_parser.op_string, len);
8743       new_token.str[len] = '\0';
8744     }
8745
8746   else if (is_identifier_char (*intel_parser.op_string))
8747     {
8748       char *p = new_token.str;
8749       char *q = intel_parser.op_string;
8750
8751       /* A '.' or '$' followed by an identifier char is an identifier.
8752          Otherwise, it's operator '.' followed by an expression.  */
8753       if ((*q == '.' || *q == '$') && !is_identifier_char (*(q + 1)))
8754         {
8755           new_token.code = '.';
8756           new_token.str[0] = '.';
8757           new_token.str[1] = '\0';
8758         }
8759       else
8760         {
8761           while (is_identifier_char (*q) || *q == '@')
8762             *p++ = *q++;
8763           *p = '\0';
8764
8765           if (strcasecmp (new_token.str, "NOT") == 0)
8766             new_token.code = '~';
8767
8768           else if (strcasecmp (new_token.str, "MOD") == 0)
8769             new_token.code = '%';
8770
8771           else if (strcasecmp (new_token.str, "AND") == 0)
8772             new_token.code = '&';
8773
8774           else if (strcasecmp (new_token.str, "OR") == 0)
8775             new_token.code = '|';
8776
8777           else if (strcasecmp (new_token.str, "XOR") == 0)
8778             new_token.code = '^';
8779
8780           else if (strcasecmp (new_token.str, "SHL") == 0)
8781             new_token.code = T_SHL;
8782
8783           else if (strcasecmp (new_token.str, "SHR") == 0)
8784             new_token.code = T_SHR;
8785
8786           else if (strcasecmp (new_token.str, "BYTE") == 0)
8787             new_token.code = T_BYTE;
8788
8789           else if (strcasecmp (new_token.str, "WORD") == 0)
8790             new_token.code = T_WORD;
8791
8792           else if (strcasecmp (new_token.str, "DWORD") == 0)
8793             new_token.code = T_DWORD;
8794
8795           else if (strcasecmp (new_token.str, "FWORD") == 0)
8796             new_token.code = T_FWORD;
8797
8798           else if (strcasecmp (new_token.str, "QWORD") == 0)
8799             new_token.code = T_QWORD;
8800
8801           else if (strcasecmp (new_token.str, "TBYTE") == 0
8802                    /* XXX remove (gcc still uses it) */
8803                    || strcasecmp (new_token.str, "XWORD") == 0)
8804             new_token.code = T_TBYTE;
8805
8806           else if (strcasecmp (new_token.str, "XMMWORD") == 0
8807                    || strcasecmp (new_token.str, "OWORD") == 0)
8808             new_token.code = T_XMMWORD;
8809
8810           else if (strcasecmp (new_token.str, "PTR") == 0)
8811             new_token.code = T_PTR;
8812
8813           else if (strcasecmp (new_token.str, "SHORT") == 0)
8814             new_token.code = T_SHORT;
8815
8816           else if (strcasecmp (new_token.str, "OFFSET") == 0)
8817             {
8818               new_token.code = T_OFFSET;
8819
8820               /* ??? This is not mentioned in the MASM grammar but gcc
8821                      makes use of it with -mintel-syntax.  OFFSET may be
8822                      followed by FLAT:  */
8823               if (strncasecmp (q, " FLAT:", 6) == 0)
8824                 strcat (new_token.str, " FLAT:");
8825             }
8826
8827           /* ??? This is not mentioned in the MASM grammar.  */
8828           else if (strcasecmp (new_token.str, "FLAT") == 0)
8829             {
8830               new_token.code = T_OFFSET;
8831               if (*q == ':')
8832                 strcat (new_token.str, ":");
8833               else
8834                 as_bad (_("`:' expected"));
8835             }
8836
8837           else
8838             new_token.code = T_ID;
8839         }
8840     }
8841
8842   else if (strchr ("+-/*%|&^:[]()~", *intel_parser.op_string))
8843     {
8844       new_token.code = *intel_parser.op_string;
8845       new_token.str[0] = *intel_parser.op_string;
8846       new_token.str[1] = '\0';
8847     }
8848
8849   else if (strchr ("<>", *intel_parser.op_string)
8850            && *intel_parser.op_string == *(intel_parser.op_string + 1))
8851     {
8852       new_token.code = *intel_parser.op_string == '<' ? T_SHL : T_SHR;
8853       new_token.str[0] = *intel_parser.op_string;
8854       new_token.str[1] = *intel_parser.op_string;
8855       new_token.str[2] = '\0';
8856     }
8857
8858   else
8859     as_bad (_("Unrecognized token `%s'"), intel_parser.op_string);
8860
8861   intel_parser.op_string += strlen (new_token.str);
8862   cur_token = new_token;
8863 }
8864
8865 /* Put cur_token back into the token stream and make cur_token point to
8866    prev_token.  */
8867 static void
8868 intel_putback_token (void)
8869 {
8870   if (cur_token.code != T_NIL)
8871     {
8872       intel_parser.op_string -= strlen (cur_token.str);
8873       free (cur_token.str);
8874     }
8875   cur_token = prev_token;
8876
8877   /* Forget prev_token.  */
8878   prev_token.code = T_NIL;
8879   prev_token.reg = NULL;
8880   prev_token.str = NULL;
8881 }
8882
8883 int
8884 tc_x86_regname_to_dw2regnum (char *regname)
8885 {
8886   unsigned int regnum;
8887   unsigned int regnames_count;
8888   static const char *const regnames_32[] =
8889     {
8890       "eax", "ecx", "edx", "ebx",
8891       "esp", "ebp", "esi", "edi",
8892       "eip", "eflags", NULL,
8893       "st0", "st1", "st2", "st3",
8894       "st4", "st5", "st6", "st7",
8895       NULL, NULL,
8896       "xmm0", "xmm1", "xmm2", "xmm3",
8897       "xmm4", "xmm5", "xmm6", "xmm7",
8898       "mm0", "mm1", "mm2", "mm3",
8899       "mm4", "mm5", "mm6", "mm7",
8900       "fcw", "fsw", "mxcsr",
8901       "es", "cs", "ss", "ds", "fs", "gs", NULL, NULL,
8902       "tr", "ldtr"
8903     };
8904   static const char *const regnames_64[] =
8905     {
8906       "rax", "rdx", "rcx", "rbx",
8907       "rsi", "rdi", "rbp", "rsp",
8908       "r8",  "r9",  "r10", "r11",
8909       "r12", "r13", "r14", "r15",
8910       "rip",
8911       "xmm0",  "xmm1",  "xmm2",  "xmm3",
8912       "xmm4",  "xmm5",  "xmm6",  "xmm7",
8913       "xmm8",  "xmm9",  "xmm10", "xmm11",
8914       "xmm12", "xmm13", "xmm14", "xmm15",
8915       "st0", "st1", "st2", "st3",
8916       "st4", "st5", "st6", "st7",
8917       "mm0", "mm1", "mm2", "mm3",
8918       "mm4", "mm5", "mm6", "mm7",
8919       "rflags",
8920       "es", "cs", "ss", "ds", "fs", "gs", NULL, NULL,
8921       "fs.base", "gs.base", NULL, NULL,
8922       "tr", "ldtr",
8923       "mxcsr", "fcw", "fsw"
8924     };
8925   const char *const *regnames;
8926
8927   if (flag_code == CODE_64BIT)
8928     {
8929       regnames = regnames_64;
8930       regnames_count = ARRAY_SIZE (regnames_64);
8931     }
8932   else
8933     {
8934       regnames = regnames_32;
8935       regnames_count = ARRAY_SIZE (regnames_32);
8936     }
8937
8938   for (regnum = 0; regnum < regnames_count; regnum++)
8939     if (regnames[regnum] != NULL
8940         && strcmp (regname, regnames[regnum]) == 0)
8941       return regnum;
8942
8943   return -1;
8944 }
8945
8946 void
8947 tc_x86_frame_initial_instructions (void)
8948 {
8949   static unsigned int sp_regno;
8950
8951   if (!sp_regno)
8952     sp_regno = tc_x86_regname_to_dw2regnum (flag_code == CODE_64BIT
8953                                             ? "rsp" : "esp");
8954
8955   cfi_add_CFA_def_cfa (sp_regno, -x86_cie_data_alignment);
8956   cfi_add_CFA_offset (x86_dwarf2_return_column, x86_cie_data_alignment);
8957 }
8958
8959 int
8960 i386_elf_section_type (const char *str, size_t len)
8961 {
8962   if (flag_code == CODE_64BIT
8963       && len == sizeof ("unwind") - 1
8964       && strncmp (str, "unwind", 6) == 0)
8965     return SHT_X86_64_UNWIND;
8966
8967   return -1;
8968 }
8969
8970 #ifdef TE_PE
8971 void
8972 tc_pe_dwarf2_emit_offset (symbolS *symbol, unsigned int size)
8973 {
8974   expressionS expr;
8975
8976   expr.X_op = O_secrel;
8977   expr.X_add_symbol = symbol;
8978   expr.X_add_number = 0;
8979   emit_expr (&expr, size);
8980 }
8981 #endif
8982
8983 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
8984 /* For ELF on x86-64, add support for SHF_X86_64_LARGE.  */
8985
8986 int
8987 x86_64_section_letter (int letter, char **ptr_msg)
8988 {
8989   if (flag_code == CODE_64BIT)
8990     {
8991       if (letter == 'l')
8992         return SHF_X86_64_LARGE;
8993
8994       *ptr_msg = _("Bad .section directive: want a,l,w,x,M,S,G,T in string");
8995     }
8996   else
8997     *ptr_msg = _("Bad .section directive: want a,w,x,M,S,G,T in string");
8998   return -1;
8999 }
9000
9001 int
9002 x86_64_section_word (char *str, size_t len)
9003 {
9004   if (len == 5 && flag_code == CODE_64BIT && CONST_STRNEQ (str, "large"))
9005     return SHF_X86_64_LARGE;
9006
9007   return -1;
9008 }
9009
9010 static void
9011 handle_large_common (int small ATTRIBUTE_UNUSED)
9012 {
9013   if (flag_code != CODE_64BIT)
9014     {
9015       s_comm_internal (0, elf_common_parse);
9016       as_warn (_(".largecomm supported only in 64bit mode, producing .comm"));
9017     }
9018   else
9019     {
9020       static segT lbss_section;
9021       asection *saved_com_section_ptr = elf_com_section_ptr;
9022       asection *saved_bss_section = bss_section;
9023
9024       if (lbss_section == NULL)
9025         {
9026           flagword applicable;
9027           segT seg = now_seg;
9028           subsegT subseg = now_subseg;
9029
9030           /* The .lbss section is for local .largecomm symbols.  */
9031           lbss_section = subseg_new (".lbss", 0);
9032           applicable = bfd_applicable_section_flags (stdoutput);
9033           bfd_set_section_flags (stdoutput, lbss_section,
9034                                  applicable & SEC_ALLOC);
9035           seg_info (lbss_section)->bss = 1;
9036
9037           subseg_set (seg, subseg);
9038         }
9039
9040       elf_com_section_ptr = &_bfd_elf_large_com_section;
9041       bss_section = lbss_section;
9042
9043       s_comm_internal (0, elf_common_parse);
9044
9045       elf_com_section_ptr = saved_com_section_ptr;
9046       bss_section = saved_bss_section;
9047     }
9048 }
9049 #endif /* OBJ_ELF || OBJ_MAYBE_ELF */