AArch64: Wire through instr_sequence
[external/binutils.git] / gas / config / tc-aarch64.c
1 /* tc-aarch64.c -- Assemble for the AArch64 ISA
2
3    Copyright (C) 2009-2018 Free Software Foundation, Inc.
4    Contributed by ARM Ltd.
5
6    This file is part of GAS.
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 of the license, or
11    (at your option) 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 this program; see the file COPYING3. If not,
20    see <http://www.gnu.org/licenses/>.  */
21
22 #include "as.h"
23 #include <limits.h>
24 #include <stdarg.h>
25 #include "bfd_stdint.h"
26 #define  NO_RELOC 0
27 #include "safe-ctype.h"
28 #include "subsegs.h"
29 #include "obstack.h"
30
31 #ifdef OBJ_ELF
32 #include "elf/aarch64.h"
33 #include "dw2gencfi.h"
34 #endif
35
36 #include "dwarf2dbg.h"
37
38 /* Types of processor to assemble for.  */
39 #ifndef CPU_DEFAULT
40 #define CPU_DEFAULT AARCH64_ARCH_V8
41 #endif
42
43 #define streq(a, b)           (strcmp (a, b) == 0)
44
45 #define END_OF_INSN '\0'
46
47 static aarch64_feature_set cpu_variant;
48
49 /* Variables that we set while parsing command-line options.  Once all
50    options have been read we re-process these values to set the real
51    assembly flags.  */
52 static const aarch64_feature_set *mcpu_cpu_opt = NULL;
53 static const aarch64_feature_set *march_cpu_opt = NULL;
54
55 /* Constants for known architecture features.  */
56 static const aarch64_feature_set cpu_default = CPU_DEFAULT;
57
58 /* Currently active instruction sequence.  */
59 static aarch64_instr_sequence *insn_sequence = NULL;
60
61 #ifdef OBJ_ELF
62 /* Pre-defined "_GLOBAL_OFFSET_TABLE_"  */
63 static symbolS *GOT_symbol;
64
65 /* Which ABI to use.  */
66 enum aarch64_abi_type
67 {
68   AARCH64_ABI_NONE = 0,
69   AARCH64_ABI_LP64 = 1,
70   AARCH64_ABI_ILP32 = 2
71 };
72
73 #ifndef DEFAULT_ARCH
74 #define DEFAULT_ARCH "aarch64"
75 #endif
76
77 /* DEFAULT_ARCH is initialized in gas/configure.tgt.  */
78 static const char *default_arch = DEFAULT_ARCH;
79
80 /* AArch64 ABI for the output file.  */
81 static enum aarch64_abi_type aarch64_abi = AARCH64_ABI_NONE;
82
83 /* When non-zero, program to a 32-bit model, in which the C data types
84    int, long and all pointer types are 32-bit objects (ILP32); or to a
85    64-bit model, in which the C int type is 32-bits but the C long type
86    and all pointer types are 64-bit objects (LP64).  */
87 #define ilp32_p         (aarch64_abi == AARCH64_ABI_ILP32)
88 #endif
89
90 enum vector_el_type
91 {
92   NT_invtype = -1,
93   NT_b,
94   NT_h,
95   NT_s,
96   NT_d,
97   NT_q,
98   NT_zero,
99   NT_merge
100 };
101
102 /* Bits for DEFINED field in vector_type_el.  */
103 #define NTA_HASTYPE     1
104 #define NTA_HASINDEX    2
105 #define NTA_HASVARWIDTH 4
106
107 struct vector_type_el
108 {
109   enum vector_el_type type;
110   unsigned char defined;
111   unsigned width;
112   int64_t index;
113 };
114
115 #define FIXUP_F_HAS_EXPLICIT_SHIFT      0x00000001
116
117 struct reloc
118 {
119   bfd_reloc_code_real_type type;
120   expressionS exp;
121   int pc_rel;
122   enum aarch64_opnd opnd;
123   uint32_t flags;
124   unsigned need_libopcodes_p : 1;
125 };
126
127 struct aarch64_instruction
128 {
129   /* libopcodes structure for instruction intermediate representation.  */
130   aarch64_inst base;
131   /* Record assembly errors found during the parsing.  */
132   struct
133     {
134       enum aarch64_operand_error_kind kind;
135       const char *error;
136     } parsing_error;
137   /* The condition that appears in the assembly line.  */
138   int cond;
139   /* Relocation information (including the GAS internal fixup).  */
140   struct reloc reloc;
141   /* Need to generate an immediate in the literal pool.  */
142   unsigned gen_lit_pool : 1;
143 };
144
145 typedef struct aarch64_instruction aarch64_instruction;
146
147 static aarch64_instruction inst;
148
149 static bfd_boolean parse_operands (char *, const aarch64_opcode *);
150 static bfd_boolean programmer_friendly_fixup (aarch64_instruction *);
151
152 #ifdef OBJ_ELF
153 #  define now_instr_sequence seg_info \
154                 (now_seg)->tc_segment_info_data.insn_sequence
155 #else
156 static struct aarch64_instr_sequence now_instr_sequence;
157 #endif
158
159 /* Diagnostics inline function utilities.
160
161    These are lightweight utilities which should only be called by parse_operands
162    and other parsers.  GAS processes each assembly line by parsing it against
163    instruction template(s), in the case of multiple templates (for the same
164    mnemonic name), those templates are tried one by one until one succeeds or
165    all fail.  An assembly line may fail a few templates before being
166    successfully parsed; an error saved here in most cases is not a user error
167    but an error indicating the current template is not the right template.
168    Therefore it is very important that errors can be saved at a low cost during
169    the parsing; we don't want to slow down the whole parsing by recording
170    non-user errors in detail.
171
172    Remember that the objective is to help GAS pick up the most appropriate
173    error message in the case of multiple templates, e.g. FMOV which has 8
174    templates.  */
175
176 static inline void
177 clear_error (void)
178 {
179   inst.parsing_error.kind = AARCH64_OPDE_NIL;
180   inst.parsing_error.error = NULL;
181 }
182
183 static inline bfd_boolean
184 error_p (void)
185 {
186   return inst.parsing_error.kind != AARCH64_OPDE_NIL;
187 }
188
189 static inline const char *
190 get_error_message (void)
191 {
192   return inst.parsing_error.error;
193 }
194
195 static inline enum aarch64_operand_error_kind
196 get_error_kind (void)
197 {
198   return inst.parsing_error.kind;
199 }
200
201 static inline void
202 set_error (enum aarch64_operand_error_kind kind, const char *error)
203 {
204   inst.parsing_error.kind = kind;
205   inst.parsing_error.error = error;
206 }
207
208 static inline void
209 set_recoverable_error (const char *error)
210 {
211   set_error (AARCH64_OPDE_RECOVERABLE, error);
212 }
213
214 /* Use the DESC field of the corresponding aarch64_operand entry to compose
215    the error message.  */
216 static inline void
217 set_default_error (void)
218 {
219   set_error (AARCH64_OPDE_SYNTAX_ERROR, NULL);
220 }
221
222 static inline void
223 set_syntax_error (const char *error)
224 {
225   set_error (AARCH64_OPDE_SYNTAX_ERROR, error);
226 }
227
228 static inline void
229 set_first_syntax_error (const char *error)
230 {
231   if (! error_p ())
232     set_error (AARCH64_OPDE_SYNTAX_ERROR, error);
233 }
234
235 static inline void
236 set_fatal_syntax_error (const char *error)
237 {
238   set_error (AARCH64_OPDE_FATAL_SYNTAX_ERROR, error);
239 }
240 \f
241 /* Number of littlenums required to hold an extended precision number.  */
242 #define MAX_LITTLENUMS 6
243
244 /* Return value for certain parsers when the parsing fails; those parsers
245    return the information of the parsed result, e.g. register number, on
246    success.  */
247 #define PARSE_FAIL -1
248
249 /* This is an invalid condition code that means no conditional field is
250    present. */
251 #define COND_ALWAYS 0x10
252
253 typedef struct
254 {
255   const char *template;
256   unsigned long value;
257 } asm_barrier_opt;
258
259 typedef struct
260 {
261   const char *template;
262   uint32_t value;
263 } asm_nzcv;
264
265 struct reloc_entry
266 {
267   char *name;
268   bfd_reloc_code_real_type reloc;
269 };
270
271 /* Macros to define the register types and masks for the purpose
272    of parsing.  */
273
274 #undef AARCH64_REG_TYPES
275 #define AARCH64_REG_TYPES       \
276   BASIC_REG_TYPE(R_32)  /* w[0-30] */   \
277   BASIC_REG_TYPE(R_64)  /* x[0-30] */   \
278   BASIC_REG_TYPE(SP_32) /* wsp     */   \
279   BASIC_REG_TYPE(SP_64) /* sp      */   \
280   BASIC_REG_TYPE(Z_32)  /* wzr     */   \
281   BASIC_REG_TYPE(Z_64)  /* xzr     */   \
282   BASIC_REG_TYPE(FP_B)  /* b[0-31] *//* NOTE: keep FP_[BHSDQ] consecutive! */\
283   BASIC_REG_TYPE(FP_H)  /* h[0-31] */   \
284   BASIC_REG_TYPE(FP_S)  /* s[0-31] */   \
285   BASIC_REG_TYPE(FP_D)  /* d[0-31] */   \
286   BASIC_REG_TYPE(FP_Q)  /* q[0-31] */   \
287   BASIC_REG_TYPE(VN)    /* v[0-31] */   \
288   BASIC_REG_TYPE(ZN)    /* z[0-31] */   \
289   BASIC_REG_TYPE(PN)    /* p[0-15] */   \
290   /* Typecheck: any 64-bit int reg         (inc SP exc XZR).  */        \
291   MULTI_REG_TYPE(R64_SP, REG_TYPE(R_64) | REG_TYPE(SP_64))              \
292   /* Typecheck: same, plus SVE registers.  */                           \
293   MULTI_REG_TYPE(SVE_BASE, REG_TYPE(R_64) | REG_TYPE(SP_64)             \
294                  | REG_TYPE(ZN))                                        \
295   /* Typecheck: x[0-30], w[0-30] or [xw]zr.  */                         \
296   MULTI_REG_TYPE(R_Z, REG_TYPE(R_32) | REG_TYPE(R_64)                   \
297                  | REG_TYPE(Z_32) | REG_TYPE(Z_64))                     \
298   /* Typecheck: same, plus SVE registers.  */                           \
299   MULTI_REG_TYPE(SVE_OFFSET, REG_TYPE(R_32) | REG_TYPE(R_64)            \
300                  | REG_TYPE(Z_32) | REG_TYPE(Z_64)                      \
301                  | REG_TYPE(ZN))                                        \
302   /* Typecheck: x[0-30], w[0-30] or {w}sp.  */                          \
303   MULTI_REG_TYPE(R_SP, REG_TYPE(R_32) | REG_TYPE(R_64)                  \
304                  | REG_TYPE(SP_32) | REG_TYPE(SP_64))                   \
305   /* Typecheck: any int                    (inc {W}SP inc [WX]ZR).  */  \
306   MULTI_REG_TYPE(R_Z_SP, REG_TYPE(R_32) | REG_TYPE(R_64)                \
307                  | REG_TYPE(SP_32) | REG_TYPE(SP_64)                    \
308                  | REG_TYPE(Z_32) | REG_TYPE(Z_64))                     \
309   /* Typecheck: any [BHSDQ]P FP.  */                                    \
310   MULTI_REG_TYPE(BHSDQ, REG_TYPE(FP_B) | REG_TYPE(FP_H)                 \
311                  | REG_TYPE(FP_S) | REG_TYPE(FP_D) | REG_TYPE(FP_Q))    \
312   /* Typecheck: any int or [BHSDQ]P FP or V reg (exc SP inc [WX]ZR).  */ \
313   MULTI_REG_TYPE(R_Z_BHSDQ_V, REG_TYPE(R_32) | REG_TYPE(R_64)           \
314                  | REG_TYPE(Z_32) | REG_TYPE(Z_64) | REG_TYPE(VN)       \
315                  | REG_TYPE(FP_B) | REG_TYPE(FP_H)                      \
316                  | REG_TYPE(FP_S) | REG_TYPE(FP_D) | REG_TYPE(FP_Q))    \
317   /* Typecheck: as above, but also Zn, Pn, and {W}SP.  This should only \
318      be used for SVE instructions, since Zn and Pn are valid symbols    \
319      in other contexts.  */                                             \
320   MULTI_REG_TYPE(R_Z_SP_BHSDQ_VZP, REG_TYPE(R_32) | REG_TYPE(R_64)      \
321                  | REG_TYPE(SP_32) | REG_TYPE(SP_64)                    \
322                  | REG_TYPE(Z_32) | REG_TYPE(Z_64) | REG_TYPE(VN)       \
323                  | REG_TYPE(FP_B) | REG_TYPE(FP_H)                      \
324                  | REG_TYPE(FP_S) | REG_TYPE(FP_D) | REG_TYPE(FP_Q)     \
325                  | REG_TYPE(ZN) | REG_TYPE(PN))                         \
326   /* Any integer register; used for error messages only.  */            \
327   MULTI_REG_TYPE(R_N, REG_TYPE(R_32) | REG_TYPE(R_64)                   \
328                  | REG_TYPE(SP_32) | REG_TYPE(SP_64)                    \
329                  | REG_TYPE(Z_32) | REG_TYPE(Z_64))                     \
330   /* Pseudo type to mark the end of the enumerator sequence.  */        \
331   BASIC_REG_TYPE(MAX)
332
333 #undef BASIC_REG_TYPE
334 #define BASIC_REG_TYPE(T)       REG_TYPE_##T,
335 #undef MULTI_REG_TYPE
336 #define MULTI_REG_TYPE(T,V)     BASIC_REG_TYPE(T)
337
338 /* Register type enumerators.  */
339 typedef enum aarch64_reg_type_
340 {
341   /* A list of REG_TYPE_*.  */
342   AARCH64_REG_TYPES
343 } aarch64_reg_type;
344
345 #undef BASIC_REG_TYPE
346 #define BASIC_REG_TYPE(T)       1 << REG_TYPE_##T,
347 #undef REG_TYPE
348 #define REG_TYPE(T)             (1 << REG_TYPE_##T)
349 #undef MULTI_REG_TYPE
350 #define MULTI_REG_TYPE(T,V)     V,
351
352 /* Structure for a hash table entry for a register.  */
353 typedef struct
354 {
355   const char *name;
356   unsigned char number;
357   ENUM_BITFIELD (aarch64_reg_type_) type : 8;
358   unsigned char builtin;
359 } reg_entry;
360
361 /* Values indexed by aarch64_reg_type to assist the type checking.  */
362 static const unsigned reg_type_masks[] =
363 {
364   AARCH64_REG_TYPES
365 };
366
367 #undef BASIC_REG_TYPE
368 #undef REG_TYPE
369 #undef MULTI_REG_TYPE
370 #undef AARCH64_REG_TYPES
371
372 /* Diagnostics used when we don't get a register of the expected type.
373    Note:  this has to synchronized with aarch64_reg_type definitions
374    above.  */
375 static const char *
376 get_reg_expected_msg (aarch64_reg_type reg_type)
377 {
378   const char *msg;
379
380   switch (reg_type)
381     {
382     case REG_TYPE_R_32:
383       msg = N_("integer 32-bit register expected");
384       break;
385     case REG_TYPE_R_64:
386       msg = N_("integer 64-bit register expected");
387       break;
388     case REG_TYPE_R_N:
389       msg = N_("integer register expected");
390       break;
391     case REG_TYPE_R64_SP:
392       msg = N_("64-bit integer or SP register expected");
393       break;
394     case REG_TYPE_SVE_BASE:
395       msg = N_("base register expected");
396       break;
397     case REG_TYPE_R_Z:
398       msg = N_("integer or zero register expected");
399       break;
400     case REG_TYPE_SVE_OFFSET:
401       msg = N_("offset register expected");
402       break;
403     case REG_TYPE_R_SP:
404       msg = N_("integer or SP register expected");
405       break;
406     case REG_TYPE_R_Z_SP:
407       msg = N_("integer, zero or SP register expected");
408       break;
409     case REG_TYPE_FP_B:
410       msg = N_("8-bit SIMD scalar register expected");
411       break;
412     case REG_TYPE_FP_H:
413       msg = N_("16-bit SIMD scalar or floating-point half precision "
414                "register expected");
415       break;
416     case REG_TYPE_FP_S:
417       msg = N_("32-bit SIMD scalar or floating-point single precision "
418                "register expected");
419       break;
420     case REG_TYPE_FP_D:
421       msg = N_("64-bit SIMD scalar or floating-point double precision "
422                "register expected");
423       break;
424     case REG_TYPE_FP_Q:
425       msg = N_("128-bit SIMD scalar or floating-point quad precision "
426                "register expected");
427       break;
428     case REG_TYPE_R_Z_BHSDQ_V:
429     case REG_TYPE_R_Z_SP_BHSDQ_VZP:
430       msg = N_("register expected");
431       break;
432     case REG_TYPE_BHSDQ:        /* any [BHSDQ]P FP  */
433       msg = N_("SIMD scalar or floating-point register expected");
434       break;
435     case REG_TYPE_VN:           /* any V reg  */
436       msg = N_("vector register expected");
437       break;
438     case REG_TYPE_ZN:
439       msg = N_("SVE vector register expected");
440       break;
441     case REG_TYPE_PN:
442       msg = N_("SVE predicate register expected");
443       break;
444     default:
445       as_fatal (_("invalid register type %d"), reg_type);
446     }
447   return msg;
448 }
449
450 /* Some well known registers that we refer to directly elsewhere.  */
451 #define REG_SP  31
452
453 /* Instructions take 4 bytes in the object file.  */
454 #define INSN_SIZE       4
455
456 static struct hash_control *aarch64_ops_hsh;
457 static struct hash_control *aarch64_cond_hsh;
458 static struct hash_control *aarch64_shift_hsh;
459 static struct hash_control *aarch64_sys_regs_hsh;
460 static struct hash_control *aarch64_pstatefield_hsh;
461 static struct hash_control *aarch64_sys_regs_ic_hsh;
462 static struct hash_control *aarch64_sys_regs_dc_hsh;
463 static struct hash_control *aarch64_sys_regs_at_hsh;
464 static struct hash_control *aarch64_sys_regs_tlbi_hsh;
465 static struct hash_control *aarch64_reg_hsh;
466 static struct hash_control *aarch64_barrier_opt_hsh;
467 static struct hash_control *aarch64_nzcv_hsh;
468 static struct hash_control *aarch64_pldop_hsh;
469 static struct hash_control *aarch64_hint_opt_hsh;
470
471 /* Stuff needed to resolve the label ambiguity
472    As:
473      ...
474      label:   <insn>
475    may differ from:
476      ...
477      label:
478               <insn>  */
479
480 static symbolS *last_label_seen;
481
482 /* Literal pool structure.  Held on a per-section
483    and per-sub-section basis.  */
484
485 #define MAX_LITERAL_POOL_SIZE 1024
486 typedef struct literal_expression
487 {
488   expressionS exp;
489   /* If exp.op == O_big then this bignum holds a copy of the global bignum value.  */
490   LITTLENUM_TYPE * bignum;
491 } literal_expression;
492
493 typedef struct literal_pool
494 {
495   literal_expression literals[MAX_LITERAL_POOL_SIZE];
496   unsigned int next_free_entry;
497   unsigned int id;
498   symbolS *symbol;
499   segT section;
500   subsegT sub_section;
501   int size;
502   struct literal_pool *next;
503 } literal_pool;
504
505 /* Pointer to a linked list of literal pools.  */
506 static literal_pool *list_of_pools = NULL;
507 \f
508 /* Pure syntax.  */
509
510 /* This array holds the chars that always start a comment.  If the
511    pre-processor is disabled, these aren't very useful.  */
512 const char comment_chars[] = "";
513
514 /* This array holds the chars that only start a comment at the beginning of
515    a line.  If the line seems to have the form '# 123 filename'
516    .line and .file directives will appear in the pre-processed output.  */
517 /* Note that input_file.c hand checks for '#' at the beginning of the
518    first line of the input file.  This is because the compiler outputs
519    #NO_APP at the beginning of its output.  */
520 /* Also note that comments like this one will always work.  */
521 const char line_comment_chars[] = "#";
522
523 const char line_separator_chars[] = ";";
524
525 /* Chars that can be used to separate mant
526    from exp in floating point numbers.  */
527 const char EXP_CHARS[] = "eE";
528
529 /* Chars that mean this number is a floating point constant.  */
530 /* As in 0f12.456  */
531 /* or    0d1.2345e12  */
532
533 const char FLT_CHARS[] = "rRsSfFdDxXeEpP";
534
535 /* Prefix character that indicates the start of an immediate value.  */
536 #define is_immediate_prefix(C) ((C) == '#')
537
538 /* Separator character handling.  */
539
540 #define skip_whitespace(str)  do { if (*(str) == ' ') ++(str); } while (0)
541
542 static inline bfd_boolean
543 skip_past_char (char **str, char c)
544 {
545   if (**str == c)
546     {
547       (*str)++;
548       return TRUE;
549     }
550   else
551     return FALSE;
552 }
553
554 #define skip_past_comma(str) skip_past_char (str, ',')
555
556 /* Arithmetic expressions (possibly involving symbols).  */
557
558 static bfd_boolean in_my_get_expression_p = FALSE;
559
560 /* Third argument to my_get_expression.  */
561 #define GE_NO_PREFIX 0
562 #define GE_OPT_PREFIX 1
563
564 /* Return TRUE if the string pointed by *STR is successfully parsed
565    as an valid expression; *EP will be filled with the information of
566    such an expression.  Otherwise return FALSE.  */
567
568 static bfd_boolean
569 my_get_expression (expressionS * ep, char **str, int prefix_mode,
570                    int reject_absent)
571 {
572   char *save_in;
573   segT seg;
574   int prefix_present_p = 0;
575
576   switch (prefix_mode)
577     {
578     case GE_NO_PREFIX:
579       break;
580     case GE_OPT_PREFIX:
581       if (is_immediate_prefix (**str))
582         {
583           (*str)++;
584           prefix_present_p = 1;
585         }
586       break;
587     default:
588       abort ();
589     }
590
591   memset (ep, 0, sizeof (expressionS));
592
593   save_in = input_line_pointer;
594   input_line_pointer = *str;
595   in_my_get_expression_p = TRUE;
596   seg = expression (ep);
597   in_my_get_expression_p = FALSE;
598
599   if (ep->X_op == O_illegal || (reject_absent && ep->X_op == O_absent))
600     {
601       /* We found a bad expression in md_operand().  */
602       *str = input_line_pointer;
603       input_line_pointer = save_in;
604       if (prefix_present_p && ! error_p ())
605         set_fatal_syntax_error (_("bad expression"));
606       else
607         set_first_syntax_error (_("bad expression"));
608       return FALSE;
609     }
610
611 #ifdef OBJ_AOUT
612   if (seg != absolute_section
613       && seg != text_section
614       && seg != data_section
615       && seg != bss_section && seg != undefined_section)
616     {
617       set_syntax_error (_("bad segment"));
618       *str = input_line_pointer;
619       input_line_pointer = save_in;
620       return FALSE;
621     }
622 #else
623   (void) seg;
624 #endif
625
626   *str = input_line_pointer;
627   input_line_pointer = save_in;
628   return TRUE;
629 }
630
631 /* Turn a string in input_line_pointer into a floating point constant
632    of type TYPE, and store the appropriate bytes in *LITP.  The number
633    of LITTLENUMS emitted is stored in *SIZEP.  An error message is
634    returned, or NULL on OK.  */
635
636 const char *
637 md_atof (int type, char *litP, int *sizeP)
638 {
639   return ieee_md_atof (type, litP, sizeP, target_big_endian);
640 }
641
642 /* We handle all bad expressions here, so that we can report the faulty
643    instruction in the error message.  */
644 void
645 md_operand (expressionS * exp)
646 {
647   if (in_my_get_expression_p)
648     exp->X_op = O_illegal;
649 }
650
651 /* Immediate values.  */
652
653 /* Errors may be set multiple times during parsing or bit encoding
654    (particularly in the Neon bits), but usually the earliest error which is set
655    will be the most meaningful. Avoid overwriting it with later (cascading)
656    errors by calling this function.  */
657
658 static void
659 first_error (const char *error)
660 {
661   if (! error_p ())
662     set_syntax_error (error);
663 }
664
665 /* Similar to first_error, but this function accepts formatted error
666    message.  */
667 static void
668 first_error_fmt (const char *format, ...)
669 {
670   va_list args;
671   enum
672   { size = 100 };
673   /* N.B. this single buffer will not cause error messages for different
674      instructions to pollute each other; this is because at the end of
675      processing of each assembly line, error message if any will be
676      collected by as_bad.  */
677   static char buffer[size];
678
679   if (! error_p ())
680     {
681       int ret ATTRIBUTE_UNUSED;
682       va_start (args, format);
683       ret = vsnprintf (buffer, size, format, args);
684       know (ret <= size - 1 && ret >= 0);
685       va_end (args);
686       set_syntax_error (buffer);
687     }
688 }
689
690 /* Register parsing.  */
691
692 /* Generic register parser which is called by other specialized
693    register parsers.
694    CCP points to what should be the beginning of a register name.
695    If it is indeed a valid register name, advance CCP over it and
696    return the reg_entry structure; otherwise return NULL.
697    It does not issue diagnostics.  */
698
699 static reg_entry *
700 parse_reg (char **ccp)
701 {
702   char *start = *ccp;
703   char *p;
704   reg_entry *reg;
705
706 #ifdef REGISTER_PREFIX
707   if (*start != REGISTER_PREFIX)
708     return NULL;
709   start++;
710 #endif
711
712   p = start;
713   if (!ISALPHA (*p) || !is_name_beginner (*p))
714     return NULL;
715
716   do
717     p++;
718   while (ISALPHA (*p) || ISDIGIT (*p) || *p == '_');
719
720   reg = (reg_entry *) hash_find_n (aarch64_reg_hsh, start, p - start);
721
722   if (!reg)
723     return NULL;
724
725   *ccp = p;
726   return reg;
727 }
728
729 /* Return TRUE if REG->TYPE is a valid type of TYPE; otherwise
730    return FALSE.  */
731 static bfd_boolean
732 aarch64_check_reg_type (const reg_entry *reg, aarch64_reg_type type)
733 {
734   return (reg_type_masks[type] & (1 << reg->type)) != 0;
735 }
736
737 /* Try to parse a base or offset register.  Allow SVE base and offset
738    registers if REG_TYPE includes SVE registers.  Return the register
739    entry on success, setting *QUALIFIER to the register qualifier.
740    Return null otherwise.
741
742    Note that this function does not issue any diagnostics.  */
743
744 static const reg_entry *
745 aarch64_addr_reg_parse (char **ccp, aarch64_reg_type reg_type,
746                         aarch64_opnd_qualifier_t *qualifier)
747 {
748   char *str = *ccp;
749   const reg_entry *reg = parse_reg (&str);
750
751   if (reg == NULL)
752     return NULL;
753
754   switch (reg->type)
755     {
756     case REG_TYPE_R_32:
757     case REG_TYPE_SP_32:
758     case REG_TYPE_Z_32:
759       *qualifier = AARCH64_OPND_QLF_W;
760       break;
761
762     case REG_TYPE_R_64:
763     case REG_TYPE_SP_64:
764     case REG_TYPE_Z_64:
765       *qualifier = AARCH64_OPND_QLF_X;
766       break;
767
768     case REG_TYPE_ZN:
769       if ((reg_type_masks[reg_type] & (1 << REG_TYPE_ZN)) == 0
770           || str[0] != '.')
771         return NULL;
772       switch (TOLOWER (str[1]))
773         {
774         case 's':
775           *qualifier = AARCH64_OPND_QLF_S_S;
776           break;
777         case 'd':
778           *qualifier = AARCH64_OPND_QLF_S_D;
779           break;
780         default:
781           return NULL;
782         }
783       str += 2;
784       break;
785
786     default:
787       return NULL;
788     }
789
790   *ccp = str;
791
792   return reg;
793 }
794
795 /* Try to parse a base or offset register.  Return the register entry
796    on success, setting *QUALIFIER to the register qualifier.  Return null
797    otherwise.
798
799    Note that this function does not issue any diagnostics.  */
800
801 static const reg_entry *
802 aarch64_reg_parse_32_64 (char **ccp, aarch64_opnd_qualifier_t *qualifier)
803 {
804   return aarch64_addr_reg_parse (ccp, REG_TYPE_R_Z_SP, qualifier);
805 }
806
807 /* Parse the qualifier of a vector register or vector element of type
808    REG_TYPE.  Fill in *PARSED_TYPE and return TRUE if the parsing
809    succeeds; otherwise return FALSE.
810
811    Accept only one occurrence of:
812    4b 8b 16b 2h 4h 8h 2s 4s 1d 2d
813    b h s d q  */
814 static bfd_boolean
815 parse_vector_type_for_operand (aarch64_reg_type reg_type,
816                                struct vector_type_el *parsed_type, char **str)
817 {
818   char *ptr = *str;
819   unsigned width;
820   unsigned element_size;
821   enum vector_el_type type;
822
823   /* skip '.' */
824   gas_assert (*ptr == '.');
825   ptr++;
826
827   if (reg_type == REG_TYPE_ZN || reg_type == REG_TYPE_PN || !ISDIGIT (*ptr))
828     {
829       width = 0;
830       goto elt_size;
831     }
832   width = strtoul (ptr, &ptr, 10);
833   if (width != 1 && width != 2 && width != 4 && width != 8 && width != 16)
834     {
835       first_error_fmt (_("bad size %d in vector width specifier"), width);
836       return FALSE;
837     }
838
839 elt_size:
840   switch (TOLOWER (*ptr))
841     {
842     case 'b':
843       type = NT_b;
844       element_size = 8;
845       break;
846     case 'h':
847       type = NT_h;
848       element_size = 16;
849       break;
850     case 's':
851       type = NT_s;
852       element_size = 32;
853       break;
854     case 'd':
855       type = NT_d;
856       element_size = 64;
857       break;
858     case 'q':
859       if (reg_type == REG_TYPE_ZN || width == 1)
860         {
861           type = NT_q;
862           element_size = 128;
863           break;
864         }
865       /* fall through.  */
866     default:
867       if (*ptr != '\0')
868         first_error_fmt (_("unexpected character `%c' in element size"), *ptr);
869       else
870         first_error (_("missing element size"));
871       return FALSE;
872     }
873   if (width != 0 && width * element_size != 64
874       && width * element_size != 128
875       && !(width == 2 && element_size == 16)
876       && !(width == 4 && element_size == 8))
877     {
878       first_error_fmt (_
879                        ("invalid element size %d and vector size combination %c"),
880                        width, *ptr);
881       return FALSE;
882     }
883   ptr++;
884
885   parsed_type->type = type;
886   parsed_type->width = width;
887
888   *str = ptr;
889
890   return TRUE;
891 }
892
893 /* *STR contains an SVE zero/merge predication suffix.  Parse it into
894    *PARSED_TYPE and point *STR at the end of the suffix.  */
895
896 static bfd_boolean
897 parse_predication_for_operand (struct vector_type_el *parsed_type, char **str)
898 {
899   char *ptr = *str;
900
901   /* Skip '/'.  */
902   gas_assert (*ptr == '/');
903   ptr++;
904   switch (TOLOWER (*ptr))
905     {
906     case 'z':
907       parsed_type->type = NT_zero;
908       break;
909     case 'm':
910       parsed_type->type = NT_merge;
911       break;
912     default:
913       if (*ptr != '\0' && *ptr != ',')
914         first_error_fmt (_("unexpected character `%c' in predication type"),
915                          *ptr);
916       else
917         first_error (_("missing predication type"));
918       return FALSE;
919     }
920   parsed_type->width = 0;
921   *str = ptr + 1;
922   return TRUE;
923 }
924
925 /* Parse a register of the type TYPE.
926
927    Return PARSE_FAIL if the string pointed by *CCP is not a valid register
928    name or the parsed register is not of TYPE.
929
930    Otherwise return the register number, and optionally fill in the actual
931    type of the register in *RTYPE when multiple alternatives were given, and
932    return the register shape and element index information in *TYPEINFO.
933
934    IN_REG_LIST should be set with TRUE if the caller is parsing a register
935    list.  */
936
937 static int
938 parse_typed_reg (char **ccp, aarch64_reg_type type, aarch64_reg_type *rtype,
939                  struct vector_type_el *typeinfo, bfd_boolean in_reg_list)
940 {
941   char *str = *ccp;
942   const reg_entry *reg = parse_reg (&str);
943   struct vector_type_el atype;
944   struct vector_type_el parsetype;
945   bfd_boolean is_typed_vecreg = FALSE;
946
947   atype.defined = 0;
948   atype.type = NT_invtype;
949   atype.width = -1;
950   atype.index = 0;
951
952   if (reg == NULL)
953     {
954       if (typeinfo)
955         *typeinfo = atype;
956       set_default_error ();
957       return PARSE_FAIL;
958     }
959
960   if (! aarch64_check_reg_type (reg, type))
961     {
962       DEBUG_TRACE ("reg type check failed");
963       set_default_error ();
964       return PARSE_FAIL;
965     }
966   type = reg->type;
967
968   if ((type == REG_TYPE_VN || type == REG_TYPE_ZN || type == REG_TYPE_PN)
969       && (*str == '.' || (type == REG_TYPE_PN && *str == '/')))
970     {
971       if (*str == '.')
972         {
973           if (!parse_vector_type_for_operand (type, &parsetype, &str))
974             return PARSE_FAIL;
975         }
976       else
977         {
978           if (!parse_predication_for_operand (&parsetype, &str))
979             return PARSE_FAIL;
980         }
981
982       /* Register if of the form Vn.[bhsdq].  */
983       is_typed_vecreg = TRUE;
984
985       if (type == REG_TYPE_ZN || type == REG_TYPE_PN)
986         {
987           /* The width is always variable; we don't allow an integer width
988              to be specified.  */
989           gas_assert (parsetype.width == 0);
990           atype.defined |= NTA_HASVARWIDTH | NTA_HASTYPE;
991         }
992       else if (parsetype.width == 0)
993         /* Expect index. In the new scheme we cannot have
994            Vn.[bhsdq] represent a scalar. Therefore any
995            Vn.[bhsdq] should have an index following it.
996            Except in reglists of course.  */
997         atype.defined |= NTA_HASINDEX;
998       else
999         atype.defined |= NTA_HASTYPE;
1000
1001       atype.type = parsetype.type;
1002       atype.width = parsetype.width;
1003     }
1004
1005   if (skip_past_char (&str, '['))
1006     {
1007       expressionS exp;
1008
1009       /* Reject Sn[index] syntax.  */
1010       if (!is_typed_vecreg)
1011         {
1012           first_error (_("this type of register can't be indexed"));
1013           return PARSE_FAIL;
1014         }
1015
1016       if (in_reg_list)
1017         {
1018           first_error (_("index not allowed inside register list"));
1019           return PARSE_FAIL;
1020         }
1021
1022       atype.defined |= NTA_HASINDEX;
1023
1024       my_get_expression (&exp, &str, GE_NO_PREFIX, 1);
1025
1026       if (exp.X_op != O_constant)
1027         {
1028           first_error (_("constant expression required"));
1029           return PARSE_FAIL;
1030         }
1031
1032       if (! skip_past_char (&str, ']'))
1033         return PARSE_FAIL;
1034
1035       atype.index = exp.X_add_number;
1036     }
1037   else if (!in_reg_list && (atype.defined & NTA_HASINDEX) != 0)
1038     {
1039       /* Indexed vector register expected.  */
1040       first_error (_("indexed vector register expected"));
1041       return PARSE_FAIL;
1042     }
1043
1044   /* A vector reg Vn should be typed or indexed.  */
1045   if (type == REG_TYPE_VN && atype.defined == 0)
1046     {
1047       first_error (_("invalid use of vector register"));
1048     }
1049
1050   if (typeinfo)
1051     *typeinfo = atype;
1052
1053   if (rtype)
1054     *rtype = type;
1055
1056   *ccp = str;
1057
1058   return reg->number;
1059 }
1060
1061 /* Parse register.
1062
1063    Return the register number on success; return PARSE_FAIL otherwise.
1064
1065    If RTYPE is not NULL, return in *RTYPE the (possibly restricted) type of
1066    the register (e.g. NEON double or quad reg when either has been requested).
1067
1068    If this is a NEON vector register with additional type information, fill
1069    in the struct pointed to by VECTYPE (if non-NULL).
1070
1071    This parser does not handle register list.  */
1072
1073 static int
1074 aarch64_reg_parse (char **ccp, aarch64_reg_type type,
1075                    aarch64_reg_type *rtype, struct vector_type_el *vectype)
1076 {
1077   struct vector_type_el atype;
1078   char *str = *ccp;
1079   int reg = parse_typed_reg (&str, type, rtype, &atype,
1080                              /*in_reg_list= */ FALSE);
1081
1082   if (reg == PARSE_FAIL)
1083     return PARSE_FAIL;
1084
1085   if (vectype)
1086     *vectype = atype;
1087
1088   *ccp = str;
1089
1090   return reg;
1091 }
1092
1093 static inline bfd_boolean
1094 eq_vector_type_el (struct vector_type_el e1, struct vector_type_el e2)
1095 {
1096   return
1097     e1.type == e2.type
1098     && e1.defined == e2.defined
1099     && e1.width == e2.width && e1.index == e2.index;
1100 }
1101
1102 /* This function parses a list of vector registers of type TYPE.
1103    On success, it returns the parsed register list information in the
1104    following encoded format:
1105
1106    bit   18-22   |   13-17   |   7-11    |    2-6    |   0-1
1107        4th regno | 3rd regno | 2nd regno | 1st regno | num_of_reg
1108
1109    The information of the register shape and/or index is returned in
1110    *VECTYPE.
1111
1112    It returns PARSE_FAIL if the register list is invalid.
1113
1114    The list contains one to four registers.
1115    Each register can be one of:
1116    <Vt>.<T>[<index>]
1117    <Vt>.<T>
1118    All <T> should be identical.
1119    All <index> should be identical.
1120    There are restrictions on <Vt> numbers which are checked later
1121    (by reg_list_valid_p).  */
1122
1123 static int
1124 parse_vector_reg_list (char **ccp, aarch64_reg_type type,
1125                        struct vector_type_el *vectype)
1126 {
1127   char *str = *ccp;
1128   int nb_regs;
1129   struct vector_type_el typeinfo, typeinfo_first;
1130   int val, val_range;
1131   int in_range;
1132   int ret_val;
1133   int i;
1134   bfd_boolean error = FALSE;
1135   bfd_boolean expect_index = FALSE;
1136
1137   if (*str != '{')
1138     {
1139       set_syntax_error (_("expecting {"));
1140       return PARSE_FAIL;
1141     }
1142   str++;
1143
1144   nb_regs = 0;
1145   typeinfo_first.defined = 0;
1146   typeinfo_first.type = NT_invtype;
1147   typeinfo_first.width = -1;
1148   typeinfo_first.index = 0;
1149   ret_val = 0;
1150   val = -1;
1151   val_range = -1;
1152   in_range = 0;
1153   do
1154     {
1155       if (in_range)
1156         {
1157           str++;                /* skip over '-' */
1158           val_range = val;
1159         }
1160       val = parse_typed_reg (&str, type, NULL, &typeinfo,
1161                              /*in_reg_list= */ TRUE);
1162       if (val == PARSE_FAIL)
1163         {
1164           set_first_syntax_error (_("invalid vector register in list"));
1165           error = TRUE;
1166           continue;
1167         }
1168       /* reject [bhsd]n */
1169       if (type == REG_TYPE_VN && typeinfo.defined == 0)
1170         {
1171           set_first_syntax_error (_("invalid scalar register in list"));
1172           error = TRUE;
1173           continue;
1174         }
1175
1176       if (typeinfo.defined & NTA_HASINDEX)
1177         expect_index = TRUE;
1178
1179       if (in_range)
1180         {
1181           if (val < val_range)
1182             {
1183               set_first_syntax_error
1184                 (_("invalid range in vector register list"));
1185               error = TRUE;
1186             }
1187           val_range++;
1188         }
1189       else
1190         {
1191           val_range = val;
1192           if (nb_regs == 0)
1193             typeinfo_first = typeinfo;
1194           else if (! eq_vector_type_el (typeinfo_first, typeinfo))
1195             {
1196               set_first_syntax_error
1197                 (_("type mismatch in vector register list"));
1198               error = TRUE;
1199             }
1200         }
1201       if (! error)
1202         for (i = val_range; i <= val; i++)
1203           {
1204             ret_val |= i << (5 * nb_regs);
1205             nb_regs++;
1206           }
1207       in_range = 0;
1208     }
1209   while (skip_past_comma (&str) || (in_range = 1, *str == '-'));
1210
1211   skip_whitespace (str);
1212   if (*str != '}')
1213     {
1214       set_first_syntax_error (_("end of vector register list not found"));
1215       error = TRUE;
1216     }
1217   str++;
1218
1219   skip_whitespace (str);
1220
1221   if (expect_index)
1222     {
1223       if (skip_past_char (&str, '['))
1224         {
1225           expressionS exp;
1226
1227           my_get_expression (&exp, &str, GE_NO_PREFIX, 1);
1228           if (exp.X_op != O_constant)
1229             {
1230               set_first_syntax_error (_("constant expression required."));
1231               error = TRUE;
1232             }
1233           if (! skip_past_char (&str, ']'))
1234             error = TRUE;
1235           else
1236             typeinfo_first.index = exp.X_add_number;
1237         }
1238       else
1239         {
1240           set_first_syntax_error (_("expected index"));
1241           error = TRUE;
1242         }
1243     }
1244
1245   if (nb_regs > 4)
1246     {
1247       set_first_syntax_error (_("too many registers in vector register list"));
1248       error = TRUE;
1249     }
1250   else if (nb_regs == 0)
1251     {
1252       set_first_syntax_error (_("empty vector register list"));
1253       error = TRUE;
1254     }
1255
1256   *ccp = str;
1257   if (! error)
1258     *vectype = typeinfo_first;
1259
1260   return error ? PARSE_FAIL : (ret_val << 2) | (nb_regs - 1);
1261 }
1262
1263 /* Directives: register aliases.  */
1264
1265 static reg_entry *
1266 insert_reg_alias (char *str, int number, aarch64_reg_type type)
1267 {
1268   reg_entry *new;
1269   const char *name;
1270
1271   if ((new = hash_find (aarch64_reg_hsh, str)) != 0)
1272     {
1273       if (new->builtin)
1274         as_warn (_("ignoring attempt to redefine built-in register '%s'"),
1275                  str);
1276
1277       /* Only warn about a redefinition if it's not defined as the
1278          same register.  */
1279       else if (new->number != number || new->type != type)
1280         as_warn (_("ignoring redefinition of register alias '%s'"), str);
1281
1282       return NULL;
1283     }
1284
1285   name = xstrdup (str);
1286   new = XNEW (reg_entry);
1287
1288   new->name = name;
1289   new->number = number;
1290   new->type = type;
1291   new->builtin = FALSE;
1292
1293   if (hash_insert (aarch64_reg_hsh, name, (void *) new))
1294     abort ();
1295
1296   return new;
1297 }
1298
1299 /* Look for the .req directive.  This is of the form:
1300
1301         new_register_name .req existing_register_name
1302
1303    If we find one, or if it looks sufficiently like one that we want to
1304    handle any error here, return TRUE.  Otherwise return FALSE.  */
1305
1306 static bfd_boolean
1307 create_register_alias (char *newname, char *p)
1308 {
1309   const reg_entry *old;
1310   char *oldname, *nbuf;
1311   size_t nlen;
1312
1313   /* The input scrubber ensures that whitespace after the mnemonic is
1314      collapsed to single spaces.  */
1315   oldname = p;
1316   if (strncmp (oldname, " .req ", 6) != 0)
1317     return FALSE;
1318
1319   oldname += 6;
1320   if (*oldname == '\0')
1321     return FALSE;
1322
1323   old = hash_find (aarch64_reg_hsh, oldname);
1324   if (!old)
1325     {
1326       as_warn (_("unknown register '%s' -- .req ignored"), oldname);
1327       return TRUE;
1328     }
1329
1330   /* If TC_CASE_SENSITIVE is defined, then newname already points to
1331      the desired alias name, and p points to its end.  If not, then
1332      the desired alias name is in the global original_case_string.  */
1333 #ifdef TC_CASE_SENSITIVE
1334   nlen = p - newname;
1335 #else
1336   newname = original_case_string;
1337   nlen = strlen (newname);
1338 #endif
1339
1340   nbuf = xmemdup0 (newname, nlen);
1341
1342   /* Create aliases under the new name as stated; an all-lowercase
1343      version of the new name; and an all-uppercase version of the new
1344      name.  */
1345   if (insert_reg_alias (nbuf, old->number, old->type) != NULL)
1346     {
1347       for (p = nbuf; *p; p++)
1348         *p = TOUPPER (*p);
1349
1350       if (strncmp (nbuf, newname, nlen))
1351         {
1352           /* If this attempt to create an additional alias fails, do not bother
1353              trying to create the all-lower case alias.  We will fail and issue
1354              a second, duplicate error message.  This situation arises when the
1355              programmer does something like:
1356              foo .req r0
1357              Foo .req r1
1358              The second .req creates the "Foo" alias but then fails to create
1359              the artificial FOO alias because it has already been created by the
1360              first .req.  */
1361           if (insert_reg_alias (nbuf, old->number, old->type) == NULL)
1362             {
1363               free (nbuf);
1364               return TRUE;
1365             }
1366         }
1367
1368       for (p = nbuf; *p; p++)
1369         *p = TOLOWER (*p);
1370
1371       if (strncmp (nbuf, newname, nlen))
1372         insert_reg_alias (nbuf, old->number, old->type);
1373     }
1374
1375   free (nbuf);
1376   return TRUE;
1377 }
1378
1379 /* Should never be called, as .req goes between the alias and the
1380    register name, not at the beginning of the line.  */
1381 static void
1382 s_req (int a ATTRIBUTE_UNUSED)
1383 {
1384   as_bad (_("invalid syntax for .req directive"));
1385 }
1386
1387 /* The .unreq directive deletes an alias which was previously defined
1388    by .req.  For example:
1389
1390        my_alias .req r11
1391        .unreq my_alias    */
1392
1393 static void
1394 s_unreq (int a ATTRIBUTE_UNUSED)
1395 {
1396   char *name;
1397   char saved_char;
1398
1399   name = input_line_pointer;
1400
1401   while (*input_line_pointer != 0
1402          && *input_line_pointer != ' ' && *input_line_pointer != '\n')
1403     ++input_line_pointer;
1404
1405   saved_char = *input_line_pointer;
1406   *input_line_pointer = 0;
1407
1408   if (!*name)
1409     as_bad (_("invalid syntax for .unreq directive"));
1410   else
1411     {
1412       reg_entry *reg = hash_find (aarch64_reg_hsh, name);
1413
1414       if (!reg)
1415         as_bad (_("unknown register alias '%s'"), name);
1416       else if (reg->builtin)
1417         as_warn (_("ignoring attempt to undefine built-in register '%s'"),
1418                  name);
1419       else
1420         {
1421           char *p;
1422           char *nbuf;
1423
1424           hash_delete (aarch64_reg_hsh, name, FALSE);
1425           free ((char *) reg->name);
1426           free (reg);
1427
1428           /* Also locate the all upper case and all lower case versions.
1429              Do not complain if we cannot find one or the other as it
1430              was probably deleted above.  */
1431
1432           nbuf = strdup (name);
1433           for (p = nbuf; *p; p++)
1434             *p = TOUPPER (*p);
1435           reg = hash_find (aarch64_reg_hsh, nbuf);
1436           if (reg)
1437             {
1438               hash_delete (aarch64_reg_hsh, nbuf, FALSE);
1439               free ((char *) reg->name);
1440               free (reg);
1441             }
1442
1443           for (p = nbuf; *p; p++)
1444             *p = TOLOWER (*p);
1445           reg = hash_find (aarch64_reg_hsh, nbuf);
1446           if (reg)
1447             {
1448               hash_delete (aarch64_reg_hsh, nbuf, FALSE);
1449               free ((char *) reg->name);
1450               free (reg);
1451             }
1452
1453           free (nbuf);
1454         }
1455     }
1456
1457   *input_line_pointer = saved_char;
1458   demand_empty_rest_of_line ();
1459 }
1460
1461 /* Directives: Instruction set selection.  */
1462
1463 #ifdef OBJ_ELF
1464 /* This code is to handle mapping symbols as defined in the ARM AArch64 ELF
1465    spec.  (See "Mapping symbols", section 4.5.4, ARM AAELF64 version 0.05).
1466    Note that previously, $a and $t has type STT_FUNC (BSF_OBJECT flag),
1467    and $d has type STT_OBJECT (BSF_OBJECT flag). Now all three are untyped.  */
1468
1469 /* Create a new mapping symbol for the transition to STATE.  */
1470
1471 static void
1472 make_mapping_symbol (enum mstate state, valueT value, fragS * frag)
1473 {
1474   symbolS *symbolP;
1475   const char *symname;
1476   int type;
1477
1478   switch (state)
1479     {
1480     case MAP_DATA:
1481       symname = "$d";
1482       type = BSF_NO_FLAGS;
1483       break;
1484     case MAP_INSN:
1485       symname = "$x";
1486       type = BSF_NO_FLAGS;
1487       break;
1488     default:
1489       abort ();
1490     }
1491
1492   symbolP = symbol_new (symname, now_seg, value, frag);
1493   symbol_get_bfdsym (symbolP)->flags |= type | BSF_LOCAL;
1494
1495   /* Save the mapping symbols for future reference.  Also check that
1496      we do not place two mapping symbols at the same offset within a
1497      frag.  We'll handle overlap between frags in
1498      check_mapping_symbols.
1499
1500      If .fill or other data filling directive generates zero sized data,
1501      the mapping symbol for the following code will have the same value
1502      as the one generated for the data filling directive.  In this case,
1503      we replace the old symbol with the new one at the same address.  */
1504   if (value == 0)
1505     {
1506       if (frag->tc_frag_data.first_map != NULL)
1507         {
1508           know (S_GET_VALUE (frag->tc_frag_data.first_map) == 0);
1509           symbol_remove (frag->tc_frag_data.first_map, &symbol_rootP,
1510                          &symbol_lastP);
1511         }
1512       frag->tc_frag_data.first_map = symbolP;
1513     }
1514   if (frag->tc_frag_data.last_map != NULL)
1515     {
1516       know (S_GET_VALUE (frag->tc_frag_data.last_map) <=
1517             S_GET_VALUE (symbolP));
1518       if (S_GET_VALUE (frag->tc_frag_data.last_map) == S_GET_VALUE (symbolP))
1519         symbol_remove (frag->tc_frag_data.last_map, &symbol_rootP,
1520                        &symbol_lastP);
1521     }
1522   frag->tc_frag_data.last_map = symbolP;
1523 }
1524
1525 /* We must sometimes convert a region marked as code to data during
1526    code alignment, if an odd number of bytes have to be padded.  The
1527    code mapping symbol is pushed to an aligned address.  */
1528
1529 static void
1530 insert_data_mapping_symbol (enum mstate state,
1531                             valueT value, fragS * frag, offsetT bytes)
1532 {
1533   /* If there was already a mapping symbol, remove it.  */
1534   if (frag->tc_frag_data.last_map != NULL
1535       && S_GET_VALUE (frag->tc_frag_data.last_map) ==
1536       frag->fr_address + value)
1537     {
1538       symbolS *symp = frag->tc_frag_data.last_map;
1539
1540       if (value == 0)
1541         {
1542           know (frag->tc_frag_data.first_map == symp);
1543           frag->tc_frag_data.first_map = NULL;
1544         }
1545       frag->tc_frag_data.last_map = NULL;
1546       symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1547     }
1548
1549   make_mapping_symbol (MAP_DATA, value, frag);
1550   make_mapping_symbol (state, value + bytes, frag);
1551 }
1552
1553 static void mapping_state_2 (enum mstate state, int max_chars);
1554
1555 /* Set the mapping state to STATE.  Only call this when about to
1556    emit some STATE bytes to the file.  */
1557
1558 void
1559 mapping_state (enum mstate state)
1560 {
1561   enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
1562
1563   if (state == MAP_INSN)
1564     /* AArch64 instructions require 4-byte alignment.  When emitting
1565        instructions into any section, record the appropriate section
1566        alignment.  */
1567     record_alignment (now_seg, 2);
1568
1569   if (mapstate == state)
1570     /* The mapping symbol has already been emitted.
1571        There is nothing else to do.  */
1572     return;
1573
1574 #define TRANSITION(from, to) (mapstate == (from) && state == (to))
1575   if (TRANSITION (MAP_UNDEFINED, MAP_DATA) && !subseg_text_p (now_seg))
1576     /* Emit MAP_DATA within executable section in order.  Otherwise, it will be
1577        evaluated later in the next else.  */
1578     return;
1579   else if (TRANSITION (MAP_UNDEFINED, MAP_INSN))
1580     {
1581       /* Only add the symbol if the offset is > 0:
1582          if we're at the first frag, check it's size > 0;
1583          if we're not at the first frag, then for sure
1584          the offset is > 0.  */
1585       struct frag *const frag_first = seg_info (now_seg)->frchainP->frch_root;
1586       const int add_symbol = (frag_now != frag_first)
1587         || (frag_now_fix () > 0);
1588
1589       if (add_symbol)
1590         make_mapping_symbol (MAP_DATA, (valueT) 0, frag_first);
1591     }
1592 #undef TRANSITION
1593
1594   mapping_state_2 (state, 0);
1595 }
1596
1597 /* Same as mapping_state, but MAX_CHARS bytes have already been
1598    allocated.  Put the mapping symbol that far back.  */
1599
1600 static void
1601 mapping_state_2 (enum mstate state, int max_chars)
1602 {
1603   enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
1604
1605   if (!SEG_NORMAL (now_seg))
1606     return;
1607
1608   if (mapstate == state)
1609     /* The mapping symbol has already been emitted.
1610        There is nothing else to do.  */
1611     return;
1612
1613   seg_info (now_seg)->tc_segment_info_data.mapstate = state;
1614   make_mapping_symbol (state, (valueT) frag_now_fix () - max_chars, frag_now);
1615 }
1616 #else
1617 #define mapping_state(x)        /* nothing */
1618 #define mapping_state_2(x, y)   /* nothing */
1619 #endif
1620
1621 /* Directives: sectioning and alignment.  */
1622
1623 static void
1624 s_bss (int ignore ATTRIBUTE_UNUSED)
1625 {
1626   /* We don't support putting frags in the BSS segment, we fake it by
1627      marking in_bss, then looking at s_skip for clues.  */
1628   subseg_set (bss_section, 0);
1629   demand_empty_rest_of_line ();
1630   mapping_state (MAP_DATA);
1631 }
1632
1633 static void
1634 s_even (int ignore ATTRIBUTE_UNUSED)
1635 {
1636   /* Never make frag if expect extra pass.  */
1637   if (!need_pass_2)
1638     frag_align (1, 0, 0);
1639
1640   record_alignment (now_seg, 1);
1641
1642   demand_empty_rest_of_line ();
1643 }
1644
1645 /* Directives: Literal pools.  */
1646
1647 static literal_pool *
1648 find_literal_pool (int size)
1649 {
1650   literal_pool *pool;
1651
1652   for (pool = list_of_pools; pool != NULL; pool = pool->next)
1653     {
1654       if (pool->section == now_seg
1655           && pool->sub_section == now_subseg && pool->size == size)
1656         break;
1657     }
1658
1659   return pool;
1660 }
1661
1662 static literal_pool *
1663 find_or_make_literal_pool (int size)
1664 {
1665   /* Next literal pool ID number.  */
1666   static unsigned int latest_pool_num = 1;
1667   literal_pool *pool;
1668
1669   pool = find_literal_pool (size);
1670
1671   if (pool == NULL)
1672     {
1673       /* Create a new pool.  */
1674       pool = XNEW (literal_pool);
1675       if (!pool)
1676         return NULL;
1677
1678       /* Currently we always put the literal pool in the current text
1679          section.  If we were generating "small" model code where we
1680          knew that all code and initialised data was within 1MB then
1681          we could output literals to mergeable, read-only data
1682          sections. */
1683
1684       pool->next_free_entry = 0;
1685       pool->section = now_seg;
1686       pool->sub_section = now_subseg;
1687       pool->size = size;
1688       pool->next = list_of_pools;
1689       pool->symbol = NULL;
1690
1691       /* Add it to the list.  */
1692       list_of_pools = pool;
1693     }
1694
1695   /* New pools, and emptied pools, will have a NULL symbol.  */
1696   if (pool->symbol == NULL)
1697     {
1698       pool->symbol = symbol_create (FAKE_LABEL_NAME, undefined_section,
1699                                     (valueT) 0, &zero_address_frag);
1700       pool->id = latest_pool_num++;
1701     }
1702
1703   /* Done.  */
1704   return pool;
1705 }
1706
1707 /* Add the literal of size SIZE in *EXP to the relevant literal pool.
1708    Return TRUE on success, otherwise return FALSE.  */
1709 static bfd_boolean
1710 add_to_lit_pool (expressionS *exp, int size)
1711 {
1712   literal_pool *pool;
1713   unsigned int entry;
1714
1715   pool = find_or_make_literal_pool (size);
1716
1717   /* Check if this literal value is already in the pool.  */
1718   for (entry = 0; entry < pool->next_free_entry; entry++)
1719     {
1720       expressionS * litexp = & pool->literals[entry].exp;
1721
1722       if ((litexp->X_op == exp->X_op)
1723           && (exp->X_op == O_constant)
1724           && (litexp->X_add_number == exp->X_add_number)
1725           && (litexp->X_unsigned == exp->X_unsigned))
1726         break;
1727
1728       if ((litexp->X_op == exp->X_op)
1729           && (exp->X_op == O_symbol)
1730           && (litexp->X_add_number == exp->X_add_number)
1731           && (litexp->X_add_symbol == exp->X_add_symbol)
1732           && (litexp->X_op_symbol == exp->X_op_symbol))
1733         break;
1734     }
1735
1736   /* Do we need to create a new entry?  */
1737   if (entry == pool->next_free_entry)
1738     {
1739       if (entry >= MAX_LITERAL_POOL_SIZE)
1740         {
1741           set_syntax_error (_("literal pool overflow"));
1742           return FALSE;
1743         }
1744
1745       pool->literals[entry].exp = *exp;
1746       pool->next_free_entry += 1;
1747       if (exp->X_op == O_big)
1748         {
1749           /* PR 16688: Bignums are held in a single global array.  We must
1750              copy and preserve that value now, before it is overwritten.  */
1751           pool->literals[entry].bignum = XNEWVEC (LITTLENUM_TYPE,
1752                                                   exp->X_add_number);
1753           memcpy (pool->literals[entry].bignum, generic_bignum,
1754                   CHARS_PER_LITTLENUM * exp->X_add_number);
1755         }
1756       else
1757         pool->literals[entry].bignum = NULL;
1758     }
1759
1760   exp->X_op = O_symbol;
1761   exp->X_add_number = ((int) entry) * size;
1762   exp->X_add_symbol = pool->symbol;
1763
1764   return TRUE;
1765 }
1766
1767 /* Can't use symbol_new here, so have to create a symbol and then at
1768    a later date assign it a value. That's what these functions do.  */
1769
1770 static void
1771 symbol_locate (symbolS * symbolP,
1772                const char *name,/* It is copied, the caller can modify.  */
1773                segT segment,    /* Segment identifier (SEG_<something>).  */
1774                valueT valu,     /* Symbol value.  */
1775                fragS * frag)    /* Associated fragment.  */
1776 {
1777   size_t name_length;
1778   char *preserved_copy_of_name;
1779
1780   name_length = strlen (name) + 1;      /* +1 for \0.  */
1781   obstack_grow (&notes, name, name_length);
1782   preserved_copy_of_name = obstack_finish (&notes);
1783
1784 #ifdef tc_canonicalize_symbol_name
1785   preserved_copy_of_name =
1786     tc_canonicalize_symbol_name (preserved_copy_of_name);
1787 #endif
1788
1789   S_SET_NAME (symbolP, preserved_copy_of_name);
1790
1791   S_SET_SEGMENT (symbolP, segment);
1792   S_SET_VALUE (symbolP, valu);
1793   symbol_clear_list_pointers (symbolP);
1794
1795   symbol_set_frag (symbolP, frag);
1796
1797   /* Link to end of symbol chain.  */
1798   {
1799     extern int symbol_table_frozen;
1800
1801     if (symbol_table_frozen)
1802       abort ();
1803   }
1804
1805   symbol_append (symbolP, symbol_lastP, &symbol_rootP, &symbol_lastP);
1806
1807   obj_symbol_new_hook (symbolP);
1808
1809 #ifdef tc_symbol_new_hook
1810   tc_symbol_new_hook (symbolP);
1811 #endif
1812
1813 #ifdef DEBUG_SYMS
1814   verify_symbol_chain (symbol_rootP, symbol_lastP);
1815 #endif /* DEBUG_SYMS  */
1816 }
1817
1818
1819 static void
1820 s_ltorg (int ignored ATTRIBUTE_UNUSED)
1821 {
1822   unsigned int entry;
1823   literal_pool *pool;
1824   char sym_name[20];
1825   int align;
1826
1827   for (align = 2; align <= 4; align++)
1828     {
1829       int size = 1 << align;
1830
1831       pool = find_literal_pool (size);
1832       if (pool == NULL || pool->symbol == NULL || pool->next_free_entry == 0)
1833         continue;
1834
1835       /* Align pool as you have word accesses.
1836          Only make a frag if we have to.  */
1837       if (!need_pass_2)
1838         frag_align (align, 0, 0);
1839
1840       mapping_state (MAP_DATA);
1841
1842       record_alignment (now_seg, align);
1843
1844       sprintf (sym_name, "$$lit_\002%x", pool->id);
1845
1846       symbol_locate (pool->symbol, sym_name, now_seg,
1847                      (valueT) frag_now_fix (), frag_now);
1848       symbol_table_insert (pool->symbol);
1849
1850       for (entry = 0; entry < pool->next_free_entry; entry++)
1851         {
1852           expressionS * exp = & pool->literals[entry].exp;
1853
1854           if (exp->X_op == O_big)
1855             {
1856               /* PR 16688: Restore the global bignum value.  */
1857               gas_assert (pool->literals[entry].bignum != NULL);
1858               memcpy (generic_bignum, pool->literals[entry].bignum,
1859                       CHARS_PER_LITTLENUM * exp->X_add_number);
1860             }
1861
1862           /* First output the expression in the instruction to the pool.  */
1863           emit_expr (exp, size);        /* .word|.xword  */
1864
1865           if (exp->X_op == O_big)
1866             {
1867               free (pool->literals[entry].bignum);
1868               pool->literals[entry].bignum = NULL;
1869             }
1870         }
1871
1872       /* Mark the pool as empty.  */
1873       pool->next_free_entry = 0;
1874       pool->symbol = NULL;
1875     }
1876 }
1877
1878 #ifdef OBJ_ELF
1879 /* Forward declarations for functions below, in the MD interface
1880    section.  */
1881 static fixS *fix_new_aarch64 (fragS *, int, short, expressionS *, int, int);
1882 static struct reloc_table_entry * find_reloc_table_entry (char **);
1883
1884 /* Directives: Data.  */
1885 /* N.B. the support for relocation suffix in this directive needs to be
1886    implemented properly.  */
1887
1888 static void
1889 s_aarch64_elf_cons (int nbytes)
1890 {
1891   expressionS exp;
1892
1893 #ifdef md_flush_pending_output
1894   md_flush_pending_output ();
1895 #endif
1896
1897   if (is_it_end_of_statement ())
1898     {
1899       demand_empty_rest_of_line ();
1900       return;
1901     }
1902
1903 #ifdef md_cons_align
1904   md_cons_align (nbytes);
1905 #endif
1906
1907   mapping_state (MAP_DATA);
1908   do
1909     {
1910       struct reloc_table_entry *reloc;
1911
1912       expression (&exp);
1913
1914       if (exp.X_op != O_symbol)
1915         emit_expr (&exp, (unsigned int) nbytes);
1916       else
1917         {
1918           skip_past_char (&input_line_pointer, '#');
1919           if (skip_past_char (&input_line_pointer, ':'))
1920             {
1921               reloc = find_reloc_table_entry (&input_line_pointer);
1922               if (reloc == NULL)
1923                 as_bad (_("unrecognized relocation suffix"));
1924               else
1925                 as_bad (_("unimplemented relocation suffix"));
1926               ignore_rest_of_line ();
1927               return;
1928             }
1929           else
1930             emit_expr (&exp, (unsigned int) nbytes);
1931         }
1932     }
1933   while (*input_line_pointer++ == ',');
1934
1935   /* Put terminator back into stream.  */
1936   input_line_pointer--;
1937   demand_empty_rest_of_line ();
1938 }
1939
1940 #endif /* OBJ_ELF */
1941
1942 /* Output a 32-bit word, but mark as an instruction.  */
1943
1944 static void
1945 s_aarch64_inst (int ignored ATTRIBUTE_UNUSED)
1946 {
1947   expressionS exp;
1948
1949 #ifdef md_flush_pending_output
1950   md_flush_pending_output ();
1951 #endif
1952
1953   if (is_it_end_of_statement ())
1954     {
1955       demand_empty_rest_of_line ();
1956       return;
1957     }
1958
1959   /* Sections are assumed to start aligned. In executable section, there is no
1960      MAP_DATA symbol pending. So we only align the address during
1961      MAP_DATA --> MAP_INSN transition.
1962      For other sections, this is not guaranteed.  */
1963   enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
1964   if (!need_pass_2 && subseg_text_p (now_seg) && mapstate == MAP_DATA)
1965     frag_align_code (2, 0);
1966
1967 #ifdef OBJ_ELF
1968   mapping_state (MAP_INSN);
1969 #endif
1970
1971   do
1972     {
1973       expression (&exp);
1974       if (exp.X_op != O_constant)
1975         {
1976           as_bad (_("constant expression required"));
1977           ignore_rest_of_line ();
1978           return;
1979         }
1980
1981       if (target_big_endian)
1982         {
1983           unsigned int val = exp.X_add_number;
1984           exp.X_add_number = SWAP_32 (val);
1985         }
1986       emit_expr (&exp, 4);
1987     }
1988   while (*input_line_pointer++ == ',');
1989
1990   /* Put terminator back into stream.  */
1991   input_line_pointer--;
1992   demand_empty_rest_of_line ();
1993 }
1994
1995 #ifdef OBJ_ELF
1996 /* Emit BFD_RELOC_AARCH64_TLSDESC_ADD on the next ADD instruction.  */
1997
1998 static void
1999 s_tlsdescadd (int ignored ATTRIBUTE_UNUSED)
2000 {
2001   expressionS exp;
2002
2003   expression (&exp);
2004   frag_grow (4);
2005   fix_new_aarch64 (frag_now, frag_more (0) - frag_now->fr_literal, 4, &exp, 0,
2006                    BFD_RELOC_AARCH64_TLSDESC_ADD);
2007
2008   demand_empty_rest_of_line ();
2009 }
2010
2011 /* Emit BFD_RELOC_AARCH64_TLSDESC_CALL on the next BLR instruction.  */
2012
2013 static void
2014 s_tlsdesccall (int ignored ATTRIBUTE_UNUSED)
2015 {
2016   expressionS exp;
2017
2018   /* Since we're just labelling the code, there's no need to define a
2019      mapping symbol.  */
2020   expression (&exp);
2021   /* Make sure there is enough room in this frag for the following
2022      blr.  This trick only works if the blr follows immediately after
2023      the .tlsdesc directive.  */
2024   frag_grow (4);
2025   fix_new_aarch64 (frag_now, frag_more (0) - frag_now->fr_literal, 4, &exp, 0,
2026                    BFD_RELOC_AARCH64_TLSDESC_CALL);
2027
2028   demand_empty_rest_of_line ();
2029 }
2030
2031 /* Emit BFD_RELOC_AARCH64_TLSDESC_LDR on the next LDR instruction.  */
2032
2033 static void
2034 s_tlsdescldr (int ignored ATTRIBUTE_UNUSED)
2035 {
2036   expressionS exp;
2037
2038   expression (&exp);
2039   frag_grow (4);
2040   fix_new_aarch64 (frag_now, frag_more (0) - frag_now->fr_literal, 4, &exp, 0,
2041                    BFD_RELOC_AARCH64_TLSDESC_LDR);
2042
2043   demand_empty_rest_of_line ();
2044 }
2045 #endif  /* OBJ_ELF */
2046
2047 static void s_aarch64_arch (int);
2048 static void s_aarch64_cpu (int);
2049 static void s_aarch64_arch_extension (int);
2050
2051 /* This table describes all the machine specific pseudo-ops the assembler
2052    has to support.  The fields are:
2053      pseudo-op name without dot
2054      function to call to execute this pseudo-op
2055      Integer arg to pass to the function.  */
2056
2057 const pseudo_typeS md_pseudo_table[] = {
2058   /* Never called because '.req' does not start a line.  */
2059   {"req", s_req, 0},
2060   {"unreq", s_unreq, 0},
2061   {"bss", s_bss, 0},
2062   {"even", s_even, 0},
2063   {"ltorg", s_ltorg, 0},
2064   {"pool", s_ltorg, 0},
2065   {"cpu", s_aarch64_cpu, 0},
2066   {"arch", s_aarch64_arch, 0},
2067   {"arch_extension", s_aarch64_arch_extension, 0},
2068   {"inst", s_aarch64_inst, 0},
2069 #ifdef OBJ_ELF
2070   {"tlsdescadd", s_tlsdescadd, 0},
2071   {"tlsdesccall", s_tlsdesccall, 0},
2072   {"tlsdescldr", s_tlsdescldr, 0},
2073   {"word", s_aarch64_elf_cons, 4},
2074   {"long", s_aarch64_elf_cons, 4},
2075   {"xword", s_aarch64_elf_cons, 8},
2076   {"dword", s_aarch64_elf_cons, 8},
2077 #endif
2078   {0, 0, 0}
2079 };
2080 \f
2081
2082 /* Check whether STR points to a register name followed by a comma or the
2083    end of line; REG_TYPE indicates which register types are checked
2084    against.  Return TRUE if STR is such a register name; otherwise return
2085    FALSE.  The function does not intend to produce any diagnostics, but since
2086    the register parser aarch64_reg_parse, which is called by this function,
2087    does produce diagnostics, we call clear_error to clear any diagnostics
2088    that may be generated by aarch64_reg_parse.
2089    Also, the function returns FALSE directly if there is any user error
2090    present at the function entry.  This prevents the existing diagnostics
2091    state from being spoiled.
2092    The function currently serves parse_constant_immediate and
2093    parse_big_immediate only.  */
2094 static bfd_boolean
2095 reg_name_p (char *str, aarch64_reg_type reg_type)
2096 {
2097   int reg;
2098
2099   /* Prevent the diagnostics state from being spoiled.  */
2100   if (error_p ())
2101     return FALSE;
2102
2103   reg = aarch64_reg_parse (&str, reg_type, NULL, NULL);
2104
2105   /* Clear the parsing error that may be set by the reg parser.  */
2106   clear_error ();
2107
2108   if (reg == PARSE_FAIL)
2109     return FALSE;
2110
2111   skip_whitespace (str);
2112   if (*str == ',' || is_end_of_line[(unsigned int) *str])
2113     return TRUE;
2114
2115   return FALSE;
2116 }
2117
2118 /* Parser functions used exclusively in instruction operands.  */
2119
2120 /* Parse an immediate expression which may not be constant.
2121
2122    To prevent the expression parser from pushing a register name
2123    into the symbol table as an undefined symbol, firstly a check is
2124    done to find out whether STR is a register of type REG_TYPE followed
2125    by a comma or the end of line.  Return FALSE if STR is such a string.  */
2126
2127 static bfd_boolean
2128 parse_immediate_expression (char **str, expressionS *exp,
2129                             aarch64_reg_type reg_type)
2130 {
2131   if (reg_name_p (*str, reg_type))
2132     {
2133       set_recoverable_error (_("immediate operand required"));
2134       return FALSE;
2135     }
2136
2137   my_get_expression (exp, str, GE_OPT_PREFIX, 1);
2138
2139   if (exp->X_op == O_absent)
2140     {
2141       set_fatal_syntax_error (_("missing immediate expression"));
2142       return FALSE;
2143     }
2144
2145   return TRUE;
2146 }
2147
2148 /* Constant immediate-value read function for use in insn parsing.
2149    STR points to the beginning of the immediate (with the optional
2150    leading #); *VAL receives the value.  REG_TYPE says which register
2151    names should be treated as registers rather than as symbolic immediates.
2152
2153    Return TRUE on success; otherwise return FALSE.  */
2154
2155 static bfd_boolean
2156 parse_constant_immediate (char **str, int64_t *val, aarch64_reg_type reg_type)
2157 {
2158   expressionS exp;
2159
2160   if (! parse_immediate_expression (str, &exp, reg_type))
2161     return FALSE;
2162
2163   if (exp.X_op != O_constant)
2164     {
2165       set_syntax_error (_("constant expression required"));
2166       return FALSE;
2167     }
2168
2169   *val = exp.X_add_number;
2170   return TRUE;
2171 }
2172
2173 static uint32_t
2174 encode_imm_float_bits (uint32_t imm)
2175 {
2176   return ((imm >> 19) & 0x7f)   /* b[25:19] -> b[6:0] */
2177     | ((imm >> (31 - 7)) & 0x80);       /* b[31]    -> b[7]   */
2178 }
2179
2180 /* Return TRUE if the single-precision floating-point value encoded in IMM
2181    can be expressed in the AArch64 8-bit signed floating-point format with
2182    3-bit exponent and normalized 4 bits of precision; in other words, the
2183    floating-point value must be expressable as
2184      (+/-) n / 16 * power (2, r)
2185    where n and r are integers such that 16 <= n <=31 and -3 <= r <= 4.  */
2186
2187 static bfd_boolean
2188 aarch64_imm_float_p (uint32_t imm)
2189 {
2190   /* If a single-precision floating-point value has the following bit
2191      pattern, it can be expressed in the AArch64 8-bit floating-point
2192      format:
2193
2194      3 32222222 2221111111111
2195      1 09876543 21098765432109876543210
2196      n Eeeeeexx xxxx0000000000000000000
2197
2198      where n, e and each x are either 0 or 1 independently, with
2199      E == ~ e.  */
2200
2201   uint32_t pattern;
2202
2203   /* Prepare the pattern for 'Eeeeee'.  */
2204   if (((imm >> 30) & 0x1) == 0)
2205     pattern = 0x3e000000;
2206   else
2207     pattern = 0x40000000;
2208
2209   return (imm & 0x7ffff) == 0           /* lower 19 bits are 0.  */
2210     && ((imm & 0x7e000000) == pattern); /* bits 25 - 29 == ~ bit 30.  */
2211 }
2212
2213 /* Return TRUE if the IEEE double value encoded in IMM can be expressed
2214    as an IEEE float without any loss of precision.  Store the value in
2215    *FPWORD if so.  */
2216
2217 static bfd_boolean
2218 can_convert_double_to_float (uint64_t imm, uint32_t *fpword)
2219 {
2220   /* If a double-precision floating-point value has the following bit
2221      pattern, it can be expressed in a float:
2222
2223      6 66655555555 5544 44444444 33333333 33222222 22221111 111111
2224      3 21098765432 1098 76543210 98765432 10987654 32109876 54321098 76543210
2225      n E~~~eeeeeee ssss ssssssss ssssssss SSS00000 00000000 00000000 00000000
2226
2227        ----------------------------->     nEeeeeee esssssss ssssssss sssssSSS
2228          if Eeee_eeee != 1111_1111
2229
2230      where n, e, s and S are either 0 or 1 independently and where ~ is the
2231      inverse of E.  */
2232
2233   uint32_t pattern;
2234   uint32_t high32 = imm >> 32;
2235   uint32_t low32 = imm;
2236
2237   /* Lower 29 bits need to be 0s.  */
2238   if ((imm & 0x1fffffff) != 0)
2239     return FALSE;
2240
2241   /* Prepare the pattern for 'Eeeeeeeee'.  */
2242   if (((high32 >> 30) & 0x1) == 0)
2243     pattern = 0x38000000;
2244   else
2245     pattern = 0x40000000;
2246
2247   /* Check E~~~.  */
2248   if ((high32 & 0x78000000) != pattern)
2249     return FALSE;
2250
2251   /* Check Eeee_eeee != 1111_1111.  */
2252   if ((high32 & 0x7ff00000) == 0x47f00000)
2253     return FALSE;
2254
2255   *fpword = ((high32 & 0xc0000000)              /* 1 n bit and 1 E bit.  */
2256              | ((high32 << 3) & 0x3ffffff8)     /* 7 e and 20 s bits.  */
2257              | (low32 >> 29));                  /* 3 S bits.  */
2258   return TRUE;
2259 }
2260
2261 /* Return true if we should treat OPERAND as a double-precision
2262    floating-point operand rather than a single-precision one.  */
2263 static bfd_boolean
2264 double_precision_operand_p (const aarch64_opnd_info *operand)
2265 {
2266   /* Check for unsuffixed SVE registers, which are allowed
2267      for LDR and STR but not in instructions that require an
2268      immediate.  We get better error messages if we arbitrarily
2269      pick one size, parse the immediate normally, and then
2270      report the match failure in the normal way.  */
2271   return (operand->qualifier == AARCH64_OPND_QLF_NIL
2272           || aarch64_get_qualifier_esize (operand->qualifier) == 8);
2273 }
2274
2275 /* Parse a floating-point immediate.  Return TRUE on success and return the
2276    value in *IMMED in the format of IEEE754 single-precision encoding.
2277    *CCP points to the start of the string; DP_P is TRUE when the immediate
2278    is expected to be in double-precision (N.B. this only matters when
2279    hexadecimal representation is involved).  REG_TYPE says which register
2280    names should be treated as registers rather than as symbolic immediates.
2281
2282    This routine accepts any IEEE float; it is up to the callers to reject
2283    invalid ones.  */
2284
2285 static bfd_boolean
2286 parse_aarch64_imm_float (char **ccp, int *immed, bfd_boolean dp_p,
2287                          aarch64_reg_type reg_type)
2288 {
2289   char *str = *ccp;
2290   char *fpnum;
2291   LITTLENUM_TYPE words[MAX_LITTLENUMS];
2292   int64_t val = 0;
2293   unsigned fpword = 0;
2294   bfd_boolean hex_p = FALSE;
2295
2296   skip_past_char (&str, '#');
2297
2298   fpnum = str;
2299   skip_whitespace (fpnum);
2300
2301   if (strncmp (fpnum, "0x", 2) == 0)
2302     {
2303       /* Support the hexadecimal representation of the IEEE754 encoding.
2304          Double-precision is expected when DP_P is TRUE, otherwise the
2305          representation should be in single-precision.  */
2306       if (! parse_constant_immediate (&str, &val, reg_type))
2307         goto invalid_fp;
2308
2309       if (dp_p)
2310         {
2311           if (!can_convert_double_to_float (val, &fpword))
2312             goto invalid_fp;
2313         }
2314       else if ((uint64_t) val > 0xffffffff)
2315         goto invalid_fp;
2316       else
2317         fpword = val;
2318
2319       hex_p = TRUE;
2320     }
2321   else if (reg_name_p (str, reg_type))
2322    {
2323      set_recoverable_error (_("immediate operand required"));
2324      return FALSE;
2325     }
2326
2327   if (! hex_p)
2328     {
2329       int i;
2330
2331       if ((str = atof_ieee (str, 's', words)) == NULL)
2332         goto invalid_fp;
2333
2334       /* Our FP word must be 32 bits (single-precision FP).  */
2335       for (i = 0; i < 32 / LITTLENUM_NUMBER_OF_BITS; i++)
2336         {
2337           fpword <<= LITTLENUM_NUMBER_OF_BITS;
2338           fpword |= words[i];
2339         }
2340     }
2341
2342   *immed = fpword;
2343   *ccp = str;
2344   return TRUE;
2345
2346 invalid_fp:
2347   set_fatal_syntax_error (_("invalid floating-point constant"));
2348   return FALSE;
2349 }
2350
2351 /* Less-generic immediate-value read function with the possibility of loading
2352    a big (64-bit) immediate, as required by AdvSIMD Modified immediate
2353    instructions.
2354
2355    To prevent the expression parser from pushing a register name into the
2356    symbol table as an undefined symbol, a check is firstly done to find
2357    out whether STR is a register of type REG_TYPE followed by a comma or
2358    the end of line.  Return FALSE if STR is such a register.  */
2359
2360 static bfd_boolean
2361 parse_big_immediate (char **str, int64_t *imm, aarch64_reg_type reg_type)
2362 {
2363   char *ptr = *str;
2364
2365   if (reg_name_p (ptr, reg_type))
2366     {
2367       set_syntax_error (_("immediate operand required"));
2368       return FALSE;
2369     }
2370
2371   my_get_expression (&inst.reloc.exp, &ptr, GE_OPT_PREFIX, 1);
2372
2373   if (inst.reloc.exp.X_op == O_constant)
2374     *imm = inst.reloc.exp.X_add_number;
2375
2376   *str = ptr;
2377
2378   return TRUE;
2379 }
2380
2381 /* Set operand IDX of the *INSTR that needs a GAS internal fixup.
2382    if NEED_LIBOPCODES is non-zero, the fixup will need
2383    assistance from the libopcodes.   */
2384
2385 static inline void
2386 aarch64_set_gas_internal_fixup (struct reloc *reloc,
2387                                 const aarch64_opnd_info *operand,
2388                                 int need_libopcodes_p)
2389 {
2390   reloc->type = BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP;
2391   reloc->opnd = operand->type;
2392   if (need_libopcodes_p)
2393     reloc->need_libopcodes_p = 1;
2394 };
2395
2396 /* Return TRUE if the instruction needs to be fixed up later internally by
2397    the GAS; otherwise return FALSE.  */
2398
2399 static inline bfd_boolean
2400 aarch64_gas_internal_fixup_p (void)
2401 {
2402   return inst.reloc.type == BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP;
2403 }
2404
2405 /* Assign the immediate value to the relevant field in *OPERAND if
2406    RELOC->EXP is a constant expression; otherwise, flag that *OPERAND
2407    needs an internal fixup in a later stage.
2408    ADDR_OFF_P determines whether it is the field ADDR.OFFSET.IMM or
2409    IMM.VALUE that may get assigned with the constant.  */
2410 static inline void
2411 assign_imm_if_const_or_fixup_later (struct reloc *reloc,
2412                                     aarch64_opnd_info *operand,
2413                                     int addr_off_p,
2414                                     int need_libopcodes_p,
2415                                     int skip_p)
2416 {
2417   if (reloc->exp.X_op == O_constant)
2418     {
2419       if (addr_off_p)
2420         operand->addr.offset.imm = reloc->exp.X_add_number;
2421       else
2422         operand->imm.value = reloc->exp.X_add_number;
2423       reloc->type = BFD_RELOC_UNUSED;
2424     }
2425   else
2426     {
2427       aarch64_set_gas_internal_fixup (reloc, operand, need_libopcodes_p);
2428       /* Tell libopcodes to ignore this operand or not.  This is helpful
2429          when one of the operands needs to be fixed up later but we need
2430          libopcodes to check the other operands.  */
2431       operand->skip = skip_p;
2432     }
2433 }
2434
2435 /* Relocation modifiers.  Each entry in the table contains the textual
2436    name for the relocation which may be placed before a symbol used as
2437    a load/store offset, or add immediate. It must be surrounded by a
2438    leading and trailing colon, for example:
2439
2440         ldr     x0, [x1, #:rello:varsym]
2441         add     x0, x1, #:rello:varsym  */
2442
2443 struct reloc_table_entry
2444 {
2445   const char *name;
2446   int pc_rel;
2447   bfd_reloc_code_real_type adr_type;
2448   bfd_reloc_code_real_type adrp_type;
2449   bfd_reloc_code_real_type movw_type;
2450   bfd_reloc_code_real_type add_type;
2451   bfd_reloc_code_real_type ldst_type;
2452   bfd_reloc_code_real_type ld_literal_type;
2453 };
2454
2455 static struct reloc_table_entry reloc_table[] = {
2456   /* Low 12 bits of absolute address: ADD/i and LDR/STR */
2457   {"lo12", 0,
2458    0,                           /* adr_type */
2459    0,
2460    0,
2461    BFD_RELOC_AARCH64_ADD_LO12,
2462    BFD_RELOC_AARCH64_LDST_LO12,
2463    0},
2464
2465   /* Higher 21 bits of pc-relative page offset: ADRP */
2466   {"pg_hi21", 1,
2467    0,                           /* adr_type */
2468    BFD_RELOC_AARCH64_ADR_HI21_PCREL,
2469    0,
2470    0,
2471    0,
2472    0},
2473
2474   /* Higher 21 bits of pc-relative page offset: ADRP, no check */
2475   {"pg_hi21_nc", 1,
2476    0,                           /* adr_type */
2477    BFD_RELOC_AARCH64_ADR_HI21_NC_PCREL,
2478    0,
2479    0,
2480    0,
2481    0},
2482
2483   /* Most significant bits 0-15 of unsigned address/value: MOVZ */
2484   {"abs_g0", 0,
2485    0,                           /* adr_type */
2486    0,
2487    BFD_RELOC_AARCH64_MOVW_G0,
2488    0,
2489    0,
2490    0},
2491
2492   /* Most significant bits 0-15 of signed address/value: MOVN/Z */
2493   {"abs_g0_s", 0,
2494    0,                           /* adr_type */
2495    0,
2496    BFD_RELOC_AARCH64_MOVW_G0_S,
2497    0,
2498    0,
2499    0},
2500
2501   /* Less significant bits 0-15 of address/value: MOVK, no check */
2502   {"abs_g0_nc", 0,
2503    0,                           /* adr_type */
2504    0,
2505    BFD_RELOC_AARCH64_MOVW_G0_NC,
2506    0,
2507    0,
2508    0},
2509
2510   /* Most significant bits 16-31 of unsigned address/value: MOVZ */
2511   {"abs_g1", 0,
2512    0,                           /* adr_type */
2513    0,
2514    BFD_RELOC_AARCH64_MOVW_G1,
2515    0,
2516    0,
2517    0},
2518
2519   /* Most significant bits 16-31 of signed address/value: MOVN/Z */
2520   {"abs_g1_s", 0,
2521    0,                           /* adr_type */
2522    0,
2523    BFD_RELOC_AARCH64_MOVW_G1_S,
2524    0,
2525    0,
2526    0},
2527
2528   /* Less significant bits 16-31 of address/value: MOVK, no check */
2529   {"abs_g1_nc", 0,
2530    0,                           /* adr_type */
2531    0,
2532    BFD_RELOC_AARCH64_MOVW_G1_NC,
2533    0,
2534    0,
2535    0},
2536
2537   /* Most significant bits 32-47 of unsigned address/value: MOVZ */
2538   {"abs_g2", 0,
2539    0,                           /* adr_type */
2540    0,
2541    BFD_RELOC_AARCH64_MOVW_G2,
2542    0,
2543    0,
2544    0},
2545
2546   /* Most significant bits 32-47 of signed address/value: MOVN/Z */
2547   {"abs_g2_s", 0,
2548    0,                           /* adr_type */
2549    0,
2550    BFD_RELOC_AARCH64_MOVW_G2_S,
2551    0,
2552    0,
2553    0},
2554
2555   /* Less significant bits 32-47 of address/value: MOVK, no check */
2556   {"abs_g2_nc", 0,
2557    0,                           /* adr_type */
2558    0,
2559    BFD_RELOC_AARCH64_MOVW_G2_NC,
2560    0,
2561    0,
2562    0},
2563
2564   /* Most significant bits 48-63 of signed/unsigned address/value: MOVZ */
2565   {"abs_g3", 0,
2566    0,                           /* adr_type */
2567    0,
2568    BFD_RELOC_AARCH64_MOVW_G3,
2569    0,
2570    0,
2571    0},
2572
2573   /* Most significant bits 0-15 of signed/unsigned address/value: MOVZ */
2574   {"prel_g0", 1,
2575    0,                           /* adr_type */
2576    0,
2577    BFD_RELOC_AARCH64_MOVW_PREL_G0,
2578    0,
2579    0,
2580    0},
2581
2582   /* Most significant bits 0-15 of signed/unsigned address/value: MOVK */
2583   {"prel_g0_nc", 1,
2584    0,                           /* adr_type */
2585    0,
2586    BFD_RELOC_AARCH64_MOVW_PREL_G0_NC,
2587    0,
2588    0,
2589    0},
2590
2591   /* Most significant bits 16-31 of signed/unsigned address/value: MOVZ */
2592   {"prel_g1", 1,
2593    0,                           /* adr_type */
2594    0,
2595    BFD_RELOC_AARCH64_MOVW_PREL_G1,
2596    0,
2597    0,
2598    0},
2599
2600   /* Most significant bits 16-31 of signed/unsigned address/value: MOVK */
2601   {"prel_g1_nc", 1,
2602    0,                           /* adr_type */
2603    0,
2604    BFD_RELOC_AARCH64_MOVW_PREL_G1_NC,
2605    0,
2606    0,
2607    0},
2608
2609   /* Most significant bits 32-47 of signed/unsigned address/value: MOVZ */
2610   {"prel_g2", 1,
2611    0,                           /* adr_type */
2612    0,
2613    BFD_RELOC_AARCH64_MOVW_PREL_G2,
2614    0,
2615    0,
2616    0},
2617
2618   /* Most significant bits 32-47 of signed/unsigned address/value: MOVK */
2619   {"prel_g2_nc", 1,
2620    0,                           /* adr_type */
2621    0,
2622    BFD_RELOC_AARCH64_MOVW_PREL_G2_NC,
2623    0,
2624    0,
2625    0},
2626
2627   /* Most significant bits 48-63 of signed/unsigned address/value: MOVZ */
2628   {"prel_g3", 1,
2629    0,                           /* adr_type */
2630    0,
2631    BFD_RELOC_AARCH64_MOVW_PREL_G3,
2632    0,
2633    0,
2634    0},
2635
2636   /* Get to the page containing GOT entry for a symbol.  */
2637   {"got", 1,
2638    0,                           /* adr_type */
2639    BFD_RELOC_AARCH64_ADR_GOT_PAGE,
2640    0,
2641    0,
2642    0,
2643    BFD_RELOC_AARCH64_GOT_LD_PREL19},
2644
2645   /* 12 bit offset into the page containing GOT entry for that symbol.  */
2646   {"got_lo12", 0,
2647    0,                           /* adr_type */
2648    0,
2649    0,
2650    0,
2651    BFD_RELOC_AARCH64_LD_GOT_LO12_NC,
2652    0},
2653
2654   /* 0-15 bits of address/value: MOVk, no check.  */
2655   {"gotoff_g0_nc", 0,
2656    0,                           /* adr_type */
2657    0,
2658    BFD_RELOC_AARCH64_MOVW_GOTOFF_G0_NC,
2659    0,
2660    0,
2661    0},
2662
2663   /* Most significant bits 16-31 of address/value: MOVZ.  */
2664   {"gotoff_g1", 0,
2665    0,                           /* adr_type */
2666    0,
2667    BFD_RELOC_AARCH64_MOVW_GOTOFF_G1,
2668    0,
2669    0,
2670    0},
2671
2672   /* 15 bit offset into the page containing GOT entry for that symbol.  */
2673   {"gotoff_lo15", 0,
2674    0,                           /* adr_type */
2675    0,
2676    0,
2677    0,
2678    BFD_RELOC_AARCH64_LD64_GOTOFF_LO15,
2679    0},
2680
2681   /* Get to the page containing GOT TLS entry for a symbol */
2682   {"gottprel_g0_nc", 0,
2683    0,                           /* adr_type */
2684    0,
2685    BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC,
2686    0,
2687    0,
2688    0},
2689
2690   /* Get to the page containing GOT TLS entry for a symbol */
2691   {"gottprel_g1", 0,
2692    0,                           /* adr_type */
2693    0,
2694    BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1,
2695    0,
2696    0,
2697    0},
2698
2699   /* Get to the page containing GOT TLS entry for a symbol */
2700   {"tlsgd", 0,
2701    BFD_RELOC_AARCH64_TLSGD_ADR_PREL21, /* adr_type */
2702    BFD_RELOC_AARCH64_TLSGD_ADR_PAGE21,
2703    0,
2704    0,
2705    0,
2706    0},
2707
2708   /* 12 bit offset into the page containing GOT TLS entry for a symbol */
2709   {"tlsgd_lo12", 0,
2710    0,                           /* adr_type */
2711    0,
2712    0,
2713    BFD_RELOC_AARCH64_TLSGD_ADD_LO12_NC,
2714    0,
2715    0},
2716
2717   /* Lower 16 bits address/value: MOVk.  */
2718   {"tlsgd_g0_nc", 0,
2719    0,                           /* adr_type */
2720    0,
2721    BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC,
2722    0,
2723    0,
2724    0},
2725
2726   /* Most significant bits 16-31 of address/value: MOVZ.  */
2727   {"tlsgd_g1", 0,
2728    0,                           /* adr_type */
2729    0,
2730    BFD_RELOC_AARCH64_TLSGD_MOVW_G1,
2731    0,
2732    0,
2733    0},
2734
2735   /* Get to the page containing GOT TLS entry for a symbol */
2736   {"tlsdesc", 0,
2737    BFD_RELOC_AARCH64_TLSDESC_ADR_PREL21, /* adr_type */
2738    BFD_RELOC_AARCH64_TLSDESC_ADR_PAGE21,
2739    0,
2740    0,
2741    0,
2742    BFD_RELOC_AARCH64_TLSDESC_LD_PREL19},
2743
2744   /* 12 bit offset into the page containing GOT TLS entry for a symbol */
2745   {"tlsdesc_lo12", 0,
2746    0,                           /* adr_type */
2747    0,
2748    0,
2749    BFD_RELOC_AARCH64_TLSDESC_ADD_LO12,
2750    BFD_RELOC_AARCH64_TLSDESC_LD_LO12_NC,
2751    0},
2752
2753   /* Get to the page containing GOT TLS entry for a symbol.
2754      The same as GD, we allocate two consecutive GOT slots
2755      for module index and module offset, the only difference
2756      with GD is the module offset should be initialized to
2757      zero without any outstanding runtime relocation. */
2758   {"tlsldm", 0,
2759    BFD_RELOC_AARCH64_TLSLD_ADR_PREL21, /* adr_type */
2760    BFD_RELOC_AARCH64_TLSLD_ADR_PAGE21,
2761    0,
2762    0,
2763    0,
2764    0},
2765
2766   /* 12 bit offset into the page containing GOT TLS entry for a symbol */
2767   {"tlsldm_lo12_nc", 0,
2768    0,                           /* adr_type */
2769    0,
2770    0,
2771    BFD_RELOC_AARCH64_TLSLD_ADD_LO12_NC,
2772    0,
2773    0},
2774
2775   /* 12 bit offset into the module TLS base address.  */
2776   {"dtprel_lo12", 0,
2777    0,                           /* adr_type */
2778    0,
2779    0,
2780    BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12,
2781    BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12,
2782    0},
2783
2784   /* Same as dtprel_lo12, no overflow check.  */
2785   {"dtprel_lo12_nc", 0,
2786    0,                           /* adr_type */
2787    0,
2788    0,
2789    BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12_NC,
2790    BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC,
2791    0},
2792
2793   /* bits[23:12] of offset to the module TLS base address.  */
2794   {"dtprel_hi12", 0,
2795    0,                           /* adr_type */
2796    0,
2797    0,
2798    BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_HI12,
2799    0,
2800    0},
2801
2802   /* bits[15:0] of offset to the module TLS base address.  */
2803   {"dtprel_g0", 0,
2804    0,                           /* adr_type */
2805    0,
2806    BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0,
2807    0,
2808    0,
2809    0},
2810
2811   /* No overflow check version of BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0.  */
2812   {"dtprel_g0_nc", 0,
2813    0,                           /* adr_type */
2814    0,
2815    BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC,
2816    0,
2817    0,
2818    0},
2819
2820   /* bits[31:16] of offset to the module TLS base address.  */
2821   {"dtprel_g1", 0,
2822    0,                           /* adr_type */
2823    0,
2824    BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1,
2825    0,
2826    0,
2827    0},
2828
2829   /* No overflow check version of BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1.  */
2830   {"dtprel_g1_nc", 0,
2831    0,                           /* adr_type */
2832    0,
2833    BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC,
2834    0,
2835    0,
2836    0},
2837
2838   /* bits[47:32] of offset to the module TLS base address.  */
2839   {"dtprel_g2", 0,
2840    0,                           /* adr_type */
2841    0,
2842    BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2,
2843    0,
2844    0,
2845    0},
2846
2847   /* Lower 16 bit offset into GOT entry for a symbol */
2848   {"tlsdesc_off_g0_nc", 0,
2849    0,                           /* adr_type */
2850    0,
2851    BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC,
2852    0,
2853    0,
2854    0},
2855
2856   /* Higher 16 bit offset into GOT entry for a symbol */
2857   {"tlsdesc_off_g1", 0,
2858    0,                           /* adr_type */
2859    0,
2860    BFD_RELOC_AARCH64_TLSDESC_OFF_G1,
2861    0,
2862    0,
2863    0},
2864
2865   /* Get to the page containing GOT TLS entry for a symbol */
2866   {"gottprel", 0,
2867    0,                           /* adr_type */
2868    BFD_RELOC_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21,
2869    0,
2870    0,
2871    0,
2872    BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_PREL19},
2873
2874   /* 12 bit offset into the page containing GOT TLS entry for a symbol */
2875   {"gottprel_lo12", 0,
2876    0,                           /* adr_type */
2877    0,
2878    0,
2879    0,
2880    BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_LO12_NC,
2881    0},
2882
2883   /* Get tp offset for a symbol.  */
2884   {"tprel", 0,
2885    0,                           /* adr_type */
2886    0,
2887    0,
2888    BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12,
2889    0,
2890    0},
2891
2892   /* Get tp offset for a symbol.  */
2893   {"tprel_lo12", 0,
2894    0,                           /* adr_type */
2895    0,
2896    0,
2897    BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12,
2898    BFD_RELOC_AARCH64_TLSLE_LDST_TPREL_LO12,
2899    0},
2900
2901   /* Get tp offset for a symbol.  */
2902   {"tprel_hi12", 0,
2903    0,                           /* adr_type */
2904    0,
2905    0,
2906    BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12,
2907    0,
2908    0},
2909
2910   /* Get tp offset for a symbol.  */
2911   {"tprel_lo12_nc", 0,
2912    0,                           /* adr_type */
2913    0,
2914    0,
2915    BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12_NC,
2916    BFD_RELOC_AARCH64_TLSLE_LDST_TPREL_LO12_NC,
2917    0},
2918
2919   /* Most significant bits 32-47 of address/value: MOVZ.  */
2920   {"tprel_g2", 0,
2921    0,                           /* adr_type */
2922    0,
2923    BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2,
2924    0,
2925    0,
2926    0},
2927
2928   /* Most significant bits 16-31 of address/value: MOVZ.  */
2929   {"tprel_g1", 0,
2930    0,                           /* adr_type */
2931    0,
2932    BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1,
2933    0,
2934    0,
2935    0},
2936
2937   /* Most significant bits 16-31 of address/value: MOVZ, no check.  */
2938   {"tprel_g1_nc", 0,
2939    0,                           /* adr_type */
2940    0,
2941    BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC,
2942    0,
2943    0,
2944    0},
2945
2946   /* Most significant bits 0-15 of address/value: MOVZ.  */
2947   {"tprel_g0", 0,
2948    0,                           /* adr_type */
2949    0,
2950    BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0,
2951    0,
2952    0,
2953    0},
2954
2955   /* Most significant bits 0-15 of address/value: MOVZ, no check.  */
2956   {"tprel_g0_nc", 0,
2957    0,                           /* adr_type */
2958    0,
2959    BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC,
2960    0,
2961    0,
2962    0},
2963
2964   /* 15bit offset from got entry to base address of GOT table.  */
2965   {"gotpage_lo15", 0,
2966    0,
2967    0,
2968    0,
2969    0,
2970    BFD_RELOC_AARCH64_LD64_GOTPAGE_LO15,
2971    0},
2972
2973   /* 14bit offset from got entry to base address of GOT table.  */
2974   {"gotpage_lo14", 0,
2975    0,
2976    0,
2977    0,
2978    0,
2979    BFD_RELOC_AARCH64_LD32_GOTPAGE_LO14,
2980    0},
2981 };
2982
2983 /* Given the address of a pointer pointing to the textual name of a
2984    relocation as may appear in assembler source, attempt to find its
2985    details in reloc_table.  The pointer will be updated to the character
2986    after the trailing colon.  On failure, NULL will be returned;
2987    otherwise return the reloc_table_entry.  */
2988
2989 static struct reloc_table_entry *
2990 find_reloc_table_entry (char **str)
2991 {
2992   unsigned int i;
2993   for (i = 0; i < ARRAY_SIZE (reloc_table); i++)
2994     {
2995       int length = strlen (reloc_table[i].name);
2996
2997       if (strncasecmp (reloc_table[i].name, *str, length) == 0
2998           && (*str)[length] == ':')
2999         {
3000           *str += (length + 1);
3001           return &reloc_table[i];
3002         }
3003     }
3004
3005   return NULL;
3006 }
3007
3008 /* Mode argument to parse_shift and parser_shifter_operand.  */
3009 enum parse_shift_mode
3010 {
3011   SHIFTED_NONE,                 /* no shifter allowed  */
3012   SHIFTED_ARITH_IMM,            /* "rn{,lsl|lsr|asl|asr|uxt|sxt #n}" or
3013                                    "#imm{,lsl #n}"  */
3014   SHIFTED_LOGIC_IMM,            /* "rn{,lsl|lsr|asl|asr|ror #n}" or
3015                                    "#imm"  */
3016   SHIFTED_LSL,                  /* bare "lsl #n"  */
3017   SHIFTED_MUL,                  /* bare "mul #n"  */
3018   SHIFTED_LSL_MSL,              /* "lsl|msl #n"  */
3019   SHIFTED_MUL_VL,               /* "mul vl"  */
3020   SHIFTED_REG_OFFSET            /* [su]xtw|sxtx {#n} or lsl #n  */
3021 };
3022
3023 /* Parse a <shift> operator on an AArch64 data processing instruction.
3024    Return TRUE on success; otherwise return FALSE.  */
3025 static bfd_boolean
3026 parse_shift (char **str, aarch64_opnd_info *operand, enum parse_shift_mode mode)
3027 {
3028   const struct aarch64_name_value_pair *shift_op;
3029   enum aarch64_modifier_kind kind;
3030   expressionS exp;
3031   int exp_has_prefix;
3032   char *s = *str;
3033   char *p = s;
3034
3035   for (p = *str; ISALPHA (*p); p++)
3036     ;
3037
3038   if (p == *str)
3039     {
3040       set_syntax_error (_("shift expression expected"));
3041       return FALSE;
3042     }
3043
3044   shift_op = hash_find_n (aarch64_shift_hsh, *str, p - *str);
3045
3046   if (shift_op == NULL)
3047     {
3048       set_syntax_error (_("shift operator expected"));
3049       return FALSE;
3050     }
3051
3052   kind = aarch64_get_operand_modifier (shift_op);
3053
3054   if (kind == AARCH64_MOD_MSL && mode != SHIFTED_LSL_MSL)
3055     {
3056       set_syntax_error (_("invalid use of 'MSL'"));
3057       return FALSE;
3058     }
3059
3060   if (kind == AARCH64_MOD_MUL
3061       && mode != SHIFTED_MUL
3062       && mode != SHIFTED_MUL_VL)
3063     {
3064       set_syntax_error (_("invalid use of 'MUL'"));
3065       return FALSE;
3066     }
3067
3068   switch (mode)
3069     {
3070     case SHIFTED_LOGIC_IMM:
3071       if (aarch64_extend_operator_p (kind))
3072         {
3073           set_syntax_error (_("extending shift is not permitted"));
3074           return FALSE;
3075         }
3076       break;
3077
3078     case SHIFTED_ARITH_IMM:
3079       if (kind == AARCH64_MOD_ROR)
3080         {
3081           set_syntax_error (_("'ROR' shift is not permitted"));
3082           return FALSE;
3083         }
3084       break;
3085
3086     case SHIFTED_LSL:
3087       if (kind != AARCH64_MOD_LSL)
3088         {
3089           set_syntax_error (_("only 'LSL' shift is permitted"));
3090           return FALSE;
3091         }
3092       break;
3093
3094     case SHIFTED_MUL:
3095       if (kind != AARCH64_MOD_MUL)
3096         {
3097           set_syntax_error (_("only 'MUL' is permitted"));
3098           return FALSE;
3099         }
3100       break;
3101
3102     case SHIFTED_MUL_VL:
3103       /* "MUL VL" consists of two separate tokens.  Require the first
3104          token to be "MUL" and look for a following "VL".  */
3105       if (kind == AARCH64_MOD_MUL)
3106         {
3107           skip_whitespace (p);
3108           if (strncasecmp (p, "vl", 2) == 0 && !ISALPHA (p[2]))
3109             {
3110               p += 2;
3111               kind = AARCH64_MOD_MUL_VL;
3112               break;
3113             }
3114         }
3115       set_syntax_error (_("only 'MUL VL' is permitted"));
3116       return FALSE;
3117
3118     case SHIFTED_REG_OFFSET:
3119       if (kind != AARCH64_MOD_UXTW && kind != AARCH64_MOD_LSL
3120           && kind != AARCH64_MOD_SXTW && kind != AARCH64_MOD_SXTX)
3121         {
3122           set_fatal_syntax_error
3123             (_("invalid shift for the register offset addressing mode"));
3124           return FALSE;
3125         }
3126       break;
3127
3128     case SHIFTED_LSL_MSL:
3129       if (kind != AARCH64_MOD_LSL && kind != AARCH64_MOD_MSL)
3130         {
3131           set_syntax_error (_("invalid shift operator"));
3132           return FALSE;
3133         }
3134       break;
3135
3136     default:
3137       abort ();
3138     }
3139
3140   /* Whitespace can appear here if the next thing is a bare digit.  */
3141   skip_whitespace (p);
3142
3143   /* Parse shift amount.  */
3144   exp_has_prefix = 0;
3145   if ((mode == SHIFTED_REG_OFFSET && *p == ']') || kind == AARCH64_MOD_MUL_VL)
3146     exp.X_op = O_absent;
3147   else
3148     {
3149       if (is_immediate_prefix (*p))
3150         {
3151           p++;
3152           exp_has_prefix = 1;
3153         }
3154       my_get_expression (&exp, &p, GE_NO_PREFIX, 0);
3155     }
3156   if (kind == AARCH64_MOD_MUL_VL)
3157     /* For consistency, give MUL VL the same shift amount as an implicit
3158        MUL #1.  */
3159     operand->shifter.amount = 1;
3160   else if (exp.X_op == O_absent)
3161     {
3162       if (!aarch64_extend_operator_p (kind) || exp_has_prefix)
3163         {
3164           set_syntax_error (_("missing shift amount"));
3165           return FALSE;
3166         }
3167       operand->shifter.amount = 0;
3168     }
3169   else if (exp.X_op != O_constant)
3170     {
3171       set_syntax_error (_("constant shift amount required"));
3172       return FALSE;
3173     }
3174   /* For parsing purposes, MUL #n has no inherent range.  The range
3175      depends on the operand and will be checked by operand-specific
3176      routines.  */
3177   else if (kind != AARCH64_MOD_MUL
3178            && (exp.X_add_number < 0 || exp.X_add_number > 63))
3179     {
3180       set_fatal_syntax_error (_("shift amount out of range 0 to 63"));
3181       return FALSE;
3182     }
3183   else
3184     {
3185       operand->shifter.amount = exp.X_add_number;
3186       operand->shifter.amount_present = 1;
3187     }
3188
3189   operand->shifter.operator_present = 1;
3190   operand->shifter.kind = kind;
3191
3192   *str = p;
3193   return TRUE;
3194 }
3195
3196 /* Parse a <shifter_operand> for a data processing instruction:
3197
3198       #<immediate>
3199       #<immediate>, LSL #imm
3200
3201    Validation of immediate operands is deferred to md_apply_fix.
3202
3203    Return TRUE on success; otherwise return FALSE.  */
3204
3205 static bfd_boolean
3206 parse_shifter_operand_imm (char **str, aarch64_opnd_info *operand,
3207                            enum parse_shift_mode mode)
3208 {
3209   char *p;
3210
3211   if (mode != SHIFTED_ARITH_IMM && mode != SHIFTED_LOGIC_IMM)
3212     return FALSE;
3213
3214   p = *str;
3215
3216   /* Accept an immediate expression.  */
3217   if (! my_get_expression (&inst.reloc.exp, &p, GE_OPT_PREFIX, 1))
3218     return FALSE;
3219
3220   /* Accept optional LSL for arithmetic immediate values.  */
3221   if (mode == SHIFTED_ARITH_IMM && skip_past_comma (&p))
3222     if (! parse_shift (&p, operand, SHIFTED_LSL))
3223       return FALSE;
3224
3225   /* Not accept any shifter for logical immediate values.  */
3226   if (mode == SHIFTED_LOGIC_IMM && skip_past_comma (&p)
3227       && parse_shift (&p, operand, mode))
3228     {
3229       set_syntax_error (_("unexpected shift operator"));
3230       return FALSE;
3231     }
3232
3233   *str = p;
3234   return TRUE;
3235 }
3236
3237 /* Parse a <shifter_operand> for a data processing instruction:
3238
3239       <Rm>
3240       <Rm>, <shift>
3241       #<immediate>
3242       #<immediate>, LSL #imm
3243
3244    where <shift> is handled by parse_shift above, and the last two
3245    cases are handled by the function above.
3246
3247    Validation of immediate operands is deferred to md_apply_fix.
3248
3249    Return TRUE on success; otherwise return FALSE.  */
3250
3251 static bfd_boolean
3252 parse_shifter_operand (char **str, aarch64_opnd_info *operand,
3253                        enum parse_shift_mode mode)
3254 {
3255   const reg_entry *reg;
3256   aarch64_opnd_qualifier_t qualifier;
3257   enum aarch64_operand_class opd_class
3258     = aarch64_get_operand_class (operand->type);
3259
3260   reg = aarch64_reg_parse_32_64 (str, &qualifier);
3261   if (reg)
3262     {
3263       if (opd_class == AARCH64_OPND_CLASS_IMMEDIATE)
3264         {
3265           set_syntax_error (_("unexpected register in the immediate operand"));
3266           return FALSE;
3267         }
3268
3269       if (!aarch64_check_reg_type (reg, REG_TYPE_R_Z))
3270         {
3271           set_syntax_error (_(get_reg_expected_msg (REG_TYPE_R_Z)));
3272           return FALSE;
3273         }
3274
3275       operand->reg.regno = reg->number;
3276       operand->qualifier = qualifier;
3277
3278       /* Accept optional shift operation on register.  */
3279       if (! skip_past_comma (str))
3280         return TRUE;
3281
3282       if (! parse_shift (str, operand, mode))
3283         return FALSE;
3284
3285       return TRUE;
3286     }
3287   else if (opd_class == AARCH64_OPND_CLASS_MODIFIED_REG)
3288     {
3289       set_syntax_error
3290         (_("integer register expected in the extended/shifted operand "
3291            "register"));
3292       return FALSE;
3293     }
3294
3295   /* We have a shifted immediate variable.  */
3296   return parse_shifter_operand_imm (str, operand, mode);
3297 }
3298
3299 /* Return TRUE on success; return FALSE otherwise.  */
3300
3301 static bfd_boolean
3302 parse_shifter_operand_reloc (char **str, aarch64_opnd_info *operand,
3303                              enum parse_shift_mode mode)
3304 {
3305   char *p = *str;
3306
3307   /* Determine if we have the sequence of characters #: or just :
3308      coming next.  If we do, then we check for a :rello: relocation
3309      modifier.  If we don't, punt the whole lot to
3310      parse_shifter_operand.  */
3311
3312   if ((p[0] == '#' && p[1] == ':') || p[0] == ':')
3313     {
3314       struct reloc_table_entry *entry;
3315
3316       if (p[0] == '#')
3317         p += 2;
3318       else
3319         p++;
3320       *str = p;
3321
3322       /* Try to parse a relocation.  Anything else is an error.  */
3323       if (!(entry = find_reloc_table_entry (str)))
3324         {
3325           set_syntax_error (_("unknown relocation modifier"));
3326           return FALSE;
3327         }
3328
3329       if (entry->add_type == 0)
3330         {
3331           set_syntax_error
3332             (_("this relocation modifier is not allowed on this instruction"));
3333           return FALSE;
3334         }
3335
3336       /* Save str before we decompose it.  */
3337       p = *str;
3338
3339       /* Next, we parse the expression.  */
3340       if (! my_get_expression (&inst.reloc.exp, str, GE_NO_PREFIX, 1))
3341         return FALSE;
3342
3343       /* Record the relocation type (use the ADD variant here).  */
3344       inst.reloc.type = entry->add_type;
3345       inst.reloc.pc_rel = entry->pc_rel;
3346
3347       /* If str is empty, we've reached the end, stop here.  */
3348       if (**str == '\0')
3349         return TRUE;
3350
3351       /* Otherwise, we have a shifted reloc modifier, so rewind to
3352          recover the variable name and continue parsing for the shifter.  */
3353       *str = p;
3354       return parse_shifter_operand_imm (str, operand, mode);
3355     }
3356
3357   return parse_shifter_operand (str, operand, mode);
3358 }
3359
3360 /* Parse all forms of an address expression.  Information is written
3361    to *OPERAND and/or inst.reloc.
3362
3363    The A64 instruction set has the following addressing modes:
3364
3365    Offset
3366      [base]                      // in SIMD ld/st structure
3367      [base{,#0}]                 // in ld/st exclusive
3368      [base{,#imm}]
3369      [base,Xm{,LSL #imm}]
3370      [base,Xm,SXTX {#imm}]
3371      [base,Wm,(S|U)XTW {#imm}]
3372    Pre-indexed
3373      [base,#imm]!
3374    Post-indexed
3375      [base],#imm
3376      [base],Xm                   // in SIMD ld/st structure
3377    PC-relative (literal)
3378      label
3379    SVE:
3380      [base,#imm,MUL VL]
3381      [base,Zm.D{,LSL #imm}]
3382      [base,Zm.S,(S|U)XTW {#imm}]
3383      [base,Zm.D,(S|U)XTW {#imm}] // ignores top 32 bits of Zm.D elements
3384      [Zn.S,#imm]
3385      [Zn.D,#imm]
3386      [Zn.S,Zm.S{,LSL #imm}]      // in ADR
3387      [Zn.D,Zm.D{,LSL #imm}]      // in ADR
3388      [Zn.D,Zm.D,(S|U)XTW {#imm}] // in ADR
3389
3390    (As a convenience, the notation "=immediate" is permitted in conjunction
3391    with the pc-relative literal load instructions to automatically place an
3392    immediate value or symbolic address in a nearby literal pool and generate
3393    a hidden label which references it.)
3394
3395    Upon a successful parsing, the address structure in *OPERAND will be
3396    filled in the following way:
3397
3398      .base_regno = <base>
3399      .offset.is_reg     // 1 if the offset is a register
3400      .offset.imm = <imm>
3401      .offset.regno = <Rm>
3402
3403    For different addressing modes defined in the A64 ISA:
3404
3405    Offset
3406      .pcrel=0; .preind=1; .postind=0; .writeback=0
3407    Pre-indexed
3408      .pcrel=0; .preind=1; .postind=0; .writeback=1
3409    Post-indexed
3410      .pcrel=0; .preind=0; .postind=1; .writeback=1
3411    PC-relative (literal)
3412      .pcrel=1; .preind=1; .postind=0; .writeback=0
3413
3414    The shift/extension information, if any, will be stored in .shifter.
3415    The base and offset qualifiers will be stored in *BASE_QUALIFIER and
3416    *OFFSET_QUALIFIER respectively, with NIL being used if there's no
3417    corresponding register.
3418
3419    BASE_TYPE says which types of base register should be accepted and
3420    OFFSET_TYPE says the same for offset registers.  IMM_SHIFT_MODE
3421    is the type of shifter that is allowed for immediate offsets,
3422    or SHIFTED_NONE if none.
3423
3424    In all other respects, it is the caller's responsibility to check
3425    for addressing modes not supported by the instruction, and to set
3426    inst.reloc.type.  */
3427
3428 static bfd_boolean
3429 parse_address_main (char **str, aarch64_opnd_info *operand,
3430                     aarch64_opnd_qualifier_t *base_qualifier,
3431                     aarch64_opnd_qualifier_t *offset_qualifier,
3432                     aarch64_reg_type base_type, aarch64_reg_type offset_type,
3433                     enum parse_shift_mode imm_shift_mode)
3434 {
3435   char *p = *str;
3436   const reg_entry *reg;
3437   expressionS *exp = &inst.reloc.exp;
3438
3439   *base_qualifier = AARCH64_OPND_QLF_NIL;
3440   *offset_qualifier = AARCH64_OPND_QLF_NIL;
3441   if (! skip_past_char (&p, '['))
3442     {
3443       /* =immediate or label.  */
3444       operand->addr.pcrel = 1;
3445       operand->addr.preind = 1;
3446
3447       /* #:<reloc_op>:<symbol>  */
3448       skip_past_char (&p, '#');
3449       if (skip_past_char (&p, ':'))
3450         {
3451           bfd_reloc_code_real_type ty;
3452           struct reloc_table_entry *entry;
3453
3454           /* Try to parse a relocation modifier.  Anything else is
3455              an error.  */
3456           entry = find_reloc_table_entry (&p);
3457           if (! entry)
3458             {
3459               set_syntax_error (_("unknown relocation modifier"));
3460               return FALSE;
3461             }
3462
3463           switch (operand->type)
3464             {
3465             case AARCH64_OPND_ADDR_PCREL21:
3466               /* adr */
3467               ty = entry->adr_type;
3468               break;
3469
3470             default:
3471               ty = entry->ld_literal_type;
3472               break;
3473             }
3474
3475           if (ty == 0)
3476             {
3477               set_syntax_error
3478                 (_("this relocation modifier is not allowed on this "
3479                    "instruction"));
3480               return FALSE;
3481             }
3482
3483           /* #:<reloc_op>:  */
3484           if (! my_get_expression (exp, &p, GE_NO_PREFIX, 1))
3485             {
3486               set_syntax_error (_("invalid relocation expression"));
3487               return FALSE;
3488             }
3489
3490           /* #:<reloc_op>:<expr>  */
3491           /* Record the relocation type.  */
3492           inst.reloc.type = ty;
3493           inst.reloc.pc_rel = entry->pc_rel;
3494         }
3495       else
3496         {
3497
3498           if (skip_past_char (&p, '='))
3499             /* =immediate; need to generate the literal in the literal pool. */
3500             inst.gen_lit_pool = 1;
3501
3502           if (!my_get_expression (exp, &p, GE_NO_PREFIX, 1))
3503             {
3504               set_syntax_error (_("invalid address"));
3505               return FALSE;
3506             }
3507         }
3508
3509       *str = p;
3510       return TRUE;
3511     }
3512
3513   /* [ */
3514
3515   reg = aarch64_addr_reg_parse (&p, base_type, base_qualifier);
3516   if (!reg || !aarch64_check_reg_type (reg, base_type))
3517     {
3518       set_syntax_error (_(get_reg_expected_msg (base_type)));
3519       return FALSE;
3520     }
3521   operand->addr.base_regno = reg->number;
3522
3523   /* [Xn */
3524   if (skip_past_comma (&p))
3525     {
3526       /* [Xn, */
3527       operand->addr.preind = 1;
3528
3529       reg = aarch64_addr_reg_parse (&p, offset_type, offset_qualifier);
3530       if (reg)
3531         {
3532           if (!aarch64_check_reg_type (reg, offset_type))
3533             {
3534               set_syntax_error (_(get_reg_expected_msg (offset_type)));
3535               return FALSE;
3536             }
3537
3538           /* [Xn,Rm  */
3539           operand->addr.offset.regno = reg->number;
3540           operand->addr.offset.is_reg = 1;
3541           /* Shifted index.  */
3542           if (skip_past_comma (&p))
3543             {
3544               /* [Xn,Rm,  */
3545               if (! parse_shift (&p, operand, SHIFTED_REG_OFFSET))
3546                 /* Use the diagnostics set in parse_shift, so not set new
3547                    error message here.  */
3548                 return FALSE;
3549             }
3550           /* We only accept:
3551              [base,Xm{,LSL #imm}]
3552              [base,Xm,SXTX {#imm}]
3553              [base,Wm,(S|U)XTW {#imm}]  */
3554           if (operand->shifter.kind == AARCH64_MOD_NONE
3555               || operand->shifter.kind == AARCH64_MOD_LSL
3556               || operand->shifter.kind == AARCH64_MOD_SXTX)
3557             {
3558               if (*offset_qualifier == AARCH64_OPND_QLF_W)
3559                 {
3560                   set_syntax_error (_("invalid use of 32-bit register offset"));
3561                   return FALSE;
3562                 }
3563               if (aarch64_get_qualifier_esize (*base_qualifier)
3564                   != aarch64_get_qualifier_esize (*offset_qualifier))
3565                 {
3566                   set_syntax_error (_("offset has different size from base"));
3567                   return FALSE;
3568                 }
3569             }
3570           else if (*offset_qualifier == AARCH64_OPND_QLF_X)
3571             {
3572               set_syntax_error (_("invalid use of 64-bit register offset"));
3573               return FALSE;
3574             }
3575         }
3576       else
3577         {
3578           /* [Xn,#:<reloc_op>:<symbol>  */
3579           skip_past_char (&p, '#');
3580           if (skip_past_char (&p, ':'))
3581             {
3582               struct reloc_table_entry *entry;
3583
3584               /* Try to parse a relocation modifier.  Anything else is
3585                  an error.  */
3586               if (!(entry = find_reloc_table_entry (&p)))
3587                 {
3588                   set_syntax_error (_("unknown relocation modifier"));
3589                   return FALSE;
3590                 }
3591
3592               if (entry->ldst_type == 0)
3593                 {
3594                   set_syntax_error
3595                     (_("this relocation modifier is not allowed on this "
3596                        "instruction"));
3597                   return FALSE;
3598                 }
3599
3600               /* [Xn,#:<reloc_op>:  */
3601               /* We now have the group relocation table entry corresponding to
3602                  the name in the assembler source.  Next, we parse the
3603                  expression.  */
3604               if (! my_get_expression (exp, &p, GE_NO_PREFIX, 1))
3605                 {
3606                   set_syntax_error (_("invalid relocation expression"));
3607                   return FALSE;
3608                 }
3609
3610               /* [Xn,#:<reloc_op>:<expr>  */
3611               /* Record the load/store relocation type.  */
3612               inst.reloc.type = entry->ldst_type;
3613               inst.reloc.pc_rel = entry->pc_rel;
3614             }
3615           else
3616             {
3617               if (! my_get_expression (exp, &p, GE_OPT_PREFIX, 1))
3618                 {
3619                   set_syntax_error (_("invalid expression in the address"));
3620                   return FALSE;
3621                 }
3622               /* [Xn,<expr>  */
3623               if (imm_shift_mode != SHIFTED_NONE && skip_past_comma (&p))
3624                 /* [Xn,<expr>,<shifter>  */
3625                 if (! parse_shift (&p, operand, imm_shift_mode))
3626                   return FALSE;
3627             }
3628         }
3629     }
3630
3631   if (! skip_past_char (&p, ']'))
3632     {
3633       set_syntax_error (_("']' expected"));
3634       return FALSE;
3635     }
3636
3637   if (skip_past_char (&p, '!'))
3638     {
3639       if (operand->addr.preind && operand->addr.offset.is_reg)
3640         {
3641           set_syntax_error (_("register offset not allowed in pre-indexed "
3642                               "addressing mode"));
3643           return FALSE;
3644         }
3645       /* [Xn]! */
3646       operand->addr.writeback = 1;
3647     }
3648   else if (skip_past_comma (&p))
3649     {
3650       /* [Xn], */
3651       operand->addr.postind = 1;
3652       operand->addr.writeback = 1;
3653
3654       if (operand->addr.preind)
3655         {
3656           set_syntax_error (_("cannot combine pre- and post-indexing"));
3657           return FALSE;
3658         }
3659
3660       reg = aarch64_reg_parse_32_64 (&p, offset_qualifier);
3661       if (reg)
3662         {
3663           /* [Xn],Xm */
3664           if (!aarch64_check_reg_type (reg, REG_TYPE_R_64))
3665             {
3666               set_syntax_error (_(get_reg_expected_msg (REG_TYPE_R_64)));
3667               return FALSE;
3668             }
3669
3670           operand->addr.offset.regno = reg->number;
3671           operand->addr.offset.is_reg = 1;
3672         }
3673       else if (! my_get_expression (exp, &p, GE_OPT_PREFIX, 1))
3674         {
3675           /* [Xn],#expr */
3676           set_syntax_error (_("invalid expression in the address"));
3677           return FALSE;
3678         }
3679     }
3680
3681   /* If at this point neither .preind nor .postind is set, we have a
3682      bare [Rn]{!}; reject [Rn]! but accept [Rn] as a shorthand for [Rn,#0].  */
3683   if (operand->addr.preind == 0 && operand->addr.postind == 0)
3684     {
3685       if (operand->addr.writeback)
3686         {
3687           /* Reject [Rn]!   */
3688           set_syntax_error (_("missing offset in the pre-indexed address"));
3689           return FALSE;
3690         }
3691
3692       operand->addr.preind = 1;
3693       inst.reloc.exp.X_op = O_constant;
3694       inst.reloc.exp.X_add_number = 0;
3695     }
3696
3697   *str = p;
3698   return TRUE;
3699 }
3700
3701 /* Parse a base AArch64 address (as opposed to an SVE one).  Return TRUE
3702    on success.  */
3703 static bfd_boolean
3704 parse_address (char **str, aarch64_opnd_info *operand)
3705 {
3706   aarch64_opnd_qualifier_t base_qualifier, offset_qualifier;
3707   return parse_address_main (str, operand, &base_qualifier, &offset_qualifier,
3708                              REG_TYPE_R64_SP, REG_TYPE_R_Z, SHIFTED_NONE);
3709 }
3710
3711 /* Parse an address in which SVE vector registers and MUL VL are allowed.
3712    The arguments have the same meaning as for parse_address_main.
3713    Return TRUE on success.  */
3714 static bfd_boolean
3715 parse_sve_address (char **str, aarch64_opnd_info *operand,
3716                    aarch64_opnd_qualifier_t *base_qualifier,
3717                    aarch64_opnd_qualifier_t *offset_qualifier)
3718 {
3719   return parse_address_main (str, operand, base_qualifier, offset_qualifier,
3720                              REG_TYPE_SVE_BASE, REG_TYPE_SVE_OFFSET,
3721                              SHIFTED_MUL_VL);
3722 }
3723
3724 /* Parse an operand for a MOVZ, MOVN or MOVK instruction.
3725    Return TRUE on success; otherwise return FALSE.  */
3726 static bfd_boolean
3727 parse_half (char **str, int *internal_fixup_p)
3728 {
3729   char *p = *str;
3730
3731   skip_past_char (&p, '#');
3732
3733   gas_assert (internal_fixup_p);
3734   *internal_fixup_p = 0;
3735
3736   if (*p == ':')
3737     {
3738       struct reloc_table_entry *entry;
3739
3740       /* Try to parse a relocation.  Anything else is an error.  */
3741       ++p;
3742       if (!(entry = find_reloc_table_entry (&p)))
3743         {
3744           set_syntax_error (_("unknown relocation modifier"));
3745           return FALSE;
3746         }
3747
3748       if (entry->movw_type == 0)
3749         {
3750           set_syntax_error
3751             (_("this relocation modifier is not allowed on this instruction"));
3752           return FALSE;
3753         }
3754
3755       inst.reloc.type = entry->movw_type;
3756     }
3757   else
3758     *internal_fixup_p = 1;
3759
3760   if (! my_get_expression (&inst.reloc.exp, &p, GE_NO_PREFIX, 1))
3761     return FALSE;
3762
3763   *str = p;
3764   return TRUE;
3765 }
3766
3767 /* Parse an operand for an ADRP instruction:
3768      ADRP <Xd>, <label>
3769    Return TRUE on success; otherwise return FALSE.  */
3770
3771 static bfd_boolean
3772 parse_adrp (char **str)
3773 {
3774   char *p;
3775
3776   p = *str;
3777   if (*p == ':')
3778     {
3779       struct reloc_table_entry *entry;
3780
3781       /* Try to parse a relocation.  Anything else is an error.  */
3782       ++p;
3783       if (!(entry = find_reloc_table_entry (&p)))
3784         {
3785           set_syntax_error (_("unknown relocation modifier"));
3786           return FALSE;
3787         }
3788
3789       if (entry->adrp_type == 0)
3790         {
3791           set_syntax_error
3792             (_("this relocation modifier is not allowed on this instruction"));
3793           return FALSE;
3794         }
3795
3796       inst.reloc.type = entry->adrp_type;
3797     }
3798   else
3799     inst.reloc.type = BFD_RELOC_AARCH64_ADR_HI21_PCREL;
3800
3801   inst.reloc.pc_rel = 1;
3802
3803   if (! my_get_expression (&inst.reloc.exp, &p, GE_NO_PREFIX, 1))
3804     return FALSE;
3805
3806   *str = p;
3807   return TRUE;
3808 }
3809
3810 /* Miscellaneous. */
3811
3812 /* Parse a symbolic operand such as "pow2" at *STR.  ARRAY is an array
3813    of SIZE tokens in which index I gives the token for field value I,
3814    or is null if field value I is invalid.  REG_TYPE says which register
3815    names should be treated as registers rather than as symbolic immediates.
3816
3817    Return true on success, moving *STR past the operand and storing the
3818    field value in *VAL.  */
3819
3820 static int
3821 parse_enum_string (char **str, int64_t *val, const char *const *array,
3822                    size_t size, aarch64_reg_type reg_type)
3823 {
3824   expressionS exp;
3825   char *p, *q;
3826   size_t i;
3827
3828   /* Match C-like tokens.  */
3829   p = q = *str;
3830   while (ISALNUM (*q))
3831     q++;
3832
3833   for (i = 0; i < size; ++i)
3834     if (array[i]
3835         && strncasecmp (array[i], p, q - p) == 0
3836         && array[i][q - p] == 0)
3837       {
3838         *val = i;
3839         *str = q;
3840         return TRUE;
3841       }
3842
3843   if (!parse_immediate_expression (&p, &exp, reg_type))
3844     return FALSE;
3845
3846   if (exp.X_op == O_constant
3847       && (uint64_t) exp.X_add_number < size)
3848     {
3849       *val = exp.X_add_number;
3850       *str = p;
3851       return TRUE;
3852     }
3853
3854   /* Use the default error for this operand.  */
3855   return FALSE;
3856 }
3857
3858 /* Parse an option for a preload instruction.  Returns the encoding for the
3859    option, or PARSE_FAIL.  */
3860
3861 static int
3862 parse_pldop (char **str)
3863 {
3864   char *p, *q;
3865   const struct aarch64_name_value_pair *o;
3866
3867   p = q = *str;
3868   while (ISALNUM (*q))
3869     q++;
3870
3871   o = hash_find_n (aarch64_pldop_hsh, p, q - p);
3872   if (!o)
3873     return PARSE_FAIL;
3874
3875   *str = q;
3876   return o->value;
3877 }
3878
3879 /* Parse an option for a barrier instruction.  Returns the encoding for the
3880    option, or PARSE_FAIL.  */
3881
3882 static int
3883 parse_barrier (char **str)
3884 {
3885   char *p, *q;
3886   const asm_barrier_opt *o;
3887
3888   p = q = *str;
3889   while (ISALPHA (*q))
3890     q++;
3891
3892   o = hash_find_n (aarch64_barrier_opt_hsh, p, q - p);
3893   if (!o)
3894     return PARSE_FAIL;
3895
3896   *str = q;
3897   return o->value;
3898 }
3899
3900 /* Parse an operand for a PSB barrier.  Set *HINT_OPT to the hint-option record
3901    return 0 if successful.  Otherwise return PARSE_FAIL.  */
3902
3903 static int
3904 parse_barrier_psb (char **str,
3905                    const struct aarch64_name_value_pair ** hint_opt)
3906 {
3907   char *p, *q;
3908   const struct aarch64_name_value_pair *o;
3909
3910   p = q = *str;
3911   while (ISALPHA (*q))
3912     q++;
3913
3914   o = hash_find_n (aarch64_hint_opt_hsh, p, q - p);
3915   if (!o)
3916     {
3917       set_fatal_syntax_error
3918         ( _("unknown or missing option to PSB"));
3919       return PARSE_FAIL;
3920     }
3921
3922   if (o->value != 0x11)
3923     {
3924       /* PSB only accepts option name 'CSYNC'.  */
3925       set_syntax_error
3926         (_("the specified option is not accepted for PSB"));
3927       return PARSE_FAIL;
3928     }
3929
3930   *str = q;
3931   *hint_opt = o;
3932   return 0;
3933 }
3934
3935 /* Parse a system register or a PSTATE field name for an MSR/MRS instruction.
3936    Returns the encoding for the option, or PARSE_FAIL.
3937
3938    If IMPLE_DEFINED_P is non-zero, the function will also try to parse the
3939    implementation defined system register name S<op0>_<op1>_<Cn>_<Cm>_<op2>.
3940
3941    If PSTATEFIELD_P is non-zero, the function will parse the name as a PSTATE
3942    field, otherwise as a system register.
3943 */
3944
3945 static int
3946 parse_sys_reg (char **str, struct hash_control *sys_regs,
3947                int imple_defined_p, int pstatefield_p,
3948                uint32_t* flags)
3949 {
3950   char *p, *q;
3951   char buf[32];
3952   const aarch64_sys_reg *o;
3953   int value;
3954
3955   p = buf;
3956   for (q = *str; ISALNUM (*q) || *q == '_'; q++)
3957     if (p < buf + 31)
3958       *p++ = TOLOWER (*q);
3959   *p = '\0';
3960   /* Assert that BUF be large enough.  */
3961   gas_assert (p - buf == q - *str);
3962
3963   o = hash_find (sys_regs, buf);
3964   if (!o)
3965     {
3966       if (!imple_defined_p)
3967         return PARSE_FAIL;
3968       else
3969         {
3970           /* Parse S<op0>_<op1>_<Cn>_<Cm>_<op2>.  */
3971           unsigned int op0, op1, cn, cm, op2;
3972
3973           if (sscanf (buf, "s%u_%u_c%u_c%u_%u", &op0, &op1, &cn, &cm, &op2)
3974               != 5)
3975             return PARSE_FAIL;
3976           if (op0 > 3 || op1 > 7 || cn > 15 || cm > 15 || op2 > 7)
3977             return PARSE_FAIL;
3978           value = (op0 << 14) | (op1 << 11) | (cn << 7) | (cm << 3) | op2;
3979           if (flags)
3980             *flags = 0;
3981         }
3982     }
3983   else
3984     {
3985       if (pstatefield_p && !aarch64_pstatefield_supported_p (cpu_variant, o))
3986         as_bad (_("selected processor does not support PSTATE field "
3987                   "name '%s'"), buf);
3988       if (!pstatefield_p && !aarch64_sys_reg_supported_p (cpu_variant, o))
3989         as_bad (_("selected processor does not support system register "
3990                   "name '%s'"), buf);
3991       if (aarch64_sys_reg_deprecated_p (o))
3992         as_warn (_("system register name '%s' is deprecated and may be "
3993                    "removed in a future release"), buf);
3994       value = o->value;
3995       if (flags)
3996         *flags = o->flags;
3997     }
3998
3999   *str = q;
4000   return value;
4001 }
4002
4003 /* Parse a system reg for ic/dc/at/tlbi instructions.  Returns the table entry
4004    for the option, or NULL.  */
4005
4006 static const aarch64_sys_ins_reg *
4007 parse_sys_ins_reg (char **str, struct hash_control *sys_ins_regs)
4008 {
4009   char *p, *q;
4010   char buf[32];
4011   const aarch64_sys_ins_reg *o;
4012
4013   p = buf;
4014   for (q = *str; ISALNUM (*q) || *q == '_'; q++)
4015     if (p < buf + 31)
4016       *p++ = TOLOWER (*q);
4017   *p = '\0';
4018
4019   o = hash_find (sys_ins_regs, buf);
4020   if (!o)
4021     return NULL;
4022
4023   if (!aarch64_sys_ins_reg_supported_p (cpu_variant, o))
4024     as_bad (_("selected processor does not support system register "
4025               "name '%s'"), buf);
4026
4027   *str = q;
4028   return o;
4029 }
4030 \f
4031 #define po_char_or_fail(chr) do {                               \
4032     if (! skip_past_char (&str, chr))                           \
4033       goto failure;                                             \
4034 } while (0)
4035
4036 #define po_reg_or_fail(regtype) do {                            \
4037     val = aarch64_reg_parse (&str, regtype, &rtype, NULL);      \
4038     if (val == PARSE_FAIL)                                      \
4039       {                                                         \
4040         set_default_error ();                                   \
4041         goto failure;                                           \
4042       }                                                         \
4043   } while (0)
4044
4045 #define po_int_reg_or_fail(reg_type) do {                       \
4046     reg = aarch64_reg_parse_32_64 (&str, &qualifier);           \
4047     if (!reg || !aarch64_check_reg_type (reg, reg_type))        \
4048       {                                                         \
4049         set_default_error ();                                   \
4050         goto failure;                                           \
4051       }                                                         \
4052     info->reg.regno = reg->number;                              \
4053     info->qualifier = qualifier;                                \
4054   } while (0)
4055
4056 #define po_imm_nc_or_fail() do {                                \
4057     if (! parse_constant_immediate (&str, &val, imm_reg_type))  \
4058       goto failure;                                             \
4059   } while (0)
4060
4061 #define po_imm_or_fail(min, max) do {                           \
4062     if (! parse_constant_immediate (&str, &val, imm_reg_type))  \
4063       goto failure;                                             \
4064     if (val < min || val > max)                                 \
4065       {                                                         \
4066         set_fatal_syntax_error (_("immediate value out of range "\
4067 #min " to "#max));                                              \
4068         goto failure;                                           \
4069       }                                                         \
4070   } while (0)
4071
4072 #define po_enum_or_fail(array) do {                             \
4073     if (!parse_enum_string (&str, &val, array,                  \
4074                             ARRAY_SIZE (array), imm_reg_type))  \
4075       goto failure;                                             \
4076   } while (0)
4077
4078 #define po_misc_or_fail(expr) do {                              \
4079     if (!expr)                                                  \
4080       goto failure;                                             \
4081   } while (0)
4082 \f
4083 /* encode the 12-bit imm field of Add/sub immediate */
4084 static inline uint32_t
4085 encode_addsub_imm (uint32_t imm)
4086 {
4087   return imm << 10;
4088 }
4089
4090 /* encode the shift amount field of Add/sub immediate */
4091 static inline uint32_t
4092 encode_addsub_imm_shift_amount (uint32_t cnt)
4093 {
4094   return cnt << 22;
4095 }
4096
4097
4098 /* encode the imm field of Adr instruction */
4099 static inline uint32_t
4100 encode_adr_imm (uint32_t imm)
4101 {
4102   return (((imm & 0x3) << 29)   /*  [1:0] -> [30:29] */
4103           | ((imm & (0x7ffff << 2)) << 3));     /* [20:2] -> [23:5]  */
4104 }
4105
4106 /* encode the immediate field of Move wide immediate */
4107 static inline uint32_t
4108 encode_movw_imm (uint32_t imm)
4109 {
4110   return imm << 5;
4111 }
4112
4113 /* encode the 26-bit offset of unconditional branch */
4114 static inline uint32_t
4115 encode_branch_ofs_26 (uint32_t ofs)
4116 {
4117   return ofs & ((1 << 26) - 1);
4118 }
4119
4120 /* encode the 19-bit offset of conditional branch and compare & branch */
4121 static inline uint32_t
4122 encode_cond_branch_ofs_19 (uint32_t ofs)
4123 {
4124   return (ofs & ((1 << 19) - 1)) << 5;
4125 }
4126
4127 /* encode the 19-bit offset of ld literal */
4128 static inline uint32_t
4129 encode_ld_lit_ofs_19 (uint32_t ofs)
4130 {
4131   return (ofs & ((1 << 19) - 1)) << 5;
4132 }
4133
4134 /* Encode the 14-bit offset of test & branch.  */
4135 static inline uint32_t
4136 encode_tst_branch_ofs_14 (uint32_t ofs)
4137 {
4138   return (ofs & ((1 << 14) - 1)) << 5;
4139 }
4140
4141 /* Encode the 16-bit imm field of svc/hvc/smc.  */
4142 static inline uint32_t
4143 encode_svc_imm (uint32_t imm)
4144 {
4145   return imm << 5;
4146 }
4147
4148 /* Reencode add(s) to sub(s), or sub(s) to add(s).  */
4149 static inline uint32_t
4150 reencode_addsub_switch_add_sub (uint32_t opcode)
4151 {
4152   return opcode ^ (1 << 30);
4153 }
4154
4155 static inline uint32_t
4156 reencode_movzn_to_movz (uint32_t opcode)
4157 {
4158   return opcode | (1 << 30);
4159 }
4160
4161 static inline uint32_t
4162 reencode_movzn_to_movn (uint32_t opcode)
4163 {
4164   return opcode & ~(1 << 30);
4165 }
4166
4167 /* Overall per-instruction processing.  */
4168
4169 /* We need to be able to fix up arbitrary expressions in some statements.
4170    This is so that we can handle symbols that are an arbitrary distance from
4171    the pc.  The most common cases are of the form ((+/-sym -/+ . - 8) & mask),
4172    which returns part of an address in a form which will be valid for
4173    a data instruction.  We do this by pushing the expression into a symbol
4174    in the expr_section, and creating a fix for that.  */
4175
4176 static fixS *
4177 fix_new_aarch64 (fragS * frag,
4178                  int where,
4179                  short int size, expressionS * exp, int pc_rel, int reloc)
4180 {
4181   fixS *new_fix;
4182
4183   switch (exp->X_op)
4184     {
4185     case O_constant:
4186     case O_symbol:
4187     case O_add:
4188     case O_subtract:
4189       new_fix = fix_new_exp (frag, where, size, exp, pc_rel, reloc);
4190       break;
4191
4192     default:
4193       new_fix = fix_new (frag, where, size, make_expr_symbol (exp), 0,
4194                          pc_rel, reloc);
4195       break;
4196     }
4197   return new_fix;
4198 }
4199 \f
4200 /* Diagnostics on operands errors.  */
4201
4202 /* By default, output verbose error message.
4203    Disable the verbose error message by -mno-verbose-error.  */
4204 static int verbose_error_p = 1;
4205
4206 #ifdef DEBUG_AARCH64
4207 /* N.B. this is only for the purpose of debugging.  */
4208 const char* operand_mismatch_kind_names[] =
4209 {
4210   "AARCH64_OPDE_NIL",
4211   "AARCH64_OPDE_RECOVERABLE",
4212   "AARCH64_OPDE_SYNTAX_ERROR",
4213   "AARCH64_OPDE_FATAL_SYNTAX_ERROR",
4214   "AARCH64_OPDE_INVALID_VARIANT",
4215   "AARCH64_OPDE_OUT_OF_RANGE",
4216   "AARCH64_OPDE_UNALIGNED",
4217   "AARCH64_OPDE_REG_LIST",
4218   "AARCH64_OPDE_OTHER_ERROR",
4219 };
4220 #endif /* DEBUG_AARCH64 */
4221
4222 /* Return TRUE if LHS is of higher severity than RHS, otherwise return FALSE.
4223
4224    When multiple errors of different kinds are found in the same assembly
4225    line, only the error of the highest severity will be picked up for
4226    issuing the diagnostics.  */
4227
4228 static inline bfd_boolean
4229 operand_error_higher_severity_p (enum aarch64_operand_error_kind lhs,
4230                                  enum aarch64_operand_error_kind rhs)
4231 {
4232   gas_assert (AARCH64_OPDE_RECOVERABLE > AARCH64_OPDE_NIL);
4233   gas_assert (AARCH64_OPDE_SYNTAX_ERROR > AARCH64_OPDE_RECOVERABLE);
4234   gas_assert (AARCH64_OPDE_FATAL_SYNTAX_ERROR > AARCH64_OPDE_SYNTAX_ERROR);
4235   gas_assert (AARCH64_OPDE_INVALID_VARIANT > AARCH64_OPDE_FATAL_SYNTAX_ERROR);
4236   gas_assert (AARCH64_OPDE_OUT_OF_RANGE > AARCH64_OPDE_INVALID_VARIANT);
4237   gas_assert (AARCH64_OPDE_UNALIGNED > AARCH64_OPDE_OUT_OF_RANGE);
4238   gas_assert (AARCH64_OPDE_REG_LIST > AARCH64_OPDE_UNALIGNED);
4239   gas_assert (AARCH64_OPDE_OTHER_ERROR > AARCH64_OPDE_REG_LIST);
4240   return lhs > rhs;
4241 }
4242
4243 /* Helper routine to get the mnemonic name from the assembly instruction
4244    line; should only be called for the diagnosis purpose, as there is
4245    string copy operation involved, which may affect the runtime
4246    performance if used in elsewhere.  */
4247
4248 static const char*
4249 get_mnemonic_name (const char *str)
4250 {
4251   static char mnemonic[32];
4252   char *ptr;
4253
4254   /* Get the first 15 bytes and assume that the full name is included.  */
4255   strncpy (mnemonic, str, 31);
4256   mnemonic[31] = '\0';
4257
4258   /* Scan up to the end of the mnemonic, which must end in white space,
4259      '.', or end of string.  */
4260   for (ptr = mnemonic; is_part_of_name(*ptr); ++ptr)
4261     ;
4262
4263   *ptr = '\0';
4264
4265   /* Append '...' to the truncated long name.  */
4266   if (ptr - mnemonic == 31)
4267     mnemonic[28] = mnemonic[29] = mnemonic[30] = '.';
4268
4269   return mnemonic;
4270 }
4271
4272 static void
4273 reset_aarch64_instruction (aarch64_instruction *instruction)
4274 {
4275   memset (instruction, '\0', sizeof (aarch64_instruction));
4276   instruction->reloc.type = BFD_RELOC_UNUSED;
4277 }
4278
4279 /* Data structures storing one user error in the assembly code related to
4280    operands.  */
4281
4282 struct operand_error_record
4283 {
4284   const aarch64_opcode *opcode;
4285   aarch64_operand_error detail;
4286   struct operand_error_record *next;
4287 };
4288
4289 typedef struct operand_error_record operand_error_record;
4290
4291 struct operand_errors
4292 {
4293   operand_error_record *head;
4294   operand_error_record *tail;
4295 };
4296
4297 typedef struct operand_errors operand_errors;
4298
4299 /* Top-level data structure reporting user errors for the current line of
4300    the assembly code.
4301    The way md_assemble works is that all opcodes sharing the same mnemonic
4302    name are iterated to find a match to the assembly line.  In this data
4303    structure, each of the such opcodes will have one operand_error_record
4304    allocated and inserted.  In other words, excessive errors related with
4305    a single opcode are disregarded.  */
4306 operand_errors operand_error_report;
4307
4308 /* Free record nodes.  */
4309 static operand_error_record *free_opnd_error_record_nodes = NULL;
4310
4311 /* Initialize the data structure that stores the operand mismatch
4312    information on assembling one line of the assembly code.  */
4313 static void
4314 init_operand_error_report (void)
4315 {
4316   if (operand_error_report.head != NULL)
4317     {
4318       gas_assert (operand_error_report.tail != NULL);
4319       operand_error_report.tail->next = free_opnd_error_record_nodes;
4320       free_opnd_error_record_nodes = operand_error_report.head;
4321       operand_error_report.head = NULL;
4322       operand_error_report.tail = NULL;
4323       return;
4324     }
4325   gas_assert (operand_error_report.tail == NULL);
4326 }
4327
4328 /* Return TRUE if some operand error has been recorded during the
4329    parsing of the current assembly line using the opcode *OPCODE;
4330    otherwise return FALSE.  */
4331 static inline bfd_boolean
4332 opcode_has_operand_error_p (const aarch64_opcode *opcode)
4333 {
4334   operand_error_record *record = operand_error_report.head;
4335   return record && record->opcode == opcode;
4336 }
4337
4338 /* Add the error record *NEW_RECORD to operand_error_report.  The record's
4339    OPCODE field is initialized with OPCODE.
4340    N.B. only one record for each opcode, i.e. the maximum of one error is
4341    recorded for each instruction template.  */
4342
4343 static void
4344 add_operand_error_record (const operand_error_record* new_record)
4345 {
4346   const aarch64_opcode *opcode = new_record->opcode;
4347   operand_error_record* record = operand_error_report.head;
4348
4349   /* The record may have been created for this opcode.  If not, we need
4350      to prepare one.  */
4351   if (! opcode_has_operand_error_p (opcode))
4352     {
4353       /* Get one empty record.  */
4354       if (free_opnd_error_record_nodes == NULL)
4355         {
4356           record = XNEW (operand_error_record);
4357         }
4358       else
4359         {
4360           record = free_opnd_error_record_nodes;
4361           free_opnd_error_record_nodes = record->next;
4362         }
4363       record->opcode = opcode;
4364       /* Insert at the head.  */
4365       record->next = operand_error_report.head;
4366       operand_error_report.head = record;
4367       if (operand_error_report.tail == NULL)
4368         operand_error_report.tail = record;
4369     }
4370   else if (record->detail.kind != AARCH64_OPDE_NIL
4371            && record->detail.index <= new_record->detail.index
4372            && operand_error_higher_severity_p (record->detail.kind,
4373                                                new_record->detail.kind))
4374     {
4375       /* In the case of multiple errors found on operands related with a
4376          single opcode, only record the error of the leftmost operand and
4377          only if the error is of higher severity.  */
4378       DEBUG_TRACE ("error %s on operand %d not added to the report due to"
4379                    " the existing error %s on operand %d",
4380                    operand_mismatch_kind_names[new_record->detail.kind],
4381                    new_record->detail.index,
4382                    operand_mismatch_kind_names[record->detail.kind],
4383                    record->detail.index);
4384       return;
4385     }
4386
4387   record->detail = new_record->detail;
4388 }
4389
4390 static inline void
4391 record_operand_error_info (const aarch64_opcode *opcode,
4392                            aarch64_operand_error *error_info)
4393 {
4394   operand_error_record record;
4395   record.opcode = opcode;
4396   record.detail = *error_info;
4397   add_operand_error_record (&record);
4398 }
4399
4400 /* Record an error of kind KIND and, if ERROR is not NULL, of the detailed
4401    error message *ERROR, for operand IDX (count from 0).  */
4402
4403 static void
4404 record_operand_error (const aarch64_opcode *opcode, int idx,
4405                       enum aarch64_operand_error_kind kind,
4406                       const char* error)
4407 {
4408   aarch64_operand_error info;
4409   memset(&info, 0, sizeof (info));
4410   info.index = idx;
4411   info.kind = kind;
4412   info.error = error;
4413   info.non_fatal = FALSE;
4414   record_operand_error_info (opcode, &info);
4415 }
4416
4417 static void
4418 record_operand_error_with_data (const aarch64_opcode *opcode, int idx,
4419                                 enum aarch64_operand_error_kind kind,
4420                                 const char* error, const int *extra_data)
4421 {
4422   aarch64_operand_error info;
4423   info.index = idx;
4424   info.kind = kind;
4425   info.error = error;
4426   info.data[0] = extra_data[0];
4427   info.data[1] = extra_data[1];
4428   info.data[2] = extra_data[2];
4429   info.non_fatal = FALSE;
4430   record_operand_error_info (opcode, &info);
4431 }
4432
4433 static void
4434 record_operand_out_of_range_error (const aarch64_opcode *opcode, int idx,
4435                                    const char* error, int lower_bound,
4436                                    int upper_bound)
4437 {
4438   int data[3] = {lower_bound, upper_bound, 0};
4439   record_operand_error_with_data (opcode, idx, AARCH64_OPDE_OUT_OF_RANGE,
4440                                   error, data);
4441 }
4442
4443 /* Remove the operand error record for *OPCODE.  */
4444 static void ATTRIBUTE_UNUSED
4445 remove_operand_error_record (const aarch64_opcode *opcode)
4446 {
4447   if (opcode_has_operand_error_p (opcode))
4448     {
4449       operand_error_record* record = operand_error_report.head;
4450       gas_assert (record != NULL && operand_error_report.tail != NULL);
4451       operand_error_report.head = record->next;
4452       record->next = free_opnd_error_record_nodes;
4453       free_opnd_error_record_nodes = record;
4454       if (operand_error_report.head == NULL)
4455         {
4456           gas_assert (operand_error_report.tail == record);
4457           operand_error_report.tail = NULL;
4458         }
4459     }
4460 }
4461
4462 /* Given the instruction in *INSTR, return the index of the best matched
4463    qualifier sequence in the list (an array) headed by QUALIFIERS_LIST.
4464
4465    Return -1 if there is no qualifier sequence; return the first match
4466    if there is multiple matches found.  */
4467
4468 static int
4469 find_best_match (const aarch64_inst *instr,
4470                  const aarch64_opnd_qualifier_seq_t *qualifiers_list)
4471 {
4472   int i, num_opnds, max_num_matched, idx;
4473
4474   num_opnds = aarch64_num_of_operands (instr->opcode);
4475   if (num_opnds == 0)
4476     {
4477       DEBUG_TRACE ("no operand");
4478       return -1;
4479     }
4480
4481   max_num_matched = 0;
4482   idx = 0;
4483
4484   /* For each pattern.  */
4485   for (i = 0; i < AARCH64_MAX_QLF_SEQ_NUM; ++i, ++qualifiers_list)
4486     {
4487       int j, num_matched;
4488       const aarch64_opnd_qualifier_t *qualifiers = *qualifiers_list;
4489
4490       /* Most opcodes has much fewer patterns in the list.  */
4491       if (empty_qualifier_sequence_p (qualifiers))
4492         {
4493           DEBUG_TRACE_IF (i == 0, "empty list of qualifier sequence");
4494           break;
4495         }
4496
4497       for (j = 0, num_matched = 0; j < num_opnds; ++j, ++qualifiers)
4498         if (*qualifiers == instr->operands[j].qualifier)
4499           ++num_matched;
4500
4501       if (num_matched > max_num_matched)
4502         {
4503           max_num_matched = num_matched;
4504           idx = i;
4505         }
4506     }
4507
4508   DEBUG_TRACE ("return with %d", idx);
4509   return idx;
4510 }
4511
4512 /* Assign qualifiers in the qualifier sequence (headed by QUALIFIERS) to the
4513    corresponding operands in *INSTR.  */
4514
4515 static inline void
4516 assign_qualifier_sequence (aarch64_inst *instr,
4517                            const aarch64_opnd_qualifier_t *qualifiers)
4518 {
4519   int i = 0;
4520   int num_opnds = aarch64_num_of_operands (instr->opcode);
4521   gas_assert (num_opnds);
4522   for (i = 0; i < num_opnds; ++i, ++qualifiers)
4523     instr->operands[i].qualifier = *qualifiers;
4524 }
4525
4526 /* Print operands for the diagnosis purpose.  */
4527
4528 static void
4529 print_operands (char *buf, const aarch64_opcode *opcode,
4530                 const aarch64_opnd_info *opnds)
4531 {
4532   int i;
4533
4534   for (i = 0; i < AARCH64_MAX_OPND_NUM; ++i)
4535     {
4536       char str[128];
4537
4538       /* We regard the opcode operand info more, however we also look into
4539          the inst->operands to support the disassembling of the optional
4540          operand.
4541          The two operand code should be the same in all cases, apart from
4542          when the operand can be optional.  */
4543       if (opcode->operands[i] == AARCH64_OPND_NIL
4544           || opnds[i].type == AARCH64_OPND_NIL)
4545         break;
4546
4547       /* Generate the operand string in STR.  */
4548       aarch64_print_operand (str, sizeof (str), 0, opcode, opnds, i, NULL, NULL,
4549                              NULL);
4550
4551       /* Delimiter.  */
4552       if (str[0] != '\0')
4553         strcat (buf, i == 0 ? " " : ", ");
4554
4555       /* Append the operand string.  */
4556       strcat (buf, str);
4557     }
4558 }
4559
4560 /* Send to stderr a string as information.  */
4561
4562 static void
4563 output_info (const char *format, ...)
4564 {
4565   const char *file;
4566   unsigned int line;
4567   va_list args;
4568
4569   file = as_where (&line);
4570   if (file)
4571     {
4572       if (line != 0)
4573         fprintf (stderr, "%s:%u: ", file, line);
4574       else
4575         fprintf (stderr, "%s: ", file);
4576     }
4577   fprintf (stderr, _("Info: "));
4578   va_start (args, format);
4579   vfprintf (stderr, format, args);
4580   va_end (args);
4581   (void) putc ('\n', stderr);
4582 }
4583
4584 /* Output one operand error record.  */
4585
4586 static void
4587 output_operand_error_record (const operand_error_record *record, char *str)
4588 {
4589   const aarch64_operand_error *detail = &record->detail;
4590   int idx = detail->index;
4591   const aarch64_opcode *opcode = record->opcode;
4592   enum aarch64_opnd opd_code = (idx >= 0 ? opcode->operands[idx]
4593                                 : AARCH64_OPND_NIL);
4594
4595   typedef void (*handler_t)(const char *format, ...);
4596   handler_t handler = detail->non_fatal ? as_warn : as_bad;
4597
4598   switch (detail->kind)
4599     {
4600     case AARCH64_OPDE_NIL:
4601       gas_assert (0);
4602       break;
4603     case AARCH64_OPDE_SYNTAX_ERROR:
4604     case AARCH64_OPDE_RECOVERABLE:
4605     case AARCH64_OPDE_FATAL_SYNTAX_ERROR:
4606     case AARCH64_OPDE_OTHER_ERROR:
4607       /* Use the prepared error message if there is, otherwise use the
4608          operand description string to describe the error.  */
4609       if (detail->error != NULL)
4610         {
4611           if (idx < 0)
4612             handler (_("%s -- `%s'"), detail->error, str);
4613           else
4614             handler (_("%s at operand %d -- `%s'"),
4615                      detail->error, idx + 1, str);
4616         }
4617       else
4618         {
4619           gas_assert (idx >= 0);
4620           handler (_("operand %d must be %s -- `%s'"), idx + 1,
4621                    aarch64_get_operand_desc (opd_code), str);
4622         }
4623       break;
4624
4625     case AARCH64_OPDE_INVALID_VARIANT:
4626       handler (_("operand mismatch -- `%s'"), str);
4627       if (verbose_error_p)
4628         {
4629           /* We will try to correct the erroneous instruction and also provide
4630              more information e.g. all other valid variants.
4631
4632              The string representation of the corrected instruction and other
4633              valid variants are generated by
4634
4635              1) obtaining the intermediate representation of the erroneous
4636              instruction;
4637              2) manipulating the IR, e.g. replacing the operand qualifier;
4638              3) printing out the instruction by calling the printer functions
4639              shared with the disassembler.
4640
4641              The limitation of this method is that the exact input assembly
4642              line cannot be accurately reproduced in some cases, for example an
4643              optional operand present in the actual assembly line will be
4644              omitted in the output; likewise for the optional syntax rules,
4645              e.g. the # before the immediate.  Another limitation is that the
4646              assembly symbols and relocation operations in the assembly line
4647              currently cannot be printed out in the error report.  Last but not
4648              least, when there is other error(s) co-exist with this error, the
4649              'corrected' instruction may be still incorrect, e.g.  given
4650                'ldnp h0,h1,[x0,#6]!'
4651              this diagnosis will provide the version:
4652                'ldnp s0,s1,[x0,#6]!'
4653              which is still not right.  */
4654           size_t len = strlen (get_mnemonic_name (str));
4655           int i, qlf_idx;
4656           bfd_boolean result;
4657           char buf[2048];
4658           aarch64_inst *inst_base = &inst.base;
4659           const aarch64_opnd_qualifier_seq_t *qualifiers_list;
4660
4661           /* Init inst.  */
4662           reset_aarch64_instruction (&inst);
4663           inst_base->opcode = opcode;
4664
4665           /* Reset the error report so that there is no side effect on the
4666              following operand parsing.  */
4667           init_operand_error_report ();
4668
4669           /* Fill inst.  */
4670           result = parse_operands (str + len, opcode)
4671             && programmer_friendly_fixup (&inst);
4672           gas_assert (result);
4673           result = aarch64_opcode_encode (opcode, inst_base, &inst_base->value,
4674                                           NULL, NULL, insn_sequence);
4675           gas_assert (!result);
4676
4677           /* Find the most matched qualifier sequence.  */
4678           qlf_idx = find_best_match (inst_base, opcode->qualifiers_list);
4679           gas_assert (qlf_idx > -1);
4680
4681           /* Assign the qualifiers.  */
4682           assign_qualifier_sequence (inst_base,
4683                                      opcode->qualifiers_list[qlf_idx]);
4684
4685           /* Print the hint.  */
4686           output_info (_("   did you mean this?"));
4687           snprintf (buf, sizeof (buf), "\t%s", get_mnemonic_name (str));
4688           print_operands (buf, opcode, inst_base->operands);
4689           output_info (_("   %s"), buf);
4690
4691           /* Print out other variant(s) if there is any.  */
4692           if (qlf_idx != 0 ||
4693               !empty_qualifier_sequence_p (opcode->qualifiers_list[1]))
4694             output_info (_("   other valid variant(s):"));
4695
4696           /* For each pattern.  */
4697           qualifiers_list = opcode->qualifiers_list;
4698           for (i = 0; i < AARCH64_MAX_QLF_SEQ_NUM; ++i, ++qualifiers_list)
4699             {
4700               /* Most opcodes has much fewer patterns in the list.
4701                  First NIL qualifier indicates the end in the list.   */
4702               if (empty_qualifier_sequence_p (*qualifiers_list))
4703                 break;
4704
4705               if (i != qlf_idx)
4706                 {
4707                   /* Mnemonics name.  */
4708                   snprintf (buf, sizeof (buf), "\t%s", get_mnemonic_name (str));
4709
4710                   /* Assign the qualifiers.  */
4711                   assign_qualifier_sequence (inst_base, *qualifiers_list);
4712
4713                   /* Print instruction.  */
4714                   print_operands (buf, opcode, inst_base->operands);
4715
4716                   output_info (_("   %s"), buf);
4717                 }
4718             }
4719         }
4720       break;
4721
4722     case AARCH64_OPDE_UNTIED_OPERAND:
4723       handler (_("operand %d must be the same register as operand 1 -- `%s'"),
4724                detail->index + 1, str);
4725       break;
4726
4727     case AARCH64_OPDE_OUT_OF_RANGE:
4728       if (detail->data[0] != detail->data[1])
4729         handler (_("%s out of range %d to %d at operand %d -- `%s'"),
4730                  detail->error ? detail->error : _("immediate value"),
4731                  detail->data[0], detail->data[1], idx + 1, str);
4732       else
4733         handler (_("%s must be %d at operand %d -- `%s'"),
4734                  detail->error ? detail->error : _("immediate value"),
4735                  detail->data[0], idx + 1, str);
4736       break;
4737
4738     case AARCH64_OPDE_REG_LIST:
4739       if (detail->data[0] == 1)
4740         handler (_("invalid number of registers in the list; "
4741                    "only 1 register is expected at operand %d -- `%s'"),
4742                  idx + 1, str);
4743       else
4744         handler (_("invalid number of registers in the list; "
4745                    "%d registers are expected at operand %d -- `%s'"),
4746                detail->data[0], idx + 1, str);
4747       break;
4748
4749     case AARCH64_OPDE_UNALIGNED:
4750       handler (_("immediate value must be a multiple of "
4751                  "%d at operand %d -- `%s'"),
4752                detail->data[0], idx + 1, str);
4753       break;
4754
4755     default:
4756       gas_assert (0);
4757       break;
4758     }
4759 }
4760
4761 /* Process and output the error message about the operand mismatching.
4762
4763    When this function is called, the operand error information had
4764    been collected for an assembly line and there will be multiple
4765    errors in the case of multiple instruction templates; output the
4766    error message that most closely describes the problem.
4767
4768    The errors to be printed can be filtered on printing all errors
4769    or only non-fatal errors.  This distinction has to be made because
4770    the error buffer may already be filled with fatal errors we don't want to
4771    print due to the different instruction templates.  */
4772
4773 static void
4774 output_operand_error_report (char *str, bfd_boolean non_fatal_only)
4775 {
4776   int largest_error_pos;
4777   const char *msg = NULL;
4778   enum aarch64_operand_error_kind kind;
4779   operand_error_record *curr;
4780   operand_error_record *head = operand_error_report.head;
4781   operand_error_record *record = NULL;
4782
4783   /* No error to report.  */
4784   if (head == NULL)
4785     return;
4786
4787   gas_assert (head != NULL && operand_error_report.tail != NULL);
4788
4789   /* Only one error.  */
4790   if (head == operand_error_report.tail)
4791     {
4792       /* If the only error is a non-fatal one and we don't want to print it,
4793          just exit.  */
4794       if (!non_fatal_only || head->detail.non_fatal)
4795         {
4796           DEBUG_TRACE ("single opcode entry with error kind: %s",
4797                        operand_mismatch_kind_names[head->detail.kind]);
4798           output_operand_error_record (head, str);
4799         }
4800       return;
4801     }
4802
4803   /* Find the error kind of the highest severity.  */
4804   DEBUG_TRACE ("multiple opcode entries with error kind");
4805   kind = AARCH64_OPDE_NIL;
4806   for (curr = head; curr != NULL; curr = curr->next)
4807     {
4808       gas_assert (curr->detail.kind != AARCH64_OPDE_NIL);
4809       DEBUG_TRACE ("\t%s", operand_mismatch_kind_names[curr->detail.kind]);
4810       if (operand_error_higher_severity_p (curr->detail.kind, kind))
4811         kind = curr->detail.kind;
4812     }
4813   gas_assert (kind != AARCH64_OPDE_NIL);
4814
4815   /* Pick up one of errors of KIND to report.  */
4816   largest_error_pos = -2; /* Index can be -1 which means unknown index.  */
4817   for (curr = head; curr != NULL; curr = curr->next)
4818     {
4819       /* If we don't want to print non-fatal errors then don't consider them
4820          at all.  */
4821       if (curr->detail.kind != kind
4822           || (non_fatal_only && !curr->detail.non_fatal))
4823         continue;
4824       /* If there are multiple errors, pick up the one with the highest
4825          mismatching operand index.  In the case of multiple errors with
4826          the equally highest operand index, pick up the first one or the
4827          first one with non-NULL error message.  */
4828       if (curr->detail.index > largest_error_pos
4829           || (curr->detail.index == largest_error_pos && msg == NULL
4830               && curr->detail.error != NULL))
4831         {
4832           largest_error_pos = curr->detail.index;
4833           record = curr;
4834           msg = record->detail.error;
4835         }
4836     }
4837
4838   /* The way errors are collected in the back-end is a bit non-intuitive.  But
4839      essentially, because each operand template is tried recursively you may
4840      always have errors collected from the previous tried OPND.  These are
4841      usually skipped if there is one successful match.  However now with the
4842      non-fatal errors we have to ignore those previously collected hard errors
4843      when we're only interested in printing the non-fatal ones.  This condition
4844      prevents us from printing errors that are not appropriate, since we did
4845      match a condition, but it also has warnings that it wants to print.  */
4846   if (non_fatal_only && !record)
4847     return;
4848
4849   gas_assert (largest_error_pos != -2 && record != NULL);
4850   DEBUG_TRACE ("Pick up error kind %s to report",
4851                operand_mismatch_kind_names[record->detail.kind]);
4852
4853   /* Output.  */
4854   output_operand_error_record (record, str);
4855 }
4856 \f
4857 /* Write an AARCH64 instruction to buf - always little-endian.  */
4858 static void
4859 put_aarch64_insn (char *buf, uint32_t insn)
4860 {
4861   unsigned char *where = (unsigned char *) buf;
4862   where[0] = insn;
4863   where[1] = insn >> 8;
4864   where[2] = insn >> 16;
4865   where[3] = insn >> 24;
4866 }
4867
4868 static uint32_t
4869 get_aarch64_insn (char *buf)
4870 {
4871   unsigned char *where = (unsigned char *) buf;
4872   uint32_t result;
4873   result = (where[0] | (where[1] << 8) | (where[2] << 16) | (where[3] << 24));
4874   return result;
4875 }
4876
4877 static void
4878 output_inst (struct aarch64_inst *new_inst)
4879 {
4880   char *to = NULL;
4881
4882   to = frag_more (INSN_SIZE);
4883
4884   frag_now->tc_frag_data.recorded = 1;
4885
4886   put_aarch64_insn (to, inst.base.value);
4887
4888   if (inst.reloc.type != BFD_RELOC_UNUSED)
4889     {
4890       fixS *fixp = fix_new_aarch64 (frag_now, to - frag_now->fr_literal,
4891                                     INSN_SIZE, &inst.reloc.exp,
4892                                     inst.reloc.pc_rel,
4893                                     inst.reloc.type);
4894       DEBUG_TRACE ("Prepared relocation fix up");
4895       /* Don't check the addend value against the instruction size,
4896          that's the job of our code in md_apply_fix(). */
4897       fixp->fx_no_overflow = 1;
4898       if (new_inst != NULL)
4899         fixp->tc_fix_data.inst = new_inst;
4900       if (aarch64_gas_internal_fixup_p ())
4901         {
4902           gas_assert (inst.reloc.opnd != AARCH64_OPND_NIL);
4903           fixp->tc_fix_data.opnd = inst.reloc.opnd;
4904           fixp->fx_addnumber = inst.reloc.flags;
4905         }
4906     }
4907
4908   dwarf2_emit_insn (INSN_SIZE);
4909 }
4910
4911 /* Link together opcodes of the same name.  */
4912
4913 struct templates
4914 {
4915   aarch64_opcode *opcode;
4916   struct templates *next;
4917 };
4918
4919 typedef struct templates templates;
4920
4921 static templates *
4922 lookup_mnemonic (const char *start, int len)
4923 {
4924   templates *templ = NULL;
4925
4926   templ = hash_find_n (aarch64_ops_hsh, start, len);
4927   return templ;
4928 }
4929
4930 /* Subroutine of md_assemble, responsible for looking up the primary
4931    opcode from the mnemonic the user wrote.  STR points to the
4932    beginning of the mnemonic. */
4933
4934 static templates *
4935 opcode_lookup (char **str)
4936 {
4937   char *end, *base, *dot;
4938   const aarch64_cond *cond;
4939   char condname[16];
4940   int len;
4941
4942   /* Scan up to the end of the mnemonic, which must end in white space,
4943      '.', or end of string.  */
4944   dot = 0;
4945   for (base = end = *str; is_part_of_name(*end); end++)
4946     if (*end == '.' && !dot)
4947       dot = end;
4948
4949   if (end == base || dot == base)
4950     return 0;
4951
4952   inst.cond = COND_ALWAYS;
4953
4954   /* Handle a possible condition.  */
4955   if (dot)
4956     {
4957       cond = hash_find_n (aarch64_cond_hsh, dot + 1, end - dot - 1);
4958       if (cond)
4959         {
4960           inst.cond = cond->value;
4961           *str = end;
4962         }
4963       else
4964         {
4965           *str = dot;
4966           return 0;
4967         }
4968       len = dot - base;
4969     }
4970   else
4971     {
4972       *str = end;
4973       len = end - base;
4974     }
4975
4976   if (inst.cond == COND_ALWAYS)
4977     {
4978       /* Look for unaffixed mnemonic.  */
4979       return lookup_mnemonic (base, len);
4980     }
4981   else if (len <= 13)
4982     {
4983       /* append ".c" to mnemonic if conditional */
4984       memcpy (condname, base, len);
4985       memcpy (condname + len, ".c", 2);
4986       base = condname;
4987       len += 2;
4988       return lookup_mnemonic (base, len);
4989     }
4990
4991   return NULL;
4992 }
4993
4994 /* Internal helper routine converting a vector_type_el structure *VECTYPE
4995    to a corresponding operand qualifier.  */
4996
4997 static inline aarch64_opnd_qualifier_t
4998 vectype_to_qualifier (const struct vector_type_el *vectype)
4999 {
5000   /* Element size in bytes indexed by vector_el_type.  */
5001   const unsigned char ele_size[5]
5002     = {1, 2, 4, 8, 16};
5003   const unsigned int ele_base [5] =
5004     {
5005       AARCH64_OPND_QLF_V_4B,
5006       AARCH64_OPND_QLF_V_2H,
5007       AARCH64_OPND_QLF_V_2S,
5008       AARCH64_OPND_QLF_V_1D,
5009       AARCH64_OPND_QLF_V_1Q
5010   };
5011
5012   if (!vectype->defined || vectype->type == NT_invtype)
5013     goto vectype_conversion_fail;
5014
5015   if (vectype->type == NT_zero)
5016     return AARCH64_OPND_QLF_P_Z;
5017   if (vectype->type == NT_merge)
5018     return AARCH64_OPND_QLF_P_M;
5019
5020   gas_assert (vectype->type >= NT_b && vectype->type <= NT_q);
5021
5022   if (vectype->defined & (NTA_HASINDEX | NTA_HASVARWIDTH))
5023     {
5024       /* Special case S_4B.  */
5025       if (vectype->type == NT_b && vectype->width == 4)
5026         return AARCH64_OPND_QLF_S_4B;
5027
5028       /* Vector element register.  */
5029       return AARCH64_OPND_QLF_S_B + vectype->type;
5030     }
5031   else
5032     {
5033       /* Vector register.  */
5034       int reg_size = ele_size[vectype->type] * vectype->width;
5035       unsigned offset;
5036       unsigned shift;
5037       if (reg_size != 16 && reg_size != 8 && reg_size != 4)
5038         goto vectype_conversion_fail;
5039
5040       /* The conversion is by calculating the offset from the base operand
5041          qualifier for the vector type.  The operand qualifiers are regular
5042          enough that the offset can established by shifting the vector width by
5043          a vector-type dependent amount.  */
5044       shift = 0;
5045       if (vectype->type == NT_b)
5046         shift = 3;
5047       else if (vectype->type == NT_h || vectype->type == NT_s)
5048         shift = 2;
5049       else if (vectype->type >= NT_d)
5050         shift = 1;
5051       else
5052         gas_assert (0);
5053
5054       offset = ele_base [vectype->type] + (vectype->width >> shift);
5055       gas_assert (AARCH64_OPND_QLF_V_4B <= offset
5056                   && offset <= AARCH64_OPND_QLF_V_1Q);
5057       return offset;
5058     }
5059
5060 vectype_conversion_fail:
5061   first_error (_("bad vector arrangement type"));
5062   return AARCH64_OPND_QLF_NIL;
5063 }
5064
5065 /* Process an optional operand that is found omitted from the assembly line.
5066    Fill *OPERAND for such an operand of type TYPE.  OPCODE points to the
5067    instruction's opcode entry while IDX is the index of this omitted operand.
5068    */
5069
5070 static void
5071 process_omitted_operand (enum aarch64_opnd type, const aarch64_opcode *opcode,
5072                          int idx, aarch64_opnd_info *operand)
5073 {
5074   aarch64_insn default_value = get_optional_operand_default_value (opcode);
5075   gas_assert (optional_operand_p (opcode, idx));
5076   gas_assert (!operand->present);
5077
5078   switch (type)
5079     {
5080     case AARCH64_OPND_Rd:
5081     case AARCH64_OPND_Rn:
5082     case AARCH64_OPND_Rm:
5083     case AARCH64_OPND_Rt:
5084     case AARCH64_OPND_Rt2:
5085     case AARCH64_OPND_Rs:
5086     case AARCH64_OPND_Ra:
5087     case AARCH64_OPND_Rt_SYS:
5088     case AARCH64_OPND_Rd_SP:
5089     case AARCH64_OPND_Rn_SP:
5090     case AARCH64_OPND_Rm_SP:
5091     case AARCH64_OPND_Fd:
5092     case AARCH64_OPND_Fn:
5093     case AARCH64_OPND_Fm:
5094     case AARCH64_OPND_Fa:
5095     case AARCH64_OPND_Ft:
5096     case AARCH64_OPND_Ft2:
5097     case AARCH64_OPND_Sd:
5098     case AARCH64_OPND_Sn:
5099     case AARCH64_OPND_Sm:
5100     case AARCH64_OPND_Va:
5101     case AARCH64_OPND_Vd:
5102     case AARCH64_OPND_Vn:
5103     case AARCH64_OPND_Vm:
5104     case AARCH64_OPND_VdD1:
5105     case AARCH64_OPND_VnD1:
5106       operand->reg.regno = default_value;
5107       break;
5108
5109     case AARCH64_OPND_Ed:
5110     case AARCH64_OPND_En:
5111     case AARCH64_OPND_Em:
5112     case AARCH64_OPND_Em16:
5113     case AARCH64_OPND_SM3_IMM2:
5114       operand->reglane.regno = default_value;
5115       break;
5116
5117     case AARCH64_OPND_IDX:
5118     case AARCH64_OPND_BIT_NUM:
5119     case AARCH64_OPND_IMMR:
5120     case AARCH64_OPND_IMMS:
5121     case AARCH64_OPND_SHLL_IMM:
5122     case AARCH64_OPND_IMM_VLSL:
5123     case AARCH64_OPND_IMM_VLSR:
5124     case AARCH64_OPND_CCMP_IMM:
5125     case AARCH64_OPND_FBITS:
5126     case AARCH64_OPND_UIMM4:
5127     case AARCH64_OPND_UIMM3_OP1:
5128     case AARCH64_OPND_UIMM3_OP2:
5129     case AARCH64_OPND_IMM:
5130     case AARCH64_OPND_IMM_2:
5131     case AARCH64_OPND_WIDTH:
5132     case AARCH64_OPND_UIMM7:
5133     case AARCH64_OPND_NZCV:
5134     case AARCH64_OPND_SVE_PATTERN:
5135     case AARCH64_OPND_SVE_PRFOP:
5136       operand->imm.value = default_value;
5137       break;
5138
5139     case AARCH64_OPND_SVE_PATTERN_SCALED:
5140       operand->imm.value = default_value;
5141       operand->shifter.kind = AARCH64_MOD_MUL;
5142       operand->shifter.amount = 1;
5143       break;
5144
5145     case AARCH64_OPND_EXCEPTION:
5146       inst.reloc.type = BFD_RELOC_UNUSED;
5147       break;
5148
5149     case AARCH64_OPND_BARRIER_ISB:
5150       operand->barrier = aarch64_barrier_options + default_value;
5151
5152     default:
5153       break;
5154     }
5155 }
5156
5157 /* Process the relocation type for move wide instructions.
5158    Return TRUE on success; otherwise return FALSE.  */
5159
5160 static bfd_boolean
5161 process_movw_reloc_info (void)
5162 {
5163   int is32;
5164   unsigned shift;
5165
5166   is32 = inst.base.operands[0].qualifier == AARCH64_OPND_QLF_W ? 1 : 0;
5167
5168   if (inst.base.opcode->op == OP_MOVK)
5169     switch (inst.reloc.type)
5170       {
5171       case BFD_RELOC_AARCH64_MOVW_G0_S:
5172       case BFD_RELOC_AARCH64_MOVW_G1_S:
5173       case BFD_RELOC_AARCH64_MOVW_G2_S:
5174       case BFD_RELOC_AARCH64_MOVW_PREL_G0:
5175       case BFD_RELOC_AARCH64_MOVW_PREL_G1:
5176       case BFD_RELOC_AARCH64_MOVW_PREL_G2:
5177       case BFD_RELOC_AARCH64_MOVW_PREL_G3:
5178       case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
5179       case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
5180       case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
5181       case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
5182         set_syntax_error
5183           (_("the specified relocation type is not allowed for MOVK"));
5184         return FALSE;
5185       default:
5186         break;
5187       }
5188
5189   switch (inst.reloc.type)
5190     {
5191     case BFD_RELOC_AARCH64_MOVW_G0:
5192     case BFD_RELOC_AARCH64_MOVW_G0_NC:
5193     case BFD_RELOC_AARCH64_MOVW_G0_S:
5194     case BFD_RELOC_AARCH64_MOVW_GOTOFF_G0_NC:
5195     case BFD_RELOC_AARCH64_MOVW_PREL_G0:
5196     case BFD_RELOC_AARCH64_MOVW_PREL_G0_NC:
5197     case BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC:
5198     case BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC:
5199     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC:
5200     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0:
5201     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
5202     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
5203     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
5204       shift = 0;
5205       break;
5206     case BFD_RELOC_AARCH64_MOVW_G1:
5207     case BFD_RELOC_AARCH64_MOVW_G1_NC:
5208     case BFD_RELOC_AARCH64_MOVW_G1_S:
5209     case BFD_RELOC_AARCH64_MOVW_GOTOFF_G1:
5210     case BFD_RELOC_AARCH64_MOVW_PREL_G1:
5211     case BFD_RELOC_AARCH64_MOVW_PREL_G1_NC:
5212     case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
5213     case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
5214     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1:
5215     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1:
5216     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC:
5217     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
5218     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
5219       shift = 16;
5220       break;
5221     case BFD_RELOC_AARCH64_MOVW_G2:
5222     case BFD_RELOC_AARCH64_MOVW_G2_NC:
5223     case BFD_RELOC_AARCH64_MOVW_G2_S:
5224     case BFD_RELOC_AARCH64_MOVW_PREL_G2:
5225     case BFD_RELOC_AARCH64_MOVW_PREL_G2_NC:
5226     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2:
5227     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
5228       if (is32)
5229         {
5230           set_fatal_syntax_error
5231             (_("the specified relocation type is not allowed for 32-bit "
5232                "register"));
5233           return FALSE;
5234         }
5235       shift = 32;
5236       break;
5237     case BFD_RELOC_AARCH64_MOVW_G3:
5238     case BFD_RELOC_AARCH64_MOVW_PREL_G3:
5239       if (is32)
5240         {
5241           set_fatal_syntax_error
5242             (_("the specified relocation type is not allowed for 32-bit "
5243                "register"));
5244           return FALSE;
5245         }
5246       shift = 48;
5247       break;
5248     default:
5249       /* More cases should be added when more MOVW-related relocation types
5250          are supported in GAS.  */
5251       gas_assert (aarch64_gas_internal_fixup_p ());
5252       /* The shift amount should have already been set by the parser.  */
5253       return TRUE;
5254     }
5255   inst.base.operands[1].shifter.amount = shift;
5256   return TRUE;
5257 }
5258
5259 /* A primitive log calculator.  */
5260
5261 static inline unsigned int
5262 get_logsz (unsigned int size)
5263 {
5264   const unsigned char ls[16] =
5265     {0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, 4};
5266   if (size > 16)
5267     {
5268       gas_assert (0);
5269       return -1;
5270     }
5271   gas_assert (ls[size - 1] != (unsigned char)-1);
5272   return ls[size - 1];
5273 }
5274
5275 /* Determine and return the real reloc type code for an instruction
5276    with the pseudo reloc type code BFD_RELOC_AARCH64_LDST_LO12.  */
5277
5278 static inline bfd_reloc_code_real_type
5279 ldst_lo12_determine_real_reloc_type (void)
5280 {
5281   unsigned logsz;
5282   enum aarch64_opnd_qualifier opd0_qlf = inst.base.operands[0].qualifier;
5283   enum aarch64_opnd_qualifier opd1_qlf = inst.base.operands[1].qualifier;
5284
5285   const bfd_reloc_code_real_type reloc_ldst_lo12[5][5] = {
5286     {
5287       BFD_RELOC_AARCH64_LDST8_LO12,
5288       BFD_RELOC_AARCH64_LDST16_LO12,
5289       BFD_RELOC_AARCH64_LDST32_LO12,
5290       BFD_RELOC_AARCH64_LDST64_LO12,
5291       BFD_RELOC_AARCH64_LDST128_LO12
5292     },
5293     {
5294       BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12,
5295       BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12,
5296       BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12,
5297       BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12,
5298       BFD_RELOC_AARCH64_NONE
5299     },
5300     {
5301       BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC,
5302       BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC,
5303       BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC,
5304       BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC,
5305       BFD_RELOC_AARCH64_NONE
5306     },
5307     {
5308       BFD_RELOC_AARCH64_TLSLE_LDST8_TPREL_LO12,
5309       BFD_RELOC_AARCH64_TLSLE_LDST16_TPREL_LO12,
5310       BFD_RELOC_AARCH64_TLSLE_LDST32_TPREL_LO12,
5311       BFD_RELOC_AARCH64_TLSLE_LDST64_TPREL_LO12,
5312       BFD_RELOC_AARCH64_NONE
5313     },
5314     {
5315       BFD_RELOC_AARCH64_TLSLE_LDST8_TPREL_LO12_NC,
5316       BFD_RELOC_AARCH64_TLSLE_LDST16_TPREL_LO12_NC,
5317       BFD_RELOC_AARCH64_TLSLE_LDST32_TPREL_LO12_NC,
5318       BFD_RELOC_AARCH64_TLSLE_LDST64_TPREL_LO12_NC,
5319       BFD_RELOC_AARCH64_NONE
5320     }
5321   };
5322
5323   gas_assert (inst.reloc.type == BFD_RELOC_AARCH64_LDST_LO12
5324               || inst.reloc.type == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12
5325               || (inst.reloc.type
5326                   == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC)
5327               || (inst.reloc.type
5328                   == BFD_RELOC_AARCH64_TLSLE_LDST_TPREL_LO12)
5329               || (inst.reloc.type
5330                   == BFD_RELOC_AARCH64_TLSLE_LDST_TPREL_LO12_NC));
5331   gas_assert (inst.base.opcode->operands[1] == AARCH64_OPND_ADDR_UIMM12);
5332
5333   if (opd1_qlf == AARCH64_OPND_QLF_NIL)
5334     opd1_qlf =
5335       aarch64_get_expected_qualifier (inst.base.opcode->qualifiers_list,
5336                                       1, opd0_qlf, 0);
5337   gas_assert (opd1_qlf != AARCH64_OPND_QLF_NIL);
5338
5339   logsz = get_logsz (aarch64_get_qualifier_esize (opd1_qlf));
5340   if (inst.reloc.type == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12
5341       || inst.reloc.type == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC
5342       || inst.reloc.type == BFD_RELOC_AARCH64_TLSLE_LDST_TPREL_LO12
5343       || inst.reloc.type == BFD_RELOC_AARCH64_TLSLE_LDST_TPREL_LO12_NC)
5344     gas_assert (logsz <= 3);
5345   else
5346     gas_assert (logsz <= 4);
5347
5348   /* In reloc.c, these pseudo relocation types should be defined in similar
5349      order as above reloc_ldst_lo12 array. Because the array index calculation
5350      below relies on this.  */
5351   return reloc_ldst_lo12[inst.reloc.type - BFD_RELOC_AARCH64_LDST_LO12][logsz];
5352 }
5353
5354 /* Check whether a register list REGINFO is valid.  The registers must be
5355    numbered in increasing order (modulo 32), in increments of one or two.
5356
5357    If ACCEPT_ALTERNATE is non-zero, the register numbers should be in
5358    increments of two.
5359
5360    Return FALSE if such a register list is invalid, otherwise return TRUE.  */
5361
5362 static bfd_boolean
5363 reg_list_valid_p (uint32_t reginfo, int accept_alternate)
5364 {
5365   uint32_t i, nb_regs, prev_regno, incr;
5366
5367   nb_regs = 1 + (reginfo & 0x3);
5368   reginfo >>= 2;
5369   prev_regno = reginfo & 0x1f;
5370   incr = accept_alternate ? 2 : 1;
5371
5372   for (i = 1; i < nb_regs; ++i)
5373     {
5374       uint32_t curr_regno;
5375       reginfo >>= 5;
5376       curr_regno = reginfo & 0x1f;
5377       if (curr_regno != ((prev_regno + incr) & 0x1f))
5378         return FALSE;
5379       prev_regno = curr_regno;
5380     }
5381
5382   return TRUE;
5383 }
5384
5385 /* Generic instruction operand parser.  This does no encoding and no
5386    semantic validation; it merely squirrels values away in the inst
5387    structure.  Returns TRUE or FALSE depending on whether the
5388    specified grammar matched.  */
5389
5390 static bfd_boolean
5391 parse_operands (char *str, const aarch64_opcode *opcode)
5392 {
5393   int i;
5394   char *backtrack_pos = 0;
5395   const enum aarch64_opnd *operands = opcode->operands;
5396   aarch64_reg_type imm_reg_type;
5397
5398   clear_error ();
5399   skip_whitespace (str);
5400
5401   if (AARCH64_CPU_HAS_FEATURE (AARCH64_FEATURE_SVE, *opcode->avariant))
5402     imm_reg_type = REG_TYPE_R_Z_SP_BHSDQ_VZP;
5403   else
5404     imm_reg_type = REG_TYPE_R_Z_BHSDQ_V;
5405
5406   for (i = 0; operands[i] != AARCH64_OPND_NIL; i++)
5407     {
5408       int64_t val;
5409       const reg_entry *reg;
5410       int comma_skipped_p = 0;
5411       aarch64_reg_type rtype;
5412       struct vector_type_el vectype;
5413       aarch64_opnd_qualifier_t qualifier, base_qualifier, offset_qualifier;
5414       aarch64_opnd_info *info = &inst.base.operands[i];
5415       aarch64_reg_type reg_type;
5416
5417       DEBUG_TRACE ("parse operand %d", i);
5418
5419       /* Assign the operand code.  */
5420       info->type = operands[i];
5421
5422       if (optional_operand_p (opcode, i))
5423         {
5424           /* Remember where we are in case we need to backtrack.  */
5425           gas_assert (!backtrack_pos);
5426           backtrack_pos = str;
5427         }
5428
5429       /* Expect comma between operands; the backtrack mechanism will take
5430          care of cases of omitted optional operand.  */
5431       if (i > 0 && ! skip_past_char (&str, ','))
5432         {
5433           set_syntax_error (_("comma expected between operands"));
5434           goto failure;
5435         }
5436       else
5437         comma_skipped_p = 1;
5438
5439       switch (operands[i])
5440         {
5441         case AARCH64_OPND_Rd:
5442         case AARCH64_OPND_Rn:
5443         case AARCH64_OPND_Rm:
5444         case AARCH64_OPND_Rt:
5445         case AARCH64_OPND_Rt2:
5446         case AARCH64_OPND_Rs:
5447         case AARCH64_OPND_Ra:
5448         case AARCH64_OPND_Rt_SYS:
5449         case AARCH64_OPND_PAIRREG:
5450         case AARCH64_OPND_SVE_Rm:
5451           po_int_reg_or_fail (REG_TYPE_R_Z);
5452           break;
5453
5454         case AARCH64_OPND_Rd_SP:
5455         case AARCH64_OPND_Rn_SP:
5456         case AARCH64_OPND_SVE_Rn_SP:
5457         case AARCH64_OPND_Rm_SP:
5458           po_int_reg_or_fail (REG_TYPE_R_SP);
5459           break;
5460
5461         case AARCH64_OPND_Rm_EXT:
5462         case AARCH64_OPND_Rm_SFT:
5463           po_misc_or_fail (parse_shifter_operand
5464                            (&str, info, (operands[i] == AARCH64_OPND_Rm_EXT
5465                                          ? SHIFTED_ARITH_IMM
5466                                          : SHIFTED_LOGIC_IMM)));
5467           if (!info->shifter.operator_present)
5468             {
5469               /* Default to LSL if not present.  Libopcodes prefers shifter
5470                  kind to be explicit.  */
5471               gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
5472               info->shifter.kind = AARCH64_MOD_LSL;
5473               /* For Rm_EXT, libopcodes will carry out further check on whether
5474                  or not stack pointer is used in the instruction (Recall that
5475                  "the extend operator is not optional unless at least one of
5476                  "Rd" or "Rn" is '11111' (i.e. WSP)").  */
5477             }
5478           break;
5479
5480         case AARCH64_OPND_Fd:
5481         case AARCH64_OPND_Fn:
5482         case AARCH64_OPND_Fm:
5483         case AARCH64_OPND_Fa:
5484         case AARCH64_OPND_Ft:
5485         case AARCH64_OPND_Ft2:
5486         case AARCH64_OPND_Sd:
5487         case AARCH64_OPND_Sn:
5488         case AARCH64_OPND_Sm:
5489         case AARCH64_OPND_SVE_VZn:
5490         case AARCH64_OPND_SVE_Vd:
5491         case AARCH64_OPND_SVE_Vm:
5492         case AARCH64_OPND_SVE_Vn:
5493           val = aarch64_reg_parse (&str, REG_TYPE_BHSDQ, &rtype, NULL);
5494           if (val == PARSE_FAIL)
5495             {
5496               first_error (_(get_reg_expected_msg (REG_TYPE_BHSDQ)));
5497               goto failure;
5498             }
5499           gas_assert (rtype >= REG_TYPE_FP_B && rtype <= REG_TYPE_FP_Q);
5500
5501           info->reg.regno = val;
5502           info->qualifier = AARCH64_OPND_QLF_S_B + (rtype - REG_TYPE_FP_B);
5503           break;
5504
5505         case AARCH64_OPND_SVE_Pd:
5506         case AARCH64_OPND_SVE_Pg3:
5507         case AARCH64_OPND_SVE_Pg4_5:
5508         case AARCH64_OPND_SVE_Pg4_10:
5509         case AARCH64_OPND_SVE_Pg4_16:
5510         case AARCH64_OPND_SVE_Pm:
5511         case AARCH64_OPND_SVE_Pn:
5512         case AARCH64_OPND_SVE_Pt:
5513           reg_type = REG_TYPE_PN;
5514           goto vector_reg;
5515
5516         case AARCH64_OPND_SVE_Za_5:
5517         case AARCH64_OPND_SVE_Za_16:
5518         case AARCH64_OPND_SVE_Zd:
5519         case AARCH64_OPND_SVE_Zm_5:
5520         case AARCH64_OPND_SVE_Zm_16:
5521         case AARCH64_OPND_SVE_Zn:
5522         case AARCH64_OPND_SVE_Zt:
5523           reg_type = REG_TYPE_ZN;
5524           goto vector_reg;
5525
5526         case AARCH64_OPND_Va:
5527         case AARCH64_OPND_Vd:
5528         case AARCH64_OPND_Vn:
5529         case AARCH64_OPND_Vm:
5530           reg_type = REG_TYPE_VN;
5531         vector_reg:
5532           val = aarch64_reg_parse (&str, reg_type, NULL, &vectype);
5533           if (val == PARSE_FAIL)
5534             {
5535               first_error (_(get_reg_expected_msg (reg_type)));
5536               goto failure;
5537             }
5538           if (vectype.defined & NTA_HASINDEX)
5539             goto failure;
5540
5541           info->reg.regno = val;
5542           if ((reg_type == REG_TYPE_PN || reg_type == REG_TYPE_ZN)
5543               && vectype.type == NT_invtype)
5544             /* Unqualified Pn and Zn registers are allowed in certain
5545                contexts.  Rely on F_STRICT qualifier checking to catch
5546                invalid uses.  */
5547             info->qualifier = AARCH64_OPND_QLF_NIL;
5548           else
5549             {
5550               info->qualifier = vectype_to_qualifier (&vectype);
5551               if (info->qualifier == AARCH64_OPND_QLF_NIL)
5552                 goto failure;
5553             }
5554           break;
5555
5556         case AARCH64_OPND_VdD1:
5557         case AARCH64_OPND_VnD1:
5558           val = aarch64_reg_parse (&str, REG_TYPE_VN, NULL, &vectype);
5559           if (val == PARSE_FAIL)
5560             {
5561               set_first_syntax_error (_(get_reg_expected_msg (REG_TYPE_VN)));
5562               goto failure;
5563             }
5564           if (vectype.type != NT_d || vectype.index != 1)
5565             {
5566               set_fatal_syntax_error
5567                 (_("the top half of a 128-bit FP/SIMD register is expected"));
5568               goto failure;
5569             }
5570           info->reg.regno = val;
5571           /* N.B: VdD1 and VnD1 are treated as an fp or advsimd scalar register
5572              here; it is correct for the purpose of encoding/decoding since
5573              only the register number is explicitly encoded in the related
5574              instructions, although this appears a bit hacky.  */
5575           info->qualifier = AARCH64_OPND_QLF_S_D;
5576           break;
5577
5578         case AARCH64_OPND_SVE_Zm3_INDEX:
5579         case AARCH64_OPND_SVE_Zm3_22_INDEX:
5580         case AARCH64_OPND_SVE_Zm4_INDEX:
5581         case AARCH64_OPND_SVE_Zn_INDEX:
5582           reg_type = REG_TYPE_ZN;
5583           goto vector_reg_index;
5584
5585         case AARCH64_OPND_Ed:
5586         case AARCH64_OPND_En:
5587         case AARCH64_OPND_Em:
5588         case AARCH64_OPND_Em16:
5589         case AARCH64_OPND_SM3_IMM2:
5590           reg_type = REG_TYPE_VN;
5591         vector_reg_index:
5592           val = aarch64_reg_parse (&str, reg_type, NULL, &vectype);
5593           if (val == PARSE_FAIL)
5594             {
5595               first_error (_(get_reg_expected_msg (reg_type)));
5596               goto failure;
5597             }
5598           if (vectype.type == NT_invtype || !(vectype.defined & NTA_HASINDEX))
5599             goto failure;
5600
5601           info->reglane.regno = val;
5602           info->reglane.index = vectype.index;
5603           info->qualifier = vectype_to_qualifier (&vectype);
5604           if (info->qualifier == AARCH64_OPND_QLF_NIL)
5605             goto failure;
5606           break;
5607
5608         case AARCH64_OPND_SVE_ZnxN:
5609         case AARCH64_OPND_SVE_ZtxN:
5610           reg_type = REG_TYPE_ZN;
5611           goto vector_reg_list;
5612
5613         case AARCH64_OPND_LVn:
5614         case AARCH64_OPND_LVt:
5615         case AARCH64_OPND_LVt_AL:
5616         case AARCH64_OPND_LEt:
5617           reg_type = REG_TYPE_VN;
5618         vector_reg_list:
5619           if (reg_type == REG_TYPE_ZN
5620               && get_opcode_dependent_value (opcode) == 1
5621               && *str != '{')
5622             {
5623               val = aarch64_reg_parse (&str, reg_type, NULL, &vectype);
5624               if (val == PARSE_FAIL)
5625                 {
5626                   first_error (_(get_reg_expected_msg (reg_type)));
5627                   goto failure;
5628                 }
5629               info->reglist.first_regno = val;
5630               info->reglist.num_regs = 1;
5631             }
5632           else
5633             {
5634               val = parse_vector_reg_list (&str, reg_type, &vectype);
5635               if (val == PARSE_FAIL)
5636                 goto failure;
5637               if (! reg_list_valid_p (val, /* accept_alternate */ 0))
5638                 {
5639                   set_fatal_syntax_error (_("invalid register list"));
5640                   goto failure;
5641                 }
5642               info->reglist.first_regno = (val >> 2) & 0x1f;
5643               info->reglist.num_regs = (val & 0x3) + 1;
5644             }
5645           if (operands[i] == AARCH64_OPND_LEt)
5646             {
5647               if (!(vectype.defined & NTA_HASINDEX))
5648                 goto failure;
5649               info->reglist.has_index = 1;
5650               info->reglist.index = vectype.index;
5651             }
5652           else
5653             {
5654               if (vectype.defined & NTA_HASINDEX)
5655                 goto failure;
5656               if (!(vectype.defined & NTA_HASTYPE))
5657                 {
5658                   if (reg_type == REG_TYPE_ZN)
5659                     set_fatal_syntax_error (_("missing type suffix"));
5660                   goto failure;
5661                 }
5662             }
5663           info->qualifier = vectype_to_qualifier (&vectype);
5664           if (info->qualifier == AARCH64_OPND_QLF_NIL)
5665             goto failure;
5666           break;
5667
5668         case AARCH64_OPND_CRn:
5669         case AARCH64_OPND_CRm:
5670             {
5671               char prefix = *(str++);
5672               if (prefix != 'c' && prefix != 'C')
5673                 goto failure;
5674
5675               po_imm_nc_or_fail ();
5676               if (val > 15)
5677                 {
5678                   set_fatal_syntax_error (_(N_ ("C0 - C15 expected")));
5679                   goto failure;
5680                 }
5681               info->qualifier = AARCH64_OPND_QLF_CR;
5682               info->imm.value = val;
5683               break;
5684             }
5685
5686         case AARCH64_OPND_SHLL_IMM:
5687         case AARCH64_OPND_IMM_VLSR:
5688           po_imm_or_fail (1, 64);
5689           info->imm.value = val;
5690           break;
5691
5692         case AARCH64_OPND_CCMP_IMM:
5693         case AARCH64_OPND_SIMM5:
5694         case AARCH64_OPND_FBITS:
5695         case AARCH64_OPND_UIMM4:
5696         case AARCH64_OPND_UIMM3_OP1:
5697         case AARCH64_OPND_UIMM3_OP2:
5698         case AARCH64_OPND_IMM_VLSL:
5699         case AARCH64_OPND_IMM:
5700         case AARCH64_OPND_IMM_2:
5701         case AARCH64_OPND_WIDTH:
5702         case AARCH64_OPND_SVE_INV_LIMM:
5703         case AARCH64_OPND_SVE_LIMM:
5704         case AARCH64_OPND_SVE_LIMM_MOV:
5705         case AARCH64_OPND_SVE_SHLIMM_PRED:
5706         case AARCH64_OPND_SVE_SHLIMM_UNPRED:
5707         case AARCH64_OPND_SVE_SHRIMM_PRED:
5708         case AARCH64_OPND_SVE_SHRIMM_UNPRED:
5709         case AARCH64_OPND_SVE_SIMM5:
5710         case AARCH64_OPND_SVE_SIMM5B:
5711         case AARCH64_OPND_SVE_SIMM6:
5712         case AARCH64_OPND_SVE_SIMM8:
5713         case AARCH64_OPND_SVE_UIMM3:
5714         case AARCH64_OPND_SVE_UIMM7:
5715         case AARCH64_OPND_SVE_UIMM8:
5716         case AARCH64_OPND_SVE_UIMM8_53:
5717         case AARCH64_OPND_IMM_ROT1:
5718         case AARCH64_OPND_IMM_ROT2:
5719         case AARCH64_OPND_IMM_ROT3:
5720         case AARCH64_OPND_SVE_IMM_ROT1:
5721         case AARCH64_OPND_SVE_IMM_ROT2:
5722           po_imm_nc_or_fail ();
5723           info->imm.value = val;
5724           break;
5725
5726         case AARCH64_OPND_SVE_AIMM:
5727         case AARCH64_OPND_SVE_ASIMM:
5728           po_imm_nc_or_fail ();
5729           info->imm.value = val;
5730           skip_whitespace (str);
5731           if (skip_past_comma (&str))
5732             po_misc_or_fail (parse_shift (&str, info, SHIFTED_LSL));
5733           else
5734             inst.base.operands[i].shifter.kind = AARCH64_MOD_LSL;
5735           break;
5736
5737         case AARCH64_OPND_SVE_PATTERN:
5738           po_enum_or_fail (aarch64_sve_pattern_array);
5739           info->imm.value = val;
5740           break;
5741
5742         case AARCH64_OPND_SVE_PATTERN_SCALED:
5743           po_enum_or_fail (aarch64_sve_pattern_array);
5744           info->imm.value = val;
5745           if (skip_past_comma (&str)
5746               && !parse_shift (&str, info, SHIFTED_MUL))
5747             goto failure;
5748           if (!info->shifter.operator_present)
5749             {
5750               gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
5751               info->shifter.kind = AARCH64_MOD_MUL;
5752               info->shifter.amount = 1;
5753             }
5754           break;
5755
5756         case AARCH64_OPND_SVE_PRFOP:
5757           po_enum_or_fail (aarch64_sve_prfop_array);
5758           info->imm.value = val;
5759           break;
5760
5761         case AARCH64_OPND_UIMM7:
5762           po_imm_or_fail (0, 127);
5763           info->imm.value = val;
5764           break;
5765
5766         case AARCH64_OPND_IDX:
5767         case AARCH64_OPND_MASK:
5768         case AARCH64_OPND_BIT_NUM:
5769         case AARCH64_OPND_IMMR:
5770         case AARCH64_OPND_IMMS:
5771           po_imm_or_fail (0, 63);
5772           info->imm.value = val;
5773           break;
5774
5775         case AARCH64_OPND_IMM0:
5776           po_imm_nc_or_fail ();
5777           if (val != 0)
5778             {
5779               set_fatal_syntax_error (_("immediate zero expected"));
5780               goto failure;
5781             }
5782           info->imm.value = 0;
5783           break;
5784
5785         case AARCH64_OPND_FPIMM0:
5786           {
5787             int qfloat;
5788             bfd_boolean res1 = FALSE, res2 = FALSE;
5789             /* N.B. -0.0 will be rejected; although -0.0 shouldn't be rejected,
5790                it is probably not worth the effort to support it.  */
5791             if (!(res1 = parse_aarch64_imm_float (&str, &qfloat, FALSE,
5792                                                   imm_reg_type))
5793                 && (error_p ()
5794                     || !(res2 = parse_constant_immediate (&str, &val,
5795                                                           imm_reg_type))))
5796               goto failure;
5797             if ((res1 && qfloat == 0) || (res2 && val == 0))
5798               {
5799                 info->imm.value = 0;
5800                 info->imm.is_fp = 1;
5801                 break;
5802               }
5803             set_fatal_syntax_error (_("immediate zero expected"));
5804             goto failure;
5805           }
5806
5807         case AARCH64_OPND_IMM_MOV:
5808           {
5809             char *saved = str;
5810             if (reg_name_p (str, REG_TYPE_R_Z_SP) ||
5811                 reg_name_p (str, REG_TYPE_VN))
5812               goto failure;
5813             str = saved;
5814             po_misc_or_fail (my_get_expression (&inst.reloc.exp, &str,
5815                                                 GE_OPT_PREFIX, 1));
5816             /* The MOV immediate alias will be fixed up by fix_mov_imm_insn
5817                later.  fix_mov_imm_insn will try to determine a machine
5818                instruction (MOVZ, MOVN or ORR) for it and will issue an error
5819                message if the immediate cannot be moved by a single
5820                instruction.  */
5821             aarch64_set_gas_internal_fixup (&inst.reloc, info, 1);
5822             inst.base.operands[i].skip = 1;
5823           }
5824           break;
5825
5826         case AARCH64_OPND_SIMD_IMM:
5827         case AARCH64_OPND_SIMD_IMM_SFT:
5828           if (! parse_big_immediate (&str, &val, imm_reg_type))
5829             goto failure;
5830           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
5831                                               /* addr_off_p */ 0,
5832                                               /* need_libopcodes_p */ 1,
5833                                               /* skip_p */ 1);
5834           /* Parse shift.
5835              N.B. although AARCH64_OPND_SIMD_IMM doesn't permit any
5836              shift, we don't check it here; we leave the checking to
5837              the libopcodes (operand_general_constraint_met_p).  By
5838              doing this, we achieve better diagnostics.  */
5839           if (skip_past_comma (&str)
5840               && ! parse_shift (&str, info, SHIFTED_LSL_MSL))
5841             goto failure;
5842           if (!info->shifter.operator_present
5843               && info->type == AARCH64_OPND_SIMD_IMM_SFT)
5844             {
5845               /* Default to LSL if not present.  Libopcodes prefers shifter
5846                  kind to be explicit.  */
5847               gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
5848               info->shifter.kind = AARCH64_MOD_LSL;
5849             }
5850           break;
5851
5852         case AARCH64_OPND_FPIMM:
5853         case AARCH64_OPND_SIMD_FPIMM:
5854         case AARCH64_OPND_SVE_FPIMM8:
5855           {
5856             int qfloat;
5857             bfd_boolean dp_p;
5858
5859             dp_p = double_precision_operand_p (&inst.base.operands[0]);
5860             if (!parse_aarch64_imm_float (&str, &qfloat, dp_p, imm_reg_type)
5861                 || !aarch64_imm_float_p (qfloat))
5862               {
5863                 if (!error_p ())
5864                   set_fatal_syntax_error (_("invalid floating-point"
5865                                             " constant"));
5866                 goto failure;
5867               }
5868             inst.base.operands[i].imm.value = encode_imm_float_bits (qfloat);
5869             inst.base.operands[i].imm.is_fp = 1;
5870           }
5871           break;
5872
5873         case AARCH64_OPND_SVE_I1_HALF_ONE:
5874         case AARCH64_OPND_SVE_I1_HALF_TWO:
5875         case AARCH64_OPND_SVE_I1_ZERO_ONE:
5876           {
5877             int qfloat;
5878             bfd_boolean dp_p;
5879
5880             dp_p = double_precision_operand_p (&inst.base.operands[0]);
5881             if (!parse_aarch64_imm_float (&str, &qfloat, dp_p, imm_reg_type))
5882               {
5883                 if (!error_p ())
5884                   set_fatal_syntax_error (_("invalid floating-point"
5885                                             " constant"));
5886                 goto failure;
5887               }
5888             inst.base.operands[i].imm.value = qfloat;
5889             inst.base.operands[i].imm.is_fp = 1;
5890           }
5891           break;
5892
5893         case AARCH64_OPND_LIMM:
5894           po_misc_or_fail (parse_shifter_operand (&str, info,
5895                                                   SHIFTED_LOGIC_IMM));
5896           if (info->shifter.operator_present)
5897             {
5898               set_fatal_syntax_error
5899                 (_("shift not allowed for bitmask immediate"));
5900               goto failure;
5901             }
5902           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
5903                                               /* addr_off_p */ 0,
5904                                               /* need_libopcodes_p */ 1,
5905                                               /* skip_p */ 1);
5906           break;
5907
5908         case AARCH64_OPND_AIMM:
5909           if (opcode->op == OP_ADD)
5910             /* ADD may have relocation types.  */
5911             po_misc_or_fail (parse_shifter_operand_reloc (&str, info,
5912                                                           SHIFTED_ARITH_IMM));
5913           else
5914             po_misc_or_fail (parse_shifter_operand (&str, info,
5915                                                     SHIFTED_ARITH_IMM));
5916           switch (inst.reloc.type)
5917             {
5918             case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12:
5919               info->shifter.amount = 12;
5920               break;
5921             case BFD_RELOC_UNUSED:
5922               aarch64_set_gas_internal_fixup (&inst.reloc, info, 0);
5923               if (info->shifter.kind != AARCH64_MOD_NONE)
5924                 inst.reloc.flags = FIXUP_F_HAS_EXPLICIT_SHIFT;
5925               inst.reloc.pc_rel = 0;
5926               break;
5927             default:
5928               break;
5929             }
5930           info->imm.value = 0;
5931           if (!info->shifter.operator_present)
5932             {
5933               /* Default to LSL if not present.  Libopcodes prefers shifter
5934                  kind to be explicit.  */
5935               gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
5936               info->shifter.kind = AARCH64_MOD_LSL;
5937             }
5938           break;
5939
5940         case AARCH64_OPND_HALF:
5941             {
5942               /* #<imm16> or relocation.  */
5943               int internal_fixup_p;
5944               po_misc_or_fail (parse_half (&str, &internal_fixup_p));
5945               if (internal_fixup_p)
5946                 aarch64_set_gas_internal_fixup (&inst.reloc, info, 0);
5947               skip_whitespace (str);
5948               if (skip_past_comma (&str))
5949                 {
5950                   /* {, LSL #<shift>}  */
5951                   if (! aarch64_gas_internal_fixup_p ())
5952                     {
5953                       set_fatal_syntax_error (_("can't mix relocation modifier "
5954                                                 "with explicit shift"));
5955                       goto failure;
5956                     }
5957                   po_misc_or_fail (parse_shift (&str, info, SHIFTED_LSL));
5958                 }
5959               else
5960                 inst.base.operands[i].shifter.amount = 0;
5961               inst.base.operands[i].shifter.kind = AARCH64_MOD_LSL;
5962               inst.base.operands[i].imm.value = 0;
5963               if (! process_movw_reloc_info ())
5964                 goto failure;
5965             }
5966           break;
5967
5968         case AARCH64_OPND_EXCEPTION:
5969           po_misc_or_fail (parse_immediate_expression (&str, &inst.reloc.exp,
5970                                                        imm_reg_type));
5971           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
5972                                               /* addr_off_p */ 0,
5973                                               /* need_libopcodes_p */ 0,
5974                                               /* skip_p */ 1);
5975           break;
5976
5977         case AARCH64_OPND_NZCV:
5978           {
5979             const asm_nzcv *nzcv = hash_find_n (aarch64_nzcv_hsh, str, 4);
5980             if (nzcv != NULL)
5981               {
5982                 str += 4;
5983                 info->imm.value = nzcv->value;
5984                 break;
5985               }
5986             po_imm_or_fail (0, 15);
5987             info->imm.value = val;
5988           }
5989           break;
5990
5991         case AARCH64_OPND_COND:
5992         case AARCH64_OPND_COND1:
5993           {
5994             char *start = str;
5995             do
5996               str++;
5997             while (ISALPHA (*str));
5998             info->cond = hash_find_n (aarch64_cond_hsh, start, str - start);
5999             if (info->cond == NULL)
6000               {
6001                 set_syntax_error (_("invalid condition"));
6002                 goto failure;
6003               }
6004             else if (operands[i] == AARCH64_OPND_COND1
6005                      && (info->cond->value & 0xe) == 0xe)
6006               {
6007                 /* Do not allow AL or NV.  */
6008                 set_default_error ();
6009                 goto failure;
6010               }
6011           }
6012           break;
6013
6014         case AARCH64_OPND_ADDR_ADRP:
6015           po_misc_or_fail (parse_adrp (&str));
6016           /* Clear the value as operand needs to be relocated.  */
6017           info->imm.value = 0;
6018           break;
6019
6020         case AARCH64_OPND_ADDR_PCREL14:
6021         case AARCH64_OPND_ADDR_PCREL19:
6022         case AARCH64_OPND_ADDR_PCREL21:
6023         case AARCH64_OPND_ADDR_PCREL26:
6024           po_misc_or_fail (parse_address (&str, info));
6025           if (!info->addr.pcrel)
6026             {
6027               set_syntax_error (_("invalid pc-relative address"));
6028               goto failure;
6029             }
6030           if (inst.gen_lit_pool
6031               && (opcode->iclass != loadlit || opcode->op == OP_PRFM_LIT))
6032             {
6033               /* Only permit "=value" in the literal load instructions.
6034                  The literal will be generated by programmer_friendly_fixup.  */
6035               set_syntax_error (_("invalid use of \"=immediate\""));
6036               goto failure;
6037             }
6038           if (inst.reloc.exp.X_op == O_symbol && find_reloc_table_entry (&str))
6039             {
6040               set_syntax_error (_("unrecognized relocation suffix"));
6041               goto failure;
6042             }
6043           if (inst.reloc.exp.X_op == O_constant && !inst.gen_lit_pool)
6044             {
6045               info->imm.value = inst.reloc.exp.X_add_number;
6046               inst.reloc.type = BFD_RELOC_UNUSED;
6047             }
6048           else
6049             {
6050               info->imm.value = 0;
6051               if (inst.reloc.type == BFD_RELOC_UNUSED)
6052                 switch (opcode->iclass)
6053                   {
6054                   case compbranch:
6055                   case condbranch:
6056                     /* e.g. CBZ or B.COND  */
6057                     gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL19);
6058                     inst.reloc.type = BFD_RELOC_AARCH64_BRANCH19;
6059                     break;
6060                   case testbranch:
6061                     /* e.g. TBZ  */
6062                     gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL14);
6063                     inst.reloc.type = BFD_RELOC_AARCH64_TSTBR14;
6064                     break;
6065                   case branch_imm:
6066                     /* e.g. B or BL  */
6067                     gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL26);
6068                     inst.reloc.type =
6069                       (opcode->op == OP_BL) ? BFD_RELOC_AARCH64_CALL26
6070                          : BFD_RELOC_AARCH64_JUMP26;
6071                     break;
6072                   case loadlit:
6073                     gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL19);
6074                     inst.reloc.type = BFD_RELOC_AARCH64_LD_LO19_PCREL;
6075                     break;
6076                   case pcreladdr:
6077                     gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL21);
6078                     inst.reloc.type = BFD_RELOC_AARCH64_ADR_LO21_PCREL;
6079                     break;
6080                   default:
6081                     gas_assert (0);
6082                     abort ();
6083                   }
6084               inst.reloc.pc_rel = 1;
6085             }
6086           break;
6087
6088         case AARCH64_OPND_ADDR_SIMPLE:
6089         case AARCH64_OPND_SIMD_ADDR_SIMPLE:
6090           {
6091             /* [<Xn|SP>{, #<simm>}]  */
6092             char *start = str;
6093             /* First use the normal address-parsing routines, to get
6094                the usual syntax errors.  */
6095             po_misc_or_fail (parse_address (&str, info));
6096             if (info->addr.pcrel || info->addr.offset.is_reg
6097                 || !info->addr.preind || info->addr.postind
6098                 || info->addr.writeback)
6099               {
6100                 set_syntax_error (_("invalid addressing mode"));
6101                 goto failure;
6102               }
6103
6104             /* Then retry, matching the specific syntax of these addresses.  */
6105             str = start;
6106             po_char_or_fail ('[');
6107             po_reg_or_fail (REG_TYPE_R64_SP);
6108             /* Accept optional ", #0".  */
6109             if (operands[i] == AARCH64_OPND_ADDR_SIMPLE
6110                 && skip_past_char (&str, ','))
6111               {
6112                 skip_past_char (&str, '#');
6113                 if (! skip_past_char (&str, '0'))
6114                   {
6115                     set_fatal_syntax_error
6116                       (_("the optional immediate offset can only be 0"));
6117                     goto failure;
6118                   }
6119               }
6120             po_char_or_fail (']');
6121             break;
6122           }
6123
6124         case AARCH64_OPND_ADDR_REGOFF:
6125           /* [<Xn|SP>, <R><m>{, <extend> {<amount>}}]  */
6126           po_misc_or_fail (parse_address (&str, info));
6127         regoff_addr:
6128           if (info->addr.pcrel || !info->addr.offset.is_reg
6129               || !info->addr.preind || info->addr.postind
6130               || info->addr.writeback)
6131             {
6132               set_syntax_error (_("invalid addressing mode"));
6133               goto failure;
6134             }
6135           if (!info->shifter.operator_present)
6136             {
6137               /* Default to LSL if not present.  Libopcodes prefers shifter
6138                  kind to be explicit.  */
6139               gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
6140               info->shifter.kind = AARCH64_MOD_LSL;
6141             }
6142           /* Qualifier to be deduced by libopcodes.  */
6143           break;
6144
6145         case AARCH64_OPND_ADDR_SIMM7:
6146           po_misc_or_fail (parse_address (&str, info));
6147           if (info->addr.pcrel || info->addr.offset.is_reg
6148               || (!info->addr.preind && !info->addr.postind))
6149             {
6150               set_syntax_error (_("invalid addressing mode"));
6151               goto failure;
6152             }
6153           if (inst.reloc.type != BFD_RELOC_UNUSED)
6154             {
6155               set_syntax_error (_("relocation not allowed"));
6156               goto failure;
6157             }
6158           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
6159                                               /* addr_off_p */ 1,
6160                                               /* need_libopcodes_p */ 1,
6161                                               /* skip_p */ 0);
6162           break;
6163
6164         case AARCH64_OPND_ADDR_SIMM9:
6165         case AARCH64_OPND_ADDR_SIMM9_2:
6166           po_misc_or_fail (parse_address (&str, info));
6167           if (info->addr.pcrel || info->addr.offset.is_reg
6168               || (!info->addr.preind && !info->addr.postind)
6169               || (operands[i] == AARCH64_OPND_ADDR_SIMM9_2
6170                   && info->addr.writeback))
6171             {
6172               set_syntax_error (_("invalid addressing mode"));
6173               goto failure;
6174             }
6175           if (inst.reloc.type != BFD_RELOC_UNUSED)
6176             {
6177               set_syntax_error (_("relocation not allowed"));
6178               goto failure;
6179             }
6180           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
6181                                               /* addr_off_p */ 1,
6182                                               /* need_libopcodes_p */ 1,
6183                                               /* skip_p */ 0);
6184           break;
6185
6186         case AARCH64_OPND_ADDR_SIMM10:
6187         case AARCH64_OPND_ADDR_OFFSET:
6188           po_misc_or_fail (parse_address (&str, info));
6189           if (info->addr.pcrel || info->addr.offset.is_reg
6190               || !info->addr.preind || info->addr.postind)
6191             {
6192               set_syntax_error (_("invalid addressing mode"));
6193               goto failure;
6194             }
6195           if (inst.reloc.type != BFD_RELOC_UNUSED)
6196             {
6197               set_syntax_error (_("relocation not allowed"));
6198               goto failure;
6199             }
6200           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
6201                                               /* addr_off_p */ 1,
6202                                               /* need_libopcodes_p */ 1,
6203                                               /* skip_p */ 0);
6204           break;
6205
6206         case AARCH64_OPND_ADDR_UIMM12:
6207           po_misc_or_fail (parse_address (&str, info));
6208           if (info->addr.pcrel || info->addr.offset.is_reg
6209               || !info->addr.preind || info->addr.writeback)
6210             {
6211               set_syntax_error (_("invalid addressing mode"));
6212               goto failure;
6213             }
6214           if (inst.reloc.type == BFD_RELOC_UNUSED)
6215             aarch64_set_gas_internal_fixup (&inst.reloc, info, 1);
6216           else if (inst.reloc.type == BFD_RELOC_AARCH64_LDST_LO12
6217                    || (inst.reloc.type
6218                        == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12)
6219                    || (inst.reloc.type
6220                        == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC)
6221                    || (inst.reloc.type
6222                        == BFD_RELOC_AARCH64_TLSLE_LDST_TPREL_LO12)
6223                    || (inst.reloc.type
6224                        == BFD_RELOC_AARCH64_TLSLE_LDST_TPREL_LO12_NC))
6225             inst.reloc.type = ldst_lo12_determine_real_reloc_type ();
6226           /* Leave qualifier to be determined by libopcodes.  */
6227           break;
6228
6229         case AARCH64_OPND_SIMD_ADDR_POST:
6230           /* [<Xn|SP>], <Xm|#<amount>>  */
6231           po_misc_or_fail (parse_address (&str, info));
6232           if (!info->addr.postind || !info->addr.writeback)
6233             {
6234               set_syntax_error (_("invalid addressing mode"));
6235               goto failure;
6236             }
6237           if (!info->addr.offset.is_reg)
6238             {
6239               if (inst.reloc.exp.X_op == O_constant)
6240                 info->addr.offset.imm = inst.reloc.exp.X_add_number;
6241               else
6242                 {
6243                   set_fatal_syntax_error
6244                     (_("writeback value must be an immediate constant"));
6245                   goto failure;
6246                 }
6247             }
6248           /* No qualifier.  */
6249           break;
6250
6251         case AARCH64_OPND_SVE_ADDR_RI_S4x16:
6252         case AARCH64_OPND_SVE_ADDR_RI_S4xVL:
6253         case AARCH64_OPND_SVE_ADDR_RI_S4x2xVL:
6254         case AARCH64_OPND_SVE_ADDR_RI_S4x3xVL:
6255         case AARCH64_OPND_SVE_ADDR_RI_S4x4xVL:
6256         case AARCH64_OPND_SVE_ADDR_RI_S6xVL:
6257         case AARCH64_OPND_SVE_ADDR_RI_S9xVL:
6258         case AARCH64_OPND_SVE_ADDR_RI_U6:
6259         case AARCH64_OPND_SVE_ADDR_RI_U6x2:
6260         case AARCH64_OPND_SVE_ADDR_RI_U6x4:
6261         case AARCH64_OPND_SVE_ADDR_RI_U6x8:
6262           /* [X<n>{, #imm, MUL VL}]
6263              [X<n>{, #imm}]
6264              but recognizing SVE registers.  */
6265           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6266                                               &offset_qualifier));
6267           if (base_qualifier != AARCH64_OPND_QLF_X)
6268             {
6269               set_syntax_error (_("invalid addressing mode"));
6270               goto failure;
6271             }
6272         sve_regimm:
6273           if (info->addr.pcrel || info->addr.offset.is_reg
6274               || !info->addr.preind || info->addr.writeback)
6275             {
6276               set_syntax_error (_("invalid addressing mode"));
6277               goto failure;
6278             }
6279           if (inst.reloc.type != BFD_RELOC_UNUSED
6280               || inst.reloc.exp.X_op != O_constant)
6281             {
6282               /* Make sure this has priority over
6283                  "invalid addressing mode".  */
6284               set_fatal_syntax_error (_("constant offset required"));
6285               goto failure;
6286             }
6287           info->addr.offset.imm = inst.reloc.exp.X_add_number;
6288           break;
6289
6290         case AARCH64_OPND_SVE_ADDR_R:
6291           /* [<Xn|SP>{, <R><m>}]
6292              but recognizing SVE registers.  */
6293           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6294                                               &offset_qualifier));
6295           if (offset_qualifier == AARCH64_OPND_QLF_NIL)
6296             {
6297               offset_qualifier = AARCH64_OPND_QLF_X;
6298               info->addr.offset.is_reg = 1;
6299               info->addr.offset.regno = 31;
6300             }
6301           else if (base_qualifier != AARCH64_OPND_QLF_X
6302               || offset_qualifier != AARCH64_OPND_QLF_X)
6303             {
6304               set_syntax_error (_("invalid addressing mode"));
6305               goto failure;
6306             }
6307           goto regoff_addr;
6308           
6309         case AARCH64_OPND_SVE_ADDR_RR:
6310         case AARCH64_OPND_SVE_ADDR_RR_LSL1:
6311         case AARCH64_OPND_SVE_ADDR_RR_LSL2:
6312         case AARCH64_OPND_SVE_ADDR_RR_LSL3:
6313         case AARCH64_OPND_SVE_ADDR_RX:
6314         case AARCH64_OPND_SVE_ADDR_RX_LSL1:
6315         case AARCH64_OPND_SVE_ADDR_RX_LSL2:
6316         case AARCH64_OPND_SVE_ADDR_RX_LSL3:
6317           /* [<Xn|SP>, <R><m>{, lsl #<amount>}]
6318              but recognizing SVE registers.  */
6319           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6320                                               &offset_qualifier));
6321           if (base_qualifier != AARCH64_OPND_QLF_X
6322               || offset_qualifier != AARCH64_OPND_QLF_X)
6323             {
6324               set_syntax_error (_("invalid addressing mode"));
6325               goto failure;
6326             }
6327           goto regoff_addr;
6328
6329         case AARCH64_OPND_SVE_ADDR_RZ:
6330         case AARCH64_OPND_SVE_ADDR_RZ_LSL1:
6331         case AARCH64_OPND_SVE_ADDR_RZ_LSL2:
6332         case AARCH64_OPND_SVE_ADDR_RZ_LSL3:
6333         case AARCH64_OPND_SVE_ADDR_RZ_XTW_14:
6334         case AARCH64_OPND_SVE_ADDR_RZ_XTW_22:
6335         case AARCH64_OPND_SVE_ADDR_RZ_XTW1_14:
6336         case AARCH64_OPND_SVE_ADDR_RZ_XTW1_22:
6337         case AARCH64_OPND_SVE_ADDR_RZ_XTW2_14:
6338         case AARCH64_OPND_SVE_ADDR_RZ_XTW2_22:
6339         case AARCH64_OPND_SVE_ADDR_RZ_XTW3_14:
6340         case AARCH64_OPND_SVE_ADDR_RZ_XTW3_22:
6341           /* [<Xn|SP>, Z<m>.D{, LSL #<amount>}]
6342              [<Xn|SP>, Z<m>.<T>, <extend> {#<amount>}]  */
6343           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6344                                               &offset_qualifier));
6345           if (base_qualifier != AARCH64_OPND_QLF_X
6346               || (offset_qualifier != AARCH64_OPND_QLF_S_S
6347                   && offset_qualifier != AARCH64_OPND_QLF_S_D))
6348             {
6349               set_syntax_error (_("invalid addressing mode"));
6350               goto failure;
6351             }
6352           info->qualifier = offset_qualifier;
6353           goto regoff_addr;
6354
6355         case AARCH64_OPND_SVE_ADDR_ZI_U5:
6356         case AARCH64_OPND_SVE_ADDR_ZI_U5x2:
6357         case AARCH64_OPND_SVE_ADDR_ZI_U5x4:
6358         case AARCH64_OPND_SVE_ADDR_ZI_U5x8:
6359           /* [Z<n>.<T>{, #imm}]  */
6360           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6361                                               &offset_qualifier));
6362           if (base_qualifier != AARCH64_OPND_QLF_S_S
6363               && base_qualifier != AARCH64_OPND_QLF_S_D)
6364             {
6365               set_syntax_error (_("invalid addressing mode"));
6366               goto failure;
6367             }
6368           info->qualifier = base_qualifier;
6369           goto sve_regimm;
6370
6371         case AARCH64_OPND_SVE_ADDR_ZZ_LSL:
6372         case AARCH64_OPND_SVE_ADDR_ZZ_SXTW:
6373         case AARCH64_OPND_SVE_ADDR_ZZ_UXTW:
6374           /* [Z<n>.<T>, Z<m>.<T>{, LSL #<amount>}]
6375              [Z<n>.D, Z<m>.D, <extend> {#<amount>}]
6376
6377              We don't reject:
6378
6379              [Z<n>.S, Z<m>.S, <extend> {#<amount>}]
6380
6381              here since we get better error messages by leaving it to
6382              the qualifier checking routines.  */
6383           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6384                                               &offset_qualifier));
6385           if ((base_qualifier != AARCH64_OPND_QLF_S_S
6386                && base_qualifier != AARCH64_OPND_QLF_S_D)
6387               || offset_qualifier != base_qualifier)
6388             {
6389               set_syntax_error (_("invalid addressing mode"));
6390               goto failure;
6391             }
6392           info->qualifier = base_qualifier;
6393           goto regoff_addr;
6394
6395         case AARCH64_OPND_SYSREG:
6396           {
6397             uint32_t sysreg_flags;
6398             if ((val = parse_sys_reg (&str, aarch64_sys_regs_hsh, 1, 0,
6399                                       &sysreg_flags)) == PARSE_FAIL)
6400               {
6401                 set_syntax_error (_("unknown or missing system register name"));
6402                 goto failure;
6403               }
6404             inst.base.operands[i].sysreg.value = val;
6405             inst.base.operands[i].sysreg.flags = sysreg_flags;
6406             break;
6407           }
6408
6409         case AARCH64_OPND_PSTATEFIELD:
6410           if ((val = parse_sys_reg (&str, aarch64_pstatefield_hsh, 0, 1, NULL))
6411               == PARSE_FAIL)
6412             {
6413               set_syntax_error (_("unknown or missing PSTATE field name"));
6414               goto failure;
6415             }
6416           inst.base.operands[i].pstatefield = val;
6417           break;
6418
6419         case AARCH64_OPND_SYSREG_IC:
6420           inst.base.operands[i].sysins_op =
6421             parse_sys_ins_reg (&str, aarch64_sys_regs_ic_hsh);
6422           goto sys_reg_ins;
6423         case AARCH64_OPND_SYSREG_DC:
6424           inst.base.operands[i].sysins_op =
6425             parse_sys_ins_reg (&str, aarch64_sys_regs_dc_hsh);
6426           goto sys_reg_ins;
6427         case AARCH64_OPND_SYSREG_AT:
6428           inst.base.operands[i].sysins_op =
6429             parse_sys_ins_reg (&str, aarch64_sys_regs_at_hsh);
6430           goto sys_reg_ins;
6431         case AARCH64_OPND_SYSREG_TLBI:
6432           inst.base.operands[i].sysins_op =
6433             parse_sys_ins_reg (&str, aarch64_sys_regs_tlbi_hsh);
6434 sys_reg_ins:
6435           if (inst.base.operands[i].sysins_op == NULL)
6436             {
6437               set_fatal_syntax_error ( _("unknown or missing operation name"));
6438               goto failure;
6439             }
6440           break;
6441
6442         case AARCH64_OPND_BARRIER:
6443         case AARCH64_OPND_BARRIER_ISB:
6444           val = parse_barrier (&str);
6445           if (val != PARSE_FAIL
6446               && operands[i] == AARCH64_OPND_BARRIER_ISB && val != 0xf)
6447             {
6448               /* ISB only accepts options name 'sy'.  */
6449               set_syntax_error
6450                 (_("the specified option is not accepted in ISB"));
6451               /* Turn off backtrack as this optional operand is present.  */
6452               backtrack_pos = 0;
6453               goto failure;
6454             }
6455           /* This is an extension to accept a 0..15 immediate.  */
6456           if (val == PARSE_FAIL)
6457             po_imm_or_fail (0, 15);
6458           info->barrier = aarch64_barrier_options + val;
6459           break;
6460
6461         case AARCH64_OPND_PRFOP:
6462           val = parse_pldop (&str);
6463           /* This is an extension to accept a 0..31 immediate.  */
6464           if (val == PARSE_FAIL)
6465             po_imm_or_fail (0, 31);
6466           inst.base.operands[i].prfop = aarch64_prfops + val;
6467           break;
6468
6469         case AARCH64_OPND_BARRIER_PSB:
6470           val = parse_barrier_psb (&str, &(info->hint_option));
6471           if (val == PARSE_FAIL)
6472             goto failure;
6473           break;
6474
6475         default:
6476           as_fatal (_("unhandled operand code %d"), operands[i]);
6477         }
6478
6479       /* If we get here, this operand was successfully parsed.  */
6480       inst.base.operands[i].present = 1;
6481       continue;
6482
6483 failure:
6484       /* The parse routine should already have set the error, but in case
6485          not, set a default one here.  */
6486       if (! error_p ())
6487         set_default_error ();
6488
6489       if (! backtrack_pos)
6490         goto parse_operands_return;
6491
6492       {
6493         /* We reach here because this operand is marked as optional, and
6494            either no operand was supplied or the operand was supplied but it
6495            was syntactically incorrect.  In the latter case we report an
6496            error.  In the former case we perform a few more checks before
6497            dropping through to the code to insert the default operand.  */
6498
6499         char *tmp = backtrack_pos;
6500         char endchar = END_OF_INSN;
6501
6502         if (i != (aarch64_num_of_operands (opcode) - 1))
6503           endchar = ',';
6504         skip_past_char (&tmp, ',');
6505
6506         if (*tmp != endchar)
6507           /* The user has supplied an operand in the wrong format.  */
6508           goto parse_operands_return;
6509
6510         /* Make sure there is not a comma before the optional operand.
6511            For example the fifth operand of 'sys' is optional:
6512
6513              sys #0,c0,c0,#0,  <--- wrong
6514              sys #0,c0,c0,#0   <--- correct.  */
6515         if (comma_skipped_p && i && endchar == END_OF_INSN)
6516           {
6517             set_fatal_syntax_error
6518               (_("unexpected comma before the omitted optional operand"));
6519             goto parse_operands_return;
6520           }
6521       }
6522
6523       /* Reaching here means we are dealing with an optional operand that is
6524          omitted from the assembly line.  */
6525       gas_assert (optional_operand_p (opcode, i));
6526       info->present = 0;
6527       process_omitted_operand (operands[i], opcode, i, info);
6528
6529       /* Try again, skipping the optional operand at backtrack_pos.  */
6530       str = backtrack_pos;
6531       backtrack_pos = 0;
6532
6533       /* Clear any error record after the omitted optional operand has been
6534          successfully handled.  */
6535       clear_error ();
6536     }
6537
6538   /* Check if we have parsed all the operands.  */
6539   if (*str != '\0' && ! error_p ())
6540     {
6541       /* Set I to the index of the last present operand; this is
6542          for the purpose of diagnostics.  */
6543       for (i -= 1; i >= 0 && !inst.base.operands[i].present; --i)
6544         ;
6545       set_fatal_syntax_error
6546         (_("unexpected characters following instruction"));
6547     }
6548
6549 parse_operands_return:
6550
6551   if (error_p ())
6552     {
6553       DEBUG_TRACE ("parsing FAIL: %s - %s",
6554                    operand_mismatch_kind_names[get_error_kind ()],
6555                    get_error_message ());
6556       /* Record the operand error properly; this is useful when there
6557          are multiple instruction templates for a mnemonic name, so that
6558          later on, we can select the error that most closely describes
6559          the problem.  */
6560       record_operand_error (opcode, i, get_error_kind (),
6561                             get_error_message ());
6562       return FALSE;
6563     }
6564   else
6565     {
6566       DEBUG_TRACE ("parsing SUCCESS");
6567       return TRUE;
6568     }
6569 }
6570
6571 /* It does some fix-up to provide some programmer friendly feature while
6572    keeping the libopcodes happy, i.e. libopcodes only accepts
6573    the preferred architectural syntax.
6574    Return FALSE if there is any failure; otherwise return TRUE.  */
6575
6576 static bfd_boolean
6577 programmer_friendly_fixup (aarch64_instruction *instr)
6578 {
6579   aarch64_inst *base = &instr->base;
6580   const aarch64_opcode *opcode = base->opcode;
6581   enum aarch64_op op = opcode->op;
6582   aarch64_opnd_info *operands = base->operands;
6583
6584   DEBUG_TRACE ("enter");
6585
6586   switch (opcode->iclass)
6587     {
6588     case testbranch:
6589       /* TBNZ Xn|Wn, #uimm6, label
6590          Test and Branch Not Zero: conditionally jumps to label if bit number
6591          uimm6 in register Xn is not zero.  The bit number implies the width of
6592          the register, which may be written and should be disassembled as Wn if
6593          uimm is less than 32.  */
6594       if (operands[0].qualifier == AARCH64_OPND_QLF_W)
6595         {
6596           if (operands[1].imm.value >= 32)
6597             {
6598               record_operand_out_of_range_error (opcode, 1, _("immediate value"),
6599                                                  0, 31);
6600               return FALSE;
6601             }
6602           operands[0].qualifier = AARCH64_OPND_QLF_X;
6603         }
6604       break;
6605     case loadlit:
6606       /* LDR Wt, label | =value
6607          As a convenience assemblers will typically permit the notation
6608          "=value" in conjunction with the pc-relative literal load instructions
6609          to automatically place an immediate value or symbolic address in a
6610          nearby literal pool and generate a hidden label which references it.
6611          ISREG has been set to 0 in the case of =value.  */
6612       if (instr->gen_lit_pool
6613           && (op == OP_LDR_LIT || op == OP_LDRV_LIT || op == OP_LDRSW_LIT))
6614         {
6615           int size = aarch64_get_qualifier_esize (operands[0].qualifier);
6616           if (op == OP_LDRSW_LIT)
6617             size = 4;
6618           if (instr->reloc.exp.X_op != O_constant
6619               && instr->reloc.exp.X_op != O_big
6620               && instr->reloc.exp.X_op != O_symbol)
6621             {
6622               record_operand_error (opcode, 1,
6623                                     AARCH64_OPDE_FATAL_SYNTAX_ERROR,
6624                                     _("constant expression expected"));
6625               return FALSE;
6626             }
6627           if (! add_to_lit_pool (&instr->reloc.exp, size))
6628             {
6629               record_operand_error (opcode, 1,
6630                                     AARCH64_OPDE_OTHER_ERROR,
6631                                     _("literal pool insertion failed"));
6632               return FALSE;
6633             }
6634         }
6635       break;
6636     case log_shift:
6637     case bitfield:
6638       /* UXT[BHW] Wd, Wn
6639          Unsigned Extend Byte|Halfword|Word: UXT[BH] is architectural alias
6640          for UBFM Wd,Wn,#0,#7|15, while UXTW is pseudo instruction which is
6641          encoded using ORR Wd, WZR, Wn (MOV Wd,Wn).
6642          A programmer-friendly assembler should accept a destination Xd in
6643          place of Wd, however that is not the preferred form for disassembly.
6644          */
6645       if ((op == OP_UXTB || op == OP_UXTH || op == OP_UXTW)
6646           && operands[1].qualifier == AARCH64_OPND_QLF_W
6647           && operands[0].qualifier == AARCH64_OPND_QLF_X)
6648         operands[0].qualifier = AARCH64_OPND_QLF_W;
6649       break;
6650
6651     case addsub_ext:
6652         {
6653           /* In the 64-bit form, the final register operand is written as Wm
6654              for all but the (possibly omitted) UXTX/LSL and SXTX
6655              operators.
6656              As a programmer-friendly assembler, we accept e.g.
6657              ADDS <Xd>, <Xn|SP>, <Xm>{, UXTB {#<amount>}} and change it to
6658              ADDS <Xd>, <Xn|SP>, <Wm>{, UXTB {#<amount>}}.  */
6659           int idx = aarch64_operand_index (opcode->operands,
6660                                            AARCH64_OPND_Rm_EXT);
6661           gas_assert (idx == 1 || idx == 2);
6662           if (operands[0].qualifier == AARCH64_OPND_QLF_X
6663               && operands[idx].qualifier == AARCH64_OPND_QLF_X
6664               && operands[idx].shifter.kind != AARCH64_MOD_LSL
6665               && operands[idx].shifter.kind != AARCH64_MOD_UXTX
6666               && operands[idx].shifter.kind != AARCH64_MOD_SXTX)
6667             operands[idx].qualifier = AARCH64_OPND_QLF_W;
6668         }
6669       break;
6670
6671     default:
6672       break;
6673     }
6674
6675   DEBUG_TRACE ("exit with SUCCESS");
6676   return TRUE;
6677 }
6678
6679 /* Check for loads and stores that will cause unpredictable behavior.  */
6680
6681 static void
6682 warn_unpredictable_ldst (aarch64_instruction *instr, char *str)
6683 {
6684   aarch64_inst *base = &instr->base;
6685   const aarch64_opcode *opcode = base->opcode;
6686   const aarch64_opnd_info *opnds = base->operands;
6687   switch (opcode->iclass)
6688     {
6689     case ldst_pos:
6690     case ldst_imm9:
6691     case ldst_imm10:
6692     case ldst_unscaled:
6693     case ldst_unpriv:
6694       /* Loading/storing the base register is unpredictable if writeback.  */
6695       if ((aarch64_get_operand_class (opnds[0].type)
6696            == AARCH64_OPND_CLASS_INT_REG)
6697           && opnds[0].reg.regno == opnds[1].addr.base_regno
6698           && opnds[1].addr.base_regno != REG_SP
6699           && opnds[1].addr.writeback)
6700         as_warn (_("unpredictable transfer with writeback -- `%s'"), str);
6701       break;
6702     case ldstpair_off:
6703     case ldstnapair_offs:
6704     case ldstpair_indexed:
6705       /* Loading/storing the base register is unpredictable if writeback.  */
6706       if ((aarch64_get_operand_class (opnds[0].type)
6707            == AARCH64_OPND_CLASS_INT_REG)
6708           && (opnds[0].reg.regno == opnds[2].addr.base_regno
6709             || opnds[1].reg.regno == opnds[2].addr.base_regno)
6710           && opnds[2].addr.base_regno != REG_SP
6711           && opnds[2].addr.writeback)
6712             as_warn (_("unpredictable transfer with writeback -- `%s'"), str);
6713       /* Load operations must load different registers.  */
6714       if ((opcode->opcode & (1 << 22))
6715           && opnds[0].reg.regno == opnds[1].reg.regno)
6716             as_warn (_("unpredictable load of register pair -- `%s'"), str);
6717       break;
6718
6719     case ldstexcl:
6720       /* It is unpredictable if the destination and status registers are the
6721          same.  */
6722       if ((aarch64_get_operand_class (opnds[0].type)
6723            == AARCH64_OPND_CLASS_INT_REG)
6724           && (aarch64_get_operand_class (opnds[1].type)
6725               == AARCH64_OPND_CLASS_INT_REG)
6726           && (opnds[0].reg.regno == opnds[1].reg.regno
6727               || opnds[0].reg.regno == opnds[2].reg.regno))
6728         as_warn (_("unpredictable: identical transfer and status registers"
6729                    " --`%s'"),
6730                  str);
6731
6732       break;
6733
6734     default:
6735       break;
6736     }
6737 }
6738
6739 /* A wrapper function to interface with libopcodes on encoding and
6740    record the error message if there is any.
6741
6742    Return TRUE on success; otherwise return FALSE.  */
6743
6744 static bfd_boolean
6745 do_encode (const aarch64_opcode *opcode, aarch64_inst *instr,
6746            aarch64_insn *code)
6747 {
6748   aarch64_operand_error error_info;
6749   memset (&error_info, '\0', sizeof (error_info));
6750   error_info.kind = AARCH64_OPDE_NIL;
6751   if (aarch64_opcode_encode (opcode, instr, code, NULL, &error_info, insn_sequence)
6752       && !error_info.non_fatal)
6753     return TRUE;
6754
6755   gas_assert (error_info.kind != AARCH64_OPDE_NIL);
6756   record_operand_error_info (opcode, &error_info);
6757   return error_info.non_fatal;
6758 }
6759
6760 #ifdef DEBUG_AARCH64
6761 static inline void
6762 dump_opcode_operands (const aarch64_opcode *opcode)
6763 {
6764   int i = 0;
6765   while (opcode->operands[i] != AARCH64_OPND_NIL)
6766     {
6767       aarch64_verbose ("\t\t opnd%d: %s", i,
6768                        aarch64_get_operand_name (opcode->operands[i])[0] != '\0'
6769                        ? aarch64_get_operand_name (opcode->operands[i])
6770                        : aarch64_get_operand_desc (opcode->operands[i]));
6771       ++i;
6772     }
6773 }
6774 #endif /* DEBUG_AARCH64 */
6775
6776 /* This is the guts of the machine-dependent assembler.  STR points to a
6777    machine dependent instruction.  This function is supposed to emit
6778    the frags/bytes it assembles to.  */
6779
6780 void
6781 md_assemble (char *str)
6782 {
6783   char *p = str;
6784   templates *template;
6785   aarch64_opcode *opcode;
6786   aarch64_inst *inst_base;
6787   unsigned saved_cond;
6788
6789   /* Align the previous label if needed.  */
6790   if (last_label_seen != NULL)
6791     {
6792       symbol_set_frag (last_label_seen, frag_now);
6793       S_SET_VALUE (last_label_seen, (valueT) frag_now_fix ());
6794       S_SET_SEGMENT (last_label_seen, now_seg);
6795     }
6796
6797   /* Update the current insn_sequence from the segment.  */
6798   insn_sequence = &seg_info (now_seg)->tc_segment_info_data.insn_sequence;
6799
6800   inst.reloc.type = BFD_RELOC_UNUSED;
6801
6802   DEBUG_TRACE ("\n\n");
6803   DEBUG_TRACE ("==============================");
6804   DEBUG_TRACE ("Enter md_assemble with %s", str);
6805
6806   template = opcode_lookup (&p);
6807   if (!template)
6808     {
6809       /* It wasn't an instruction, but it might be a register alias of
6810          the form alias .req reg directive.  */
6811       if (!create_register_alias (str, p))
6812         as_bad (_("unknown mnemonic `%s' -- `%s'"), get_mnemonic_name (str),
6813                 str);
6814       return;
6815     }
6816
6817   skip_whitespace (p);
6818   if (*p == ',')
6819     {
6820       as_bad (_("unexpected comma after the mnemonic name `%s' -- `%s'"),
6821               get_mnemonic_name (str), str);
6822       return;
6823     }
6824
6825   init_operand_error_report ();
6826
6827   /* Sections are assumed to start aligned. In executable section, there is no
6828      MAP_DATA symbol pending. So we only align the address during
6829      MAP_DATA --> MAP_INSN transition.
6830      For other sections, this is not guaranteed.  */
6831   enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
6832   if (!need_pass_2 && subseg_text_p (now_seg) && mapstate == MAP_DATA)
6833     frag_align_code (2, 0);
6834
6835   saved_cond = inst.cond;
6836   reset_aarch64_instruction (&inst);
6837   inst.cond = saved_cond;
6838
6839   /* Iterate through all opcode entries with the same mnemonic name.  */
6840   do
6841     {
6842       opcode = template->opcode;
6843
6844       DEBUG_TRACE ("opcode %s found", opcode->name);
6845 #ifdef DEBUG_AARCH64
6846       if (debug_dump)
6847         dump_opcode_operands (opcode);
6848 #endif /* DEBUG_AARCH64 */
6849
6850       mapping_state (MAP_INSN);
6851
6852       inst_base = &inst.base;
6853       inst_base->opcode = opcode;
6854
6855       /* Truly conditionally executed instructions, e.g. b.cond.  */
6856       if (opcode->flags & F_COND)
6857         {
6858           gas_assert (inst.cond != COND_ALWAYS);
6859           inst_base->cond = get_cond_from_value (inst.cond);
6860           DEBUG_TRACE ("condition found %s", inst_base->cond->names[0]);
6861         }
6862       else if (inst.cond != COND_ALWAYS)
6863         {
6864           /* It shouldn't arrive here, where the assembly looks like a
6865              conditional instruction but the found opcode is unconditional.  */
6866           gas_assert (0);
6867           continue;
6868         }
6869
6870       if (parse_operands (p, opcode)
6871           && programmer_friendly_fixup (&inst)
6872           && do_encode (inst_base->opcode, &inst.base, &inst_base->value))
6873         {
6874           /* Check that this instruction is supported for this CPU.  */
6875           if (!opcode->avariant
6876               || !AARCH64_CPU_HAS_ALL_FEATURES (cpu_variant, *opcode->avariant))
6877             {
6878               as_bad (_("selected processor does not support `%s'"), str);
6879               return;
6880             }
6881
6882           warn_unpredictable_ldst (&inst, str);
6883
6884           if (inst.reloc.type == BFD_RELOC_UNUSED
6885               || !inst.reloc.need_libopcodes_p)
6886             output_inst (NULL);
6887           else
6888             {
6889               /* If there is relocation generated for the instruction,
6890                  store the instruction information for the future fix-up.  */
6891               struct aarch64_inst *copy;
6892               gas_assert (inst.reloc.type != BFD_RELOC_UNUSED);
6893               copy = XNEW (struct aarch64_inst);
6894               memcpy (copy, &inst.base, sizeof (struct aarch64_inst));
6895               output_inst (copy);
6896             }
6897
6898           /* Issue non-fatal messages if any.  */
6899           output_operand_error_report (str, TRUE);
6900           return;
6901         }
6902
6903       template = template->next;
6904       if (template != NULL)
6905         {
6906           reset_aarch64_instruction (&inst);
6907           inst.cond = saved_cond;
6908         }
6909     }
6910   while (template != NULL);
6911
6912   /* Issue the error messages if any.  */
6913   output_operand_error_report (str, FALSE);
6914 }
6915
6916 /* Various frobbings of labels and their addresses.  */
6917
6918 void
6919 aarch64_start_line_hook (void)
6920 {
6921   last_label_seen = NULL;
6922 }
6923
6924 void
6925 aarch64_frob_label (symbolS * sym)
6926 {
6927   last_label_seen = sym;
6928
6929   dwarf2_emit_label (sym);
6930 }
6931
6932 int
6933 aarch64_data_in_code (void)
6934 {
6935   if (!strncmp (input_line_pointer + 1, "data:", 5))
6936     {
6937       *input_line_pointer = '/';
6938       input_line_pointer += 5;
6939       *input_line_pointer = 0;
6940       return 1;
6941     }
6942
6943   return 0;
6944 }
6945
6946 char *
6947 aarch64_canonicalize_symbol_name (char *name)
6948 {
6949   int len;
6950
6951   if ((len = strlen (name)) > 5 && streq (name + len - 5, "/data"))
6952     *(name + len - 5) = 0;
6953
6954   return name;
6955 }
6956 \f
6957 /* Table of all register names defined by default.  The user can
6958    define additional names with .req.  Note that all register names
6959    should appear in both upper and lowercase variants.  Some registers
6960    also have mixed-case names.  */
6961
6962 #define REGDEF(s,n,t) { #s, n, REG_TYPE_##t, TRUE }
6963 #define REGDEF_ALIAS(s, n, t) { #s, n, REG_TYPE_##t, FALSE}
6964 #define REGNUM(p,n,t) REGDEF(p##n, n, t)
6965 #define REGSET16(p,t) \
6966   REGNUM(p, 0,t), REGNUM(p, 1,t), REGNUM(p, 2,t), REGNUM(p, 3,t), \
6967   REGNUM(p, 4,t), REGNUM(p, 5,t), REGNUM(p, 6,t), REGNUM(p, 7,t), \
6968   REGNUM(p, 8,t), REGNUM(p, 9,t), REGNUM(p,10,t), REGNUM(p,11,t), \
6969   REGNUM(p,12,t), REGNUM(p,13,t), REGNUM(p,14,t), REGNUM(p,15,t)
6970 #define REGSET31(p,t) \
6971   REGSET16(p, t), \
6972   REGNUM(p,16,t), REGNUM(p,17,t), REGNUM(p,18,t), REGNUM(p,19,t), \
6973   REGNUM(p,20,t), REGNUM(p,21,t), REGNUM(p,22,t), REGNUM(p,23,t), \
6974   REGNUM(p,24,t), REGNUM(p,25,t), REGNUM(p,26,t), REGNUM(p,27,t), \
6975   REGNUM(p,28,t), REGNUM(p,29,t), REGNUM(p,30,t)
6976 #define REGSET(p,t) \
6977   REGSET31(p,t), REGNUM(p,31,t)
6978
6979 /* These go into aarch64_reg_hsh hash-table.  */
6980 static const reg_entry reg_names[] = {
6981   /* Integer registers.  */
6982   REGSET31 (x, R_64), REGSET31 (X, R_64),
6983   REGSET31 (w, R_32), REGSET31 (W, R_32),
6984
6985   REGDEF_ALIAS (ip0, 16, R_64), REGDEF_ALIAS (IP0, 16, R_64),
6986   REGDEF_ALIAS (ip1, 17, R_64), REGDEF_ALIAS (IP1, 17, R_64),
6987   REGDEF_ALIAS (fp, 29, R_64), REGDEF_ALIAS (FP, 29, R_64),
6988   REGDEF_ALIAS (lr, 30, R_64), REGDEF_ALIAS (LR, 30, R_64),
6989   REGDEF (wsp, 31, SP_32), REGDEF (WSP, 31, SP_32),
6990   REGDEF (sp, 31, SP_64), REGDEF (SP, 31, SP_64),
6991
6992   REGDEF (wzr, 31, Z_32), REGDEF (WZR, 31, Z_32),
6993   REGDEF (xzr, 31, Z_64), REGDEF (XZR, 31, Z_64),
6994
6995   /* Floating-point single precision registers.  */
6996   REGSET (s, FP_S), REGSET (S, FP_S),
6997
6998   /* Floating-point double precision registers.  */
6999   REGSET (d, FP_D), REGSET (D, FP_D),
7000
7001   /* Floating-point half precision registers.  */
7002   REGSET (h, FP_H), REGSET (H, FP_H),
7003
7004   /* Floating-point byte precision registers.  */
7005   REGSET (b, FP_B), REGSET (B, FP_B),
7006
7007   /* Floating-point quad precision registers.  */
7008   REGSET (q, FP_Q), REGSET (Q, FP_Q),
7009
7010   /* FP/SIMD registers.  */
7011   REGSET (v, VN), REGSET (V, VN),
7012
7013   /* SVE vector registers.  */
7014   REGSET (z, ZN), REGSET (Z, ZN),
7015
7016   /* SVE predicate registers.  */
7017   REGSET16 (p, PN), REGSET16 (P, PN)
7018 };
7019
7020 #undef REGDEF
7021 #undef REGDEF_ALIAS
7022 #undef REGNUM
7023 #undef REGSET16
7024 #undef REGSET31
7025 #undef REGSET
7026
7027 #define N 1
7028 #define n 0
7029 #define Z 1
7030 #define z 0
7031 #define C 1
7032 #define c 0
7033 #define V 1
7034 #define v 0
7035 #define B(a,b,c,d) (((a) << 3) | ((b) << 2) | ((c) << 1) | (d))
7036 static const asm_nzcv nzcv_names[] = {
7037   {"nzcv", B (n, z, c, v)},
7038   {"nzcV", B (n, z, c, V)},
7039   {"nzCv", B (n, z, C, v)},
7040   {"nzCV", B (n, z, C, V)},
7041   {"nZcv", B (n, Z, c, v)},
7042   {"nZcV", B (n, Z, c, V)},
7043   {"nZCv", B (n, Z, C, v)},
7044   {"nZCV", B (n, Z, C, V)},
7045   {"Nzcv", B (N, z, c, v)},
7046   {"NzcV", B (N, z, c, V)},
7047   {"NzCv", B (N, z, C, v)},
7048   {"NzCV", B (N, z, C, V)},
7049   {"NZcv", B (N, Z, c, v)},
7050   {"NZcV", B (N, Z, c, V)},
7051   {"NZCv", B (N, Z, C, v)},
7052   {"NZCV", B (N, Z, C, V)}
7053 };
7054
7055 #undef N
7056 #undef n
7057 #undef Z
7058 #undef z
7059 #undef C
7060 #undef c
7061 #undef V
7062 #undef v
7063 #undef B
7064 \f
7065 /* MD interface: bits in the object file.  */
7066
7067 /* Turn an integer of n bytes (in val) into a stream of bytes appropriate
7068    for use in the a.out file, and stores them in the array pointed to by buf.
7069    This knows about the endian-ness of the target machine and does
7070    THE RIGHT THING, whatever it is.  Possible values for n are 1 (byte)
7071    2 (short) and 4 (long)  Floating numbers are put out as a series of
7072    LITTLENUMS (shorts, here at least).  */
7073
7074 void
7075 md_number_to_chars (char *buf, valueT val, int n)
7076 {
7077   if (target_big_endian)
7078     number_to_chars_bigendian (buf, val, n);
7079   else
7080     number_to_chars_littleendian (buf, val, n);
7081 }
7082
7083 /* MD interface: Sections.  */
7084
7085 /* Estimate the size of a frag before relaxing.  Assume everything fits in
7086    4 bytes.  */
7087
7088 int
7089 md_estimate_size_before_relax (fragS * fragp, segT segtype ATTRIBUTE_UNUSED)
7090 {
7091   fragp->fr_var = 4;
7092   return 4;
7093 }
7094
7095 /* Round up a section size to the appropriate boundary.  */
7096
7097 valueT
7098 md_section_align (segT segment ATTRIBUTE_UNUSED, valueT size)
7099 {
7100   return size;
7101 }
7102
7103 /* This is called from HANDLE_ALIGN in write.c.  Fill in the contents
7104    of an rs_align_code fragment.
7105
7106    Here we fill the frag with the appropriate info for padding the
7107    output stream.  The resulting frag will consist of a fixed (fr_fix)
7108    and of a repeating (fr_var) part.
7109
7110    The fixed content is always emitted before the repeating content and
7111    these two parts are used as follows in constructing the output:
7112    - the fixed part will be used to align to a valid instruction word
7113      boundary, in case that we start at a misaligned address; as no
7114      executable instruction can live at the misaligned location, we
7115      simply fill with zeros;
7116    - the variable part will be used to cover the remaining padding and
7117      we fill using the AArch64 NOP instruction.
7118
7119    Note that the size of a RS_ALIGN_CODE fragment is always 7 to provide
7120    enough storage space for up to 3 bytes for padding the back to a valid
7121    instruction alignment and exactly 4 bytes to store the NOP pattern.  */
7122
7123 void
7124 aarch64_handle_align (fragS * fragP)
7125 {
7126   /* NOP = d503201f */
7127   /* AArch64 instructions are always little-endian.  */
7128   static unsigned char const aarch64_noop[4] = { 0x1f, 0x20, 0x03, 0xd5 };
7129
7130   int bytes, fix, noop_size;
7131   char *p;
7132
7133   if (fragP->fr_type != rs_align_code)
7134     return;
7135
7136   bytes = fragP->fr_next->fr_address - fragP->fr_address - fragP->fr_fix;
7137   p = fragP->fr_literal + fragP->fr_fix;
7138
7139 #ifdef OBJ_ELF
7140   gas_assert (fragP->tc_frag_data.recorded);
7141 #endif
7142
7143   noop_size = sizeof (aarch64_noop);
7144
7145   fix = bytes & (noop_size - 1);
7146   if (fix)
7147     {
7148 #ifdef OBJ_ELF
7149       insert_data_mapping_symbol (MAP_INSN, fragP->fr_fix, fragP, fix);
7150 #endif
7151       memset (p, 0, fix);
7152       p += fix;
7153       fragP->fr_fix += fix;
7154     }
7155
7156   if (noop_size)
7157     memcpy (p, aarch64_noop, noop_size);
7158   fragP->fr_var = noop_size;
7159 }
7160
7161 /* Perform target specific initialisation of a frag.
7162    Note - despite the name this initialisation is not done when the frag
7163    is created, but only when its type is assigned.  A frag can be created
7164    and used a long time before its type is set, so beware of assuming that
7165    this initialisation is performed first.  */
7166
7167 #ifndef OBJ_ELF
7168 void
7169 aarch64_init_frag (fragS * fragP ATTRIBUTE_UNUSED,
7170                    int max_chars ATTRIBUTE_UNUSED)
7171 {
7172 }
7173
7174 #else /* OBJ_ELF is defined.  */
7175 void
7176 aarch64_init_frag (fragS * fragP, int max_chars)
7177 {
7178   /* Record a mapping symbol for alignment frags.  We will delete this
7179      later if the alignment ends up empty.  */
7180   if (!fragP->tc_frag_data.recorded)
7181     fragP->tc_frag_data.recorded = 1;
7182
7183   /* PR 21809: Do not set a mapping state for debug sections
7184      - it just confuses other tools.  */
7185   if (bfd_get_section_flags (NULL, now_seg) & SEC_DEBUGGING)
7186     return;
7187
7188   switch (fragP->fr_type)
7189     {
7190     case rs_align_test:
7191     case rs_fill:
7192       mapping_state_2 (MAP_DATA, max_chars);
7193       break;
7194     case rs_align:
7195       /* PR 20364: We can get alignment frags in code sections,
7196          so do not just assume that we should use the MAP_DATA state.  */
7197       mapping_state_2 (subseg_text_p (now_seg) ? MAP_INSN : MAP_DATA, max_chars);
7198       break;
7199     case rs_align_code:
7200       mapping_state_2 (MAP_INSN, max_chars);
7201       break;
7202     default:
7203       break;
7204     }
7205 }
7206 \f
7207 /* Initialize the DWARF-2 unwind information for this procedure.  */
7208
7209 void
7210 tc_aarch64_frame_initial_instructions (void)
7211 {
7212   cfi_add_CFA_def_cfa (REG_SP, 0);
7213 }
7214 #endif /* OBJ_ELF */
7215
7216 /* Convert REGNAME to a DWARF-2 register number.  */
7217
7218 int
7219 tc_aarch64_regname_to_dw2regnum (char *regname)
7220 {
7221   const reg_entry *reg = parse_reg (&regname);
7222   if (reg == NULL)
7223     return -1;
7224
7225   switch (reg->type)
7226     {
7227     case REG_TYPE_SP_32:
7228     case REG_TYPE_SP_64:
7229     case REG_TYPE_R_32:
7230     case REG_TYPE_R_64:
7231       return reg->number;
7232
7233     case REG_TYPE_FP_B:
7234     case REG_TYPE_FP_H:
7235     case REG_TYPE_FP_S:
7236     case REG_TYPE_FP_D:
7237     case REG_TYPE_FP_Q:
7238       return reg->number + 64;
7239
7240     default:
7241       break;
7242     }
7243   return -1;
7244 }
7245
7246 /* Implement DWARF2_ADDR_SIZE.  */
7247
7248 int
7249 aarch64_dwarf2_addr_size (void)
7250 {
7251 #if defined (OBJ_MAYBE_ELF) || defined (OBJ_ELF)
7252   if (ilp32_p)
7253     return 4;
7254 #endif
7255   return bfd_arch_bits_per_address (stdoutput) / 8;
7256 }
7257
7258 /* MD interface: Symbol and relocation handling.  */
7259
7260 /* Return the address within the segment that a PC-relative fixup is
7261    relative to.  For AArch64 PC-relative fixups applied to instructions
7262    are generally relative to the location plus AARCH64_PCREL_OFFSET bytes.  */
7263
7264 long
7265 md_pcrel_from_section (fixS * fixP, segT seg)
7266 {
7267   offsetT base = fixP->fx_where + fixP->fx_frag->fr_address;
7268
7269   /* If this is pc-relative and we are going to emit a relocation
7270      then we just want to put out any pipeline compensation that the linker
7271      will need.  Otherwise we want to use the calculated base.  */
7272   if (fixP->fx_pcrel
7273       && ((fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != seg)
7274           || aarch64_force_relocation (fixP)))
7275     base = 0;
7276
7277   /* AArch64 should be consistent for all pc-relative relocations.  */
7278   return base + AARCH64_PCREL_OFFSET;
7279 }
7280
7281 /* Under ELF we need to default _GLOBAL_OFFSET_TABLE.
7282    Otherwise we have no need to default values of symbols.  */
7283
7284 symbolS *
7285 md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
7286 {
7287 #ifdef OBJ_ELF
7288   if (name[0] == '_' && name[1] == 'G'
7289       && streq (name, GLOBAL_OFFSET_TABLE_NAME))
7290     {
7291       if (!GOT_symbol)
7292         {
7293           if (symbol_find (name))
7294             as_bad (_("GOT already in the symbol table"));
7295
7296           GOT_symbol = symbol_new (name, undefined_section,
7297                                    (valueT) 0, &zero_address_frag);
7298         }
7299
7300       return GOT_symbol;
7301     }
7302 #endif
7303
7304   return 0;
7305 }
7306
7307 /* Return non-zero if the indicated VALUE has overflowed the maximum
7308    range expressible by a unsigned number with the indicated number of
7309    BITS.  */
7310
7311 static bfd_boolean
7312 unsigned_overflow (valueT value, unsigned bits)
7313 {
7314   valueT lim;
7315   if (bits >= sizeof (valueT) * 8)
7316     return FALSE;
7317   lim = (valueT) 1 << bits;
7318   return (value >= lim);
7319 }
7320
7321
7322 /* Return non-zero if the indicated VALUE has overflowed the maximum
7323    range expressible by an signed number with the indicated number of
7324    BITS.  */
7325
7326 static bfd_boolean
7327 signed_overflow (offsetT value, unsigned bits)
7328 {
7329   offsetT lim;
7330   if (bits >= sizeof (offsetT) * 8)
7331     return FALSE;
7332   lim = (offsetT) 1 << (bits - 1);
7333   return (value < -lim || value >= lim);
7334 }
7335
7336 /* Given an instruction in *INST, which is expected to be a scaled, 12-bit,
7337    unsigned immediate offset load/store instruction, try to encode it as
7338    an unscaled, 9-bit, signed immediate offset load/store instruction.
7339    Return TRUE if it is successful; otherwise return FALSE.
7340
7341    As a programmer-friendly assembler, LDUR/STUR instructions can be generated
7342    in response to the standard LDR/STR mnemonics when the immediate offset is
7343    unambiguous, i.e. when it is negative or unaligned.  */
7344
7345 static bfd_boolean
7346 try_to_encode_as_unscaled_ldst (aarch64_inst *instr)
7347 {
7348   int idx;
7349   enum aarch64_op new_op;
7350   const aarch64_opcode *new_opcode;
7351
7352   gas_assert (instr->opcode->iclass == ldst_pos);
7353
7354   switch (instr->opcode->op)
7355     {
7356     case OP_LDRB_POS:new_op = OP_LDURB; break;
7357     case OP_STRB_POS: new_op = OP_STURB; break;
7358     case OP_LDRSB_POS: new_op = OP_LDURSB; break;
7359     case OP_LDRH_POS: new_op = OP_LDURH; break;
7360     case OP_STRH_POS: new_op = OP_STURH; break;
7361     case OP_LDRSH_POS: new_op = OP_LDURSH; break;
7362     case OP_LDR_POS: new_op = OP_LDUR; break;
7363     case OP_STR_POS: new_op = OP_STUR; break;
7364     case OP_LDRF_POS: new_op = OP_LDURV; break;
7365     case OP_STRF_POS: new_op = OP_STURV; break;
7366     case OP_LDRSW_POS: new_op = OP_LDURSW; break;
7367     case OP_PRFM_POS: new_op = OP_PRFUM; break;
7368     default: new_op = OP_NIL; break;
7369     }
7370
7371   if (new_op == OP_NIL)
7372     return FALSE;
7373
7374   new_opcode = aarch64_get_opcode (new_op);
7375   gas_assert (new_opcode != NULL);
7376
7377   DEBUG_TRACE ("Check programmer-friendly STURB/LDURB -> STRB/LDRB: %d == %d",
7378                instr->opcode->op, new_opcode->op);
7379
7380   aarch64_replace_opcode (instr, new_opcode);
7381
7382   /* Clear up the ADDR_SIMM9's qualifier; otherwise the
7383      qualifier matching may fail because the out-of-date qualifier will
7384      prevent the operand being updated with a new and correct qualifier.  */
7385   idx = aarch64_operand_index (instr->opcode->operands,
7386                                AARCH64_OPND_ADDR_SIMM9);
7387   gas_assert (idx == 1);
7388   instr->operands[idx].qualifier = AARCH64_OPND_QLF_NIL;
7389
7390   DEBUG_TRACE ("Found LDURB entry to encode programmer-friendly LDRB");
7391
7392   if (!aarch64_opcode_encode (instr->opcode, instr, &instr->value, NULL, NULL,
7393                               insn_sequence))
7394     return FALSE;
7395
7396   return TRUE;
7397 }
7398
7399 /* Called by fix_insn to fix a MOV immediate alias instruction.
7400
7401    Operand for a generic move immediate instruction, which is an alias
7402    instruction that generates a single MOVZ, MOVN or ORR instruction to loads
7403    a 32-bit/64-bit immediate value into general register.  An assembler error
7404    shall result if the immediate cannot be created by a single one of these
7405    instructions. If there is a choice, then to ensure reversability an
7406    assembler must prefer a MOVZ to MOVN, and MOVZ or MOVN to ORR.  */
7407
7408 static void
7409 fix_mov_imm_insn (fixS *fixP, char *buf, aarch64_inst *instr, offsetT value)
7410 {
7411   const aarch64_opcode *opcode;
7412
7413   /* Need to check if the destination is SP/ZR.  The check has to be done
7414      before any aarch64_replace_opcode.  */
7415   int try_mov_wide_p = !aarch64_stack_pointer_p (&instr->operands[0]);
7416   int try_mov_bitmask_p = !aarch64_zero_register_p (&instr->operands[0]);
7417
7418   instr->operands[1].imm.value = value;
7419   instr->operands[1].skip = 0;
7420
7421   if (try_mov_wide_p)
7422     {
7423       /* Try the MOVZ alias.  */
7424       opcode = aarch64_get_opcode (OP_MOV_IMM_WIDE);
7425       aarch64_replace_opcode (instr, opcode);
7426       if (aarch64_opcode_encode (instr->opcode, instr,
7427                                  &instr->value, NULL, NULL, insn_sequence))
7428         {
7429           put_aarch64_insn (buf, instr->value);
7430           return;
7431         }
7432       /* Try the MOVK alias.  */
7433       opcode = aarch64_get_opcode (OP_MOV_IMM_WIDEN);
7434       aarch64_replace_opcode (instr, opcode);
7435       if (aarch64_opcode_encode (instr->opcode, instr,
7436                                  &instr->value, NULL, NULL, insn_sequence))
7437         {
7438           put_aarch64_insn (buf, instr->value);
7439           return;
7440         }
7441     }
7442
7443   if (try_mov_bitmask_p)
7444     {
7445       /* Try the ORR alias.  */
7446       opcode = aarch64_get_opcode (OP_MOV_IMM_LOG);
7447       aarch64_replace_opcode (instr, opcode);
7448       if (aarch64_opcode_encode (instr->opcode, instr,
7449                                  &instr->value, NULL, NULL, insn_sequence))
7450         {
7451           put_aarch64_insn (buf, instr->value);
7452           return;
7453         }
7454     }
7455
7456   as_bad_where (fixP->fx_file, fixP->fx_line,
7457                 _("immediate cannot be moved by a single instruction"));
7458 }
7459
7460 /* An instruction operand which is immediate related may have symbol used
7461    in the assembly, e.g.
7462
7463      mov     w0, u32
7464      .set    u32,    0x00ffff00
7465
7466    At the time when the assembly instruction is parsed, a referenced symbol,
7467    like 'u32' in the above example may not have been seen; a fixS is created
7468    in such a case and is handled here after symbols have been resolved.
7469    Instruction is fixed up with VALUE using the information in *FIXP plus
7470    extra information in FLAGS.
7471
7472    This function is called by md_apply_fix to fix up instructions that need
7473    a fix-up described above but does not involve any linker-time relocation.  */
7474
7475 static void
7476 fix_insn (fixS *fixP, uint32_t flags, offsetT value)
7477 {
7478   int idx;
7479   uint32_t insn;
7480   char *buf = fixP->fx_where + fixP->fx_frag->fr_literal;
7481   enum aarch64_opnd opnd = fixP->tc_fix_data.opnd;
7482   aarch64_inst *new_inst = fixP->tc_fix_data.inst;
7483
7484   if (new_inst)
7485     {
7486       /* Now the instruction is about to be fixed-up, so the operand that
7487          was previously marked as 'ignored' needs to be unmarked in order
7488          to get the encoding done properly.  */
7489       idx = aarch64_operand_index (new_inst->opcode->operands, opnd);
7490       new_inst->operands[idx].skip = 0;
7491     }
7492
7493   gas_assert (opnd != AARCH64_OPND_NIL);
7494
7495   switch (opnd)
7496     {
7497     case AARCH64_OPND_EXCEPTION:
7498       if (unsigned_overflow (value, 16))
7499         as_bad_where (fixP->fx_file, fixP->fx_line,
7500                       _("immediate out of range"));
7501       insn = get_aarch64_insn (buf);
7502       insn |= encode_svc_imm (value);
7503       put_aarch64_insn (buf, insn);
7504       break;
7505
7506     case AARCH64_OPND_AIMM:
7507       /* ADD or SUB with immediate.
7508          NOTE this assumes we come here with a add/sub shifted reg encoding
7509                   3  322|2222|2  2  2 21111 111111
7510                   1  098|7654|3  2  1 09876 543210 98765 43210
7511          0b000000 sf 000|1011|shift 0 Rm    imm6   Rn    Rd    ADD
7512          2b000000 sf 010|1011|shift 0 Rm    imm6   Rn    Rd    ADDS
7513          4b000000 sf 100|1011|shift 0 Rm    imm6   Rn    Rd    SUB
7514          6b000000 sf 110|1011|shift 0 Rm    imm6   Rn    Rd    SUBS
7515          ->
7516                   3  322|2222|2 2   221111111111
7517                   1  098|7654|3 2   109876543210 98765 43210
7518          11000000 sf 001|0001|shift imm12        Rn    Rd    ADD
7519          31000000 sf 011|0001|shift imm12        Rn    Rd    ADDS
7520          51000000 sf 101|0001|shift imm12        Rn    Rd    SUB
7521          71000000 sf 111|0001|shift imm12        Rn    Rd    SUBS
7522          Fields sf Rn Rd are already set.  */
7523       insn = get_aarch64_insn (buf);
7524       if (value < 0)
7525         {
7526           /* Add <-> sub.  */
7527           insn = reencode_addsub_switch_add_sub (insn);
7528           value = -value;
7529         }
7530
7531       if ((flags & FIXUP_F_HAS_EXPLICIT_SHIFT) == 0
7532           && unsigned_overflow (value, 12))
7533         {
7534           /* Try to shift the value by 12 to make it fit.  */
7535           if (((value >> 12) << 12) == value
7536               && ! unsigned_overflow (value, 12 + 12))
7537             {
7538               value >>= 12;
7539               insn |= encode_addsub_imm_shift_amount (1);
7540             }
7541         }
7542
7543       if (unsigned_overflow (value, 12))
7544         as_bad_where (fixP->fx_file, fixP->fx_line,
7545                       _("immediate out of range"));
7546
7547       insn |= encode_addsub_imm (value);
7548
7549       put_aarch64_insn (buf, insn);
7550       break;
7551
7552     case AARCH64_OPND_SIMD_IMM:
7553     case AARCH64_OPND_SIMD_IMM_SFT:
7554     case AARCH64_OPND_LIMM:
7555       /* Bit mask immediate.  */
7556       gas_assert (new_inst != NULL);
7557       idx = aarch64_operand_index (new_inst->opcode->operands, opnd);
7558       new_inst->operands[idx].imm.value = value;
7559       if (aarch64_opcode_encode (new_inst->opcode, new_inst,
7560                                  &new_inst->value, NULL, NULL, insn_sequence))
7561         put_aarch64_insn (buf, new_inst->value);
7562       else
7563         as_bad_where (fixP->fx_file, fixP->fx_line,
7564                       _("invalid immediate"));
7565       break;
7566
7567     case AARCH64_OPND_HALF:
7568       /* 16-bit unsigned immediate.  */
7569       if (unsigned_overflow (value, 16))
7570         as_bad_where (fixP->fx_file, fixP->fx_line,
7571                       _("immediate out of range"));
7572       insn = get_aarch64_insn (buf);
7573       insn |= encode_movw_imm (value & 0xffff);
7574       put_aarch64_insn (buf, insn);
7575       break;
7576
7577     case AARCH64_OPND_IMM_MOV:
7578       /* Operand for a generic move immediate instruction, which is
7579          an alias instruction that generates a single MOVZ, MOVN or ORR
7580          instruction to loads a 32-bit/64-bit immediate value into general
7581          register.  An assembler error shall result if the immediate cannot be
7582          created by a single one of these instructions. If there is a choice,
7583          then to ensure reversability an assembler must prefer a MOVZ to MOVN,
7584          and MOVZ or MOVN to ORR.  */
7585       gas_assert (new_inst != NULL);
7586       fix_mov_imm_insn (fixP, buf, new_inst, value);
7587       break;
7588
7589     case AARCH64_OPND_ADDR_SIMM7:
7590     case AARCH64_OPND_ADDR_SIMM9:
7591     case AARCH64_OPND_ADDR_SIMM9_2:
7592     case AARCH64_OPND_ADDR_SIMM10:
7593     case AARCH64_OPND_ADDR_UIMM12:
7594       /* Immediate offset in an address.  */
7595       insn = get_aarch64_insn (buf);
7596
7597       gas_assert (new_inst != NULL && new_inst->value == insn);
7598       gas_assert (new_inst->opcode->operands[1] == opnd
7599                   || new_inst->opcode->operands[2] == opnd);
7600
7601       /* Get the index of the address operand.  */
7602       if (new_inst->opcode->operands[1] == opnd)
7603         /* e.g. STR <Xt>, [<Xn|SP>, <R><m>{, <extend> {<amount>}}].  */
7604         idx = 1;
7605       else
7606         /* e.g. LDP <Qt1>, <Qt2>, [<Xn|SP>{, #<imm>}].  */
7607         idx = 2;
7608
7609       /* Update the resolved offset value.  */
7610       new_inst->operands[idx].addr.offset.imm = value;
7611
7612       /* Encode/fix-up.  */
7613       if (aarch64_opcode_encode (new_inst->opcode, new_inst,
7614                                  &new_inst->value, NULL, NULL, insn_sequence))
7615         {
7616           put_aarch64_insn (buf, new_inst->value);
7617           break;
7618         }
7619       else if (new_inst->opcode->iclass == ldst_pos
7620                && try_to_encode_as_unscaled_ldst (new_inst))
7621         {
7622           put_aarch64_insn (buf, new_inst->value);
7623           break;
7624         }
7625
7626       as_bad_where (fixP->fx_file, fixP->fx_line,
7627                     _("immediate offset out of range"));
7628       break;
7629
7630     default:
7631       gas_assert (0);
7632       as_fatal (_("unhandled operand code %d"), opnd);
7633     }
7634 }
7635
7636 /* Apply a fixup (fixP) to segment data, once it has been determined
7637    by our caller that we have all the info we need to fix it up.
7638
7639    Parameter valP is the pointer to the value of the bits.  */
7640
7641 void
7642 md_apply_fix (fixS * fixP, valueT * valP, segT seg)
7643 {
7644   offsetT value = *valP;
7645   uint32_t insn;
7646   char *buf = fixP->fx_where + fixP->fx_frag->fr_literal;
7647   int scale;
7648   unsigned flags = fixP->fx_addnumber;
7649
7650   DEBUG_TRACE ("\n\n");
7651   DEBUG_TRACE ("~~~~~~~~~~~~~~~~~~~~~~~~~");
7652   DEBUG_TRACE ("Enter md_apply_fix");
7653
7654   gas_assert (fixP->fx_r_type <= BFD_RELOC_UNUSED);
7655
7656   /* Note whether this will delete the relocation.  */
7657
7658   if (fixP->fx_addsy == 0 && !fixP->fx_pcrel)
7659     fixP->fx_done = 1;
7660
7661   /* Process the relocations.  */
7662   switch (fixP->fx_r_type)
7663     {
7664     case BFD_RELOC_NONE:
7665       /* This will need to go in the object file.  */
7666       fixP->fx_done = 0;
7667       break;
7668
7669     case BFD_RELOC_8:
7670     case BFD_RELOC_8_PCREL:
7671       if (fixP->fx_done || !seg->use_rela_p)
7672         md_number_to_chars (buf, value, 1);
7673       break;
7674
7675     case BFD_RELOC_16:
7676     case BFD_RELOC_16_PCREL:
7677       if (fixP->fx_done || !seg->use_rela_p)
7678         md_number_to_chars (buf, value, 2);
7679       break;
7680
7681     case BFD_RELOC_32:
7682     case BFD_RELOC_32_PCREL:
7683       if (fixP->fx_done || !seg->use_rela_p)
7684         md_number_to_chars (buf, value, 4);
7685       break;
7686
7687     case BFD_RELOC_64:
7688     case BFD_RELOC_64_PCREL:
7689       if (fixP->fx_done || !seg->use_rela_p)
7690         md_number_to_chars (buf, value, 8);
7691       break;
7692
7693     case BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP:
7694       /* We claim that these fixups have been processed here, even if
7695          in fact we generate an error because we do not have a reloc
7696          for them, so tc_gen_reloc() will reject them.  */
7697       fixP->fx_done = 1;
7698       if (fixP->fx_addsy && !S_IS_DEFINED (fixP->fx_addsy))
7699         {
7700           as_bad_where (fixP->fx_file, fixP->fx_line,
7701                         _("undefined symbol %s used as an immediate value"),
7702                         S_GET_NAME (fixP->fx_addsy));
7703           goto apply_fix_return;
7704         }
7705       fix_insn (fixP, flags, value);
7706       break;
7707
7708     case BFD_RELOC_AARCH64_LD_LO19_PCREL:
7709       if (fixP->fx_done || !seg->use_rela_p)
7710         {
7711           if (value & 3)
7712             as_bad_where (fixP->fx_file, fixP->fx_line,
7713                           _("pc-relative load offset not word aligned"));
7714           if (signed_overflow (value, 21))
7715             as_bad_where (fixP->fx_file, fixP->fx_line,
7716                           _("pc-relative load offset out of range"));
7717           insn = get_aarch64_insn (buf);
7718           insn |= encode_ld_lit_ofs_19 (value >> 2);
7719           put_aarch64_insn (buf, insn);
7720         }
7721       break;
7722
7723     case BFD_RELOC_AARCH64_ADR_LO21_PCREL:
7724       if (fixP->fx_done || !seg->use_rela_p)
7725         {
7726           if (signed_overflow (value, 21))
7727             as_bad_where (fixP->fx_file, fixP->fx_line,
7728                           _("pc-relative address offset out of range"));
7729           insn = get_aarch64_insn (buf);
7730           insn |= encode_adr_imm (value);
7731           put_aarch64_insn (buf, insn);
7732         }
7733       break;
7734
7735     case BFD_RELOC_AARCH64_BRANCH19:
7736       if (fixP->fx_done || !seg->use_rela_p)
7737         {
7738           if (value & 3)
7739             as_bad_where (fixP->fx_file, fixP->fx_line,
7740                           _("conditional branch target not word aligned"));
7741           if (signed_overflow (value, 21))
7742             as_bad_where (fixP->fx_file, fixP->fx_line,
7743                           _("conditional branch out of range"));
7744           insn = get_aarch64_insn (buf);
7745           insn |= encode_cond_branch_ofs_19 (value >> 2);
7746           put_aarch64_insn (buf, insn);
7747         }
7748       break;
7749
7750     case BFD_RELOC_AARCH64_TSTBR14:
7751       if (fixP->fx_done || !seg->use_rela_p)
7752         {
7753           if (value & 3)
7754             as_bad_where (fixP->fx_file, fixP->fx_line,
7755                           _("conditional branch target not word aligned"));
7756           if (signed_overflow (value, 16))
7757             as_bad_where (fixP->fx_file, fixP->fx_line,
7758                           _("conditional branch out of range"));
7759           insn = get_aarch64_insn (buf);
7760           insn |= encode_tst_branch_ofs_14 (value >> 2);
7761           put_aarch64_insn (buf, insn);
7762         }
7763       break;
7764
7765     case BFD_RELOC_AARCH64_CALL26:
7766     case BFD_RELOC_AARCH64_JUMP26:
7767       if (fixP->fx_done || !seg->use_rela_p)
7768         {
7769           if (value & 3)
7770             as_bad_where (fixP->fx_file, fixP->fx_line,
7771                           _("branch target not word aligned"));
7772           if (signed_overflow (value, 28))
7773             as_bad_where (fixP->fx_file, fixP->fx_line,
7774                           _("branch out of range"));
7775           insn = get_aarch64_insn (buf);
7776           insn |= encode_branch_ofs_26 (value >> 2);
7777           put_aarch64_insn (buf, insn);
7778         }
7779       break;
7780
7781     case BFD_RELOC_AARCH64_MOVW_G0:
7782     case BFD_RELOC_AARCH64_MOVW_G0_NC:
7783     case BFD_RELOC_AARCH64_MOVW_G0_S:
7784     case BFD_RELOC_AARCH64_MOVW_GOTOFF_G0_NC:
7785     case BFD_RELOC_AARCH64_MOVW_PREL_G0:
7786     case BFD_RELOC_AARCH64_MOVW_PREL_G0_NC:
7787       scale = 0;
7788       goto movw_common;
7789     case BFD_RELOC_AARCH64_MOVW_G1:
7790     case BFD_RELOC_AARCH64_MOVW_G1_NC:
7791     case BFD_RELOC_AARCH64_MOVW_G1_S:
7792     case BFD_RELOC_AARCH64_MOVW_GOTOFF_G1:
7793     case BFD_RELOC_AARCH64_MOVW_PREL_G1:
7794     case BFD_RELOC_AARCH64_MOVW_PREL_G1_NC:
7795       scale = 16;
7796       goto movw_common;
7797     case BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC:
7798       scale = 0;
7799       S_SET_THREAD_LOCAL (fixP->fx_addsy);
7800       /* Should always be exported to object file, see
7801          aarch64_force_relocation().  */
7802       gas_assert (!fixP->fx_done);
7803       gas_assert (seg->use_rela_p);
7804       goto movw_common;
7805     case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
7806       scale = 16;
7807       S_SET_THREAD_LOCAL (fixP->fx_addsy);
7808       /* Should always be exported to object file, see
7809          aarch64_force_relocation().  */
7810       gas_assert (!fixP->fx_done);
7811       gas_assert (seg->use_rela_p);
7812       goto movw_common;
7813     case BFD_RELOC_AARCH64_MOVW_G2:
7814     case BFD_RELOC_AARCH64_MOVW_G2_NC:
7815     case BFD_RELOC_AARCH64_MOVW_G2_S:
7816     case BFD_RELOC_AARCH64_MOVW_PREL_G2:
7817     case BFD_RELOC_AARCH64_MOVW_PREL_G2_NC:
7818       scale = 32;
7819       goto movw_common;
7820     case BFD_RELOC_AARCH64_MOVW_G3:
7821     case BFD_RELOC_AARCH64_MOVW_PREL_G3:
7822       scale = 48;
7823     movw_common:
7824       if (fixP->fx_done || !seg->use_rela_p)
7825         {
7826           insn = get_aarch64_insn (buf);
7827
7828           if (!fixP->fx_done)
7829             {
7830               /* REL signed addend must fit in 16 bits */
7831               if (signed_overflow (value, 16))
7832                 as_bad_where (fixP->fx_file, fixP->fx_line,
7833                               _("offset out of range"));
7834             }
7835           else
7836             {
7837               /* Check for overflow and scale. */
7838               switch (fixP->fx_r_type)
7839                 {
7840                 case BFD_RELOC_AARCH64_MOVW_G0:
7841                 case BFD_RELOC_AARCH64_MOVW_G1:
7842                 case BFD_RELOC_AARCH64_MOVW_G2:
7843                 case BFD_RELOC_AARCH64_MOVW_G3:
7844                 case BFD_RELOC_AARCH64_MOVW_GOTOFF_G1:
7845                 case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
7846                   if (unsigned_overflow (value, scale + 16))
7847                     as_bad_where (fixP->fx_file, fixP->fx_line,
7848                                   _("unsigned value out of range"));
7849                   break;
7850                 case BFD_RELOC_AARCH64_MOVW_G0_S:
7851                 case BFD_RELOC_AARCH64_MOVW_G1_S:
7852                 case BFD_RELOC_AARCH64_MOVW_G2_S:
7853                 case BFD_RELOC_AARCH64_MOVW_PREL_G0:
7854                 case BFD_RELOC_AARCH64_MOVW_PREL_G1:
7855                 case BFD_RELOC_AARCH64_MOVW_PREL_G2:
7856                   /* NOTE: We can only come here with movz or movn. */
7857                   if (signed_overflow (value, scale + 16))
7858                     as_bad_where (fixP->fx_file, fixP->fx_line,
7859                                   _("signed value out of range"));
7860                   if (value < 0)
7861                     {
7862                       /* Force use of MOVN.  */
7863                       value = ~value;
7864                       insn = reencode_movzn_to_movn (insn);
7865                     }
7866                   else
7867                     {
7868                       /* Force use of MOVZ.  */
7869                       insn = reencode_movzn_to_movz (insn);
7870                     }
7871                   break;
7872                 default:
7873                   /* Unchecked relocations.  */
7874                   break;
7875                 }
7876               value >>= scale;
7877             }
7878
7879           /* Insert value into MOVN/MOVZ/MOVK instruction. */
7880           insn |= encode_movw_imm (value & 0xffff);
7881
7882           put_aarch64_insn (buf, insn);
7883         }
7884       break;
7885
7886     case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_LO12_NC:
7887       fixP->fx_r_type = (ilp32_p
7888                          ? BFD_RELOC_AARCH64_TLSIE_LD32_GOTTPREL_LO12_NC
7889                          : BFD_RELOC_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC);
7890       S_SET_THREAD_LOCAL (fixP->fx_addsy);
7891       /* Should always be exported to object file, see
7892          aarch64_force_relocation().  */
7893       gas_assert (!fixP->fx_done);
7894       gas_assert (seg->use_rela_p);
7895       break;
7896
7897     case BFD_RELOC_AARCH64_TLSDESC_LD_LO12_NC:
7898       fixP->fx_r_type = (ilp32_p
7899                          ? BFD_RELOC_AARCH64_TLSDESC_LD32_LO12_NC
7900                          : BFD_RELOC_AARCH64_TLSDESC_LD64_LO12);
7901       S_SET_THREAD_LOCAL (fixP->fx_addsy);
7902       /* Should always be exported to object file, see
7903          aarch64_force_relocation().  */
7904       gas_assert (!fixP->fx_done);
7905       gas_assert (seg->use_rela_p);
7906       break;
7907
7908     case BFD_RELOC_AARCH64_TLSDESC_ADD_LO12:
7909     case BFD_RELOC_AARCH64_TLSDESC_ADR_PAGE21:
7910     case BFD_RELOC_AARCH64_TLSDESC_ADR_PREL21:
7911     case BFD_RELOC_AARCH64_TLSDESC_LD32_LO12_NC:
7912     case BFD_RELOC_AARCH64_TLSDESC_LD64_LO12:
7913     case BFD_RELOC_AARCH64_TLSDESC_LD_PREL19:
7914     case BFD_RELOC_AARCH64_TLSGD_ADD_LO12_NC:
7915     case BFD_RELOC_AARCH64_TLSGD_ADR_PAGE21:
7916     case BFD_RELOC_AARCH64_TLSGD_ADR_PREL21:
7917     case BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC:
7918     case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
7919     case BFD_RELOC_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
7920     case BFD_RELOC_AARCH64_TLSIE_LD32_GOTTPREL_LO12_NC:
7921     case BFD_RELOC_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
7922     case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_PREL19:
7923     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC:
7924     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1:
7925     case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_HI12:
7926     case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12:
7927     case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:
7928     case BFD_RELOC_AARCH64_TLSLD_ADD_LO12_NC:
7929     case BFD_RELOC_AARCH64_TLSLD_ADR_PAGE21:
7930     case BFD_RELOC_AARCH64_TLSLD_ADR_PREL21:
7931     case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12:
7932     case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC:
7933     case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12:
7934     case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC:
7935     case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12:
7936     case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC:
7937     case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12:
7938     case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC:
7939     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0:
7940     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
7941     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1:
7942     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC:
7943     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2:
7944     case BFD_RELOC_AARCH64_TLSLE_LDST16_TPREL_LO12:
7945     case BFD_RELOC_AARCH64_TLSLE_LDST16_TPREL_LO12_NC:
7946     case BFD_RELOC_AARCH64_TLSLE_LDST32_TPREL_LO12:
7947     case BFD_RELOC_AARCH64_TLSLE_LDST32_TPREL_LO12_NC:
7948     case BFD_RELOC_AARCH64_TLSLE_LDST64_TPREL_LO12:
7949     case BFD_RELOC_AARCH64_TLSLE_LDST64_TPREL_LO12_NC:
7950     case BFD_RELOC_AARCH64_TLSLE_LDST8_TPREL_LO12:
7951     case BFD_RELOC_AARCH64_TLSLE_LDST8_TPREL_LO12_NC:
7952     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12:
7953     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12:
7954     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
7955     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
7956     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
7957     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
7958     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
7959     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
7960       S_SET_THREAD_LOCAL (fixP->fx_addsy);
7961       /* Should always be exported to object file, see
7962          aarch64_force_relocation().  */
7963       gas_assert (!fixP->fx_done);
7964       gas_assert (seg->use_rela_p);
7965       break;
7966
7967     case BFD_RELOC_AARCH64_LD_GOT_LO12_NC:
7968       /* Should always be exported to object file, see
7969          aarch64_force_relocation().  */
7970       fixP->fx_r_type = (ilp32_p
7971                          ? BFD_RELOC_AARCH64_LD32_GOT_LO12_NC
7972                          : BFD_RELOC_AARCH64_LD64_GOT_LO12_NC);
7973       gas_assert (!fixP->fx_done);
7974       gas_assert (seg->use_rela_p);
7975       break;
7976
7977     case BFD_RELOC_AARCH64_ADD_LO12:
7978     case BFD_RELOC_AARCH64_ADR_GOT_PAGE:
7979     case BFD_RELOC_AARCH64_ADR_HI21_NC_PCREL:
7980     case BFD_RELOC_AARCH64_ADR_HI21_PCREL:
7981     case BFD_RELOC_AARCH64_GOT_LD_PREL19:
7982     case BFD_RELOC_AARCH64_LD32_GOT_LO12_NC:
7983     case BFD_RELOC_AARCH64_LD32_GOTPAGE_LO14:
7984     case BFD_RELOC_AARCH64_LD64_GOTOFF_LO15:
7985     case BFD_RELOC_AARCH64_LD64_GOTPAGE_LO15:
7986     case BFD_RELOC_AARCH64_LD64_GOT_LO12_NC:
7987     case BFD_RELOC_AARCH64_LDST128_LO12:
7988     case BFD_RELOC_AARCH64_LDST16_LO12:
7989     case BFD_RELOC_AARCH64_LDST32_LO12:
7990     case BFD_RELOC_AARCH64_LDST64_LO12:
7991     case BFD_RELOC_AARCH64_LDST8_LO12:
7992       /* Should always be exported to object file, see
7993          aarch64_force_relocation().  */
7994       gas_assert (!fixP->fx_done);
7995       gas_assert (seg->use_rela_p);
7996       break;
7997
7998     case BFD_RELOC_AARCH64_TLSDESC_ADD:
7999     case BFD_RELOC_AARCH64_TLSDESC_CALL:
8000     case BFD_RELOC_AARCH64_TLSDESC_LDR:
8001       break;
8002
8003     case BFD_RELOC_UNUSED:
8004       /* An error will already have been reported.  */
8005       break;
8006
8007     default:
8008       as_bad_where (fixP->fx_file, fixP->fx_line,
8009                     _("unexpected %s fixup"),
8010                     bfd_get_reloc_code_name (fixP->fx_r_type));
8011       break;
8012     }
8013
8014 apply_fix_return:
8015   /* Free the allocated the struct aarch64_inst.
8016      N.B. currently there are very limited number of fix-up types actually use
8017      this field, so the impact on the performance should be minimal .  */
8018   if (fixP->tc_fix_data.inst != NULL)
8019     free (fixP->tc_fix_data.inst);
8020
8021   return;
8022 }
8023
8024 /* Translate internal representation of relocation info to BFD target
8025    format.  */
8026
8027 arelent *
8028 tc_gen_reloc (asection * section, fixS * fixp)
8029 {
8030   arelent *reloc;
8031   bfd_reloc_code_real_type code;
8032
8033   reloc = XNEW (arelent);
8034
8035   reloc->sym_ptr_ptr = XNEW (asymbol *);
8036   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
8037   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
8038
8039   if (fixp->fx_pcrel)
8040     {
8041       if (section->use_rela_p)
8042         fixp->fx_offset -= md_pcrel_from_section (fixp, section);
8043       else
8044         fixp->fx_offset = reloc->address;
8045     }
8046   reloc->addend = fixp->fx_offset;
8047
8048   code = fixp->fx_r_type;
8049   switch (code)
8050     {
8051     case BFD_RELOC_16:
8052       if (fixp->fx_pcrel)
8053         code = BFD_RELOC_16_PCREL;
8054       break;
8055
8056     case BFD_RELOC_32:
8057       if (fixp->fx_pcrel)
8058         code = BFD_RELOC_32_PCREL;
8059       break;
8060
8061     case BFD_RELOC_64:
8062       if (fixp->fx_pcrel)
8063         code = BFD_RELOC_64_PCREL;
8064       break;
8065
8066     default:
8067       break;
8068     }
8069
8070   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
8071   if (reloc->howto == NULL)
8072     {
8073       as_bad_where (fixp->fx_file, fixp->fx_line,
8074                     _
8075                     ("cannot represent %s relocation in this object file format"),
8076                     bfd_get_reloc_code_name (code));
8077       return NULL;
8078     }
8079
8080   return reloc;
8081 }
8082
8083 /* This fix_new is called by cons via TC_CONS_FIX_NEW.  */
8084
8085 void
8086 cons_fix_new_aarch64 (fragS * frag, int where, int size, expressionS * exp)
8087 {
8088   bfd_reloc_code_real_type type;
8089   int pcrel = 0;
8090
8091   /* Pick a reloc.
8092      FIXME: @@ Should look at CPU word size.  */
8093   switch (size)
8094     {
8095     case 1:
8096       type = BFD_RELOC_8;
8097       break;
8098     case 2:
8099       type = BFD_RELOC_16;
8100       break;
8101     case 4:
8102       type = BFD_RELOC_32;
8103       break;
8104     case 8:
8105       type = BFD_RELOC_64;
8106       break;
8107     default:
8108       as_bad (_("cannot do %u-byte relocation"), size);
8109       type = BFD_RELOC_UNUSED;
8110       break;
8111     }
8112
8113   fix_new_exp (frag, where, (int) size, exp, pcrel, type);
8114 }
8115
8116 int
8117 aarch64_force_relocation (struct fix *fixp)
8118 {
8119   switch (fixp->fx_r_type)
8120     {
8121     case BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP:
8122       /* Perform these "immediate" internal relocations
8123          even if the symbol is extern or weak.  */
8124       return 0;
8125
8126     case BFD_RELOC_AARCH64_LD_GOT_LO12_NC:
8127     case BFD_RELOC_AARCH64_TLSDESC_LD_LO12_NC:
8128     case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_LO12_NC:
8129       /* Pseudo relocs that need to be fixed up according to
8130          ilp32_p.  */
8131       return 0;
8132
8133     case BFD_RELOC_AARCH64_ADD_LO12:
8134     case BFD_RELOC_AARCH64_ADR_GOT_PAGE:
8135     case BFD_RELOC_AARCH64_ADR_HI21_NC_PCREL:
8136     case BFD_RELOC_AARCH64_ADR_HI21_PCREL:
8137     case BFD_RELOC_AARCH64_GOT_LD_PREL19:
8138     case BFD_RELOC_AARCH64_LD32_GOT_LO12_NC:
8139     case BFD_RELOC_AARCH64_LD32_GOTPAGE_LO14:
8140     case BFD_RELOC_AARCH64_LD64_GOTOFF_LO15:
8141     case BFD_RELOC_AARCH64_LD64_GOTPAGE_LO15:
8142     case BFD_RELOC_AARCH64_LD64_GOT_LO12_NC:
8143     case BFD_RELOC_AARCH64_LDST128_LO12:
8144     case BFD_RELOC_AARCH64_LDST16_LO12:
8145     case BFD_RELOC_AARCH64_LDST32_LO12:
8146     case BFD_RELOC_AARCH64_LDST64_LO12:
8147     case BFD_RELOC_AARCH64_LDST8_LO12:
8148     case BFD_RELOC_AARCH64_TLSDESC_ADD_LO12:
8149     case BFD_RELOC_AARCH64_TLSDESC_ADR_PAGE21:
8150     case BFD_RELOC_AARCH64_TLSDESC_ADR_PREL21:
8151     case BFD_RELOC_AARCH64_TLSDESC_LD32_LO12_NC:
8152     case BFD_RELOC_AARCH64_TLSDESC_LD64_LO12:
8153     case BFD_RELOC_AARCH64_TLSDESC_LD_PREL19:
8154     case BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC:
8155     case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
8156     case BFD_RELOC_AARCH64_TLSGD_ADD_LO12_NC:
8157     case BFD_RELOC_AARCH64_TLSGD_ADR_PAGE21:
8158     case BFD_RELOC_AARCH64_TLSGD_ADR_PREL21:
8159     case BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC:
8160     case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
8161     case BFD_RELOC_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
8162     case BFD_RELOC_AARCH64_TLSIE_LD32_GOTTPREL_LO12_NC:
8163     case BFD_RELOC_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
8164     case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_PREL19:
8165     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC:
8166     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1:
8167    case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_HI12:
8168     case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12:
8169     case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:
8170     case BFD_RELOC_AARCH64_TLSLD_ADD_LO12_NC:
8171     case BFD_RELOC_AARCH64_TLSLD_ADR_PAGE21:
8172     case BFD_RELOC_AARCH64_TLSLD_ADR_PREL21:
8173     case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12:
8174     case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC:
8175     case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12:
8176     case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC:
8177     case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12:
8178     case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC:
8179     case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12:
8180     case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC:
8181     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0:
8182     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
8183     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1:
8184     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC:
8185     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2:
8186     case BFD_RELOC_AARCH64_TLSLE_LDST16_TPREL_LO12:
8187     case BFD_RELOC_AARCH64_TLSLE_LDST16_TPREL_LO12_NC:
8188     case BFD_RELOC_AARCH64_TLSLE_LDST32_TPREL_LO12:
8189     case BFD_RELOC_AARCH64_TLSLE_LDST32_TPREL_LO12_NC:
8190     case BFD_RELOC_AARCH64_TLSLE_LDST64_TPREL_LO12:
8191     case BFD_RELOC_AARCH64_TLSLE_LDST64_TPREL_LO12_NC:
8192     case BFD_RELOC_AARCH64_TLSLE_LDST8_TPREL_LO12:
8193     case BFD_RELOC_AARCH64_TLSLE_LDST8_TPREL_LO12_NC:
8194     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12:
8195     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12:
8196     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
8197     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
8198     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
8199     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
8200     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
8201     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
8202       /* Always leave these relocations for the linker.  */
8203       return 1;
8204
8205     default:
8206       break;
8207     }
8208
8209   return generic_force_reloc (fixp);
8210 }
8211
8212 #ifdef OBJ_ELF
8213
8214 /* Implement md_after_parse_args.  This is the earliest time we need to decide
8215    ABI.  If no -mabi specified, the ABI will be decided by target triplet.  */
8216
8217 void
8218 aarch64_after_parse_args (void)
8219 {
8220   if (aarch64_abi != AARCH64_ABI_NONE)
8221     return;
8222
8223   /* DEFAULT_ARCH will have ":32" extension if it's configured for ILP32.  */
8224   if (strlen (default_arch) > 7 && strcmp (default_arch + 7, ":32") == 0)
8225     aarch64_abi = AARCH64_ABI_ILP32;
8226   else
8227     aarch64_abi = AARCH64_ABI_LP64;
8228 }
8229
8230 const char *
8231 elf64_aarch64_target_format (void)
8232 {
8233   if (strcmp (TARGET_OS, "cloudabi") == 0)
8234     {
8235       /* FIXME: What to do for ilp32_p ?  */
8236       return target_big_endian ? "elf64-bigaarch64-cloudabi" : "elf64-littleaarch64-cloudabi";
8237     }
8238   if (target_big_endian)
8239     return ilp32_p ? "elf32-bigaarch64" : "elf64-bigaarch64";
8240   else
8241     return ilp32_p ? "elf32-littleaarch64" : "elf64-littleaarch64";
8242 }
8243
8244 void
8245 aarch64elf_frob_symbol (symbolS * symp, int *puntp)
8246 {
8247   elf_frob_symbol (symp, puntp);
8248 }
8249 #endif
8250
8251 /* MD interface: Finalization.  */
8252
8253 /* A good place to do this, although this was probably not intended
8254    for this kind of use.  We need to dump the literal pool before
8255    references are made to a null symbol pointer.  */
8256
8257 void
8258 aarch64_cleanup (void)
8259 {
8260   literal_pool *pool;
8261
8262   for (pool = list_of_pools; pool; pool = pool->next)
8263     {
8264       /* Put it at the end of the relevant section.  */
8265       subseg_set (pool->section, pool->sub_section);
8266       s_ltorg (0);
8267     }
8268 }
8269
8270 #ifdef OBJ_ELF
8271 /* Remove any excess mapping symbols generated for alignment frags in
8272    SEC.  We may have created a mapping symbol before a zero byte
8273    alignment; remove it if there's a mapping symbol after the
8274    alignment.  */
8275 static void
8276 check_mapping_symbols (bfd * abfd ATTRIBUTE_UNUSED, asection * sec,
8277                        void *dummy ATTRIBUTE_UNUSED)
8278 {
8279   segment_info_type *seginfo = seg_info (sec);
8280   fragS *fragp;
8281
8282   if (seginfo == NULL || seginfo->frchainP == NULL)
8283     return;
8284
8285   for (fragp = seginfo->frchainP->frch_root;
8286        fragp != NULL; fragp = fragp->fr_next)
8287     {
8288       symbolS *sym = fragp->tc_frag_data.last_map;
8289       fragS *next = fragp->fr_next;
8290
8291       /* Variable-sized frags have been converted to fixed size by
8292          this point.  But if this was variable-sized to start with,
8293          there will be a fixed-size frag after it.  So don't handle
8294          next == NULL.  */
8295       if (sym == NULL || next == NULL)
8296         continue;
8297
8298       if (S_GET_VALUE (sym) < next->fr_address)
8299         /* Not at the end of this frag.  */
8300         continue;
8301       know (S_GET_VALUE (sym) == next->fr_address);
8302
8303       do
8304         {
8305           if (next->tc_frag_data.first_map != NULL)
8306             {
8307               /* Next frag starts with a mapping symbol.  Discard this
8308                  one.  */
8309               symbol_remove (sym, &symbol_rootP, &symbol_lastP);
8310               break;
8311             }
8312
8313           if (next->fr_next == NULL)
8314             {
8315               /* This mapping symbol is at the end of the section.  Discard
8316                  it.  */
8317               know (next->fr_fix == 0 && next->fr_var == 0);
8318               symbol_remove (sym, &symbol_rootP, &symbol_lastP);
8319               break;
8320             }
8321
8322           /* As long as we have empty frags without any mapping symbols,
8323              keep looking.  */
8324           /* If the next frag is non-empty and does not start with a
8325              mapping symbol, then this mapping symbol is required.  */
8326           if (next->fr_address != next->fr_next->fr_address)
8327             break;
8328
8329           next = next->fr_next;
8330         }
8331       while (next != NULL);
8332     }
8333 }
8334 #endif
8335
8336 /* Adjust the symbol table.  */
8337
8338 void
8339 aarch64_adjust_symtab (void)
8340 {
8341 #ifdef OBJ_ELF
8342   /* Remove any overlapping mapping symbols generated by alignment frags.  */
8343   bfd_map_over_sections (stdoutput, check_mapping_symbols, (char *) 0);
8344   /* Now do generic ELF adjustments.  */
8345   elf_adjust_symtab ();
8346 #endif
8347 }
8348
8349 static void
8350 checked_hash_insert (struct hash_control *table, const char *key, void *value)
8351 {
8352   const char *hash_err;
8353
8354   hash_err = hash_insert (table, key, value);
8355   if (hash_err)
8356     printf ("Internal Error:  Can't hash %s\n", key);
8357 }
8358
8359 static void
8360 fill_instruction_hash_table (void)
8361 {
8362   aarch64_opcode *opcode = aarch64_opcode_table;
8363
8364   while (opcode->name != NULL)
8365     {
8366       templates *templ, *new_templ;
8367       templ = hash_find (aarch64_ops_hsh, opcode->name);
8368
8369       new_templ = XNEW (templates);
8370       new_templ->opcode = opcode;
8371       new_templ->next = NULL;
8372
8373       if (!templ)
8374         checked_hash_insert (aarch64_ops_hsh, opcode->name, (void *) new_templ);
8375       else
8376         {
8377           new_templ->next = templ->next;
8378           templ->next = new_templ;
8379         }
8380       ++opcode;
8381     }
8382 }
8383
8384 static inline void
8385 convert_to_upper (char *dst, const char *src, size_t num)
8386 {
8387   unsigned int i;
8388   for (i = 0; i < num && *src != '\0'; ++i, ++dst, ++src)
8389     *dst = TOUPPER (*src);
8390   *dst = '\0';
8391 }
8392
8393 /* Assume STR point to a lower-case string, allocate, convert and return
8394    the corresponding upper-case string.  */
8395 static inline const char*
8396 get_upper_str (const char *str)
8397 {
8398   char *ret;
8399   size_t len = strlen (str);
8400   ret = XNEWVEC (char, len + 1);
8401   convert_to_upper (ret, str, len);
8402   return ret;
8403 }
8404
8405 /* MD interface: Initialization.  */
8406
8407 void
8408 md_begin (void)
8409 {
8410   unsigned mach;
8411   unsigned int i;
8412
8413   if ((aarch64_ops_hsh = hash_new ()) == NULL
8414       || (aarch64_cond_hsh = hash_new ()) == NULL
8415       || (aarch64_shift_hsh = hash_new ()) == NULL
8416       || (aarch64_sys_regs_hsh = hash_new ()) == NULL
8417       || (aarch64_pstatefield_hsh = hash_new ()) == NULL
8418       || (aarch64_sys_regs_ic_hsh = hash_new ()) == NULL
8419       || (aarch64_sys_regs_dc_hsh = hash_new ()) == NULL
8420       || (aarch64_sys_regs_at_hsh = hash_new ()) == NULL
8421       || (aarch64_sys_regs_tlbi_hsh = hash_new ()) == NULL
8422       || (aarch64_reg_hsh = hash_new ()) == NULL
8423       || (aarch64_barrier_opt_hsh = hash_new ()) == NULL
8424       || (aarch64_nzcv_hsh = hash_new ()) == NULL
8425       || (aarch64_pldop_hsh = hash_new ()) == NULL
8426       || (aarch64_hint_opt_hsh = hash_new ()) == NULL)
8427     as_fatal (_("virtual memory exhausted"));
8428
8429   fill_instruction_hash_table ();
8430
8431   for (i = 0; aarch64_sys_regs[i].name != NULL; ++i)
8432     checked_hash_insert (aarch64_sys_regs_hsh, aarch64_sys_regs[i].name,
8433                          (void *) (aarch64_sys_regs + i));
8434
8435   for (i = 0; aarch64_pstatefields[i].name != NULL; ++i)
8436     checked_hash_insert (aarch64_pstatefield_hsh,
8437                          aarch64_pstatefields[i].name,
8438                          (void *) (aarch64_pstatefields + i));
8439
8440   for (i = 0; aarch64_sys_regs_ic[i].name != NULL; i++)
8441     checked_hash_insert (aarch64_sys_regs_ic_hsh,
8442                          aarch64_sys_regs_ic[i].name,
8443                          (void *) (aarch64_sys_regs_ic + i));
8444
8445   for (i = 0; aarch64_sys_regs_dc[i].name != NULL; i++)
8446     checked_hash_insert (aarch64_sys_regs_dc_hsh,
8447                          aarch64_sys_regs_dc[i].name,
8448                          (void *) (aarch64_sys_regs_dc + i));
8449
8450   for (i = 0; aarch64_sys_regs_at[i].name != NULL; i++)
8451     checked_hash_insert (aarch64_sys_regs_at_hsh,
8452                          aarch64_sys_regs_at[i].name,
8453                          (void *) (aarch64_sys_regs_at + i));
8454
8455   for (i = 0; aarch64_sys_regs_tlbi[i].name != NULL; i++)
8456     checked_hash_insert (aarch64_sys_regs_tlbi_hsh,
8457                          aarch64_sys_regs_tlbi[i].name,
8458                          (void *) (aarch64_sys_regs_tlbi + i));
8459
8460   for (i = 0; i < ARRAY_SIZE (reg_names); i++)
8461     checked_hash_insert (aarch64_reg_hsh, reg_names[i].name,
8462                          (void *) (reg_names + i));
8463
8464   for (i = 0; i < ARRAY_SIZE (nzcv_names); i++)
8465     checked_hash_insert (aarch64_nzcv_hsh, nzcv_names[i].template,
8466                          (void *) (nzcv_names + i));
8467
8468   for (i = 0; aarch64_operand_modifiers[i].name != NULL; i++)
8469     {
8470       const char *name = aarch64_operand_modifiers[i].name;
8471       checked_hash_insert (aarch64_shift_hsh, name,
8472                            (void *) (aarch64_operand_modifiers + i));
8473       /* Also hash the name in the upper case.  */
8474       checked_hash_insert (aarch64_shift_hsh, get_upper_str (name),
8475                            (void *) (aarch64_operand_modifiers + i));
8476     }
8477
8478   for (i = 0; i < ARRAY_SIZE (aarch64_conds); i++)
8479     {
8480       unsigned int j;
8481       /* A condition code may have alias(es), e.g. "cc", "lo" and "ul" are
8482          the same condition code.  */
8483       for (j = 0; j < ARRAY_SIZE (aarch64_conds[i].names); ++j)
8484         {
8485           const char *name = aarch64_conds[i].names[j];
8486           if (name == NULL)
8487             break;
8488           checked_hash_insert (aarch64_cond_hsh, name,
8489                                (void *) (aarch64_conds + i));
8490           /* Also hash the name in the upper case.  */
8491           checked_hash_insert (aarch64_cond_hsh, get_upper_str (name),
8492                                (void *) (aarch64_conds + i));
8493         }
8494     }
8495
8496   for (i = 0; i < ARRAY_SIZE (aarch64_barrier_options); i++)
8497     {
8498       const char *name = aarch64_barrier_options[i].name;
8499       /* Skip xx00 - the unallocated values of option.  */
8500       if ((i & 0x3) == 0)
8501         continue;
8502       checked_hash_insert (aarch64_barrier_opt_hsh, name,
8503                            (void *) (aarch64_barrier_options + i));
8504       /* Also hash the name in the upper case.  */
8505       checked_hash_insert (aarch64_barrier_opt_hsh, get_upper_str (name),
8506                            (void *) (aarch64_barrier_options + i));
8507     }
8508
8509   for (i = 0; i < ARRAY_SIZE (aarch64_prfops); i++)
8510     {
8511       const char* name = aarch64_prfops[i].name;
8512       /* Skip the unallocated hint encodings.  */
8513       if (name == NULL)
8514         continue;
8515       checked_hash_insert (aarch64_pldop_hsh, name,
8516                            (void *) (aarch64_prfops + i));
8517       /* Also hash the name in the upper case.  */
8518       checked_hash_insert (aarch64_pldop_hsh, get_upper_str (name),
8519                            (void *) (aarch64_prfops + i));
8520     }
8521
8522   for (i = 0; aarch64_hint_options[i].name != NULL; i++)
8523     {
8524       const char* name = aarch64_hint_options[i].name;
8525
8526       checked_hash_insert (aarch64_hint_opt_hsh, name,
8527                            (void *) (aarch64_hint_options + i));
8528       /* Also hash the name in the upper case.  */
8529       checked_hash_insert (aarch64_pldop_hsh, get_upper_str (name),
8530                            (void *) (aarch64_hint_options + i));
8531     }
8532
8533   /* Set the cpu variant based on the command-line options.  */
8534   if (!mcpu_cpu_opt)
8535     mcpu_cpu_opt = march_cpu_opt;
8536
8537   if (!mcpu_cpu_opt)
8538     mcpu_cpu_opt = &cpu_default;
8539
8540   cpu_variant = *mcpu_cpu_opt;
8541
8542   /* Record the CPU type.  */
8543   mach = ilp32_p ? bfd_mach_aarch64_ilp32 : bfd_mach_aarch64;
8544
8545   bfd_set_arch_mach (stdoutput, TARGET_ARCH, mach);
8546 }
8547
8548 /* Command line processing.  */
8549
8550 const char *md_shortopts = "m:";
8551
8552 #ifdef AARCH64_BI_ENDIAN
8553 #define OPTION_EB (OPTION_MD_BASE + 0)
8554 #define OPTION_EL (OPTION_MD_BASE + 1)
8555 #else
8556 #if TARGET_BYTES_BIG_ENDIAN
8557 #define OPTION_EB (OPTION_MD_BASE + 0)
8558 #else
8559 #define OPTION_EL (OPTION_MD_BASE + 1)
8560 #endif
8561 #endif
8562
8563 struct option md_longopts[] = {
8564 #ifdef OPTION_EB
8565   {"EB", no_argument, NULL, OPTION_EB},
8566 #endif
8567 #ifdef OPTION_EL
8568   {"EL", no_argument, NULL, OPTION_EL},
8569 #endif
8570   {NULL, no_argument, NULL, 0}
8571 };
8572
8573 size_t md_longopts_size = sizeof (md_longopts);
8574
8575 struct aarch64_option_table
8576 {
8577   const char *option;                   /* Option name to match.  */
8578   const char *help;                     /* Help information.  */
8579   int *var;                     /* Variable to change.  */
8580   int value;                    /* What to change it to.  */
8581   char *deprecated;             /* If non-null, print this message.  */
8582 };
8583
8584 static struct aarch64_option_table aarch64_opts[] = {
8585   {"mbig-endian", N_("assemble for big-endian"), &target_big_endian, 1, NULL},
8586   {"mlittle-endian", N_("assemble for little-endian"), &target_big_endian, 0,
8587    NULL},
8588 #ifdef DEBUG_AARCH64
8589   {"mdebug-dump", N_("temporary switch for dumping"), &debug_dump, 1, NULL},
8590 #endif /* DEBUG_AARCH64 */
8591   {"mverbose-error", N_("output verbose error messages"), &verbose_error_p, 1,
8592    NULL},
8593   {"mno-verbose-error", N_("do not output verbose error messages"),
8594    &verbose_error_p, 0, NULL},
8595   {NULL, NULL, NULL, 0, NULL}
8596 };
8597
8598 struct aarch64_cpu_option_table
8599 {
8600   const char *name;
8601   const aarch64_feature_set value;
8602   /* The canonical name of the CPU, or NULL to use NAME converted to upper
8603      case.  */
8604   const char *canonical_name;
8605 };
8606
8607 /* This list should, at a minimum, contain all the cpu names
8608    recognized by GCC.  */
8609 static const struct aarch64_cpu_option_table aarch64_cpus[] = {
8610   {"all", AARCH64_ANY, NULL},
8611   {"cortex-a35", AARCH64_FEATURE (AARCH64_ARCH_V8,
8612                                   AARCH64_FEATURE_CRC), "Cortex-A35"},
8613   {"cortex-a53", AARCH64_FEATURE (AARCH64_ARCH_V8,
8614                                   AARCH64_FEATURE_CRC), "Cortex-A53"},
8615   {"cortex-a57", AARCH64_FEATURE (AARCH64_ARCH_V8,
8616                                   AARCH64_FEATURE_CRC), "Cortex-A57"},
8617   {"cortex-a72", AARCH64_FEATURE (AARCH64_ARCH_V8,
8618                                   AARCH64_FEATURE_CRC), "Cortex-A72"},
8619   {"cortex-a73", AARCH64_FEATURE (AARCH64_ARCH_V8,
8620                                   AARCH64_FEATURE_CRC), "Cortex-A73"},
8621   {"cortex-a55", AARCH64_FEATURE (AARCH64_ARCH_V8_2,
8622                                   AARCH64_FEATURE_RCPC | AARCH64_FEATURE_F16 | AARCH64_FEATURE_DOTPROD),
8623                                   "Cortex-A55"},
8624   {"cortex-a75", AARCH64_FEATURE (AARCH64_ARCH_V8_2,
8625                                   AARCH64_FEATURE_RCPC | AARCH64_FEATURE_F16 | AARCH64_FEATURE_DOTPROD),
8626                                   "Cortex-A75"},
8627   {"cortex-a76", AARCH64_FEATURE (AARCH64_ARCH_V8_2,
8628                                   AARCH64_FEATURE_RCPC | AARCH64_FEATURE_F16 | AARCH64_FEATURE_DOTPROD),
8629                                   "Cortex-A76"},
8630   {"exynos-m1", AARCH64_FEATURE (AARCH64_ARCH_V8,
8631                                  AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO),
8632                                 "Samsung Exynos M1"},
8633   {"falkor", AARCH64_FEATURE (AARCH64_ARCH_V8,
8634                               AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO
8635                               | AARCH64_FEATURE_RDMA),
8636    "Qualcomm Falkor"},
8637   {"qdf24xx", AARCH64_FEATURE (AARCH64_ARCH_V8,
8638                                AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO
8639                                | AARCH64_FEATURE_RDMA),
8640    "Qualcomm QDF24XX"},
8641   {"saphira", AARCH64_FEATURE (AARCH64_ARCH_V8_4,
8642                                AARCH64_FEATURE_CRYPTO | AARCH64_FEATURE_PROFILE),
8643    "Qualcomm Saphira"},
8644   {"thunderx", AARCH64_FEATURE (AARCH64_ARCH_V8,
8645                                 AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO),
8646    "Cavium ThunderX"},
8647   {"vulcan", AARCH64_FEATURE (AARCH64_ARCH_V8_1,
8648                               AARCH64_FEATURE_CRYPTO),
8649   "Broadcom Vulcan"},
8650   /* The 'xgene-1' name is an older name for 'xgene1', which was used
8651      in earlier releases and is superseded by 'xgene1' in all
8652      tools.  */
8653   {"xgene-1", AARCH64_ARCH_V8, "APM X-Gene 1"},
8654   {"xgene1", AARCH64_ARCH_V8, "APM X-Gene 1"},
8655   {"xgene2", AARCH64_FEATURE (AARCH64_ARCH_V8,
8656                               AARCH64_FEATURE_CRC), "APM X-Gene 2"},
8657   {"generic", AARCH64_ARCH_V8, NULL},
8658
8659   {NULL, AARCH64_ARCH_NONE, NULL}
8660 };
8661
8662 struct aarch64_arch_option_table
8663 {
8664   const char *name;
8665   const aarch64_feature_set value;
8666 };
8667
8668 /* This list should, at a minimum, contain all the architecture names
8669    recognized by GCC.  */
8670 static const struct aarch64_arch_option_table aarch64_archs[] = {
8671   {"all", AARCH64_ANY},
8672   {"armv8-a", AARCH64_ARCH_V8},
8673   {"armv8.1-a", AARCH64_ARCH_V8_1},
8674   {"armv8.2-a", AARCH64_ARCH_V8_2},
8675   {"armv8.3-a", AARCH64_ARCH_V8_3},
8676   {"armv8.4-a", AARCH64_ARCH_V8_4},
8677   {NULL, AARCH64_ARCH_NONE}
8678 };
8679
8680 /* ISA extensions.  */
8681 struct aarch64_option_cpu_value_table
8682 {
8683   const char *name;
8684   const aarch64_feature_set value;
8685   const aarch64_feature_set require; /* Feature dependencies.  */
8686 };
8687
8688 static const struct aarch64_option_cpu_value_table aarch64_features[] = {
8689   {"crc",               AARCH64_FEATURE (AARCH64_FEATURE_CRC, 0),
8690                         AARCH64_ARCH_NONE},
8691   {"crypto",            AARCH64_FEATURE (AARCH64_FEATURE_CRYPTO
8692                                          | AARCH64_FEATURE_AES
8693                                          | AARCH64_FEATURE_SHA2, 0),
8694                         AARCH64_FEATURE (AARCH64_FEATURE_SIMD, 0)},
8695   {"fp",                AARCH64_FEATURE (AARCH64_FEATURE_FP, 0),
8696                         AARCH64_ARCH_NONE},
8697   {"lse",               AARCH64_FEATURE (AARCH64_FEATURE_LSE, 0),
8698                         AARCH64_ARCH_NONE},
8699   {"simd",              AARCH64_FEATURE (AARCH64_FEATURE_SIMD, 0),
8700                         AARCH64_FEATURE (AARCH64_FEATURE_FP, 0)},
8701   {"pan",               AARCH64_FEATURE (AARCH64_FEATURE_PAN, 0),
8702                         AARCH64_ARCH_NONE},
8703   {"lor",               AARCH64_FEATURE (AARCH64_FEATURE_LOR, 0),
8704                         AARCH64_ARCH_NONE},
8705   {"ras",               AARCH64_FEATURE (AARCH64_FEATURE_RAS, 0),
8706                         AARCH64_ARCH_NONE},
8707   {"rdma",              AARCH64_FEATURE (AARCH64_FEATURE_RDMA, 0),
8708                         AARCH64_FEATURE (AARCH64_FEATURE_SIMD, 0)},
8709   {"fp16",              AARCH64_FEATURE (AARCH64_FEATURE_F16, 0),
8710                         AARCH64_FEATURE (AARCH64_FEATURE_FP, 0)},
8711   {"fp16fml",           AARCH64_FEATURE (AARCH64_FEATURE_F16_FML, 0),
8712                         AARCH64_FEATURE (AARCH64_FEATURE_FP
8713                                          | AARCH64_FEATURE_F16, 0)},
8714   {"profile",           AARCH64_FEATURE (AARCH64_FEATURE_PROFILE, 0),
8715                         AARCH64_ARCH_NONE},
8716   {"sve",               AARCH64_FEATURE (AARCH64_FEATURE_SVE, 0),
8717                         AARCH64_FEATURE (AARCH64_FEATURE_F16
8718                                          | AARCH64_FEATURE_SIMD
8719                                          | AARCH64_FEATURE_COMPNUM, 0)},
8720   {"compnum",           AARCH64_FEATURE (AARCH64_FEATURE_COMPNUM, 0),
8721                         AARCH64_FEATURE (AARCH64_FEATURE_F16
8722                                          | AARCH64_FEATURE_SIMD, 0)},
8723   {"rcpc",              AARCH64_FEATURE (AARCH64_FEATURE_RCPC, 0),
8724                         AARCH64_ARCH_NONE},
8725   {"dotprod",           AARCH64_FEATURE (AARCH64_FEATURE_DOTPROD, 0),
8726                         AARCH64_ARCH_NONE},
8727   {"sha2",              AARCH64_FEATURE (AARCH64_FEATURE_SHA2, 0),
8728                         AARCH64_ARCH_NONE},
8729   {"aes",               AARCH64_FEATURE (AARCH64_FEATURE_AES, 0),
8730                         AARCH64_ARCH_NONE},
8731   {"sm4",               AARCH64_FEATURE (AARCH64_FEATURE_SM4, 0),
8732                         AARCH64_ARCH_NONE},
8733   {"sha3",              AARCH64_FEATURE (AARCH64_FEATURE_SHA2
8734                                          | AARCH64_FEATURE_SHA3, 0),
8735                         AARCH64_ARCH_NONE},
8736   {NULL,                AARCH64_ARCH_NONE, AARCH64_ARCH_NONE},
8737 };
8738
8739 struct aarch64_long_option_table
8740 {
8741   const char *option;                   /* Substring to match.  */
8742   const char *help;                     /* Help information.  */
8743   int (*func) (const char *subopt);     /* Function to decode sub-option.  */
8744   char *deprecated;             /* If non-null, print this message.  */
8745 };
8746
8747 /* Transitive closure of features depending on set.  */
8748 static aarch64_feature_set
8749 aarch64_feature_disable_set (aarch64_feature_set set)
8750 {
8751   const struct aarch64_option_cpu_value_table *opt;
8752   aarch64_feature_set prev = 0;
8753
8754   while (prev != set) {
8755     prev = set;
8756     for (opt = aarch64_features; opt->name != NULL; opt++)
8757       if (AARCH64_CPU_HAS_ANY_FEATURES (opt->require, set))
8758         AARCH64_MERGE_FEATURE_SETS (set, set, opt->value);
8759   }
8760   return set;
8761 }
8762
8763 /* Transitive closure of dependencies of set.  */
8764 static aarch64_feature_set
8765 aarch64_feature_enable_set (aarch64_feature_set set)
8766 {
8767   const struct aarch64_option_cpu_value_table *opt;
8768   aarch64_feature_set prev = 0;
8769
8770   while (prev != set) {
8771     prev = set;
8772     for (opt = aarch64_features; opt->name != NULL; opt++)
8773       if (AARCH64_CPU_HAS_FEATURE (set, opt->value))
8774         AARCH64_MERGE_FEATURE_SETS (set, set, opt->require);
8775   }
8776   return set;
8777 }
8778
8779 static int
8780 aarch64_parse_features (const char *str, const aarch64_feature_set **opt_p,
8781                         bfd_boolean ext_only)
8782 {
8783   /* We insist on extensions being added before being removed.  We achieve
8784      this by using the ADDING_VALUE variable to indicate whether we are
8785      adding an extension (1) or removing it (0) and only allowing it to
8786      change in the order -1 -> 1 -> 0.  */
8787   int adding_value = -1;
8788   aarch64_feature_set *ext_set = XNEW (aarch64_feature_set);
8789
8790   /* Copy the feature set, so that we can modify it.  */
8791   *ext_set = **opt_p;
8792   *opt_p = ext_set;
8793
8794   while (str != NULL && *str != 0)
8795     {
8796       const struct aarch64_option_cpu_value_table *opt;
8797       const char *ext = NULL;
8798       int optlen;
8799
8800       if (!ext_only)
8801         {
8802           if (*str != '+')
8803             {
8804               as_bad (_("invalid architectural extension"));
8805               return 0;
8806             }
8807
8808           ext = strchr (++str, '+');
8809         }
8810
8811       if (ext != NULL)
8812         optlen = ext - str;
8813       else
8814         optlen = strlen (str);
8815
8816       if (optlen >= 2 && strncmp (str, "no", 2) == 0)
8817         {
8818           if (adding_value != 0)
8819             adding_value = 0;
8820           optlen -= 2;
8821           str += 2;
8822         }
8823       else if (optlen > 0)
8824         {
8825           if (adding_value == -1)
8826             adding_value = 1;
8827           else if (adding_value != 1)
8828             {
8829               as_bad (_("must specify extensions to add before specifying "
8830                         "those to remove"));
8831               return FALSE;
8832             }
8833         }
8834
8835       if (optlen == 0)
8836         {
8837           as_bad (_("missing architectural extension"));
8838           return 0;
8839         }
8840
8841       gas_assert (adding_value != -1);
8842
8843       for (opt = aarch64_features; opt->name != NULL; opt++)
8844         if (strncmp (opt->name, str, optlen) == 0)
8845           {
8846             aarch64_feature_set set;
8847
8848             /* Add or remove the extension.  */
8849             if (adding_value)
8850               {
8851                 set = aarch64_feature_enable_set (opt->value);
8852                 AARCH64_MERGE_FEATURE_SETS (*ext_set, *ext_set, set);
8853               }
8854             else
8855               {
8856                 set = aarch64_feature_disable_set (opt->value);
8857                 AARCH64_CLEAR_FEATURE (*ext_set, *ext_set, set);
8858               }
8859             break;
8860           }
8861
8862       if (opt->name == NULL)
8863         {
8864           as_bad (_("unknown architectural extension `%s'"), str);
8865           return 0;
8866         }
8867
8868       str = ext;
8869     };
8870
8871   return 1;
8872 }
8873
8874 static int
8875 aarch64_parse_cpu (const char *str)
8876 {
8877   const struct aarch64_cpu_option_table *opt;
8878   const char *ext = strchr (str, '+');
8879   size_t optlen;
8880
8881   if (ext != NULL)
8882     optlen = ext - str;
8883   else
8884     optlen = strlen (str);
8885
8886   if (optlen == 0)
8887     {
8888       as_bad (_("missing cpu name `%s'"), str);
8889       return 0;
8890     }
8891
8892   for (opt = aarch64_cpus; opt->name != NULL; opt++)
8893     if (strlen (opt->name) == optlen && strncmp (str, opt->name, optlen) == 0)
8894       {
8895         mcpu_cpu_opt = &opt->value;
8896         if (ext != NULL)
8897           return aarch64_parse_features (ext, &mcpu_cpu_opt, FALSE);
8898
8899         return 1;
8900       }
8901
8902   as_bad (_("unknown cpu `%s'"), str);
8903   return 0;
8904 }
8905
8906 static int
8907 aarch64_parse_arch (const char *str)
8908 {
8909   const struct aarch64_arch_option_table *opt;
8910   const char *ext = strchr (str, '+');
8911   size_t optlen;
8912
8913   if (ext != NULL)
8914     optlen = ext - str;
8915   else
8916     optlen = strlen (str);
8917
8918   if (optlen == 0)
8919     {
8920       as_bad (_("missing architecture name `%s'"), str);
8921       return 0;
8922     }
8923
8924   for (opt = aarch64_archs; opt->name != NULL; opt++)
8925     if (strlen (opt->name) == optlen && strncmp (str, opt->name, optlen) == 0)
8926       {
8927         march_cpu_opt = &opt->value;
8928         if (ext != NULL)
8929           return aarch64_parse_features (ext, &march_cpu_opt, FALSE);
8930
8931         return 1;
8932       }
8933
8934   as_bad (_("unknown architecture `%s'\n"), str);
8935   return 0;
8936 }
8937
8938 /* ABIs.  */
8939 struct aarch64_option_abi_value_table
8940 {
8941   const char *name;
8942   enum aarch64_abi_type value;
8943 };
8944
8945 static const struct aarch64_option_abi_value_table aarch64_abis[] = {
8946   {"ilp32",             AARCH64_ABI_ILP32},
8947   {"lp64",              AARCH64_ABI_LP64},
8948 };
8949
8950 static int
8951 aarch64_parse_abi (const char *str)
8952 {
8953   unsigned int i;
8954
8955   if (str[0] == '\0')
8956     {
8957       as_bad (_("missing abi name `%s'"), str);
8958       return 0;
8959     }
8960
8961   for (i = 0; i < ARRAY_SIZE (aarch64_abis); i++)
8962     if (strcmp (str, aarch64_abis[i].name) == 0)
8963       {
8964         aarch64_abi = aarch64_abis[i].value;
8965         return 1;
8966       }
8967
8968   as_bad (_("unknown abi `%s'\n"), str);
8969   return 0;
8970 }
8971
8972 static struct aarch64_long_option_table aarch64_long_opts[] = {
8973 #ifdef OBJ_ELF
8974   {"mabi=", N_("<abi name>\t  specify for ABI <abi name>"),
8975    aarch64_parse_abi, NULL},
8976 #endif /* OBJ_ELF */
8977   {"mcpu=", N_("<cpu name>\t  assemble for CPU <cpu name>"),
8978    aarch64_parse_cpu, NULL},
8979   {"march=", N_("<arch name>\t  assemble for architecture <arch name>"),
8980    aarch64_parse_arch, NULL},
8981   {NULL, NULL, 0, NULL}
8982 };
8983
8984 int
8985 md_parse_option (int c, const char *arg)
8986 {
8987   struct aarch64_option_table *opt;
8988   struct aarch64_long_option_table *lopt;
8989
8990   switch (c)
8991     {
8992 #ifdef OPTION_EB
8993     case OPTION_EB:
8994       target_big_endian = 1;
8995       break;
8996 #endif
8997
8998 #ifdef OPTION_EL
8999     case OPTION_EL:
9000       target_big_endian = 0;
9001       break;
9002 #endif
9003
9004     case 'a':
9005       /* Listing option.  Just ignore these, we don't support additional
9006          ones.  */
9007       return 0;
9008
9009     default:
9010       for (opt = aarch64_opts; opt->option != NULL; opt++)
9011         {
9012           if (c == opt->option[0]
9013               && ((arg == NULL && opt->option[1] == 0)
9014                   || streq (arg, opt->option + 1)))
9015             {
9016               /* If the option is deprecated, tell the user.  */
9017               if (opt->deprecated != NULL)
9018                 as_tsktsk (_("option `-%c%s' is deprecated: %s"), c,
9019                            arg ? arg : "", _(opt->deprecated));
9020
9021               if (opt->var != NULL)
9022                 *opt->var = opt->value;
9023
9024               return 1;
9025             }
9026         }
9027
9028       for (lopt = aarch64_long_opts; lopt->option != NULL; lopt++)
9029         {
9030           /* These options are expected to have an argument.  */
9031           if (c == lopt->option[0]
9032               && arg != NULL
9033               && strncmp (arg, lopt->option + 1,
9034                           strlen (lopt->option + 1)) == 0)
9035             {
9036               /* If the option is deprecated, tell the user.  */
9037               if (lopt->deprecated != NULL)
9038                 as_tsktsk (_("option `-%c%s' is deprecated: %s"), c, arg,
9039                            _(lopt->deprecated));
9040
9041               /* Call the sup-option parser.  */
9042               return lopt->func (arg + strlen (lopt->option) - 1);
9043             }
9044         }
9045
9046       return 0;
9047     }
9048
9049   return 1;
9050 }
9051
9052 void
9053 md_show_usage (FILE * fp)
9054 {
9055   struct aarch64_option_table *opt;
9056   struct aarch64_long_option_table *lopt;
9057
9058   fprintf (fp, _(" AArch64-specific assembler options:\n"));
9059
9060   for (opt = aarch64_opts; opt->option != NULL; opt++)
9061     if (opt->help != NULL)
9062       fprintf (fp, "  -%-23s%s\n", opt->option, _(opt->help));
9063
9064   for (lopt = aarch64_long_opts; lopt->option != NULL; lopt++)
9065     if (lopt->help != NULL)
9066       fprintf (fp, "  -%s%s\n", lopt->option, _(lopt->help));
9067
9068 #ifdef OPTION_EB
9069   fprintf (fp, _("\
9070   -EB                     assemble code for a big-endian cpu\n"));
9071 #endif
9072
9073 #ifdef OPTION_EL
9074   fprintf (fp, _("\
9075   -EL                     assemble code for a little-endian cpu\n"));
9076 #endif
9077 }
9078
9079 /* Parse a .cpu directive.  */
9080
9081 static void
9082 s_aarch64_cpu (int ignored ATTRIBUTE_UNUSED)
9083 {
9084   const struct aarch64_cpu_option_table *opt;
9085   char saved_char;
9086   char *name;
9087   char *ext;
9088   size_t optlen;
9089
9090   name = input_line_pointer;
9091   while (*input_line_pointer && !ISSPACE (*input_line_pointer))
9092     input_line_pointer++;
9093   saved_char = *input_line_pointer;
9094   *input_line_pointer = 0;
9095
9096   ext = strchr (name, '+');
9097
9098   if (ext != NULL)
9099     optlen = ext - name;
9100   else
9101     optlen = strlen (name);
9102
9103   /* Skip the first "all" entry.  */
9104   for (opt = aarch64_cpus + 1; opt->name != NULL; opt++)
9105     if (strlen (opt->name) == optlen
9106         && strncmp (name, opt->name, optlen) == 0)
9107       {
9108         mcpu_cpu_opt = &opt->value;
9109         if (ext != NULL)
9110           if (!aarch64_parse_features (ext, &mcpu_cpu_opt, FALSE))
9111             return;
9112
9113         cpu_variant = *mcpu_cpu_opt;
9114
9115         *input_line_pointer = saved_char;
9116         demand_empty_rest_of_line ();
9117         return;
9118       }
9119   as_bad (_("unknown cpu `%s'"), name);
9120   *input_line_pointer = saved_char;
9121   ignore_rest_of_line ();
9122 }
9123
9124
9125 /* Parse a .arch directive.  */
9126
9127 static void
9128 s_aarch64_arch (int ignored ATTRIBUTE_UNUSED)
9129 {
9130   const struct aarch64_arch_option_table *opt;
9131   char saved_char;
9132   char *name;
9133   char *ext;
9134   size_t optlen;
9135
9136   name = input_line_pointer;
9137   while (*input_line_pointer && !ISSPACE (*input_line_pointer))
9138     input_line_pointer++;
9139   saved_char = *input_line_pointer;
9140   *input_line_pointer = 0;
9141
9142   ext = strchr (name, '+');
9143
9144   if (ext != NULL)
9145     optlen = ext - name;
9146   else
9147     optlen = strlen (name);
9148
9149   /* Skip the first "all" entry.  */
9150   for (opt = aarch64_archs + 1; opt->name != NULL; opt++)
9151     if (strlen (opt->name) == optlen
9152         && strncmp (name, opt->name, optlen) == 0)
9153       {
9154         mcpu_cpu_opt = &opt->value;
9155         if (ext != NULL)
9156           if (!aarch64_parse_features (ext, &mcpu_cpu_opt, FALSE))
9157             return;
9158
9159         cpu_variant = *mcpu_cpu_opt;
9160
9161         *input_line_pointer = saved_char;
9162         demand_empty_rest_of_line ();
9163         return;
9164       }
9165
9166   as_bad (_("unknown architecture `%s'\n"), name);
9167   *input_line_pointer = saved_char;
9168   ignore_rest_of_line ();
9169 }
9170
9171 /* Parse a .arch_extension directive.  */
9172
9173 static void
9174 s_aarch64_arch_extension (int ignored ATTRIBUTE_UNUSED)
9175 {
9176   char saved_char;
9177   char *ext = input_line_pointer;;
9178
9179   while (*input_line_pointer && !ISSPACE (*input_line_pointer))
9180     input_line_pointer++;
9181   saved_char = *input_line_pointer;
9182   *input_line_pointer = 0;
9183
9184   if (!aarch64_parse_features (ext, &mcpu_cpu_opt, TRUE))
9185     return;
9186
9187   cpu_variant = *mcpu_cpu_opt;
9188
9189   *input_line_pointer = saved_char;
9190   demand_empty_rest_of_line ();
9191 }
9192
9193 /* Copy symbol information.  */
9194
9195 void
9196 aarch64_copy_symbol_attributes (symbolS * dest, symbolS * src)
9197 {
9198   AARCH64_GET_FLAG (dest) = AARCH64_GET_FLAG (src);
9199 }