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