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