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