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