xref: /netbsd-src/external/gpl3/binutils/dist/gas/config/tc-riscv.c (revision dd7241df2fae9da4ea2bd20a68f001fa86ecf909)
1 /* tc-riscv.c -- RISC-V assembler
2    Copyright (C) 2011-2024 Free Software Foundation, Inc.
3 
4    Contributed by Andrew Waterman (andrew@sifive.com).
5    Based on MIPS target.
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, or (at your option)
12    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 "config.h"
25 #include "subsegs.h"
26 #include "safe-ctype.h"
27 
28 #include "itbl-ops.h"
29 #include "dwarf2dbg.h"
30 #include "dw2gencfi.h"
31 
32 #include "bfd/elfxx-riscv.h"
33 #include "elf/riscv.h"
34 #include "opcode/riscv.h"
35 
36 #include <stdint.h>
37 
38 /* Information about an instruction, including its format, operands
39    and fixups.  */
40 struct riscv_cl_insn
41 {
42   /* The opcode's entry in riscv_opcodes.  */
43   const struct riscv_opcode *insn_mo;
44 
45   /* The encoded instruction bits
46      (first bits enough to extract instruction length on a long opcode).  */
47   insn_t insn_opcode;
48 
49   /* The long encoded instruction bits ([0] is non-zero on a long opcode).  */
50   char insn_long_opcode[RISCV_MAX_INSN_LEN];
51 
52   /* The frag that contains the instruction.  */
53   struct frag *frag;
54 
55   /* The offset into FRAG of the first instruction byte.  */
56   long where;
57 
58   /* The relocs associated with the instruction, if any.  */
59   fixS *fixp;
60 };
61 
62 /* The identifier of the assembler macro we are expanding, if any. */
63 static int source_macro = -1;
64 
65 /* All RISC-V CSR belong to one of these classes.  */
66 enum riscv_csr_class
67 {
68   CSR_CLASS_NONE,
69 
70   CSR_CLASS_I,
71   CSR_CLASS_I_32,	/* rv32 only */
72   CSR_CLASS_F,		/* f-ext only */
73   CSR_CLASS_ZKR,	/* zkr only */
74   CSR_CLASS_V,		/* rvv only */
75   CSR_CLASS_DEBUG,	/* debug CSR */
76   CSR_CLASS_H,		/* hypervisor */
77   CSR_CLASS_H_32,	/* hypervisor, rv32 only */
78   CSR_CLASS_SMAIA,		/* Smaia */
79   CSR_CLASS_SMAIA_32,		/* Smaia, rv32 only */
80   CSR_CLASS_SMCNTRPMF,		/* Smcntrpmf */
81   CSR_CLASS_SMCNTRPMF_32,	/* Smcntrpmf, rv32 only */
82   CSR_CLASS_SMSTATEEN,		/* Smstateen only */
83   CSR_CLASS_SMSTATEEN_32,	/* Smstateen RV32 only */
84   CSR_CLASS_SSAIA,		/* Ssaia */
85   CSR_CLASS_SSAIA_AND_H,	/* Ssaia with H */
86   CSR_CLASS_SSAIA_32,		/* Ssaia, rv32 only */
87   CSR_CLASS_SSAIA_AND_H_32,	/* Ssaia with H, rv32 only */
88   CSR_CLASS_SSSTATEEN,		/* S[ms]stateen only */
89   CSR_CLASS_SSSTATEEN_AND_H,	/* S[ms]stateen only (with H) */
90   CSR_CLASS_SSSTATEEN_AND_H_32,	/* S[ms]stateen RV32 only (with H) */
91   CSR_CLASS_SSCOFPMF,		/* Sscofpmf only */
92   CSR_CLASS_SSCOFPMF_32,	/* Sscofpmf RV32 only */
93   CSR_CLASS_SSTC,		/* Sstc only */
94   CSR_CLASS_SSTC_AND_H,		/* Sstc only (with H) */
95   CSR_CLASS_SSTC_32,		/* Sstc RV32 only */
96   CSR_CLASS_SSTC_AND_H_32,	/* Sstc RV32 only (with H) */
97   CSR_CLASS_XTHEADVECTOR,	/* xtheadvector only */
98 };
99 
100 /* This structure holds all restricted conditions for a CSR.  */
101 struct riscv_csr_extra
102 {
103   /* Class to which this CSR belongs.  Used to decide whether or
104      not this CSR is legal in the current -march context.  */
105   enum riscv_csr_class csr_class;
106 
107   /* CSR may have differnet numbers in the previous priv spec.  */
108   unsigned address;
109 
110   /* Record the CSR is defined/valid in which versions.  */
111   enum riscv_spec_class define_version;
112 
113   /* Record the CSR is aborted/invalid from which versions.  If it isn't
114      aborted in the current version, then it should be PRIV_SPEC_CLASS_DRAFT.  */
115   enum riscv_spec_class abort_version;
116 
117   /* The CSR may have more than one setting.  */
118   struct riscv_csr_extra *next;
119 };
120 
121 /* This structure contains information about errors that occur within the
122    riscv_ip function */
123 struct riscv_ip_error
124 {
125   /* General error message */
126   const char* msg;
127 
128   /* Statement that caused the error */
129   char* statement;
130 
131   /* Missing extension that needs to be enabled */
132   const char* missing_ext;
133 };
134 
135 #ifndef DEFAULT_ARCH
136 #define DEFAULT_ARCH "riscv64"
137 #endif
138 
139 #ifndef DEFAULT_RISCV_ATTR
140 #define DEFAULT_RISCV_ATTR 0
141 #endif
142 
143 /* Let riscv_after_parse_args set the default value according to xlen.  */
144 #ifndef DEFAULT_RISCV_ARCH_WITH_EXT
145 #define DEFAULT_RISCV_ARCH_WITH_EXT NULL
146 #endif
147 
148 /* Need to sync the version with RISC-V compiler.  */
149 #ifndef DEFAULT_RISCV_ISA_SPEC
150 #define DEFAULT_RISCV_ISA_SPEC "20191213"
151 #endif
152 
153 #ifndef DEFAULT_RISCV_PRIV_SPEC
154 #define DEFAULT_RISCV_PRIV_SPEC "1.11"
155 #endif
156 
157 static const char default_arch[] = DEFAULT_ARCH;
158 static const char *default_arch_with_ext = DEFAULT_RISCV_ARCH_WITH_EXT;
159 static enum riscv_spec_class default_isa_spec = ISA_SPEC_CLASS_NONE;
160 static enum riscv_spec_class default_priv_spec = PRIV_SPEC_CLASS_NONE;
161 
162 static unsigned xlen = 0; /* The width of an x-register.  */
163 static unsigned abi_xlen = 0; /* The width of a pointer in the ABI.  */
164 static bool rve_abi = false;
165 enum float_abi
166 {
167   FLOAT_ABI_DEFAULT = -1,
168   FLOAT_ABI_SOFT,
169   FLOAT_ABI_SINGLE,
170   FLOAT_ABI_DOUBLE,
171   FLOAT_ABI_QUAD
172 };
173 static enum float_abi float_abi = FLOAT_ABI_DEFAULT;
174 
175 #define LOAD_ADDRESS_INSN (abi_xlen == 64 ? "ld" : "lw")
176 #define ADD32_INSN (xlen == 64 ? "addiw" : "addi")
177 
178 static unsigned elf_flags = 0;
179 
180 static bool probing_insn_operands;
181 
182 /* Set the default_isa_spec.  Return 0 if the spec isn't supported.
183    Otherwise, return 1.  */
184 
185 static int
riscv_set_default_isa_spec(const char * s)186 riscv_set_default_isa_spec (const char *s)
187 {
188   enum riscv_spec_class class = ISA_SPEC_CLASS_NONE;
189   RISCV_GET_ISA_SPEC_CLASS (s, class);
190   if (class == ISA_SPEC_CLASS_NONE)
191     {
192       as_bad ("unknown default ISA spec `%s' set by "
193 	      "-misa-spec or --with-isa-spec", s);
194       return 0;
195     }
196   else
197     default_isa_spec = class;
198   return 1;
199 }
200 
201 /* Set the default_priv_spec.  Find the privileged elf attributes when
202    the input string is NULL.  Return 0 if the spec isn't supported.
203    Otherwise, return 1.  */
204 
205 static int
riscv_set_default_priv_spec(const char * s)206 riscv_set_default_priv_spec (const char *s)
207 {
208   enum riscv_spec_class class = PRIV_SPEC_CLASS_NONE;
209   unsigned major, minor, revision;
210   obj_attribute *attr;
211 
212   RISCV_GET_PRIV_SPEC_CLASS (s, class);
213   if (class != PRIV_SPEC_CLASS_NONE)
214     {
215       default_priv_spec = class;
216       return 1;
217     }
218 
219   if (s != NULL)
220     {
221       as_bad (_("unknown default privileged spec `%s' set by "
222 		"-mpriv-spec or --with-priv-spec"), s);
223       return 0;
224     }
225 
226   /* Set the default_priv_spec by the privileged elf attributes.  */
227   attr = elf_known_obj_attributes_proc (stdoutput);
228   major = (unsigned) attr[Tag_RISCV_priv_spec].i;
229   minor = (unsigned) attr[Tag_RISCV_priv_spec_minor].i;
230   revision = (unsigned) attr[Tag_RISCV_priv_spec_revision].i;
231   /* Version 0.0.0 is the default value and meningless.  */
232   if (major == 0 && minor == 0 && revision == 0)
233     return 1;
234 
235   riscv_get_priv_spec_class_from_numbers (major, minor, revision, &class);
236   if (class != PRIV_SPEC_CLASS_NONE)
237     {
238       default_priv_spec = class;
239       return 1;
240     }
241 
242   /* Still can not find the privileged spec class.  */
243   as_bad (_("unknown default privileged spec `%d.%d.%d' set by "
244 	    "privileged elf attributes"), major, minor, revision);
245   return 0;
246 }
247 
248 /* This is the set of options which the .option pseudo-op may modify.  */
249 struct riscv_set_options
250 {
251   int pic; /* Generate position-independent code.  */
252   int rvc; /* Generate RVC code.  */
253   int relax; /* Emit relocs the linker is allowed to relax.  */
254   int arch_attr; /* Emit architecture and privileged elf attributes.  */
255   int csr_check; /* Enable the CSR checking.  */
256 };
257 
258 static struct riscv_set_options riscv_opts =
259 {
260   0, /* pic */
261   0, /* rvc */
262   1, /* relax */
263   DEFAULT_RISCV_ATTR, /* arch_attr */
264   0, /* csr_check */
265 };
266 
267 /* Enable or disable the rvc flags for riscv_opts.  Turn on the rvc flag
268    for elf_flags once we have enabled c extension.  */
269 
270 static void
riscv_set_rvc(bool rvc_value)271 riscv_set_rvc (bool rvc_value)
272 {
273   if (rvc_value)
274     elf_flags |= EF_RISCV_RVC;
275 
276   riscv_opts.rvc = rvc_value;
277 }
278 
279 /* Turn on the tso flag for elf_flags once we have enabled ztso extension.  */
280 
281 static void
riscv_set_tso(void)282 riscv_set_tso (void)
283 {
284   elf_flags |= EF_RISCV_TSO;
285 }
286 
287 /* The linked list hanging off of .subsets_list records all enabled extensions,
288    which are parsed from the architecture string.  The architecture string can
289    be set by the -march option, the elf architecture attributes, and the
290    --with-arch configure option.  */
291 static riscv_parse_subset_t riscv_rps_as =
292 {
293   NULL,			/* subset_list, we will set it later once
294 			   riscv_opts_stack is created or updated.  */
295   as_bad,		/* error_handler.  */
296   &xlen,		/* xlen.  */
297   &default_isa_spec,	/* isa_spec.  */
298   true,			/* check_unknown_prefixed_ext.  */
299 };
300 
301 /* Update the architecture string in the subset_list.  */
302 
303 static void
riscv_reset_subsets_list_arch_str(void)304 riscv_reset_subsets_list_arch_str (void)
305 {
306   riscv_subset_list_t *subsets = riscv_rps_as.subset_list;
307   if (subsets->arch_str != NULL)
308     free ((void *) subsets->arch_str);
309   subsets->arch_str = riscv_arch_str (xlen, subsets);
310 }
311 
312 /* This structure is used to hold a stack of .option values.  */
313 struct riscv_option_stack
314 {
315   struct riscv_option_stack *next;
316   struct riscv_set_options options;
317   riscv_subset_list_t *subset_list;
318 };
319 
320 static struct riscv_option_stack *riscv_opts_stack = NULL;
321 
322 /* Set which ISA and extensions are available.  */
323 
324 static void
riscv_set_arch(const char * s)325 riscv_set_arch (const char *s)
326 {
327   if (s != NULL && strcmp (s, "") == 0)
328     {
329       as_bad (_("the architecture string of -march and elf architecture "
330 		"attributes cannot be empty"));
331       return;
332     }
333 
334   if (riscv_rps_as.subset_list == NULL)
335     {
336       riscv_rps_as.subset_list = XNEW (riscv_subset_list_t);
337       riscv_rps_as.subset_list->head = NULL;
338       riscv_rps_as.subset_list->tail = NULL;
339       riscv_rps_as.subset_list->arch_str = NULL;
340     }
341   riscv_release_subset_list (riscv_rps_as.subset_list);
342   riscv_parse_subset (&riscv_rps_as, s);
343   riscv_reset_subsets_list_arch_str ();
344 
345   riscv_set_rvc (false);
346   if (riscv_subset_supports (&riscv_rps_as, "c")
347       || riscv_subset_supports (&riscv_rps_as, "zca"))
348     riscv_set_rvc (true);
349 
350   if (riscv_subset_supports (&riscv_rps_as, "ztso"))
351     riscv_set_tso ();
352 }
353 
354 /* Indicate -mabi option is explictly set.  */
355 static bool explicit_mabi = false;
356 
357 /* Set the abi information.  */
358 
359 static void
riscv_set_abi(unsigned new_xlen,enum float_abi new_float_abi,bool rve)360 riscv_set_abi (unsigned new_xlen, enum float_abi new_float_abi, bool rve)
361 {
362   abi_xlen = new_xlen;
363   float_abi = new_float_abi;
364   rve_abi = rve;
365 }
366 
367 /* If the -mabi option isn't set, then set the abi according to the
368    ISA string.  Otherwise, check if there is any conflict.  */
369 
370 static void
riscv_set_abi_by_arch(void)371 riscv_set_abi_by_arch (void)
372 {
373   if (!explicit_mabi)
374     {
375       if (riscv_subset_supports (&riscv_rps_as, "q"))
376 	riscv_set_abi (xlen, FLOAT_ABI_QUAD, false);
377       else if (riscv_subset_supports (&riscv_rps_as, "d"))
378 	riscv_set_abi (xlen, FLOAT_ABI_DOUBLE, false);
379       else if (riscv_subset_supports (&riscv_rps_as, "e"))
380 	riscv_set_abi (xlen, FLOAT_ABI_SOFT, true);
381       else
382 	riscv_set_abi (xlen, FLOAT_ABI_SOFT, false);
383     }
384   else
385     {
386       gas_assert (abi_xlen != 0 && xlen != 0 && float_abi != FLOAT_ABI_DEFAULT);
387       if (abi_xlen > xlen)
388 	as_bad ("can't have %d-bit ABI on %d-bit ISA", abi_xlen, xlen);
389       else if (abi_xlen < xlen)
390 	as_bad ("%d-bit ABI not yet supported on %d-bit ISA", abi_xlen, xlen);
391 
392       if (riscv_subset_supports (&riscv_rps_as, "e") && !rve_abi)
393 	as_bad ("only ilp32e/lp64e ABI are supported for e extension");
394 
395       if (float_abi == FLOAT_ABI_SINGLE
396 	  && !riscv_subset_supports (&riscv_rps_as, "f"))
397 	as_bad ("ilp32f/lp64f ABI can't be used when f extension "
398 		"isn't supported");
399       else if (float_abi == FLOAT_ABI_DOUBLE
400 	       && !riscv_subset_supports (&riscv_rps_as, "d"))
401 	as_bad ("ilp32d/lp64d ABI can't be used when d extension "
402 		"isn't supported");
403       else if (float_abi == FLOAT_ABI_QUAD
404 	       && !riscv_subset_supports (&riscv_rps_as, "q"))
405 	as_bad ("ilp32q/lp64q ABI can't be used when q extension "
406 		"isn't supported");
407     }
408 
409   /* Update the EF_RISCV_FLOAT_ABI field of elf_flags.  */
410   elf_flags &= ~EF_RISCV_FLOAT_ABI;
411   elf_flags |= float_abi << 1;
412 
413   if (rve_abi)
414     elf_flags |= EF_RISCV_RVE;
415 }
416 
417 /* Handle of the OPCODE hash table.  */
418 static htab_t op_hash = NULL;
419 
420 /* Handle of the type of .insn hash table.  */
421 static htab_t insn_type_hash = NULL;
422 
423 /* This array holds the chars that always start a comment.  If the
424    pre-processor is disabled, these aren't very useful.  */
425 const char comment_chars[] = "#";
426 
427 /* This array holds the chars that only start a comment at the beginning of
428    a line.  If the line seems to have the form '# 123 filename'
429    .line and .file directives will appear in the pre-processed output
430 
431    Note that input_file.c hand checks for '#' at the beginning of the
432    first line of the input file.  This is because the compiler outputs
433    #NO_APP at the beginning of its output.
434 
435    Also note that C style comments are always supported.  */
436 const char line_comment_chars[] = "#";
437 
438 /* This array holds machine specific line separator characters.  */
439 const char line_separator_chars[] = ";";
440 
441 /* Chars that can be used to separate mant from exp in floating point nums.  */
442 const char EXP_CHARS[] = "eE";
443 
444 /* Chars that mean this number is a floating point constant.
445    As in 0f12.456 or 0d1.2345e12.  */
446 const char FLT_CHARS[] = "rRsSfFdDxXpPhH";
447 
448 /* Indicate we are already assemble any instructions or not.  */
449 static bool start_assemble = false;
450 
451 /* Indicate ELF attributes are explicitly set.  */
452 static bool explicit_attr = false;
453 
454 /* Indicate CSR or priv instructions are explicitly used.  */
455 static bool explicit_priv_attr = false;
456 
457 static char *expr_parse_end;
458 
459 /* Macros for encoding relaxation state for RVC branches and far jumps.  */
460 #define RELAX_BRANCH_ENCODE(uncond, rvc, length)	\
461   ((relax_substateT) 					\
462    (0xc0000000						\
463     | ((uncond) ? 1 : 0)				\
464     | ((rvc) ? 2 : 0)					\
465     | ((length) << 2)))
466 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
467 #define RELAX_BRANCH_LENGTH(i) (((i) >> 2) & 0xF)
468 #define RELAX_BRANCH_RVC(i) (((i) & 2) != 0)
469 #define RELAX_BRANCH_UNCOND(i) (((i) & 1) != 0)
470 
471 /* Is the given value a sign-extended 32-bit value?  */
472 #define IS_SEXT_32BIT_NUM(x)						\
473   (((x) &~ (offsetT) 0x7fffffff) == 0					\
474    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
475 
476 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
477 #define IS_ZEXT_32BIT_NUM(x)						\
478   (((x) &~ (offsetT) 0xffffffff) == 0					\
479    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
480 
481 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
482    INSN is a riscv_cl_insn structure and VALUE is evaluated exactly once.  */
483 #define INSERT_OPERAND(FIELD, INSN, VALUE) \
484   INSERT_BITS ((INSN).insn_opcode, VALUE, OP_MASK_##FIELD, OP_SH_##FIELD)
485 
486 #define INSERT_IMM(n, s, INSN, VALUE) \
487   INSERT_BITS ((INSN).insn_opcode, VALUE, (1ULL<<n) - 1, s)
488 
489 /* Determine if an instruction matches an opcode.  */
490 #define OPCODE_MATCHES(OPCODE, OP) \
491   (((OPCODE) & MASK_##OP) == MATCH_##OP)
492 
493 /* Create a new mapping symbol for the transition to STATE.  */
494 
495 static void
make_mapping_symbol(enum riscv_seg_mstate state,valueT value,fragS * frag,const char * arch_str,bool odd_data_padding)496 make_mapping_symbol (enum riscv_seg_mstate state,
497 		     valueT value,
498 		     fragS *frag,
499 		     const char *arch_str,
500 		     bool odd_data_padding)
501 {
502   const char *name;
503   char *buff = NULL;
504   switch (state)
505     {
506     case MAP_DATA:
507       name = "$d";
508       break;
509     case MAP_INSN:
510       if (arch_str != NULL)
511 	{
512 	  size_t size = strlen (arch_str) + 3; /* "$x" + '\0'  */
513 	  buff = xmalloc (size);
514 	  snprintf (buff, size, "$x%s", arch_str);
515 	  name = buff;
516 	}
517       else
518 	name = "$x";
519       break;
520     default:
521       abort ();
522     }
523 
524   symbolS *symbol = symbol_new (name, now_seg, frag, value);
525   symbol_get_bfdsym (symbol)->flags |= (BSF_NO_FLAGS | BSF_LOCAL);
526   if (arch_str != NULL)
527     {
528       /* Store current $x+arch into tc_segment_info.  */
529       seg_info (now_seg)->tc_segment_info_data.arch_map_symbol = symbol;
530       xfree ((void *) buff);
531     }
532 
533   /* If .fill or other data filling directive generates zero sized data,
534      then mapping symbol for the following code will have the same value.
535 
536      Please see gas/testsuite/gas/riscv/mapping.s: .text.zero.fill.first
537      and .text.zero.fill.last.  */
538   symbolS *first = frag->tc_frag_data.first_map_symbol;
539   symbolS *last = frag->tc_frag_data.last_map_symbol;
540   symbolS *removed = NULL;
541   if (value == 0)
542     {
543       if (first != NULL)
544 	{
545 	  know (S_GET_VALUE (first) == S_GET_VALUE (symbol)
546 		&& first == last);
547 	  /* Remove the old one.  */
548 	  removed = first;
549 	}
550       frag->tc_frag_data.first_map_symbol = symbol;
551     }
552   else if (last != NULL)
553     {
554       /* The mapping symbols should be added in offset order.  */
555       know (S_GET_VALUE (last) <= S_GET_VALUE (symbol));
556       /* Remove the old one.  */
557       if (S_GET_VALUE (last) == S_GET_VALUE (symbol))
558 	removed = last;
559     }
560   frag->tc_frag_data.last_map_symbol = symbol;
561 
562   if (removed == NULL)
563     return;
564 
565   if (odd_data_padding)
566     {
567       /* If the removed mapping symbol is $x+arch, then add it back to
568 	 the next $x.  */
569       const char *str = strncmp (S_GET_NAME (removed), "$xrv", 4) == 0
570 			? S_GET_NAME (removed) + 2 : NULL;
571       make_mapping_symbol (MAP_INSN, frag->fr_fix + 1, frag, str,
572 			   false/* odd_data_padding */);
573     }
574   symbol_remove (removed, &symbol_rootP, &symbol_lastP);
575 }
576 
577 /* Set the mapping state for frag_now.  */
578 
579 void
riscv_mapping_state(enum riscv_seg_mstate to_state,int max_chars,bool fr_align_code)580 riscv_mapping_state (enum riscv_seg_mstate to_state,
581 		     int max_chars,
582 		     bool fr_align_code)
583 {
584   enum riscv_seg_mstate from_state =
585 	seg_info (now_seg)->tc_segment_info_data.map_state;
586   bool reset_seg_arch_str = false;
587 
588   if (!SEG_NORMAL (now_seg)
589       /* For now we only add the mapping symbols to text sections.
590 	 Therefore, the dis-assembler only show the actual contents
591 	 distribution for text.  Other sections will be shown as
592 	 data without the details.  */
593       || !subseg_text_p (now_seg))
594     return;
595 
596   /* The mapping symbol should be emitted if not in the right
597      mapping state.  */
598   symbolS *seg_arch_symbol =
599 	seg_info (now_seg)->tc_segment_info_data.arch_map_symbol;
600   if (to_state == MAP_INSN && seg_arch_symbol == 0)
601     {
602       /* Always add $x+arch at the first instruction of section.  */
603       reset_seg_arch_str = true;
604     }
605   else if (seg_arch_symbol != 0
606 	   && to_state == MAP_INSN
607 	   && !fr_align_code
608 	   && strcmp (riscv_rps_as.subset_list->arch_str,
609 		      S_GET_NAME (seg_arch_symbol) + 2) != 0)
610     {
611       reset_seg_arch_str = true;
612     }
613   else if (from_state == to_state)
614     return;
615 
616   valueT value = (valueT) (frag_now_fix () - max_chars);
617   seg_info (now_seg)->tc_segment_info_data.map_state = to_state;
618   const char *arch_str = reset_seg_arch_str
619 			 ? riscv_rps_as.subset_list->arch_str : NULL;
620   make_mapping_symbol (to_state, value, frag_now, arch_str,
621 		       false/* odd_data_padding */);
622 }
623 
624 /* Add the odd bytes of paddings for riscv_handle_align.  */
625 
626 static void
riscv_add_odd_padding_symbol(fragS * frag)627 riscv_add_odd_padding_symbol (fragS *frag)
628 {
629   /* If there was already a mapping symbol, it should be
630      removed in the make_mapping_symbol.
631 
632      Please see gas/testsuite/gas/riscv/mapping.s: .text.odd.align.*.  */
633   make_mapping_symbol (MAP_DATA, frag->fr_fix, frag,
634 		       NULL/* arch_str */, true/* odd_data_padding */);
635 }
636 
637 /* Remove any excess mapping symbols generated for alignment frags in
638    SEC.  We may have created a mapping symbol before a zero byte
639    alignment; remove it if there's a mapping symbol after the
640    alignment.  */
641 
642 static void
riscv_check_mapping_symbols(bfd * abfd ATTRIBUTE_UNUSED,asection * sec,void * dummy ATTRIBUTE_UNUSED)643 riscv_check_mapping_symbols (bfd *abfd ATTRIBUTE_UNUSED,
644 			     asection *sec,
645 			     void *dummy ATTRIBUTE_UNUSED)
646 {
647   segment_info_type *seginfo = seg_info (sec);
648   fragS *fragp;
649 
650   if (seginfo == NULL || seginfo->frchainP == NULL)
651     return;
652 
653   for (fragp = seginfo->frchainP->frch_root;
654        fragp != NULL;
655        fragp = fragp->fr_next)
656     {
657       symbolS *last = fragp->tc_frag_data.last_map_symbol;
658       fragS *next = fragp->fr_next;
659 
660       if (last == NULL || next == NULL)
661 	continue;
662 
663       /* Check the last mapping symbol if it is at the boundary of
664 	 fragment.  */
665       if (S_GET_VALUE (last) < next->fr_address)
666 	continue;
667       know (S_GET_VALUE (last) == next->fr_address);
668 
669       do
670 	{
671 	  symbolS *next_first = next->tc_frag_data.first_map_symbol;
672 	  if (next_first != NULL)
673 	    {
674 	      /* The last mapping symbol overlaps with another one
675 		 which at the start of the next frag.
676 
677 		 Please see the gas/testsuite/gas/riscv/mapping.s:
678 		 .text.zero.fill.align.A and .text.zero.fill.align.B.  */
679 	      know (S_GET_VALUE (last) == S_GET_VALUE (next_first));
680 	      symbolS *removed = last;
681 	      if (strncmp (S_GET_NAME (last), "$xrv", 4) == 0
682 		  && strcmp (S_GET_NAME (next_first), "$x") == 0)
683 		removed = next_first;
684 	      symbol_remove (removed, &symbol_rootP, &symbol_lastP);
685 	      break;
686 	    }
687 
688 	  if (next->fr_next == NULL)
689 	    {
690 	      /* The last mapping symbol is at the end of the section.
691 
692 		 Please see the gas/testsuite/gas/riscv/mapping.s:
693 		 .text.last.section.  */
694 	      know (next->fr_fix == 0 && next->fr_var == 0);
695 	      symbol_remove (last, &symbol_rootP, &symbol_lastP);
696 	      break;
697 	    }
698 
699 	  /* Since we may have empty frags without any mapping symbols,
700 	     keep looking until the non-empty frag.  */
701 	  if (next->fr_address != next->fr_next->fr_address)
702 	    break;
703 
704 	  next = next->fr_next;
705 	}
706       while (next != NULL);
707     }
708 }
709 
710 /* The default target format to use.  */
711 
712 const char *
riscv_target_format(void)713 riscv_target_format (void)
714 {
715   if (target_big_endian)
716     return xlen == 64 ? "elf64-bigriscv" : "elf32-bigriscv";
717   else
718     return xlen == 64 ? "elf64-littleriscv" : "elf32-littleriscv";
719 }
720 
721 /* Return the length of instruction INSN.  */
722 
723 static inline unsigned int
insn_length(const struct riscv_cl_insn * insn)724 insn_length (const struct riscv_cl_insn *insn)
725 {
726   return riscv_insn_length (insn->insn_opcode);
727 }
728 
729 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
730 
731 static void
create_insn(struct riscv_cl_insn * insn,const struct riscv_opcode * mo)732 create_insn (struct riscv_cl_insn *insn, const struct riscv_opcode *mo)
733 {
734   insn->insn_mo = mo;
735   insn->insn_opcode = mo->match;
736   insn->insn_long_opcode[0] = 0;
737   insn->frag = NULL;
738   insn->where = 0;
739   insn->fixp = NULL;
740 }
741 
742 /* Install INSN at the location specified by its "frag" and "where" fields.  */
743 
744 static void
install_insn(const struct riscv_cl_insn * insn)745 install_insn (const struct riscv_cl_insn *insn)
746 {
747   char *f = insn->frag->fr_literal + insn->where;
748   if (insn->insn_long_opcode[0] != 0)
749     memcpy (f, insn->insn_long_opcode, insn_length (insn));
750   else
751     number_to_chars_littleendian (f, insn->insn_opcode, insn_length (insn));
752 }
753 
754 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
755    and install the opcode in the new location.  */
756 
757 static void
move_insn(struct riscv_cl_insn * insn,fragS * frag,long where)758 move_insn (struct riscv_cl_insn *insn, fragS *frag, long where)
759 {
760   insn->frag = frag;
761   insn->where = where;
762   if (insn->fixp != NULL)
763     {
764       insn->fixp->fx_frag = frag;
765       insn->fixp->fx_where = where;
766     }
767   install_insn (insn);
768 }
769 
770 /* Add INSN to the end of the output.  */
771 
772 static void
add_fixed_insn(struct riscv_cl_insn * insn)773 add_fixed_insn (struct riscv_cl_insn *insn)
774 {
775   char *f = frag_more (insn_length (insn));
776   move_insn (insn, frag_now, f - frag_now->fr_literal);
777 }
778 
779 static void
add_relaxed_insn(struct riscv_cl_insn * insn,int max_chars,int var,relax_substateT subtype,symbolS * symbol,offsetT offset)780 add_relaxed_insn (struct riscv_cl_insn *insn, int max_chars, int var,
781       relax_substateT subtype, symbolS *symbol, offsetT offset)
782 {
783   frag_grow (max_chars);
784   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
785   frag_var (rs_machine_dependent, max_chars, var,
786 	    subtype, symbol, offset, NULL);
787 }
788 
789 /* Compute the length of a branch sequence, and adjust the stored length
790    accordingly.  If FRAGP is NULL, the worst-case length is returned.  */
791 
792 static unsigned
relaxed_branch_length(fragS * fragp,asection * sec,int update)793 relaxed_branch_length (fragS *fragp, asection *sec, int update)
794 {
795   int jump, rvc, length = 8;
796 
797   if (!fragp)
798     return length;
799 
800   jump = RELAX_BRANCH_UNCOND (fragp->fr_subtype);
801   rvc = RELAX_BRANCH_RVC (fragp->fr_subtype);
802   length = RELAX_BRANCH_LENGTH (fragp->fr_subtype);
803 
804   /* Assume jumps are in range; the linker will catch any that aren't.  */
805   length = jump ? 4 : 8;
806 
807   if (fragp->fr_symbol != NULL
808       && S_IS_DEFINED (fragp->fr_symbol)
809       && !S_IS_WEAK (fragp->fr_symbol)
810       && sec == S_GET_SEGMENT (fragp->fr_symbol))
811     {
812       offsetT val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
813       bfd_vma rvc_range = jump ? RVC_JUMP_REACH : RVC_BRANCH_REACH;
814       val -= fragp->fr_address + fragp->fr_fix;
815 
816       if (rvc && (bfd_vma)(val + rvc_range/2) < rvc_range)
817 	length = 2;
818       else if ((bfd_vma)(val + RISCV_BRANCH_REACH/2) < RISCV_BRANCH_REACH)
819 	length = 4;
820       else if (!jump && rvc)
821 	length = 6;
822     }
823 
824   if (update)
825     fragp->fr_subtype = RELAX_BRANCH_ENCODE (jump, rvc, length);
826 
827   return length;
828 }
829 
830 /* Information about an opcode name, mnemonics and its value.  */
831 struct opcode_name_t
832 {
833   const char *name;
834   unsigned int val;
835 };
836 
837 /* List for all supported opcode name.  */
838 static const struct opcode_name_t opcode_name_list[] =
839 {
840   {"C0",        0x0},
841   {"C1",        0x1},
842   {"C2",        0x2},
843 
844   {"LOAD",      0x03},
845   {"LOAD_FP",   0x07},
846   {"CUSTOM_0",  0x0b},
847   {"MISC_MEM",  0x0f},
848   {"OP_IMM",    0x13},
849   {"AUIPC",     0x17},
850   {"OP_IMM_32", 0x1b},
851   /* 48b        0x1f.  */
852 
853   {"STORE",     0x23},
854   {"STORE_FP",  0x27},
855   {"CUSTOM_1",  0x2b},
856   {"AMO",       0x2f},
857   {"OP",        0x33},
858   {"LUI",       0x37},
859   {"OP_32",     0x3b},
860   /* 64b        0x3f.  */
861 
862   {"MADD",      0x43},
863   {"MSUB",      0x47},
864   {"NMADD",     0x4f},
865   {"NMSUB",     0x4b},
866   {"OP_FP",     0x53},
867   {"OP_V",      0x57},
868   {"CUSTOM_2",  0x5b},
869   /* 48b        0x5f.  */
870 
871   {"BRANCH",    0x63},
872   {"JALR",      0x67},
873   /*reserved    0x5b.  */
874   {"JAL",       0x6f},
875   {"SYSTEM",    0x73},
876   /*reserved    0x77.  */
877   {"CUSTOM_3",  0x7b},
878   /* >80b       0x7f.  */
879 
880   {NULL, 0}
881 };
882 
883 /* Hash table for lookup opcode name.  */
884 static htab_t opcode_names_hash = NULL;
885 
886 /* Initialization for hash table of opcode name.  */
887 
888 static void
init_opcode_names_hash(void)889 init_opcode_names_hash (void)
890 {
891   const struct opcode_name_t *opcode;
892 
893   for (opcode = &opcode_name_list[0]; opcode->name != NULL; ++opcode)
894     if (str_hash_insert (opcode_names_hash, opcode->name, opcode, 0) != NULL)
895       as_fatal (_("internal: duplicate %s"), opcode->name);
896 }
897 
898 /* Find `s` is a valid opcode name or not, return the opcode name info
899    if found.  */
900 
901 static const struct opcode_name_t *
opcode_name_lookup(char ** s)902 opcode_name_lookup (char **s)
903 {
904   char *e;
905   char save_c;
906   struct opcode_name_t *o;
907 
908   /* Find end of name.  */
909   e = *s;
910   if (is_name_beginner (*e))
911     ++e;
912   while (is_part_of_name (*e))
913     ++e;
914 
915   /* Terminate name.  */
916   save_c = *e;
917   *e = '\0';
918 
919   o = (struct opcode_name_t *) str_hash_find (opcode_names_hash, *s);
920 
921   /* Advance to next token if one was recognized.  */
922   if (o)
923     *s = e;
924 
925   *e = save_c;
926   expr_parse_end = e;
927 
928   return o;
929 }
930 
931 /* All RISC-V registers belong to one of these classes.  */
932 enum reg_class
933 {
934   RCLASS_GPR,
935   RCLASS_FPR,
936   RCLASS_VECR,
937   RCLASS_VECM,
938   RCLASS_MAX,
939 
940   RCLASS_CSR
941 };
942 
943 static htab_t reg_names_hash = NULL;
944 static htab_t csr_extra_hash = NULL;
945 
946 #define ENCODE_REG_HASH(cls, n) \
947   ((void *)(uintptr_t)((n) * RCLASS_MAX + (cls) + 1))
948 #define DECODE_REG_CLASS(hash) (((uintptr_t)(hash) - 1) % RCLASS_MAX)
949 #define DECODE_REG_NUM(hash) (((uintptr_t)(hash) - 1) / RCLASS_MAX)
950 
951 static void
hash_reg_name(enum reg_class class,const char * name,unsigned n)952 hash_reg_name (enum reg_class class, const char *name, unsigned n)
953 {
954   void *hash = ENCODE_REG_HASH (class, n);
955   if (str_hash_insert (reg_names_hash, name, hash, 0) != NULL)
956     as_fatal (_("internal: duplicate %s"), name);
957 }
958 
959 static void
hash_reg_names(enum reg_class class,const char names[][NRC],unsigned n)960 hash_reg_names (enum reg_class class, const char names[][NRC], unsigned n)
961 {
962   unsigned i;
963 
964   for (i = 0; i < n; i++)
965     hash_reg_name (class, names[i], i);
966 }
967 
968 /* Init hash table csr_extra_hash to handle CSR.  */
969 
970 static void
riscv_init_csr_hash(const char * name,unsigned address,enum riscv_csr_class class,enum riscv_spec_class define_version,enum riscv_spec_class abort_version)971 riscv_init_csr_hash (const char *name,
972 		     unsigned address,
973 		     enum riscv_csr_class class,
974 		     enum riscv_spec_class define_version,
975 		     enum riscv_spec_class abort_version)
976 {
977   struct riscv_csr_extra *entry, *pre_entry;
978   bool need_enrty = true;
979 
980   pre_entry = NULL;
981   entry = (struct riscv_csr_extra *) str_hash_find (csr_extra_hash, name);
982   while (need_enrty && entry != NULL)
983     {
984       if (entry->csr_class == class
985 	  && entry->address == address
986 	  && entry->define_version == define_version
987 	  && entry->abort_version == abort_version)
988 	need_enrty = false;
989       pre_entry = entry;
990       entry = entry->next;
991     }
992 
993   /* Duplicate CSR.  */
994   if (!need_enrty)
995     return;
996 
997   entry = notes_alloc (sizeof (*entry));
998   entry->csr_class = class;
999   entry->address = address;
1000   entry->define_version = define_version;
1001   entry->abort_version = abort_version;
1002   entry->next = NULL;
1003 
1004   if (pre_entry == NULL)
1005     str_hash_insert (csr_extra_hash, name, entry, 0);
1006   else
1007     pre_entry->next = entry;
1008 }
1009 
1010 /* Return the CSR address after checking the ISA dependency and
1011    the privileged spec version.
1012 
1013    There are one warning and two errors for CSR,
1014 
1015    Invalid CSR: the CSR was defined, but isn't allowed for the current ISA
1016    or the privileged spec, report warning only if -mcsr-check is set.
1017    Unknown CSR: the CSR has never been defined, report error.
1018    Improper CSR: the CSR number over the range (> 0xfff), report error.  */
1019 
1020 static unsigned int
riscv_csr_address(const char * csr_name,struct riscv_csr_extra * entry)1021 riscv_csr_address (const char *csr_name,
1022 		   struct riscv_csr_extra *entry)
1023 {
1024   struct riscv_csr_extra *saved_entry = entry;
1025   enum riscv_csr_class csr_class = entry->csr_class;
1026   bool need_check_version = false;
1027   bool is_rv32_only = false;
1028   bool is_h_required = false;
1029   const char* extension = NULL;
1030 
1031   switch (csr_class)
1032     {
1033     case CSR_CLASS_I_32:
1034       is_rv32_only = true;
1035       /* Fall through.  */
1036     case CSR_CLASS_I:
1037       need_check_version = true;
1038       extension = "i";
1039       break;
1040     case CSR_CLASS_H_32:
1041       is_rv32_only = true;
1042       /* Fall through.  */
1043     case CSR_CLASS_H:
1044       extension = "h";
1045       break;
1046     case CSR_CLASS_F:
1047       extension = "f";
1048       break;
1049     case CSR_CLASS_ZKR:
1050       extension = "zkr";
1051       break;
1052     case CSR_CLASS_V:
1053       extension = "zve32x";
1054       break;
1055     case CSR_CLASS_SMAIA_32:
1056       is_rv32_only = true;
1057       /* Fall through.  */
1058     case CSR_CLASS_SMAIA:
1059       extension = "smaia";
1060       break;
1061     case CSR_CLASS_SMCNTRPMF_32:
1062       is_rv32_only = true;
1063       /* Fall through.  */
1064     case CSR_CLASS_SMCNTRPMF:
1065       need_check_version = true;
1066       extension = "smcntrpmf";
1067       break;
1068     case CSR_CLASS_SMSTATEEN_32:
1069       is_rv32_only = true;
1070       /* Fall through.  */
1071     case CSR_CLASS_SMSTATEEN:
1072       extension = "smstateen";
1073       break;
1074     case CSR_CLASS_SSAIA:
1075     case CSR_CLASS_SSAIA_AND_H:
1076     case CSR_CLASS_SSAIA_32:
1077     case CSR_CLASS_SSAIA_AND_H_32:
1078       is_rv32_only = (csr_class == CSR_CLASS_SSAIA_32
1079 		      || csr_class == CSR_CLASS_SSAIA_AND_H_32);
1080       is_h_required = (csr_class == CSR_CLASS_SSAIA_AND_H
1081 		       || csr_class == CSR_CLASS_SSAIA_AND_H_32);
1082       extension = "ssaia";
1083       break;
1084     case CSR_CLASS_SSSTATEEN_AND_H_32:
1085       is_rv32_only = true;
1086       /* Fall through.  */
1087     case CSR_CLASS_SSSTATEEN_AND_H:
1088       is_h_required = true;
1089       /* Fall through.  */
1090     case CSR_CLASS_SSSTATEEN:
1091       extension = "ssstateen";
1092       break;
1093     case CSR_CLASS_SSCOFPMF_32:
1094       is_rv32_only = true;
1095       /* Fall through.  */
1096     case CSR_CLASS_SSCOFPMF:
1097       extension = "sscofpmf";
1098       break;
1099     case CSR_CLASS_SSTC:
1100     case CSR_CLASS_SSTC_AND_H:
1101     case CSR_CLASS_SSTC_32:
1102     case CSR_CLASS_SSTC_AND_H_32:
1103       is_rv32_only = (csr_class == CSR_CLASS_SSTC_32
1104 		      || csr_class == CSR_CLASS_SSTC_AND_H_32);
1105       is_h_required = (csr_class == CSR_CLASS_SSTC_AND_H
1106 		      || csr_class == CSR_CLASS_SSTC_AND_H_32);
1107       extension = "sstc";
1108       break;
1109     case CSR_CLASS_DEBUG:
1110       break;
1111     case CSR_CLASS_XTHEADVECTOR:
1112       extension = "xtheadvector";
1113       break;
1114     default:
1115       as_bad (_("internal: bad RISC-V CSR class (0x%x)"), csr_class);
1116     }
1117 
1118   if (riscv_opts.csr_check)
1119     {
1120       if (is_rv32_only && xlen != 32)
1121 	as_warn (_("invalid CSR `%s', needs rv32i extension"), csr_name);
1122       if (is_h_required && !riscv_subset_supports (&riscv_rps_as, "h"))
1123 	as_warn (_("invalid CSR `%s', needs `h' extension"), csr_name);
1124 
1125       if (extension != NULL
1126 	  && !riscv_subset_supports (&riscv_rps_as, extension))
1127 	as_warn (_("invalid CSR `%s', needs `%s' extension"),
1128 		 csr_name, extension);
1129     }
1130 
1131   while (entry != NULL)
1132     {
1133       if (!need_check_version
1134 	  || (default_priv_spec >= entry->define_version
1135 	      && default_priv_spec < entry->abort_version))
1136        {
1137          /* Find the CSR according to the specific version.  */
1138          return entry->address;
1139        }
1140       entry = entry->next;
1141     }
1142 
1143   /* Can not find the CSR address from the chosen privileged version,
1144      so use the newly defined value.  */
1145   if (riscv_opts.csr_check)
1146     {
1147       const char *priv_name = NULL;
1148       RISCV_GET_PRIV_SPEC_NAME (priv_name, default_priv_spec);
1149       if (priv_name != NULL)
1150 	as_warn (_("invalid CSR `%s' for the privileged spec `%s'"),
1151 		 csr_name, priv_name);
1152     }
1153 
1154   return saved_entry->address;
1155 }
1156 
1157 /* Return -1 if the CSR has never been defined.  Otherwise, return
1158    the address.  */
1159 
1160 static unsigned int
reg_csr_lookup_internal(const char * s)1161 reg_csr_lookup_internal (const char *s)
1162 {
1163   struct riscv_csr_extra *r =
1164     (struct riscv_csr_extra *) str_hash_find (csr_extra_hash, s);
1165 
1166   if (r == NULL)
1167     return -1U;
1168 
1169   return riscv_csr_address (s, r);
1170 }
1171 
1172 static unsigned int
reg_lookup_internal(const char * s,enum reg_class class)1173 reg_lookup_internal (const char *s, enum reg_class class)
1174 {
1175   void *r;
1176 
1177   if (class == RCLASS_CSR)
1178     return reg_csr_lookup_internal (s);
1179 
1180   r = str_hash_find (reg_names_hash, s);
1181   if (r == NULL || DECODE_REG_CLASS (r) != class)
1182     return -1;
1183 
1184   if (riscv_subset_supports (&riscv_rps_as, "e")
1185       && class == RCLASS_GPR
1186       && DECODE_REG_NUM (r) > 15)
1187     return -1;
1188 
1189   return DECODE_REG_NUM (r);
1190 }
1191 
1192 static bool
reg_lookup(char ** s,enum reg_class class,unsigned int * regnop)1193 reg_lookup (char **s, enum reg_class class, unsigned int *regnop)
1194 {
1195   char *e;
1196   char save_c;
1197   int reg = -1;
1198 
1199   /* Find end of name.  */
1200   e = *s;
1201   if (is_name_beginner (*e))
1202     ++e;
1203   while (is_part_of_name (*e))
1204     ++e;
1205 
1206   /* Terminate name.  */
1207   save_c = *e;
1208   *e = '\0';
1209 
1210   /* Look for the register.  Advance to next token if one was recognized.  */
1211   if ((reg = reg_lookup_internal (*s, class)) >= 0)
1212     *s = e;
1213 
1214   *e = save_c;
1215   if (regnop)
1216     *regnop = reg;
1217   return reg >= 0;
1218 }
1219 
1220 static bool
arg_lookup(char ** s,const char * const * array,size_t size,unsigned * regnop)1221 arg_lookup (char **s, const char *const *array, size_t size, unsigned *regnop)
1222 {
1223   const char *p = strchr (*s, ',');
1224   size_t i, len = p ? (size_t)(p - *s) : strlen (*s);
1225 
1226   if (len == 0)
1227     return false;
1228 
1229   for (i = 0; i < size; i++)
1230     if (array[i] != NULL && strncmp (array[i], *s, len) == 0
1231 	&& array[i][len] == '\0')
1232       {
1233 	*regnop = i;
1234 	*s += len;
1235 	return true;
1236       }
1237 
1238   return false;
1239 }
1240 
1241 static bool
flt_lookup(float f,const float * array,size_t size,unsigned * regnop)1242 flt_lookup (float f, const float *array, size_t size, unsigned *regnop)
1243 {
1244   size_t i;
1245 
1246   for (i = 0; i < size; i++)
1247     if (array[i] == f)
1248       {
1249 	*regnop = i;
1250 	return true;
1251       }
1252 
1253   return false;
1254 }
1255 
1256 #define USE_BITS(mask,shift) (used_bits |= ((insn_t)(mask) << (shift)))
1257 #define USE_IMM(n, s) \
1258   (used_bits |= ((insn_t)((1ull<<n)-1) << (s)))
1259 
1260 /* For consistency checking, verify that all bits are specified either
1261    by the match/mask part of the instruction definition, or by the
1262    operand list. The `length` could be the actual instruction length or
1263    0 for auto-detection.  */
1264 
1265 static bool
validate_riscv_insn(const struct riscv_opcode * opc,int length)1266 validate_riscv_insn (const struct riscv_opcode *opc, int length)
1267 {
1268   const char *oparg, *opargStart;
1269   insn_t used_bits = opc->mask;
1270   int insn_width;
1271   insn_t required_bits;
1272 
1273   if (length == 0)
1274     length = riscv_insn_length (opc->match);
1275   /* We don't support instructions longer than 64-bits yet.  */
1276   if (length > 8)
1277     length = 8;
1278   insn_width = 8 * length;
1279 
1280   required_bits = ((insn_t)~0ULL) >> (64 - insn_width);
1281 
1282   if ((used_bits & opc->match) != (opc->match & required_bits))
1283     {
1284       as_bad (_("internal: bad RISC-V opcode (mask error): %s %s"),
1285 	      opc->name, opc->args);
1286       return false;
1287     }
1288 
1289   for (oparg = opc->args; *oparg; ++oparg)
1290     {
1291       opargStart = oparg;
1292       switch (*oparg)
1293 	{
1294 	case 'C': /* RVC */
1295 	  switch (*++oparg)
1296 	    {
1297 	    case 'U': break; /* CRS1, constrained to equal RD.  */
1298 	    case 'c': break; /* CRS1, constrained to equal sp.  */
1299 	    case 'T': /* CRS2, floating point.  */
1300 	    case 'V': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
1301 	    case 'S': /* CRS1S, floating point.  */
1302 	    case 's': USE_BITS (OP_MASK_CRS1S, OP_SH_CRS1S); break;
1303 	    case 'w': break; /* CRS1S, constrained to equal RD.  */
1304 	    case 'D': /* CRS2S, floating point.  */
1305 	    case 't': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
1306 	    case 'x': break; /* CRS2S, constrained to equal RD.  */
1307 	    case 'z': break; /* CRS2S, constrained to be x0.  */
1308 	    case '>': /* CITYPE immediate, compressed shift.  */
1309 	    case 'u': /* CITYPE immediate, compressed lui.  */
1310 	    case 'v': /* CITYPE immediate, li to compressed lui.  */
1311 	    case 'o': /* CITYPE immediate, allow zero.  */
1312 	    case 'j': used_bits |= ENCODE_CITYPE_IMM (-1U); break;
1313 	    case 'L': used_bits |= ENCODE_CITYPE_ADDI16SP_IMM (-1U); break;
1314 	    case 'm': used_bits |= ENCODE_CITYPE_LWSP_IMM (-1U); break;
1315 	    case 'n': used_bits |= ENCODE_CITYPE_LDSP_IMM (-1U); break;
1316 	    case '6': used_bits |= ENCODE_CSSTYPE_IMM (-1U); break;
1317 	    case 'M': used_bits |= ENCODE_CSSTYPE_SWSP_IMM (-1U); break;
1318 	    case 'N': used_bits |= ENCODE_CSSTYPE_SDSP_IMM (-1U); break;
1319 	    case '8': used_bits |= ENCODE_CIWTYPE_IMM (-1U); break;
1320 	    case 'K': used_bits |= ENCODE_CIWTYPE_ADDI4SPN_IMM (-1U); break;
1321 	    /* CLTYPE and CSTYPE have the same immediate encoding.  */
1322 	    case '5': used_bits |= ENCODE_CLTYPE_IMM (-1U); break;
1323 	    case 'k': used_bits |= ENCODE_CLTYPE_LW_IMM (-1U); break;
1324 	    case 'l': used_bits |= ENCODE_CLTYPE_LD_IMM (-1U); break;
1325 	    case 'p': used_bits |= ENCODE_CBTYPE_IMM (-1U); break;
1326 	    case 'a': used_bits |= ENCODE_CJTYPE_IMM (-1U); break;
1327 	    case 'F': /* Compressed funct for .insn directive.  */
1328 	      switch (*++oparg)
1329 		{
1330 		case '6': USE_BITS (OP_MASK_CFUNCT6, OP_SH_CFUNCT6); break;
1331 		case '4': USE_BITS (OP_MASK_CFUNCT4, OP_SH_CFUNCT4); break;
1332 		case '3': USE_BITS (OP_MASK_CFUNCT3, OP_SH_CFUNCT3); break;
1333 		case '2': USE_BITS (OP_MASK_CFUNCT2, OP_SH_CFUNCT2); break;
1334 		default:
1335 		  goto unknown_validate_operand;
1336 		}
1337 	      break;
1338 	    default:
1339 	      goto unknown_validate_operand;
1340 	    }
1341 	  break;  /* end RVC */
1342 	case 'V': /* RVV */
1343 	  switch (*++oparg)
1344 	    {
1345 	    case 'd':
1346 	    case 'f': USE_BITS (OP_MASK_VD, OP_SH_VD); break;
1347 	    case 'e': USE_BITS (OP_MASK_VWD, OP_SH_VWD); break;
1348 	    case 's': USE_BITS (OP_MASK_VS1, OP_SH_VS1); break;
1349 	    case 't': USE_BITS (OP_MASK_VS2, OP_SH_VS2); break;
1350 	    case 'u': USE_BITS (OP_MASK_VS1, OP_SH_VS1);
1351 		      USE_BITS (OP_MASK_VS2, OP_SH_VS2); break;
1352 	    case 'v': USE_BITS (OP_MASK_VD, OP_SH_VD);
1353 		      USE_BITS (OP_MASK_VS1, OP_SH_VS1);
1354 		      USE_BITS (OP_MASK_VS2, OP_SH_VS2); break;
1355 	    case '0': break;
1356 	    case 'b': used_bits |= ENCODE_RVV_VB_IMM (-1U); break;
1357 	    case 'c': used_bits |= ENCODE_RVV_VC_IMM (-1U); break;
1358 	    case 'i':
1359 	    case 'j':
1360 	    case 'k': USE_BITS (OP_MASK_VIMM, OP_SH_VIMM); break;
1361 	    case 'l': used_bits |= ENCODE_RVV_VI_UIMM6 (-1U); break;
1362 	    case 'm': USE_BITS (OP_MASK_VMASK, OP_SH_VMASK); break;
1363 	    case 'M': break; /* Macro operand, must be a mask register.  */
1364 	    case 'T': break; /* Macro operand, must be a vector register.  */
1365 	    default:
1366 	      goto unknown_validate_operand;
1367 	    }
1368 	  break; /* end RVV */
1369 	case ',': break;
1370 	case '(': break;
1371 	case ')': break;
1372 	case '<': USE_BITS (OP_MASK_SHAMTW, OP_SH_SHAMTW); break;
1373 	case '>': USE_BITS (OP_MASK_SHAMT, OP_SH_SHAMT); break;
1374 	case 'A': break; /* Macro operand, must be symbol.  */
1375 	case 'B': break; /* Macro operand, must be symbol or constant.  */
1376 	case 'c': break; /* Macro operand, must be symbol or constant.  */
1377 	case 'I': break; /* Macro operand, must be constant.  */
1378 	case 'D': /* RD, floating point.  */
1379 	case 'd': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
1380 	case 'y': USE_BITS (OP_MASK_BS,	OP_SH_BS); break;
1381 	case 'Y': USE_BITS (OP_MASK_RNUM, OP_SH_RNUM); break;
1382 	case 'Z': /* RS1, CSR number.  */
1383 	case 'S': /* RS1, floating point.  */
1384 	case 's': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
1385 	case 'U': /* RS1 and RS2 are the same, floating point.  */
1386 	  USE_BITS (OP_MASK_RS1, OP_SH_RS1);
1387 	  /* Fall through.  */
1388 	case 'T': /* RS2, floating point.  */
1389 	case 't': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
1390 	case 'R': /* RS3, floating point.  */
1391 	case 'r': USE_BITS (OP_MASK_RS3, OP_SH_RS3); break;
1392 	case 'm': USE_BITS (OP_MASK_RM, OP_SH_RM); break;
1393 	case 'E': USE_BITS (OP_MASK_CSR, OP_SH_CSR); break;
1394 	case 'P': USE_BITS (OP_MASK_PRED, OP_SH_PRED); break;
1395 	case 'Q': USE_BITS (OP_MASK_SUCC, OP_SH_SUCC); break;
1396 	case 'o': /* ITYPE immediate, load displacement.  */
1397 	case 'j': used_bits |= ENCODE_ITYPE_IMM (-1U); break;
1398 	case 'a': used_bits |= ENCODE_JTYPE_IMM (-1U); break;
1399 	case 'p': used_bits |= ENCODE_BTYPE_IMM (-1U); break;
1400 	case 'q': used_bits |= ENCODE_STYPE_IMM (-1U); break;
1401 	case 'u': used_bits |= ENCODE_UTYPE_IMM (-1U); break;
1402 	case 'z': break; /* Zero immediate.  */
1403 	case '[': break; /* Unused operand.  */
1404 	case ']': break; /* Unused operand.  */
1405 	case '0': break; /* AMO displacement, must to zero.  */
1406 	case '1': break; /* Relaxation operand.  */
1407 	case 'F': /* Funct for .insn directive.  */
1408 	  switch (*++oparg)
1409 	    {
1410 	    case '7': USE_BITS (OP_MASK_FUNCT7, OP_SH_FUNCT7); break;
1411 	    case '3': USE_BITS (OP_MASK_FUNCT3, OP_SH_FUNCT3); break;
1412 	    case '2': USE_BITS (OP_MASK_FUNCT2, OP_SH_FUNCT2); break;
1413 	    default:
1414 	      goto unknown_validate_operand;
1415 	    }
1416 	  break;
1417 	case 'O': /* Opcode for .insn directive.  */
1418 	  switch (*++oparg)
1419 	    {
1420 	    case '4': USE_BITS (OP_MASK_OP, OP_SH_OP); break;
1421 	    case '2': USE_BITS (OP_MASK_OP2, OP_SH_OP2); break;
1422 	    default:
1423 	      goto unknown_validate_operand;
1424 	    }
1425 	  break;
1426 	case 'W': /* Various operands for standard z extensions.  */
1427 	  switch (*++oparg)
1428 	    {
1429 	    case 'i':
1430 	      switch (*++oparg)
1431 		{
1432 		case 'f': used_bits |= ENCODE_STYPE_IMM (-1U); break;
1433 		default:
1434 		  goto unknown_validate_operand;
1435 		}
1436 	      break;
1437 	    case 'f':
1438 	      switch (*++oparg)
1439 		{
1440 		case 'v': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
1441 		default:
1442 		  goto unknown_validate_operand;
1443 		}
1444 	      break;
1445 	    case 'c':
1446 	      switch (*++oparg)
1447 		{
1448 		/* byte immediate operators, load/store byte insns.  */
1449 		case 'h': used_bits |= ENCODE_ZCB_HALFWORD_UIMM (-1U); break;
1450 		/* halfword immediate operators, load/store halfword insns.  */
1451 		case 'b': used_bits |= ENCODE_ZCB_BYTE_UIMM (-1U); break;
1452 		case 'f': break;
1453 		default:
1454 		  goto unknown_validate_operand;
1455 		}
1456 	      break;
1457 	    default:
1458 	      goto unknown_validate_operand;
1459 	    }
1460 	  break;
1461 	case 'X': /* Vendor-specific operands.  */
1462 	  switch (*++oparg)
1463 	    {
1464 	    case 't': /* Vendor-specific (T-head) operands.  */
1465 	      {
1466 		size_t n;
1467 		size_t s;
1468 		switch (*++oparg)
1469 		  {
1470 		  case 'V':
1471 		    switch (*++oparg)
1472 		      {
1473 		      case 'c': /* Vtypei for th.vsetvli.  */
1474 			used_bits |= ENCODE_RVV_VC_IMM (-1U); break;
1475 		      default:
1476 			goto unknown_validate_operand;
1477 		      }
1478 		      break;
1479 		  case 'l': /* Integer immediate, literal.  */
1480 		    oparg += strcspn(oparg, ",") - 1;
1481 		    break;
1482 		  case 's': /* Integer immediate, 'XtsN@S' ... N-bit signed immediate at bit S.  */
1483 		    goto use_imm;
1484 		  case 'u': /* Integer immediate, 'XtuN@S' ... N-bit unsigned immediate at bit S.  */
1485 		    goto use_imm;
1486 		  use_imm:
1487 		    n = strtol (oparg + 1, (char **)&oparg, 10);
1488 		    if (*oparg != '@')
1489 		      goto unknown_validate_operand;
1490 		    s = strtol (oparg + 1, (char **)&oparg, 10);
1491 		    oparg--;
1492 
1493 		    USE_IMM (n, s);
1494 		    break;
1495 		  default:
1496 		    goto unknown_validate_operand;
1497 		  }
1498 	      }
1499 	      break;
1500 	    case 'c': /* Vendor-specific (CORE-V) operands.  */
1501 	      switch (*++oparg)
1502 		{
1503 		  case '2':
1504 		    /* ls2[4:0] */
1505 		    used_bits |= ENCODE_CV_IS2_UIMM5 (-1U);
1506 		    break;
1507 		  case '3':
1508 		    used_bits |= ENCODE_CV_IS3_UIMM5 (-1U);
1509 		    break;
1510 		  default:
1511 		    goto unknown_validate_operand;
1512 		}
1513 	      break;
1514 	    case 's': /* Vendor-specific (SiFive) operands.  */
1515 	      switch (*++oparg)
1516 		{
1517 		  case 'd': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
1518 		  case 't': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
1519 		  case 'O':
1520 		    switch (*++oparg)
1521 		      {
1522 			case '2': USE_BITS (OP_MASK_XSO2, OP_SH_XSO2); break;
1523 			case '1': USE_BITS (OP_MASK_XSO1, OP_SH_XSO1); break;
1524 			default:
1525 			  goto unknown_validate_operand;
1526 		      }
1527 		    break;
1528 		  default:
1529 		    goto unknown_validate_operand;
1530 		}
1531 		break;
1532 	    default:
1533 	      goto unknown_validate_operand;
1534 	    }
1535 	  break;
1536 	default:
1537 	unknown_validate_operand:
1538 	  as_bad (_("internal: bad RISC-V opcode "
1539 		    "(unknown operand type `%s'): %s %s"),
1540 		  opargStart, opc->name, opc->args);
1541 	  return false;
1542 	}
1543     }
1544 
1545   if (used_bits != required_bits)
1546     {
1547       as_bad (_("internal: bad RISC-V opcode "
1548 		"(bits %#llx undefined or invalid): %s %s"),
1549 	      (unsigned long long)(used_bits ^ required_bits),
1550 	      opc->name, opc->args);
1551       return false;
1552     }
1553   return true;
1554 }
1555 
1556 #undef USE_BITS
1557 
1558 struct percent_op_match
1559 {
1560   const char *str;
1561   bfd_reloc_code_real_type reloc;
1562 };
1563 
1564 /* Common hash table initialization function for instruction and .insn
1565    directive.  */
1566 
1567 static htab_t
init_opcode_hash(const struct riscv_opcode * opcodes,bool insn_directive_p)1568 init_opcode_hash (const struct riscv_opcode *opcodes,
1569 		  bool insn_directive_p)
1570 {
1571   int i = 0;
1572   int length;
1573   htab_t hash = str_htab_create ();
1574   while (opcodes[i].name)
1575     {
1576       const char *name = opcodes[i].name;
1577       if (str_hash_insert (hash, name, &opcodes[i], 0) != NULL)
1578 	as_fatal (_("internal: duplicate %s"), name);
1579 
1580       do
1581 	{
1582 	  if (opcodes[i].pinfo != INSN_MACRO)
1583 	    {
1584 	      if (insn_directive_p)
1585 		length = ((name[0] == 'c') ? 2 : 4);
1586 	      else
1587 		length = 0; /* Let assembler determine the length.  */
1588 	      if (!validate_riscv_insn (&opcodes[i], length))
1589 		as_fatal (_("internal: broken assembler.  "
1590 			    "No assembly attempted"));
1591 	    }
1592 	  else
1593 	    gas_assert (!insn_directive_p);
1594 	  ++i;
1595 	}
1596       while (opcodes[i].name && !strcmp (opcodes[i].name, name));
1597     }
1598 
1599   return hash;
1600 }
1601 
1602 /* Record all PC-relative high-part relocation that we have encountered to
1603    help us resolve the corresponding low-part relocation later.  */
1604 typedef struct
1605 {
1606   bfd_vma address;
1607   symbolS *symbol;
1608   bfd_vma target;
1609 } riscv_pcrel_hi_fixup;
1610 
1611 /* Handle of the pcrel_hi hash table.  */
1612 static htab_t riscv_pcrel_hi_fixup_hash;
1613 
1614 /* Get the key of a entry from the pcrel_hi hash table.  */
1615 
1616 static hashval_t
riscv_pcrel_fixup_hash(const void * entry)1617 riscv_pcrel_fixup_hash (const void *entry)
1618 {
1619   const riscv_pcrel_hi_fixup *e = entry;
1620   return (hashval_t) (e->address);
1621 }
1622 
1623 /* Compare the keys between two entries fo the pcrel_hi hash table.  */
1624 
1625 static int
riscv_pcrel_fixup_eq(const void * entry1,const void * entry2)1626 riscv_pcrel_fixup_eq (const void *entry1, const void *entry2)
1627 {
1628   const riscv_pcrel_hi_fixup *e1 = entry1, *e2 = entry2;
1629   return e1->address == e2->address;
1630 }
1631 
1632 /* Record the pcrel_hi relocation.  */
1633 
1634 static bool
riscv_record_pcrel_fixup(htab_t p,bfd_vma address,symbolS * symbol,bfd_vma target)1635 riscv_record_pcrel_fixup (htab_t p, bfd_vma address, symbolS *symbol,
1636 			  bfd_vma target)
1637 {
1638   riscv_pcrel_hi_fixup entry = {address, symbol, target};
1639   riscv_pcrel_hi_fixup **slot =
1640 	(riscv_pcrel_hi_fixup **) htab_find_slot (p, &entry, INSERT);
1641   if (slot == NULL)
1642     return false;
1643 
1644   *slot = (riscv_pcrel_hi_fixup *) xmalloc (sizeof (riscv_pcrel_hi_fixup));
1645   if (*slot == NULL)
1646     return false;
1647   **slot = entry;
1648   return true;
1649 }
1650 
1651 /* This function is called once, at assembler startup time.  It should set up
1652    all the tables, etc. that the MD part of the assembler will need.  */
1653 
1654 void
md_begin(void)1655 md_begin (void)
1656 {
1657   unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
1658 
1659   if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
1660     as_warn (_("could not set architecture and machine"));
1661 
1662   op_hash = init_opcode_hash (riscv_opcodes, false);
1663   insn_type_hash = init_opcode_hash (riscv_insn_types, true);
1664 
1665   reg_names_hash = str_htab_create ();
1666   hash_reg_names (RCLASS_GPR, riscv_gpr_names_numeric, NGPR);
1667   hash_reg_names (RCLASS_GPR, riscv_gpr_names_abi, NGPR);
1668   hash_reg_names (RCLASS_FPR, riscv_fpr_names_numeric, NFPR);
1669   hash_reg_names (RCLASS_FPR, riscv_fpr_names_abi, NFPR);
1670   hash_reg_names (RCLASS_VECR, riscv_vecr_names_numeric, NVECR);
1671   hash_reg_names (RCLASS_VECM, riscv_vecm_names_numeric, NVECM);
1672   /* Add "fp" as an alias for "s0".  */
1673   hash_reg_name (RCLASS_GPR, "fp", 8);
1674 
1675   /* Create and insert CSR hash tables.  */
1676   csr_extra_hash = str_htab_create ();
1677 #define DECLARE_CSR(name, num, class, define_version, abort_version) \
1678   riscv_init_csr_hash (#name, num, class, define_version, abort_version);
1679 #define DECLARE_CSR_ALIAS(name, num, class, define_version, abort_version) \
1680   DECLARE_CSR(name, num, class, define_version, abort_version);
1681 #include "opcode/riscv-opc.h"
1682 #undef DECLARE_CSR
1683 
1684   opcode_names_hash = str_htab_create ();
1685   init_opcode_names_hash ();
1686 
1687   /* Create pcrel_hi hash table to resolve the relocation while with
1688      -mno-relax.  */
1689   riscv_pcrel_hi_fixup_hash = htab_create (1024, riscv_pcrel_fixup_hash,
1690 					   riscv_pcrel_fixup_eq, free);
1691 
1692   /* Set the default alignment for the text section.  */
1693   record_alignment (text_section, riscv_opts.rvc ? 1 : 2);
1694 }
1695 
1696 static insn_t
riscv_apply_const_reloc(bfd_reloc_code_real_type reloc_type,bfd_vma value)1697 riscv_apply_const_reloc (bfd_reloc_code_real_type reloc_type, bfd_vma value)
1698 {
1699   switch (reloc_type)
1700     {
1701     case BFD_RELOC_32:
1702       return value;
1703 
1704     case BFD_RELOC_RISCV_HI20:
1705       return ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value));
1706 
1707     case BFD_RELOC_RISCV_LO12_S:
1708       return ENCODE_STYPE_IMM (value);
1709 
1710     case BFD_RELOC_RISCV_LO12_I:
1711       return ENCODE_ITYPE_IMM (value);
1712 
1713     default:
1714       abort ();
1715     }
1716 }
1717 
1718 /* Output an instruction.  IP is the instruction information.
1719    ADDRESS_EXPR is an operand of the instruction to be used with
1720    RELOC_TYPE.  */
1721 
1722 static void
append_insn(struct riscv_cl_insn * ip,expressionS * address_expr,bfd_reloc_code_real_type reloc_type)1723 append_insn (struct riscv_cl_insn *ip, expressionS *address_expr,
1724 	     bfd_reloc_code_real_type reloc_type)
1725 {
1726   dwarf2_emit_insn (0);
1727 
1728   if (reloc_type != BFD_RELOC_UNUSED)
1729     {
1730       reloc_howto_type *howto;
1731 
1732       gas_assert (address_expr);
1733       if (reloc_type == BFD_RELOC_12_PCREL
1734 	  || reloc_type == BFD_RELOC_RISCV_JMP)
1735 	{
1736 	  int j = reloc_type == BFD_RELOC_RISCV_JMP;
1737 	  int best_case = insn_length (ip);
1738 	  unsigned worst_case = relaxed_branch_length (NULL, NULL, 0);
1739 
1740 	  if (now_seg == absolute_section)
1741 	    {
1742 	      as_bad (_("relaxable branches not supported in absolute section"));
1743 	      return;
1744 	    }
1745 
1746 	  add_relaxed_insn (ip, worst_case, best_case,
1747 			    RELAX_BRANCH_ENCODE (j, best_case == 2, worst_case),
1748 			    address_expr->X_add_symbol,
1749 			    address_expr->X_add_number);
1750 	  return;
1751 	}
1752       else
1753 	{
1754 	  howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
1755 	  if (howto == NULL)
1756 	    as_bad (_("internal: unsupported RISC-V relocation number %d"),
1757 		    reloc_type);
1758 
1759 	  ip->fixp = fix_new_exp (ip->frag, ip->where,
1760 				  bfd_get_reloc_size (howto),
1761 				  address_expr, false, reloc_type);
1762 
1763 	  ip->fixp->fx_tcbit = riscv_opts.relax;
1764 	  ip->fixp->tc_fix_data.source_macro = source_macro;
1765 	}
1766     }
1767 
1768   add_fixed_insn (ip);
1769 
1770   /* We need to start a new frag after any instruction that can be
1771      optimized away or compressed by the linker during relaxation, to prevent
1772      the assembler from computing static offsets across such an instruction.
1773      This is necessary to get correct EH info.  */
1774   if (reloc_type == BFD_RELOC_RISCV_HI20
1775       || reloc_type == BFD_RELOC_RISCV_PCREL_HI20
1776       || reloc_type == BFD_RELOC_RISCV_TPREL_HI20
1777       || reloc_type == BFD_RELOC_RISCV_TPREL_ADD)
1778     {
1779       frag_wane (frag_now);
1780       frag_new (0);
1781     }
1782 }
1783 
1784 /* Build an instruction created by a macro expansion.  This is passed
1785    a pointer to the count of instructions created so far, an expression,
1786    the name of the instruction to build, an operand format string, and
1787    corresponding arguments.  */
1788 
1789 static void
macro_build(expressionS * ep,const char * name,const char * fmt,...)1790 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
1791 {
1792   const struct riscv_opcode *mo;
1793   struct riscv_cl_insn insn;
1794   bfd_reloc_code_real_type r;
1795   va_list args;
1796   const char *fmtStart;
1797 
1798   va_start (args, fmt);
1799 
1800   r = BFD_RELOC_UNUSED;
1801   mo = (struct riscv_opcode *) str_hash_find (op_hash, name);
1802   gas_assert (mo);
1803 
1804   /* Find a non-RVC variant of the instruction.  append_insn will compress
1805      it if possible.  */
1806   while (riscv_insn_length (mo->match) < 4)
1807     mo++;
1808   gas_assert (strcmp (name, mo->name) == 0);
1809 
1810   create_insn (&insn, mo);
1811   for (;; ++fmt)
1812     {
1813       fmtStart = fmt;
1814       switch (*fmt)
1815 	{
1816 	case 'V': /* RVV */
1817 	  switch (*++fmt)
1818 	    {
1819 	    case 'd':
1820 	      INSERT_OPERAND (VD, insn, va_arg (args, int));
1821 	      continue;
1822 	    case 's':
1823 	      INSERT_OPERAND (VS1, insn, va_arg (args, int));
1824 	      continue;
1825 	    case 't':
1826 	      INSERT_OPERAND (VS2, insn, va_arg (args, int));
1827 	      continue;
1828 	    case 'm':
1829 	      {
1830 		int reg = va_arg (args, int);
1831 		if (reg == -1)
1832 		  {
1833 		    INSERT_OPERAND (VMASK, insn, 1);
1834 		    continue;
1835 		  }
1836 		else if (reg == 0)
1837 		  {
1838 		    INSERT_OPERAND (VMASK, insn, 0);
1839 		    continue;
1840 		  }
1841 		else
1842 		  goto unknown_macro_argument;
1843 	      }
1844 	    default:
1845 	      goto unknown_macro_argument;
1846 	    }
1847 	  break;
1848 
1849 	case 'd':
1850 	  INSERT_OPERAND (RD, insn, va_arg (args, int));
1851 	  continue;
1852 	case 's':
1853 	  INSERT_OPERAND (RS1, insn, va_arg (args, int));
1854 	  continue;
1855 	case 't':
1856 	  INSERT_OPERAND (RS2, insn, va_arg (args, int));
1857 	  continue;
1858 
1859 	case 'j':
1860 	case 'u':
1861 	case 'q':
1862 	  gas_assert (ep != NULL);
1863 	  r = va_arg (args, int);
1864 	  continue;
1865 
1866 	case '\0':
1867 	  break;
1868 	case ',':
1869 	  continue;
1870 	default:
1871 	unknown_macro_argument:
1872 	  as_fatal (_("internal: invalid macro argument `%s'"), fmtStart);
1873 	}
1874       break;
1875     }
1876   va_end (args);
1877   gas_assert (r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
1878 
1879   append_insn (&insn, ep, r);
1880 }
1881 
1882 /* Build an instruction created by a macro expansion.  Like md_assemble but
1883    accept a printf-style format string and arguments.  */
1884 
1885 static void
md_assemblef(const char * format,...)1886 md_assemblef (const char *format, ...)
1887 {
1888   char *buf = NULL;
1889   va_list ap;
1890   int r;
1891 
1892   va_start (ap, format);
1893 
1894   r = vasprintf (&buf, format, ap);
1895 
1896   if (r < 0)
1897     as_fatal (_("internal: vasprintf failed"));
1898 
1899   md_assemble (buf);
1900   free(buf);
1901 
1902   va_end (ap);
1903 }
1904 
1905 /* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
1906    unset.  */
1907 
1908 static void
normalize_constant_expr(expressionS * ex)1909 normalize_constant_expr (expressionS *ex)
1910 {
1911   if (xlen > 32)
1912     return;
1913   if ((ex->X_op == O_constant || ex->X_op == O_symbol)
1914       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
1915     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
1916 			- 0x80000000);
1917 }
1918 
1919 /* Fail if an expression EX is not a constant.  IP is the instruction using EX.
1920    MAYBE_CSR is true if the symbol may be an unrecognized CSR name.  */
1921 
1922 static void
check_absolute_expr(struct riscv_cl_insn * ip,expressionS * ex,bool maybe_csr)1923 check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex,
1924 		     bool maybe_csr)
1925 {
1926   if (ex->X_op == O_big)
1927     as_bad (_("unsupported large constant"));
1928   else if (maybe_csr && ex->X_op == O_symbol)
1929     as_bad (_("unknown CSR `%s'"),
1930 	    S_GET_NAME (ex->X_add_symbol));
1931   else if (ex->X_op != O_constant)
1932     as_bad (_("instruction %s requires absolute expression"),
1933 	    ip->insn_mo->name);
1934   normalize_constant_expr (ex);
1935 }
1936 
1937 static symbolS *
make_internal_label(void)1938 make_internal_label (void)
1939 {
1940   return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg, frag_now,
1941 					frag_now_fix ());
1942 }
1943 
1944 /* Load an entry from the GOT.  */
1945 
1946 static void
pcrel_access(int destreg,int tempreg,expressionS * ep,const char * lo_insn,const char * lo_pattern,bfd_reloc_code_real_type hi_reloc,bfd_reloc_code_real_type lo_reloc)1947 pcrel_access (int destreg, int tempreg, expressionS *ep,
1948 	      const char *lo_insn, const char *lo_pattern,
1949 	      bfd_reloc_code_real_type hi_reloc,
1950 	      bfd_reloc_code_real_type lo_reloc)
1951 {
1952   expressionS ep2;
1953   ep2.X_op = O_symbol;
1954   ep2.X_add_symbol = make_internal_label ();
1955   ep2.X_add_number = 0;
1956 
1957   macro_build (ep, "auipc", "d,u", tempreg, hi_reloc);
1958   macro_build (&ep2, lo_insn, lo_pattern, destreg, tempreg, lo_reloc);
1959 }
1960 
1961 static void
pcrel_load(int destreg,int tempreg,expressionS * ep,const char * lo_insn,bfd_reloc_code_real_type hi_reloc,bfd_reloc_code_real_type lo_reloc)1962 pcrel_load (int destreg, int tempreg, expressionS *ep, const char *lo_insn,
1963 	    bfd_reloc_code_real_type hi_reloc,
1964 	    bfd_reloc_code_real_type lo_reloc)
1965 {
1966   pcrel_access (destreg, tempreg, ep, lo_insn, "d,s,j", hi_reloc, lo_reloc);
1967 }
1968 
1969 static void
pcrel_store(int srcreg,int tempreg,expressionS * ep,const char * lo_insn,bfd_reloc_code_real_type hi_reloc,bfd_reloc_code_real_type lo_reloc)1970 pcrel_store (int srcreg, int tempreg, expressionS *ep, const char *lo_insn,
1971 	     bfd_reloc_code_real_type hi_reloc,
1972 	     bfd_reloc_code_real_type lo_reloc)
1973 {
1974   pcrel_access (srcreg, tempreg, ep, lo_insn, "t,s,q", hi_reloc, lo_reloc);
1975 }
1976 
1977 /* PC-relative function call using AUIPC/JALR, relaxed to JAL.  */
1978 
1979 static void
riscv_call(int destreg,int tempreg,expressionS * ep,bfd_reloc_code_real_type reloc)1980 riscv_call (int destreg, int tempreg, expressionS *ep,
1981 	    bfd_reloc_code_real_type reloc)
1982 {
1983   /* Ensure the jalr is emitted to the same frag as the auipc.  */
1984   frag_grow (8);
1985   macro_build (ep, "auipc", "d,u", tempreg, reloc);
1986   macro_build (NULL, "jalr", "d,s", destreg, tempreg);
1987   /* See comment at end of append_insn.  */
1988   frag_wane (frag_now);
1989   frag_new (0);
1990 }
1991 
1992 /* Load an integer constant into a register.  */
1993 
1994 static void
load_const(int reg,expressionS * ep)1995 load_const (int reg, expressionS *ep)
1996 {
1997   int shift = RISCV_IMM_BITS;
1998   bfd_vma upper_imm, sign = (bfd_vma) 1 << (RISCV_IMM_BITS - 1);
1999   expressionS upper = *ep, lower = *ep;
2000   lower.X_add_number = ((ep->X_add_number & (sign + sign - 1)) ^ sign) - sign;
2001   upper.X_add_number -= lower.X_add_number;
2002 
2003   if (ep->X_op != O_constant)
2004     {
2005       as_bad (_("unsupported large constant"));
2006       return;
2007     }
2008 
2009   if (xlen > 32 && !IS_SEXT_32BIT_NUM (ep->X_add_number))
2010     {
2011       /* Reduce to a signed 32-bit constant using SLLI and ADDI.  */
2012       while (((upper.X_add_number >> shift) & 1) == 0)
2013 	shift++;
2014 
2015       upper.X_add_number = (int64_t) upper.X_add_number >> shift;
2016       load_const (reg, &upper);
2017 
2018       md_assemblef ("slli x%d, x%d, 0x%x", reg, reg, shift);
2019       if (lower.X_add_number != 0)
2020 	md_assemblef ("addi x%d, x%d, %" PRId64, reg, reg,
2021 		      (int64_t) lower.X_add_number);
2022     }
2023   else
2024     {
2025       /* Simply emit LUI and/or ADDI to build a 32-bit signed constant.  */
2026       int hi_reg = 0;
2027 
2028       if (upper.X_add_number != 0)
2029 	{
2030 	  /* Discard low part and zero-extend upper immediate.  */
2031 	  upper_imm = ((uint32_t)upper.X_add_number >> shift);
2032 
2033 	  md_assemblef ("lui x%d, 0x%" PRIx64, reg, (uint64_t) upper_imm);
2034 	  hi_reg = reg;
2035 	}
2036 
2037       if (lower.X_add_number != 0 || hi_reg == 0)
2038 	md_assemblef ("%s x%d, x%d, %" PRId64, ADD32_INSN, reg, hi_reg,
2039 		      (int64_t) lower.X_add_number);
2040     }
2041 }
2042 
2043 /* Zero extend and sign extend byte/half-word/word.  */
2044 
2045 static void
riscv_ext(int destreg,int srcreg,unsigned shift,bool sign)2046 riscv_ext (int destreg, int srcreg, unsigned shift, bool sign)
2047 {
2048   md_assemblef ("slli x%d, x%d, %#x", destreg, srcreg, shift);
2049   md_assemblef ("sr%ci x%d, x%d, %#x",
2050 		sign ? 'a' : 'l', destreg, destreg, shift);
2051 }
2052 
2053 /* Expand RISC-V Vector macros into one or more instructions.  */
2054 
2055 static void
vector_macro(struct riscv_cl_insn * ip)2056 vector_macro (struct riscv_cl_insn *ip)
2057 {
2058   int vd = (ip->insn_opcode >> OP_SH_VD) & OP_MASK_VD;
2059   int vs1 = (ip->insn_opcode >> OP_SH_VS1) & OP_MASK_VS1;
2060   int vs2 = (ip->insn_opcode >> OP_SH_VS2) & OP_MASK_VS2;
2061   int vm = (ip->insn_opcode >> OP_SH_VMASK) & OP_MASK_VMASK;
2062   int vtemp = (ip->insn_opcode >> OP_SH_VFUNCT6) & OP_MASK_VFUNCT6;
2063   const char *vmslt_vx = ip->insn_mo->match ? "vmsltu.vx" : "vmslt.vx";
2064   int mask = ip->insn_mo->mask;
2065 
2066   switch (mask)
2067     {
2068     case M_VMSGE:
2069       if (vm)
2070 	{
2071 	  /* Unmasked.  */
2072 	  macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vd, vs2, vs1, -1);
2073 	  macro_build (NULL, "vmnand.mm", "Vd,Vt,Vs", vd, vd, vd);
2074 	  break;
2075 	}
2076       if (vtemp != 0)
2077 	{
2078 	  /* Masked.  Have vtemp to avoid overlap constraints.  */
2079 	  if (vd == vm)
2080 	    {
2081 	      macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vtemp, vs2, vs1, -1);
2082 	      macro_build (NULL, "vmandnot.mm", "Vd,Vt,Vs", vd, vm, vtemp);
2083 	    }
2084 	  else
2085 	    {
2086 	      /* Preserve the value of vd if not updating by vm.  */
2087 	      macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vtemp, vs2, vs1, -1);
2088 	      macro_build (NULL, "vmandnot.mm", "Vd,Vt,Vs", vtemp, vm, vtemp);
2089 	      macro_build (NULL, "vmandnot.mm", "Vd,Vt,Vs", vd, vd, vm);
2090 	      macro_build (NULL, "vmor.mm", "Vd,Vt,Vs", vd, vtemp, vd);
2091 	    }
2092 	}
2093       else if (vd != vm)
2094 	{
2095 	  /* Masked.  This may cause the vd overlaps vs2, when LMUL > 1.  */
2096 	  macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vd, vs2, vs1, vm);
2097 	  macro_build (NULL, "vmxor.mm", "Vd,Vt,Vs", vd, vd, vm);
2098 	}
2099       else
2100 	as_bad (_("must provide temp if destination overlaps mask"));
2101       break;
2102 
2103     default:
2104       break;
2105     }
2106 }
2107 
2108 /* Expand RISC-V assembly macros into one or more instructions.  */
2109 
2110 static void
macro(struct riscv_cl_insn * ip,expressionS * imm_expr,bfd_reloc_code_real_type * imm_reloc)2111 macro (struct riscv_cl_insn *ip, expressionS *imm_expr,
2112        bfd_reloc_code_real_type *imm_reloc)
2113 {
2114   int rd = (ip->insn_opcode >> OP_SH_RD) & OP_MASK_RD;
2115   int rs1 = (ip->insn_opcode >> OP_SH_RS1) & OP_MASK_RS1;
2116   int rs2 = (ip->insn_opcode >> OP_SH_RS2) & OP_MASK_RS2;
2117   int mask = ip->insn_mo->mask;
2118 
2119   source_macro = mask;
2120 
2121   switch (mask)
2122     {
2123     case M_LI:
2124       load_const (rd, imm_expr);
2125       break;
2126 
2127     case M_LA:
2128     case M_LLA:
2129     case M_LGA:
2130       /* Load the address of a symbol into a register.  */
2131       if (!IS_SEXT_32BIT_NUM (imm_expr->X_add_number))
2132 	as_bad (_("offset too large"));
2133 
2134       if (imm_expr->X_op == O_constant)
2135 	load_const (rd, imm_expr);
2136       /* Global PIC symbol.  */
2137       else if ((riscv_opts.pic && mask == M_LA)
2138 	       || mask == M_LGA)
2139 	pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
2140 		    BFD_RELOC_RISCV_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2141       /* Local PIC symbol, or any non-PIC symbol.  */
2142       else
2143 	pcrel_load (rd, rd, imm_expr, "addi",
2144 		    BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2145       break;
2146 
2147     case M_LA_TLS_GD:
2148       pcrel_load (rd, rd, imm_expr, "addi",
2149 		  BFD_RELOC_RISCV_TLS_GD_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2150       break;
2151 
2152     case M_LA_TLS_IE:
2153       pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
2154 		  BFD_RELOC_RISCV_TLS_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2155       break;
2156 
2157     case M_Lx:
2158       pcrel_load (rd, rd, imm_expr, ip->insn_mo->name,
2159 		  BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2160       break;
2161 
2162     case M_FLx:
2163       pcrel_load (rd, rs1, imm_expr, ip->insn_mo->name,
2164 		  BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2165       break;
2166 
2167     case M_Sx_FSx:
2168       pcrel_store (rs2, rs1, imm_expr, ip->insn_mo->name,
2169 		   BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
2170       break;
2171 
2172     case M_CALL:
2173       riscv_call (rd, rs1, imm_expr, *imm_reloc);
2174       break;
2175 
2176     case M_EXTH:
2177       riscv_ext (rd, rs1, xlen - 16, *ip->insn_mo->name == 's');
2178       break;
2179 
2180     case M_ZEXTW:
2181       riscv_ext (rd, rs1, xlen - 32, false);
2182       break;
2183 
2184     case M_SEXTB:
2185       riscv_ext (rd, rs1, xlen - 8, true);
2186       break;
2187 
2188     case M_VMSGE:
2189       vector_macro (ip);
2190       break;
2191 
2192     default:
2193       as_bad (_("internal: macro %s not implemented"), ip->insn_mo->name);
2194       break;
2195     }
2196 
2197   source_macro = -1;
2198 }
2199 
2200 static const struct percent_op_match percent_op_utype[] =
2201 {
2202   {"tprel_hi", BFD_RELOC_RISCV_TPREL_HI20},
2203   {"pcrel_hi", BFD_RELOC_RISCV_PCREL_HI20},
2204   {"got_pcrel_hi", BFD_RELOC_RISCV_GOT_HI20},
2205   {"tls_ie_pcrel_hi", BFD_RELOC_RISCV_TLS_GOT_HI20},
2206   {"tls_gd_pcrel_hi", BFD_RELOC_RISCV_TLS_GD_HI20},
2207   {"hi", BFD_RELOC_RISCV_HI20},
2208   {0, 0}
2209 };
2210 
2211 static const struct percent_op_match percent_op_itype[] =
2212 {
2213   {"lo", BFD_RELOC_RISCV_LO12_I},
2214   {"tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_I},
2215   {"pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_I},
2216   {0, 0}
2217 };
2218 
2219 static const struct percent_op_match percent_op_stype[] =
2220 {
2221   {"lo", BFD_RELOC_RISCV_LO12_S},
2222   {"tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_S},
2223   {"pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_S},
2224   {0, 0}
2225 };
2226 
2227 static const struct percent_op_match percent_op_rtype[] =
2228 {
2229   {"tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
2230   {0, 0}
2231 };
2232 
2233 static const struct percent_op_match percent_op_null[] =
2234 {
2235   {0, 0}
2236 };
2237 
2238 /* Return true if *STR points to a relocation operator.  When returning true,
2239    move *STR over the operator and store its relocation code in *RELOC.
2240    Leave both *STR and *RELOC alone when returning false.  */
2241 
2242 static bool
parse_relocation(char ** str,bfd_reloc_code_real_type * reloc,const struct percent_op_match * percent_op)2243 parse_relocation (char **str, bfd_reloc_code_real_type *reloc,
2244 		  const struct percent_op_match *percent_op)
2245 {
2246   for ( ; percent_op->str; percent_op++)
2247     if (strncasecmp (*str + 1, percent_op->str, strlen (percent_op->str)) == 0)
2248       {
2249 	size_t len = 1 + strlen (percent_op->str);
2250 
2251 	while (ISSPACE ((*str)[len]))
2252 	  ++len;
2253 	if ((*str)[len] != '(')
2254 	  continue;
2255 
2256 	*str += len;
2257 	*reloc = percent_op->reloc;
2258 
2259 	/* Check whether the output BFD supports this relocation.
2260 	   If not, issue an error and fall back on something safe.  */
2261 	if (*reloc != BFD_RELOC_UNUSED
2262 	    && !bfd_reloc_type_lookup (stdoutput, *reloc))
2263 	  {
2264 	    as_bad ("internal: relocation %s isn't supported by the "
2265 		    "current ABI", percent_op->str);
2266 	    *reloc = BFD_RELOC_UNUSED;
2267 	  }
2268 	return true;
2269       }
2270   return false;
2271 }
2272 
2273 static void
my_getExpression(expressionS * ep,char * str)2274 my_getExpression (expressionS *ep, char *str)
2275 {
2276   char *save_in;
2277 
2278   save_in = input_line_pointer;
2279   input_line_pointer = str;
2280   expression (ep);
2281   expr_parse_end = input_line_pointer;
2282   input_line_pointer = save_in;
2283 }
2284 
2285 /* Parse string STR as a 16-bit relocatable operand.  Store the
2286    expression in *EP and the relocation, if any, in RELOC.
2287    Return the number of relocation operators used (0 or 1).
2288 
2289    On exit, EXPR_PARSE_END points to the first character after the
2290    expression.  */
2291 
2292 static size_t
my_getSmallExpression(expressionS * ep,bfd_reloc_code_real_type * reloc,char * str,const struct percent_op_match * percent_op)2293 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
2294 		       char *str, const struct percent_op_match *percent_op)
2295 {
2296   size_t reloc_index;
2297   unsigned crux_depth, str_depth;
2298   bool orig_probing = probing_insn_operands;
2299   char *crux;
2300 
2301   /* Search for the start of the main expression.
2302 
2303      End the loop with CRUX pointing to the start of the main expression and
2304      with CRUX_DEPTH containing the number of open brackets at that point.  */
2305   reloc_index = -1;
2306   str_depth = 0;
2307   do
2308     {
2309       reloc_index++;
2310       crux = str;
2311       crux_depth = str_depth;
2312 
2313       /* Skip over whitespace and brackets, keeping count of the number
2314 	 of brackets.  */
2315       while (*str == ' ' || *str == '\t' || *str == '(')
2316 	if (*str++ == '(')
2317 	  str_depth++;
2318     }
2319   while (*str == '%'
2320 	 && reloc_index < 1
2321 	 && parse_relocation (&str, reloc, percent_op));
2322 
2323   if (*str == '%')
2324     {
2325        /* expression() will choke on anything looking like an (unrecognized)
2326 	  relocation specifier.  Don't even call it, avoiding multiple (and
2327 	  perhaps redundant) error messages; our caller will issue one.  */
2328        ep->X_op = O_illegal;
2329        return 0;
2330     }
2331 
2332   /* Anything inside parentheses or subject to a relocation operator cannot
2333      be a register and hence can be treated the same as operands to
2334      directives (other than .insn).  */
2335   if (str_depth || reloc_index)
2336     probing_insn_operands = false;
2337 
2338   my_getExpression (ep, crux);
2339   str = expr_parse_end;
2340 
2341   probing_insn_operands = orig_probing;
2342 
2343   /* Match every open bracket.  */
2344   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
2345     if (*str++ == ')')
2346       crux_depth--;
2347 
2348   if (crux_depth > 0)
2349     as_bad ("unclosed '('");
2350 
2351   expr_parse_end = str;
2352 
2353   return reloc_index;
2354 }
2355 
2356 /* Parse opcode name, could be an mnemonics or number.  */
2357 
2358 static size_t
my_getOpcodeExpression(expressionS * ep,bfd_reloc_code_real_type * reloc,char * str)2359 my_getOpcodeExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
2360 			char *str)
2361 {
2362   const struct opcode_name_t *o = opcode_name_lookup (&str);
2363 
2364   if (o != NULL)
2365     {
2366       ep->X_op = O_constant;
2367       ep->X_add_number = o->val;
2368       return 0;
2369     }
2370 
2371   return my_getSmallExpression (ep, reloc, str, percent_op_null);
2372 }
2373 
2374 /* Parse string STR as a vsetvli operand.  Store the expression in *EP.
2375    On exit, EXPR_PARSE_END points to the first character after the
2376    expression.  */
2377 
2378 static void
my_getVsetvliExpression(expressionS * ep,char * str)2379 my_getVsetvliExpression (expressionS *ep, char *str)
2380 {
2381   unsigned int vsew_value = 0, vlmul_value = 0;
2382   unsigned int vta_value = 0, vma_value = 0;
2383   bfd_boolean vsew_found = FALSE, vlmul_found = FALSE;
2384   bfd_boolean vta_found = FALSE, vma_found = FALSE;
2385 
2386   if (arg_lookup (&str, riscv_vsew, ARRAY_SIZE (riscv_vsew), &vsew_value))
2387     {
2388       if (*str == ',')
2389 	++str;
2390       if (vsew_found)
2391 	as_bad (_("multiple vsew constants"));
2392       vsew_found = TRUE;
2393     }
2394   if (arg_lookup (&str, riscv_vlmul, ARRAY_SIZE (riscv_vlmul), &vlmul_value))
2395     {
2396       if (*str == ',')
2397 	++str;
2398       if (vlmul_found)
2399 	as_bad (_("multiple vlmul constants"));
2400       vlmul_found = TRUE;
2401     }
2402   if (arg_lookup (&str, riscv_vta, ARRAY_SIZE (riscv_vta), &vta_value))
2403     {
2404       if (*str == ',')
2405 	++str;
2406       if (vta_found)
2407 	as_bad (_("multiple vta constants"));
2408       vta_found = TRUE;
2409     }
2410   if (arg_lookup (&str, riscv_vma, ARRAY_SIZE (riscv_vma), &vma_value))
2411     {
2412       if (*str == ',')
2413 	++str;
2414       if (vma_found)
2415 	as_bad (_("multiple vma constants"));
2416       vma_found = TRUE;
2417     }
2418 
2419   if (vsew_found || vlmul_found || vta_found || vma_found)
2420     {
2421       ep->X_op = O_constant;
2422       ep->X_add_number = (vlmul_value << OP_SH_VLMUL)
2423 			 | (vsew_value << OP_SH_VSEW)
2424 			 | (vta_value << OP_SH_VTA)
2425 			 | (vma_value << OP_SH_VMA);
2426       expr_parse_end = str;
2427     }
2428   else
2429     {
2430       my_getExpression (ep, str);
2431       str = expr_parse_end;
2432     }
2433 }
2434 
2435 /* Parse string STR as a th.vsetvli operand.  Store the expression in *EP.
2436    On exit, EXPR_PARSE_END points to the first character after the
2437    expression.  */
2438 
2439 static void
my_getThVsetvliExpression(expressionS * ep,char * str)2440 my_getThVsetvliExpression (expressionS *ep, char *str)
2441 {
2442   unsigned int vsew_value = 0, vlen_value = 0, vediv_value = 0;
2443   bfd_boolean vsew_found = FALSE, vlen_found = FALSE, vediv_found = FALSE;
2444 
2445   if (arg_lookup (&str, riscv_vsew, ARRAY_SIZE (riscv_vsew),
2446 		  &vsew_value))
2447     {
2448       if (*str == ',')
2449 	++str;
2450       if (vsew_found)
2451 	as_bad (_("multiple vsew constants"));
2452       vsew_found = TRUE;
2453     }
2454 
2455   if (arg_lookup (&str, riscv_th_vlen, ARRAY_SIZE (riscv_th_vlen),
2456 		  &vlen_value))
2457     {
2458       if (*str == ',')
2459 	++str;
2460       if (vlen_found)
2461 	as_bad (_("multiple vlen constants"));
2462       vlen_found = TRUE;
2463     }
2464   if (arg_lookup (&str, riscv_th_vediv, ARRAY_SIZE (riscv_th_vediv),
2465 		  &vediv_value))
2466     {
2467       if (*str == ',')
2468 	++str;
2469       if (vediv_found)
2470 	as_bad (_("multiple vediv constants"));
2471       vediv_found = TRUE;
2472     }
2473 
2474   if (vlen_found || vediv_found || vsew_found)
2475     {
2476       ep->X_op = O_constant;
2477       ep->X_add_number
2478 	= (vediv_value << 5) | (vsew_value << 2) | (vlen_value);
2479       expr_parse_end = str;
2480     }
2481   else
2482     {
2483       my_getExpression (ep, str);
2484       str = expr_parse_end;
2485     }
2486 }
2487 
2488 /* Detect and handle implicitly zero load-store offsets.  For example,
2489    "lw t0, (t1)" is shorthand for "lw t0, 0(t1)".  Return true if such
2490    an implicit offset was detected.  */
2491 
2492 static bool
riscv_handle_implicit_zero_offset(expressionS * ep,const char * s)2493 riscv_handle_implicit_zero_offset (expressionS *ep, const char *s)
2494 {
2495   /* Check whether there is only a single bracketed expression left.
2496      If so, it must be the base register and the constant must be zero.  */
2497   if (*s == '(' && strchr (s + 1, '(') == 0)
2498     {
2499       ep->X_op = O_constant;
2500       ep->X_add_number = 0;
2501       return true;
2502     }
2503 
2504   return false;
2505 }
2506 
2507 /* All RISC-V CSR instructions belong to one of these classes.  */
2508 enum csr_insn_type
2509 {
2510   INSN_NOT_CSR,
2511   INSN_CSRRW,
2512   INSN_CSRRS,
2513   INSN_CSRRC
2514 };
2515 
2516 /* Return which CSR instruction is checking.  */
2517 
2518 static enum csr_insn_type
riscv_csr_insn_type(insn_t insn)2519 riscv_csr_insn_type (insn_t insn)
2520 {
2521   if (((insn ^ MATCH_CSRRW) & MASK_CSRRW) == 0
2522       || ((insn ^ MATCH_CSRRWI) & MASK_CSRRWI) == 0)
2523     return INSN_CSRRW;
2524   else if (((insn ^ MATCH_CSRRS) & MASK_CSRRS) == 0
2525 	   || ((insn ^ MATCH_CSRRSI) & MASK_CSRRSI) == 0)
2526     return INSN_CSRRS;
2527   else if (((insn ^ MATCH_CSRRC) & MASK_CSRRC) == 0
2528 	   || ((insn ^ MATCH_CSRRCI) & MASK_CSRRCI) == 0)
2529     return INSN_CSRRC;
2530   else
2531     return INSN_NOT_CSR;
2532 }
2533 
2534 /* CSRRW and CSRRWI always write CSR.  CSRRS, CSRRC, CSRRSI and CSRRCI write
2535    CSR when RS1 isn't zero.  The CSR is read only if the [11:10] bits of
2536    CSR address is 0x3.  */
2537 
2538 static bool
riscv_csr_read_only_check(insn_t insn)2539 riscv_csr_read_only_check (insn_t insn)
2540 {
2541   int csr = (insn & (OP_MASK_CSR << OP_SH_CSR)) >> OP_SH_CSR;
2542   int rs1 = (insn & (OP_MASK_RS1 << OP_SH_RS1)) >> OP_SH_RS1;
2543   int readonly = (((csr & (0x3 << 10)) >> 10) == 0x3);
2544   enum csr_insn_type csr_insn = riscv_csr_insn_type (insn);
2545 
2546   if (readonly
2547       && (((csr_insn == INSN_CSRRS
2548 	    || csr_insn == INSN_CSRRC)
2549 	   && rs1 != 0)
2550 	  || csr_insn == INSN_CSRRW))
2551     return false;
2552 
2553   return true;
2554 }
2555 
2556 /* Return true if it is a privileged instruction.  Otherwise, return false.
2557 
2558    uret is actually a N-ext instruction.  So it is better to regard it as
2559    an user instruction rather than the priv instruction.
2560 
2561    hret is used to return from traps in H-mode.  H-mode is removed since
2562    the v1.10 priv spec, but probably be added in the new hypervisor spec.
2563    Therefore, hret should be controlled by the hypervisor spec rather than
2564    priv spec in the future.
2565 
2566    dret is defined in the debug spec, so it should be checked in the future,
2567    too.  */
2568 
2569 static bool
riscv_is_priv_insn(insn_t insn)2570 riscv_is_priv_insn (insn_t insn)
2571 {
2572   return (((insn ^ MATCH_SRET) & MASK_SRET) == 0
2573 	  || ((insn ^ MATCH_MRET) & MASK_MRET) == 0
2574 	  || ((insn ^ MATCH_SFENCE_VMA) & MASK_SFENCE_VMA) == 0
2575 	  || ((insn ^ MATCH_WFI) & MASK_WFI) == 0
2576   /* The sfence.vm is dropped in the v1.10 priv specs, but we still need to
2577      check it here to keep the compatible.  */
2578 	  || ((insn ^ MATCH_SFENCE_VM) & MASK_SFENCE_VM) == 0);
2579 }
2580 
2581 static symbolS *deferred_sym_rootP;
2582 static symbolS *deferred_sym_lastP;
2583 /* Since symbols can't easily be freed, try to recycle ones which weren't
2584    committed.  */
2585 static symbolS *orphan_sym_rootP;
2586 static symbolS *orphan_sym_lastP;
2587 
2588 /* This routine assembles an instruction into its binary format.  As a
2589    side effect, it sets the global variable imm_reloc to the type of
2590    relocation to do if one of the operands is an address expression.  */
2591 
2592 static struct riscv_ip_error
riscv_ip(char * str,struct riscv_cl_insn * ip,expressionS * imm_expr,bfd_reloc_code_real_type * imm_reloc,htab_t hash)2593 riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
2594 	  bfd_reloc_code_real_type *imm_reloc, htab_t hash)
2595 {
2596   /* The operand string defined in the riscv_opcodes.  */
2597   const char *oparg, *opargStart;
2598   /* The parsed operands from assembly.  */
2599   char *asarg, *asargStart;
2600   char save_c = 0;
2601   struct riscv_opcode *insn;
2602   unsigned int regno;
2603   const struct percent_op_match *p;
2604   struct riscv_ip_error error;
2605   error.msg = "unrecognized opcode";
2606   error.statement = str;
2607   error.missing_ext = NULL;
2608   /* Indicate we are assembling instruction with CSR.  */
2609   bool insn_with_csr = false;
2610 
2611   /* Parse the name of the instruction.  Terminate the string if whitespace
2612      is found so that str_hash_find only sees the name part of the string.  */
2613   for (asarg = str; *asarg!= '\0'; ++asarg)
2614     if (ISSPACE (*asarg))
2615       {
2616 	save_c = *asarg;
2617 	*asarg++ = '\0';
2618 	break;
2619       }
2620 
2621   insn = (struct riscv_opcode *) str_hash_find (hash, str);
2622 
2623   probing_insn_operands = true;
2624 
2625   asargStart = asarg;
2626   for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
2627     {
2628       if ((insn->xlen_requirement != 0) && (xlen != insn->xlen_requirement))
2629 	continue;
2630 
2631       if (!riscv_multi_subset_supports (&riscv_rps_as, insn->insn_class))
2632 	{
2633 	  error.missing_ext = riscv_multi_subset_supports_ext (&riscv_rps_as,
2634 							       insn->insn_class);
2635 	  continue;
2636 	}
2637 
2638       /* Reset error message of the previous round.  */
2639       error.msg = _("illegal operands");
2640       error.missing_ext = NULL;
2641 
2642       /* Purge deferred symbols from the previous round, if any.  */
2643       while (deferred_sym_rootP)
2644 	{
2645 	  symbolS *sym = deferred_sym_rootP;
2646 
2647 	  symbol_remove (sym, &deferred_sym_rootP, &deferred_sym_lastP);
2648 	  symbol_append (sym, orphan_sym_lastP, &orphan_sym_rootP,
2649 			 &orphan_sym_lastP);
2650 	}
2651 
2652       create_insn (ip, insn);
2653 
2654       imm_expr->X_op = O_absent;
2655       *imm_reloc = BFD_RELOC_UNUSED;
2656       p = percent_op_null;
2657 
2658       for (oparg = insn->args;; ++oparg)
2659 	{
2660 	  opargStart = oparg;
2661 	  asarg += strspn (asarg, " \t");
2662 	  switch (*oparg)
2663 	    {
2664 	    case '\0': /* End of args.  */
2665 	      if (insn->match_func && !insn->match_func (insn, ip->insn_opcode))
2666 		break;
2667 
2668 	      if (insn->pinfo != INSN_MACRO)
2669 		{
2670 		  /* For .insn, insn->match and insn->mask are 0.  */
2671 		  if (riscv_insn_length ((insn->match == 0 && insn->mask == 0)
2672 					 ? ip->insn_opcode
2673 					 : insn->match) == 2
2674 		      && !riscv_opts.rvc)
2675 		    break;
2676 
2677 		  if (riscv_is_priv_insn (ip->insn_opcode))
2678 		    explicit_priv_attr = true;
2679 
2680 		  /* Check if we write a read-only CSR by the CSR
2681 		     instruction.  */
2682 		  if (insn_with_csr
2683 		      && riscv_opts.csr_check
2684 		      && !riscv_csr_read_only_check (ip->insn_opcode))
2685 		    {
2686 		      /* Restore the character in advance, since we want to
2687 			 report the detailed warning message here.  */
2688 		      if (save_c)
2689 			*(asargStart - 1) = save_c;
2690 		      as_warn (_("read-only CSR is written `%s'"), str);
2691 		      insn_with_csr = false;
2692 		    }
2693 
2694 		  /* The (segmant) load and store with EEW 64 cannot be used
2695 		     when zve32x is enabled.  */
2696 		  if (ip->insn_mo->pinfo & INSN_V_EEW64
2697 		      && riscv_subset_supports (&riscv_rps_as, "zve32x")
2698 		      && !riscv_subset_supports (&riscv_rps_as, "zve64x"))
2699 		    {
2700 		      error.msg = _("illegal opcode for zve32x");
2701 		      break;
2702 		    }
2703 		}
2704 	      if (*asarg != '\0')
2705 		break;
2706 
2707 	      /* Successful assembly.  */
2708 	      error.msg = NULL;
2709 	      insn_with_csr = false;
2710 
2711 	      /* Commit deferred symbols, if any.  */
2712 	      while (deferred_sym_rootP)
2713 		{
2714 		  symbolS *sym = deferred_sym_rootP;
2715 
2716 		  symbol_remove (sym, &deferred_sym_rootP,
2717 				 &deferred_sym_lastP);
2718 		  symbol_append (sym, symbol_lastP, &symbol_rootP,
2719 				 &symbol_lastP);
2720 		  symbol_table_insert (sym);
2721 		}
2722 	      goto out;
2723 
2724 	    case 'C': /* RVC */
2725 	      switch (*++oparg)
2726 		{
2727 		case 's': /* RS1 x8-x15.  */
2728 		  if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2729 		      || !(regno >= 8 && regno <= 15))
2730 		    break;
2731 		  INSERT_OPERAND (CRS1S, *ip, regno % 8);
2732 		  continue;
2733 		case 'w': /* RS1 x8-x15, constrained to equal RD x8-x15.  */
2734 		  if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2735 		      || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
2736 		    break;
2737 		  continue;
2738 		case 't': /* RS2 x8-x15.  */
2739 		  if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2740 		      || !(regno >= 8 && regno <= 15))
2741 		    break;
2742 		  INSERT_OPERAND (CRS2S, *ip, regno % 8);
2743 		  continue;
2744 		case 'x': /* RS2 x8-x15, constrained to equal RD x8-x15.  */
2745 		  if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2746 		      || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
2747 		    break;
2748 		  continue;
2749 		case 'U': /* RS1, constrained to equal RD.  */
2750 		  if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2751 		      || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
2752 		    break;
2753 		  continue;
2754 		case 'V': /* RS2 */
2755 		  if (!reg_lookup (&asarg, RCLASS_GPR, &regno))
2756 		    break;
2757 		  INSERT_OPERAND (CRS2, *ip, regno);
2758 		  continue;
2759 		case 'c': /* RS1, constrained to equal sp.  */
2760 		  if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2761 		      || regno != X_SP)
2762 		    break;
2763 		  continue;
2764 		case 'z': /* RS2, constrained to equal x0.  */
2765 		  if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2766 		      || regno != 0)
2767 		    break;
2768 		  continue;
2769 		case '>': /* Shift amount, 0 - (XLEN-1).  */
2770 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2771 		      || imm_expr->X_op != O_constant
2772 		      || (unsigned long) imm_expr->X_add_number >= xlen)
2773 		    break;
2774 		  ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2775 		rvc_imm_done:
2776 		  asarg = expr_parse_end;
2777 		  imm_expr->X_op = O_absent;
2778 		  continue;
2779 		case '5':
2780 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2781 		      || imm_expr->X_op != O_constant
2782 		      || imm_expr->X_add_number < 0
2783 		      || imm_expr->X_add_number >= 32
2784 		      || !VALID_CLTYPE_IMM ((valueT) imm_expr->X_add_number))
2785 		    break;
2786 		  ip->insn_opcode |= ENCODE_CLTYPE_IMM (imm_expr->X_add_number);
2787 		  goto rvc_imm_done;
2788 		case '6':
2789 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2790 		      || imm_expr->X_op != O_constant
2791 		      || imm_expr->X_add_number < 0
2792 		      || imm_expr->X_add_number >= 64
2793 		      || !VALID_CSSTYPE_IMM ((valueT) imm_expr->X_add_number))
2794 		    break;
2795 		  ip->insn_opcode |= ENCODE_CSSTYPE_IMM (imm_expr->X_add_number);
2796 		  goto rvc_imm_done;
2797 		case '8':
2798 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2799 		      || imm_expr->X_op != O_constant
2800 		      || imm_expr->X_add_number < 0
2801 		      || imm_expr->X_add_number >= 256
2802 		      || !VALID_CIWTYPE_IMM ((valueT) imm_expr->X_add_number))
2803 		    break;
2804 		  ip->insn_opcode |= ENCODE_CIWTYPE_IMM (imm_expr->X_add_number);
2805 		  goto rvc_imm_done;
2806 		case 'j':
2807 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2808 		      || imm_expr->X_op != O_constant
2809 		      || imm_expr->X_add_number == 0
2810 		      || !VALID_CITYPE_IMM ((valueT) imm_expr->X_add_number))
2811 		    break;
2812 		  ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2813 		  goto rvc_imm_done;
2814 		case 'k':
2815 		  if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2816 		    continue;
2817 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2818 		      || imm_expr->X_op != O_constant
2819 		      || !VALID_CLTYPE_LW_IMM ((valueT) imm_expr->X_add_number))
2820 		    break;
2821 		  ip->insn_opcode |= ENCODE_CLTYPE_LW_IMM (imm_expr->X_add_number);
2822 		  goto rvc_imm_done;
2823 		case 'l':
2824 		  if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2825 		    continue;
2826 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2827 		      || imm_expr->X_op != O_constant
2828 		      || !VALID_CLTYPE_LD_IMM ((valueT) imm_expr->X_add_number))
2829 		    break;
2830 		  ip->insn_opcode |= ENCODE_CLTYPE_LD_IMM (imm_expr->X_add_number);
2831 		  goto rvc_imm_done;
2832 		case 'm':
2833 		  if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2834 		    continue;
2835 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2836 		      || imm_expr->X_op != O_constant
2837 		      || !VALID_CITYPE_LWSP_IMM ((valueT) imm_expr->X_add_number))
2838 		    break;
2839 		  ip->insn_opcode |=
2840 		    ENCODE_CITYPE_LWSP_IMM (imm_expr->X_add_number);
2841 		  goto rvc_imm_done;
2842 		case 'n':
2843 		  if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2844 		    continue;
2845 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2846 		      || imm_expr->X_op != O_constant
2847 		      || !VALID_CITYPE_LDSP_IMM ((valueT) imm_expr->X_add_number))
2848 		    break;
2849 		  ip->insn_opcode |=
2850 		    ENCODE_CITYPE_LDSP_IMM (imm_expr->X_add_number);
2851 		  goto rvc_imm_done;
2852 		case 'o':
2853 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2854 		      || imm_expr->X_op != O_constant
2855 		      /* C.addiw, c.li, and c.andi allow zero immediate.
2856 			 C.addi allows zero immediate as hint.  Otherwise this
2857 			 is same as 'j'.  */
2858 		      || !VALID_CITYPE_IMM ((valueT) imm_expr->X_add_number))
2859 		    break;
2860 		  ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2861 		  goto rvc_imm_done;
2862 		case 'K':
2863 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2864 		      || imm_expr->X_op != O_constant
2865 		      || imm_expr->X_add_number == 0
2866 		      || !VALID_CIWTYPE_ADDI4SPN_IMM ((valueT) imm_expr->X_add_number))
2867 		    break;
2868 		  ip->insn_opcode |=
2869 		    ENCODE_CIWTYPE_ADDI4SPN_IMM (imm_expr->X_add_number);
2870 		  goto rvc_imm_done;
2871 		case 'L':
2872 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2873 		      || imm_expr->X_op != O_constant
2874 		      || !VALID_CITYPE_ADDI16SP_IMM ((valueT) imm_expr->X_add_number))
2875 		    break;
2876 		  ip->insn_opcode |=
2877 		    ENCODE_CITYPE_ADDI16SP_IMM (imm_expr->X_add_number);
2878 		  goto rvc_imm_done;
2879 		case 'M':
2880 		  if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2881 		    continue;
2882 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2883 		      || imm_expr->X_op != O_constant
2884 		      || !VALID_CSSTYPE_SWSP_IMM ((valueT) imm_expr->X_add_number))
2885 		    break;
2886 		  ip->insn_opcode |=
2887 		    ENCODE_CSSTYPE_SWSP_IMM (imm_expr->X_add_number);
2888 		  goto rvc_imm_done;
2889 		case 'N':
2890 		  if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2891 		    continue;
2892 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2893 		      || imm_expr->X_op != O_constant
2894 		      || !VALID_CSSTYPE_SDSP_IMM ((valueT) imm_expr->X_add_number))
2895 		    break;
2896 		  ip->insn_opcode |=
2897 		    ENCODE_CSSTYPE_SDSP_IMM (imm_expr->X_add_number);
2898 		  goto rvc_imm_done;
2899 		case 'u':
2900 		  p = percent_op_utype;
2901 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
2902 		    break;
2903 		rvc_lui:
2904 		  if (imm_expr->X_op != O_constant
2905 		      || imm_expr->X_add_number <= 0
2906 		      || imm_expr->X_add_number >= RISCV_BIGIMM_REACH
2907 		      || (imm_expr->X_add_number >= RISCV_RVC_IMM_REACH / 2
2908 			  && (imm_expr->X_add_number <
2909 			      RISCV_BIGIMM_REACH - RISCV_RVC_IMM_REACH / 2)))
2910 		    break;
2911 		  ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2912 		  goto rvc_imm_done;
2913 		case 'v':
2914 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2915 		      || (imm_expr->X_add_number & (RISCV_IMM_REACH - 1))
2916 		      || ((int32_t)imm_expr->X_add_number
2917 			  != imm_expr->X_add_number))
2918 		    break;
2919 		  imm_expr->X_add_number =
2920 		    ((uint32_t) imm_expr->X_add_number) >> RISCV_IMM_BITS;
2921 		  goto rvc_lui;
2922 		case 'p':
2923 		  goto branch;
2924 		case 'a':
2925 		  goto jump;
2926 		case 'S': /* Floating-point RS1 x8-x15.  */
2927 		  if (!reg_lookup (&asarg, RCLASS_FPR, &regno)
2928 		      || !(regno >= 8 && regno <= 15))
2929 		    break;
2930 		  INSERT_OPERAND (CRS1S, *ip, regno % 8);
2931 		  continue;
2932 		case 'D': /* Floating-point RS2 x8-x15.  */
2933 		  if (!reg_lookup (&asarg, RCLASS_FPR, &regno)
2934 		      || !(regno >= 8 && regno <= 15))
2935 		    break;
2936 		  INSERT_OPERAND (CRS2S, *ip, regno % 8);
2937 		  continue;
2938 		case 'T': /* Floating-point RS2.  */
2939 		  if (!reg_lookup (&asarg, RCLASS_FPR, &regno))
2940 		    break;
2941 		  INSERT_OPERAND (CRS2, *ip, regno);
2942 		  continue;
2943 		case 'F':
2944 		  switch (*++oparg)
2945 		    {
2946 		      case '6':
2947 		        if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2948 			    || imm_expr->X_op != O_constant
2949 			    || imm_expr->X_add_number < 0
2950 			    || imm_expr->X_add_number >= 64)
2951 			  {
2952 			    as_bad (_("bad value for compressed funct6 "
2953 				      "field, value must be 0...63"));
2954 			    break;
2955 			  }
2956 			INSERT_OPERAND (CFUNCT6, *ip, imm_expr->X_add_number);
2957 			imm_expr->X_op = O_absent;
2958 			asarg = expr_parse_end;
2959 			continue;
2960 
2961 		      case '4':
2962 		        if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2963 			    || imm_expr->X_op != O_constant
2964 			    || imm_expr->X_add_number < 0
2965 			    || imm_expr->X_add_number >= 16)
2966 			  {
2967 			    as_bad (_("bad value for compressed funct4 "
2968 				      "field, value must be 0...15"));
2969 			    break;
2970 			  }
2971 			INSERT_OPERAND (CFUNCT4, *ip, imm_expr->X_add_number);
2972 			imm_expr->X_op = O_absent;
2973 			asarg = expr_parse_end;
2974 			continue;
2975 
2976 		      case '3':
2977 			if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2978 			    || imm_expr->X_op != O_constant
2979 			    || imm_expr->X_add_number < 0
2980 			    || imm_expr->X_add_number >= 8)
2981 			  {
2982 			    as_bad (_("bad value for compressed funct3 "
2983 				      "field, value must be 0...7"));
2984 			    break;
2985 			  }
2986 			INSERT_OPERAND (CFUNCT3, *ip, imm_expr->X_add_number);
2987 			imm_expr->X_op = O_absent;
2988 			asarg = expr_parse_end;
2989 			continue;
2990 
2991 		      case '2':
2992 			if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2993 			    || imm_expr->X_op != O_constant
2994 			    || imm_expr->X_add_number < 0
2995 			    || imm_expr->X_add_number >= 4)
2996 			  {
2997 			    as_bad (_("bad value for compressed funct2 "
2998 				      "field, value must be 0...3"));
2999 			    break;
3000 			  }
3001 			INSERT_OPERAND (CFUNCT2, *ip, imm_expr->X_add_number);
3002 			imm_expr->X_op = O_absent;
3003 			asarg = expr_parse_end;
3004 			continue;
3005 
3006 		      default:
3007 			goto unknown_riscv_ip_operand;
3008 		    }
3009 		  break;
3010 
3011 		default:
3012 		  goto unknown_riscv_ip_operand;
3013 		}
3014 	      break; /* end RVC */
3015 
3016 	    case 'V': /* RVV */
3017 	      switch (*++oparg)
3018 		{
3019 		case 'd': /* VD */
3020 		  if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
3021 		    break;
3022 		  INSERT_OPERAND (VD, *ip, regno);
3023 		  continue;
3024 
3025 		case 'e': /* AMO VD */
3026 		  if (reg_lookup (&asarg, RCLASS_GPR, &regno) && regno == 0)
3027 		    INSERT_OPERAND (VWD, *ip, 0);
3028 		  else if (reg_lookup (&asarg, RCLASS_VECR, &regno))
3029 		    {
3030 		      INSERT_OPERAND (VWD, *ip, 1);
3031 		      INSERT_OPERAND (VD, *ip, regno);
3032 		    }
3033 		  else
3034 		    break;
3035 		  continue;
3036 
3037 		case 'f': /* AMO VS3 */
3038 		  if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
3039 		    break;
3040 		  if (!EXTRACT_OPERAND (VWD, ip->insn_opcode))
3041 		    INSERT_OPERAND (VD, *ip, regno);
3042 		  else
3043 		    {
3044 		      /* VS3 must match VD.  */
3045 		      if (EXTRACT_OPERAND (VD, ip->insn_opcode) != regno)
3046 			break;
3047 		    }
3048 		  continue;
3049 
3050 		case 's': /* VS1 */
3051 		  if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
3052 		    break;
3053 		  INSERT_OPERAND (VS1, *ip, regno);
3054 		  continue;
3055 
3056 		case 't': /* VS2 */
3057 		  if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
3058 		    break;
3059 		  INSERT_OPERAND (VS2, *ip, regno);
3060 		  continue;
3061 
3062 		case 'u': /* VS1 == VS2 */
3063 		  if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
3064 		    break;
3065 		  INSERT_OPERAND (VS1, *ip, regno);
3066 		  INSERT_OPERAND (VS2, *ip, regno);
3067 		  continue;
3068 
3069 		case 'v': /* VD == VS1 == VS2 */
3070 		  if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
3071 		    break;
3072 		  INSERT_OPERAND (VD, *ip, regno);
3073 		  INSERT_OPERAND (VS1, *ip, regno);
3074 		  INSERT_OPERAND (VS2, *ip, regno);
3075 		  continue;
3076 
3077 		/* The `V0` is carry-in register for v[m]adc and v[m]sbc,
3078 		   and is used to choose vs1/rs1/frs1/imm or vs2 for
3079 		   v[f]merge.  It use the same encoding as the vector mask
3080 		   register.  */
3081 		case '0':
3082 		  if (reg_lookup (&asarg, RCLASS_VECR, &regno) && regno == 0)
3083 		    continue;
3084 		  break;
3085 
3086 		case 'b': /* vtypei for vsetivli */
3087 		  my_getVsetvliExpression (imm_expr, asarg);
3088 		  check_absolute_expr (ip, imm_expr, FALSE);
3089 		  if (!VALID_RVV_VB_IMM (imm_expr->X_add_number))
3090 		    as_bad (_("bad value for vsetivli immediate field, "
3091 			      "value must be 0..1023"));
3092 		  ip->insn_opcode
3093 		    |= ENCODE_RVV_VB_IMM (imm_expr->X_add_number);
3094 		  imm_expr->X_op = O_absent;
3095 		  asarg = expr_parse_end;
3096 		  continue;
3097 
3098 		case 'c': /* vtypei for vsetvli */
3099 		  my_getVsetvliExpression (imm_expr, asarg);
3100 		  check_absolute_expr (ip, imm_expr, FALSE);
3101 		  if (!VALID_RVV_VC_IMM (imm_expr->X_add_number))
3102 		    as_bad (_("bad value for vsetvli immediate field, "
3103 			      "value must be 0..2047"));
3104 		  ip->insn_opcode
3105 		    |= ENCODE_RVV_VC_IMM (imm_expr->X_add_number);
3106 		  imm_expr->X_op = O_absent;
3107 		  asarg = expr_parse_end;
3108 		  continue;
3109 
3110 		case 'i': /* vector arith signed immediate */
3111 		  my_getExpression (imm_expr, asarg);
3112 		  check_absolute_expr (ip, imm_expr, FALSE);
3113 		  if (imm_expr->X_add_number > 15
3114 		      || imm_expr->X_add_number < -16)
3115 		    as_bad (_("bad value for vector immediate field, "
3116 			      "value must be -16...15"));
3117 		  INSERT_OPERAND (VIMM, *ip, imm_expr->X_add_number);
3118 		  imm_expr->X_op = O_absent;
3119 		  asarg = expr_parse_end;
3120 		  continue;
3121 
3122 		case 'j': /* vector arith unsigned immediate */
3123 		  my_getExpression (imm_expr, asarg);
3124 		  check_absolute_expr (ip, imm_expr, FALSE);
3125 		  if (imm_expr->X_add_number < 0
3126 		      || imm_expr->X_add_number >= 32)
3127 		    as_bad (_("bad value for vector immediate field, "
3128 			      "value must be 0...31"));
3129 		  INSERT_OPERAND (VIMM, *ip, imm_expr->X_add_number);
3130 		  imm_expr->X_op = O_absent;
3131 		  asarg = expr_parse_end;
3132 		  continue;
3133 
3134 		case 'k': /* vector arith signed immediate, minus 1 */
3135 		  my_getExpression (imm_expr, asarg);
3136 		  check_absolute_expr (ip, imm_expr, FALSE);
3137 		  if (imm_expr->X_add_number > 16
3138 		      || imm_expr->X_add_number < -15)
3139 		    as_bad (_("bad value for vector immediate field, "
3140 			      "value must be -15...16"));
3141 		  INSERT_OPERAND (VIMM, *ip, imm_expr->X_add_number - 1);
3142 		  imm_expr->X_op = O_absent;
3143 		  asarg = expr_parse_end;
3144 		  continue;
3145 
3146 		case 'l': /* 6-bit vector arith unsigned immediate */
3147 		  my_getExpression (imm_expr, asarg);
3148 		  check_absolute_expr (ip, imm_expr, FALSE);
3149 		  if (imm_expr->X_add_number < 0
3150 		      || imm_expr->X_add_number >= 64)
3151 		    as_bad (_("bad value for vector immediate field, "
3152 			      "value must be 0...63"));
3153 		  ip->insn_opcode |= ENCODE_RVV_VI_UIMM6 (imm_expr->X_add_number);
3154 		  imm_expr->X_op = O_absent;
3155 		  asarg = expr_parse_end;
3156 		  continue;
3157 
3158 		case 'm': /* optional vector mask */
3159 		  if (*asarg == '\0')
3160 		    {
3161 		      INSERT_OPERAND (VMASK, *ip, 1);
3162 		      continue;
3163 		    }
3164 		  else if (*asarg == ',' && asarg++
3165 			   && reg_lookup (&asarg, RCLASS_VECM, &regno)
3166 			   && regno == 0)
3167 		    {
3168 		      INSERT_OPERAND (VMASK, *ip, 0);
3169 		      continue;
3170 		    }
3171 		  break;
3172 
3173 		case 'M': /* required vector mask */
3174 		  if (reg_lookup (&asarg, RCLASS_VECM, &regno) && regno == 0)
3175 		    {
3176 		      INSERT_OPERAND (VMASK, *ip, 0);
3177 		      continue;
3178 		    }
3179 		  break;
3180 
3181 		case 'T': /* vector macro temporary register */
3182 		  if (!reg_lookup (&asarg, RCLASS_VECR, &regno) || regno == 0)
3183 		    break;
3184 		  /* Store it in the FUNCT6 field as we don't have anyplace
3185 		     else to store it.  */
3186 		  INSERT_OPERAND (VFUNCT6, *ip, regno);
3187 		  continue;
3188 
3189 		default:
3190 		  goto unknown_riscv_ip_operand;
3191 		}
3192 	      break; /* end RVV */
3193 
3194 	    case ',':
3195 	      if (*asarg++ == *oparg)
3196 		continue;
3197 	      asarg--;
3198 	      break;
3199 
3200 	    case '(':
3201 	    case ')':
3202 	    case '[':
3203 	    case ']':
3204 	      if (*asarg++ == *oparg)
3205 		continue;
3206 	      break;
3207 
3208 	    case '<': /* Shift amount, 0 - 31.  */
3209 	      my_getExpression (imm_expr, asarg);
3210 	      check_absolute_expr (ip, imm_expr, false);
3211 	      if ((unsigned long) imm_expr->X_add_number > 31)
3212 		as_bad (_("improper shift amount (%"PRIu64")"),
3213 			imm_expr->X_add_number);
3214 	      INSERT_OPERAND (SHAMTW, *ip, imm_expr->X_add_number);
3215 	      imm_expr->X_op = O_absent;
3216 	      asarg = expr_parse_end;
3217 	      continue;
3218 
3219 	    case '>': /* Shift amount, 0 - (XLEN-1).  */
3220 	      my_getExpression (imm_expr, asarg);
3221 	      check_absolute_expr (ip, imm_expr, false);
3222 	      if ((unsigned long) imm_expr->X_add_number >= xlen)
3223 		as_bad (_("improper shift amount (%"PRIu64")"),
3224 			imm_expr->X_add_number);
3225 	      INSERT_OPERAND (SHAMT, *ip, imm_expr->X_add_number);
3226 	      imm_expr->X_op = O_absent;
3227 	      asarg = expr_parse_end;
3228 	      continue;
3229 
3230 	    case 'Z': /* CSRRxI immediate.  */
3231 	      my_getExpression (imm_expr, asarg);
3232 	      check_absolute_expr (ip, imm_expr, false);
3233 	      if ((unsigned long) imm_expr->X_add_number > 31)
3234 		as_bad (_("improper CSRxI immediate (%"PRIu64")"),
3235 			imm_expr->X_add_number);
3236 	      INSERT_OPERAND (RS1, *ip, imm_expr->X_add_number);
3237 	      imm_expr->X_op = O_absent;
3238 	      asarg = expr_parse_end;
3239 	      continue;
3240 
3241 	    case 'E': /* Control register.  */
3242 	      insn_with_csr = true;
3243 	      explicit_priv_attr = true;
3244 	      if (reg_lookup (&asarg, RCLASS_CSR, &regno))
3245 		INSERT_OPERAND (CSR, *ip, regno);
3246 	      else
3247 		{
3248 		  my_getExpression (imm_expr, asarg);
3249 		  check_absolute_expr (ip, imm_expr, true);
3250 		  if ((unsigned long) imm_expr->X_add_number > 0xfff)
3251 		    as_bad (_("improper CSR address (%"PRIu64")"),
3252 			    imm_expr->X_add_number);
3253 		  INSERT_OPERAND (CSR, *ip, imm_expr->X_add_number);
3254 		  imm_expr->X_op = O_absent;
3255 		  asarg = expr_parse_end;
3256 		}
3257 	      continue;
3258 
3259 	    case 'm': /* Rounding mode.  */
3260 	      if (arg_lookup (&asarg, riscv_rm,
3261 			      ARRAY_SIZE (riscv_rm), &regno))
3262 		{
3263 		  INSERT_OPERAND (RM, *ip, regno);
3264 		  continue;
3265 		}
3266 	      break;
3267 
3268 	    case 'P':
3269 	    case 'Q': /* Fence predecessor/successor.  */
3270 	      if (arg_lookup (&asarg, riscv_pred_succ,
3271 			      ARRAY_SIZE (riscv_pred_succ), &regno))
3272 		{
3273 		  if (*oparg == 'P')
3274 		    INSERT_OPERAND (PRED, *ip, regno);
3275 		  else
3276 		    INSERT_OPERAND (SUCC, *ip, regno);
3277 		  continue;
3278 		}
3279 	      break;
3280 
3281 	    case 'd': /* Destination register.  */
3282 	    case 's': /* Source register.  */
3283 	    case 't': /* Target register.  */
3284 	    case 'r': /* RS3 */
3285 	      if (reg_lookup (&asarg, RCLASS_GPR, &regno))
3286 		{
3287 		  char c = *oparg;
3288 		  if (*asarg == ' ')
3289 		    ++asarg;
3290 
3291 		  /* Now that we have assembled one operand, we use the args
3292 		     string to figure out where it goes in the instruction.  */
3293 		  switch (c)
3294 		    {
3295 		    case 's':
3296 		      INSERT_OPERAND (RS1, *ip, regno);
3297 		      break;
3298 		    case 'd':
3299 		      INSERT_OPERAND (RD, *ip, regno);
3300 		      break;
3301 		    case 't':
3302 		      INSERT_OPERAND (RS2, *ip, regno);
3303 		      break;
3304 		    case 'r':
3305 		      INSERT_OPERAND (RS3, *ip, regno);
3306 		      break;
3307 		    }
3308 		  continue;
3309 		}
3310 	      break;
3311 
3312 	    case 'D': /* Floating point RD.  */
3313 	    case 'S': /* Floating point RS1.  */
3314 	    case 'T': /* Floating point RS2.  */
3315 	    case 'U': /* Floating point RS1 and RS2.  */
3316 	    case 'R': /* Floating point RS3.  */
3317 	      if (reg_lookup (&asarg,
3318 			      (riscv_subset_supports (&riscv_rps_as, "zfinx")
3319 			      ? RCLASS_GPR : RCLASS_FPR), &regno))
3320 		{
3321 		  char c = *oparg;
3322 		  if (*asarg == ' ')
3323 		    ++asarg;
3324 		  switch (c)
3325 		    {
3326 		    case 'D':
3327 		      INSERT_OPERAND (RD, *ip, regno);
3328 		      break;
3329 		    case 'S':
3330 		      INSERT_OPERAND (RS1, *ip, regno);
3331 		      break;
3332 		    case 'U':
3333 		      INSERT_OPERAND (RS1, *ip, regno);
3334 		      /* Fall through.  */
3335 		    case 'T':
3336 		      INSERT_OPERAND (RS2, *ip, regno);
3337 		      break;
3338 		    case 'R':
3339 		      INSERT_OPERAND (RS3, *ip, regno);
3340 		      break;
3341 		    }
3342 		  continue;
3343 		}
3344 	      break;
3345 
3346 	    case 'I':
3347 	      my_getExpression (imm_expr, asarg);
3348 	      if (imm_expr->X_op != O_big
3349 		  && imm_expr->X_op != O_constant)
3350 		break;
3351 	      normalize_constant_expr (imm_expr);
3352 	      asarg = expr_parse_end;
3353 	      continue;
3354 
3355 	    case 'A':
3356 	      my_getExpression (imm_expr, asarg);
3357 	      normalize_constant_expr (imm_expr);
3358 	      /* The 'A' format specifier must be a symbol.  */
3359 	      if (imm_expr->X_op != O_symbol)
3360 	        break;
3361 	      *imm_reloc = BFD_RELOC_32;
3362 	      asarg = expr_parse_end;
3363 	      continue;
3364 
3365 	    case 'B':
3366 	      my_getExpression (imm_expr, asarg);
3367 	      normalize_constant_expr (imm_expr);
3368 	      /* The 'B' format specifier must be a symbol or a constant.  */
3369 	      if (imm_expr->X_op != O_symbol && imm_expr->X_op != O_constant)
3370 	        break;
3371 	      if (imm_expr->X_op == O_symbol)
3372 	        *imm_reloc = BFD_RELOC_32;
3373 	      asarg = expr_parse_end;
3374 	      continue;
3375 
3376 	    case 'j': /* Sign-extended immediate.  */
3377 	      p = percent_op_itype;
3378 	      *imm_reloc = BFD_RELOC_RISCV_LO12_I;
3379 	      goto alu_op;
3380 	    case 'q': /* Store displacement.  */
3381 	      p = percent_op_stype;
3382 	      *imm_reloc = BFD_RELOC_RISCV_LO12_S;
3383 	      goto load_store;
3384 	    case 'o': /* Load displacement.  */
3385 	      p = percent_op_itype;
3386 	      *imm_reloc = BFD_RELOC_RISCV_LO12_I;
3387 	      goto load_store;
3388 	    case '1':
3389 	      /* This is used for TLS, where the fourth operand is
3390 		 %tprel_add, to get a relocation applied to an add
3391 		 instruction, for relaxation to use.  */
3392 	      p = percent_op_rtype;
3393 	      goto alu_op;
3394 	    case '0': /* AMO displacement, which must be zero.  */
3395 	    load_store:
3396 	      if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
3397 		continue;
3398 	    alu_op:
3399 	      /* If this value won't fit into a 16 bit offset, then go
3400 		 find a macro that will generate the 32 bit offset
3401 		 code pattern.  */
3402 	      if (!my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
3403 		{
3404 		  normalize_constant_expr (imm_expr);
3405 		  if (imm_expr->X_op != O_constant
3406 		      || (*oparg == '0' && imm_expr->X_add_number != 0)
3407 		      || (*oparg == '1')
3408 		      || imm_expr->X_add_number >= (signed)RISCV_IMM_REACH/2
3409 		      || imm_expr->X_add_number < -(signed)RISCV_IMM_REACH/2)
3410 		    break;
3411 		}
3412 	      asarg = expr_parse_end;
3413 	      continue;
3414 
3415 	    case 'p': /* PC-relative offset.  */
3416 	    branch:
3417 	      *imm_reloc = BFD_RELOC_12_PCREL;
3418 	      my_getExpression (imm_expr, asarg);
3419 	      asarg = expr_parse_end;
3420 	      continue;
3421 
3422 	    case 'u': /* Upper 20 bits.  */
3423 	      p = percent_op_utype;
3424 	      if (!my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
3425 		{
3426 		  if (imm_expr->X_op != O_constant)
3427 		    break;
3428 
3429 		  if (imm_expr->X_add_number < 0
3430 		      || imm_expr->X_add_number >= (signed)RISCV_BIGIMM_REACH)
3431 		    as_bad (_("lui expression not in range 0..1048575"));
3432 
3433 		  *imm_reloc = BFD_RELOC_RISCV_HI20;
3434 		  imm_expr->X_add_number <<= RISCV_IMM_BITS;
3435 		}
3436 	      asarg = expr_parse_end;
3437 	      continue;
3438 
3439 	    case 'a': /* 20-bit PC-relative offset.  */
3440 	    jump:
3441 	      my_getExpression (imm_expr, asarg);
3442 	      asarg = expr_parse_end;
3443 	      *imm_reloc = BFD_RELOC_RISCV_JMP;
3444 	      continue;
3445 
3446 	    case 'c':
3447 	      my_getExpression (imm_expr, asarg);
3448 	      asarg = expr_parse_end;
3449 	      if (strcmp (asarg, "@plt") == 0)
3450 		asarg += 4;
3451 	      *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
3452 	      continue;
3453 
3454 	    case 'O':
3455 	      switch (*++oparg)
3456 		{
3457 		case '4':
3458 		  if (my_getOpcodeExpression (imm_expr, imm_reloc, asarg)
3459 		      || imm_expr->X_op != O_constant
3460 		      || imm_expr->X_add_number < 0
3461 		      || imm_expr->X_add_number >= 128
3462 		      || (imm_expr->X_add_number & 0x3) != 3)
3463 		    {
3464 		      as_bad (_("bad value for opcode field, "
3465 				"value must be 0...127 and "
3466 				"lower 2 bits must be 0x3"));
3467 		      break;
3468 		    }
3469 		  INSERT_OPERAND (OP, *ip, imm_expr->X_add_number);
3470 		  imm_expr->X_op = O_absent;
3471 		  asarg = expr_parse_end;
3472 		  continue;
3473 
3474 		case '2':
3475 		  if (my_getOpcodeExpression (imm_expr, imm_reloc, asarg)
3476 		      || imm_expr->X_op != O_constant
3477 		      || imm_expr->X_add_number < 0
3478 		      || imm_expr->X_add_number >= 3)
3479 		    {
3480 		      as_bad (_("bad value for opcode field, "
3481 				"value must be 0...2"));
3482 		      break;
3483 		    }
3484 		  INSERT_OPERAND (OP2, *ip, imm_expr->X_add_number);
3485 		  imm_expr->X_op = O_absent;
3486 		  asarg = expr_parse_end;
3487 		  continue;
3488 
3489 		default:
3490 		  goto unknown_riscv_ip_operand;
3491 		}
3492 	      break;
3493 
3494 	    case 'F':
3495 	      switch (*++oparg)
3496 		{
3497 		case '7':
3498 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3499 		      || imm_expr->X_op != O_constant
3500 		      || imm_expr->X_add_number < 0
3501 		      || imm_expr->X_add_number >= 128)
3502 		    {
3503 		      as_bad (_("bad value for funct7 field, "
3504 				"value must be 0...127"));
3505 		      break;
3506 		    }
3507 		  INSERT_OPERAND (FUNCT7, *ip, imm_expr->X_add_number);
3508 		  imm_expr->X_op = O_absent;
3509 		  asarg = expr_parse_end;
3510 		  continue;
3511 
3512 		case '3':
3513 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3514 		      || imm_expr->X_op != O_constant
3515 		      || imm_expr->X_add_number < 0
3516 		      || imm_expr->X_add_number >= 8)
3517 		    {
3518 		      as_bad (_("bad value for funct3 field, "
3519 			        "value must be 0...7"));
3520 		      break;
3521 		    }
3522 		  INSERT_OPERAND (FUNCT3, *ip, imm_expr->X_add_number);
3523 		  imm_expr->X_op = O_absent;
3524 		  asarg = expr_parse_end;
3525 		  continue;
3526 
3527 		case '2':
3528 		  if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3529 		      || imm_expr->X_op != O_constant
3530 		      || imm_expr->X_add_number < 0
3531 		      || imm_expr->X_add_number >= 4)
3532 		    {
3533 		      as_bad (_("bad value for funct2 field, "
3534 			        "value must be 0...3"));
3535 		      break;
3536 		    }
3537 		  INSERT_OPERAND (FUNCT2, *ip, imm_expr->X_add_number);
3538 		  imm_expr->X_op = O_absent;
3539 		  asarg = expr_parse_end;
3540 		  continue;
3541 
3542 		default:
3543 		  goto unknown_riscv_ip_operand;
3544 		}
3545 	      break;
3546 
3547 	    case 'y': /* bs immediate */
3548 	      my_getExpression (imm_expr, asarg);
3549 	      check_absolute_expr (ip, imm_expr, FALSE);
3550 	      if ((unsigned long)imm_expr->X_add_number > 3)
3551 		as_bad(_("Improper bs immediate (%lu)"),
3552 		       (unsigned long)imm_expr->X_add_number);
3553 	      INSERT_OPERAND(BS, *ip, imm_expr->X_add_number);
3554 	      imm_expr->X_op = O_absent;
3555 	      asarg = expr_parse_end;
3556 	      continue;
3557 
3558 	    case 'Y': /* rnum immediate */
3559 	      my_getExpression (imm_expr, asarg);
3560 	      check_absolute_expr (ip, imm_expr, FALSE);
3561 	      if ((unsigned long)imm_expr->X_add_number > 10)
3562 		as_bad(_("Improper rnum immediate (%lu)"),
3563 		       (unsigned long)imm_expr->X_add_number);
3564 	      INSERT_OPERAND(RNUM, *ip, imm_expr->X_add_number);
3565 	      imm_expr->X_op = O_absent;
3566 	      asarg = expr_parse_end;
3567 	      continue;
3568 
3569 	    case 'z':
3570 	      if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3571 		  || imm_expr->X_op != O_constant
3572 		  || imm_expr->X_add_number != 0)
3573 		break;
3574 	      asarg = expr_parse_end;
3575 	      imm_expr->X_op = O_absent;
3576 	      continue;
3577 
3578 	    case 'W': /* Various operands for standard z extensions.  */
3579 	      switch (*++oparg)
3580 		{
3581 		case 'i':
3582 		  switch (*++oparg)
3583 		    {
3584 		    case 'f':
3585 		      /* Prefetch offset for 'Zicbop' extension.
3586 			 pseudo S-type but lower 5-bits zero.  */
3587 		      if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
3588 			continue;
3589 		      my_getExpression (imm_expr, asarg);
3590 		      check_absolute_expr (ip, imm_expr, false);
3591 		      if (((unsigned) (imm_expr->X_add_number) & 0x1fU)
3592 			  || imm_expr->X_add_number >= RISCV_IMM_REACH / 2
3593 			  || imm_expr->X_add_number < -RISCV_IMM_REACH / 2)
3594 			as_bad (_ ("improper prefetch offset (%ld)"),
3595 				(long) imm_expr->X_add_number);
3596 		      ip->insn_opcode |= ENCODE_STYPE_IMM (
3597 			  (unsigned) (imm_expr->X_add_number) & ~0x1fU);
3598 		      imm_expr->X_op = O_absent;
3599 		      asarg = expr_parse_end;
3600 		      continue;
3601 		    default:
3602 		      goto unknown_riscv_ip_operand;
3603 		    }
3604 		  break;
3605 
3606 		case 'f':
3607 		  switch (*++oparg)
3608 		    {
3609 		    case 'v':
3610 		      /* FLI.[HSDQ] value field for 'Zfa' extension.  */
3611 		      if (!arg_lookup (&asarg, riscv_fli_symval,
3612 				       ARRAY_SIZE (riscv_fli_symval), &regno))
3613 			{
3614 			  /* 0.0 is not a valid entry in riscv_fli_numval.  */
3615 			  errno = 0;
3616 			  float f = strtof (asarg, &asarg);
3617 			  if (errno != 0 || f == 0.0
3618 			      || !flt_lookup (f, riscv_fli_numval,
3619 					     ARRAY_SIZE(riscv_fli_numval),
3620 					     &regno))
3621 			    {
3622 			      as_bad (_("bad fli constant operand, "
3623 					"supported constants must be in "
3624 					"decimal or hexadecimal floating-point "
3625 					"literal form"));
3626 			      break;
3627 			    }
3628 			}
3629 		      INSERT_OPERAND (RS1, *ip, regno);
3630 		      continue;
3631 		    default:
3632 		      goto unknown_riscv_ip_operand;
3633 		    }
3634 		  break;
3635 
3636 		case 'c':
3637 		  switch (*++oparg)
3638 		    {
3639 		    case 'h': /* Immediate field for c.lh/c.lhu/c.sh.  */
3640 		      /* Handle cases, such as c.sh rs2', (rs1').  */
3641 		      if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
3642 			continue;
3643 		      if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3644 			  || imm_expr->X_op != O_constant
3645 			  || !VALID_ZCB_HALFWORD_UIMM ((valueT) imm_expr->X_add_number))
3646 			break;
3647 		      ip->insn_opcode |= ENCODE_ZCB_HALFWORD_UIMM (imm_expr->X_add_number);
3648 		      goto rvc_imm_done;
3649 		    case 'b': /* Immediate field for c.lbu/c.sb.  */
3650 		      /* Handle cases, such as c.lbu rd', (rs1').  */
3651 		      if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
3652 			continue;
3653 		      if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3654 			  || imm_expr->X_op != O_constant
3655 			  || !VALID_ZCB_BYTE_UIMM ((valueT) imm_expr->X_add_number))
3656 			break;
3657 		      ip->insn_opcode |= ENCODE_ZCB_BYTE_UIMM (imm_expr->X_add_number);
3658 		      goto rvc_imm_done;
3659 		    case 'f': /* Operand for matching immediate 255.  */
3660 		      if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3661 			  || imm_expr->X_op != O_constant
3662 			  || imm_expr->X_add_number != 255)
3663 			break;
3664 		      /* This operand is used for matching immediate 255, and
3665 			 we do not write anything to encoding by this operand.  */
3666 		      asarg = expr_parse_end;
3667 		      imm_expr->X_op = O_absent;
3668 		      continue;
3669 		    default:
3670 		      goto unknown_riscv_ip_operand;
3671 		    }
3672 		  break;
3673 
3674 		default:
3675 		  goto unknown_riscv_ip_operand;
3676 		}
3677 	      break;
3678 
3679 	    case 'X': /* Vendor-specific operands.  */
3680 	      switch (*++oparg)
3681 		{
3682 		case 't': /* Vendor-specific (T-head) operands.  */
3683 		  {
3684 		    size_t n;
3685 		    size_t s;
3686 		    bool sign;
3687 		    switch (*++oparg)
3688 		      {
3689 		      case 'V':
3690 			/* Vtypei for th.vsetvli.  */
3691 			++oparg;
3692 			if (*oparg != 'c')
3693 			  goto unknown_riscv_ip_operand;
3694 
3695 			my_getThVsetvliExpression (imm_expr, asarg);
3696 			check_absolute_expr (ip, imm_expr, FALSE);
3697 			if (!VALID_RVV_VC_IMM (imm_expr->X_add_number))
3698 			  as_bad (_("bad value for th.vsetvli immediate field, "
3699 				  "value must be 0..2047"));
3700 			ip->insn_opcode
3701 			  |= ENCODE_RVV_VC_IMM (imm_expr->X_add_number);
3702 			imm_expr->X_op = O_absent;
3703 			asarg = expr_parse_end;
3704 			continue;
3705 
3706 		      case 'l': /* Integer immediate, literal.  */
3707 			n = strcspn (++oparg, ",");
3708 			if (strncmp (oparg, asarg, n))
3709 			  as_bad (_("unexpected literal (%s)"), asarg);
3710 			oparg += n - 1;
3711 			asarg += n;
3712 			continue;
3713 		      case 's': /* Integer immediate, 'XsN@S' ... N-bit signed immediate at bit S.  */
3714 			sign = true;
3715 			goto parse_imm;
3716 		      case 'u': /* Integer immediate, 'XuN@S' ... N-bit unsigned immediate at bit S.  */
3717 			sign = false;
3718 			goto parse_imm;
3719 		      parse_imm:
3720 			n = strtol (oparg + 1, (char **)&oparg, 10);
3721 			if (*oparg != '@')
3722 			  goto unknown_riscv_ip_operand;
3723 			s = strtol (oparg + 1, (char **)&oparg, 10);
3724 			oparg--;
3725 
3726 			my_getExpression (imm_expr, asarg);
3727 			check_absolute_expr (ip, imm_expr, false);
3728 			if (!sign)
3729 			  {
3730 			    if (!VALIDATE_U_IMM (imm_expr->X_add_number, n))
3731 			      as_bad (_("improper immediate value (%"PRIu64")"),
3732 				      imm_expr->X_add_number);
3733 			  }
3734 			else
3735 			  {
3736 			    if (!VALIDATE_S_IMM (imm_expr->X_add_number, n))
3737 			      as_bad (_("improper immediate value (%"PRIi64")"),
3738 				      imm_expr->X_add_number);
3739 			  }
3740 			INSERT_IMM (n, s, *ip, imm_expr->X_add_number);
3741 			imm_expr->X_op = O_absent;
3742 			asarg = expr_parse_end;
3743 			continue;
3744 		      default:
3745 			goto unknown_riscv_ip_operand;
3746 		      }
3747 		  }
3748 		  break;
3749 
3750 		case 'c': /* Vendor-specific (CORE-V) operands.  */
3751 		  switch (*++oparg)
3752 		    {
3753 		      case '2':
3754 			my_getExpression (imm_expr, asarg);
3755 			check_absolute_expr (ip, imm_expr, FALSE);
3756 			asarg = expr_parse_end;
3757 			if (imm_expr->X_add_number<0
3758 			    || imm_expr->X_add_number>31)
3759 			  break;
3760 			ip->insn_opcode
3761 			    |= ENCODE_CV_IS2_UIMM5 (imm_expr->X_add_number);
3762 			  continue;
3763 		      case '3':
3764 			my_getExpression (imm_expr, asarg);
3765 			check_absolute_expr (ip, imm_expr, FALSE);
3766 			asarg = expr_parse_end;
3767 			if (imm_expr->X_add_number < 0
3768 			    || imm_expr->X_add_number > 31)
3769 			  break;
3770 			ip->insn_opcode
3771 			    |= ENCODE_CV_IS3_UIMM5 (imm_expr->X_add_number);
3772 			continue;
3773 		      default:
3774 			goto unknown_riscv_ip_operand;
3775 		    }
3776 		  break;
3777 
3778 		case 's': /* Vendor-specific (SiFive) operands.  */
3779 #define UIMM_BITFIELD_VAL(S, E) (1 << ((E) - (S) + 1))
3780 #define ENCODE_UIMM_BIT_FIELD(NAME, IP, EXPR, RELOC, ASARG, \
3781 			      START, END) \
3782   do \
3783     { \
3784       if (my_getOpcodeExpression (EXPR, RELOC, ASARG) \
3785 	  || EXPR->X_op != O_constant \
3786 	  || EXPR->X_add_number < 0 \
3787 	  || EXPR->X_add_number >= UIMM_BITFIELD_VAL (START, END)) \
3788 	{ \
3789 	  as_bad (_("bad value for <bit-%s-%s> " \
3790 		    "field, value must be 0...%d"), \
3791 		  #START, #END, UIMM_BITFIELD_VAL (START, END)); \
3792 	  break; \
3793 	} \
3794       INSERT_OPERAND (NAME, *IP, EXPR->X_add_number); \
3795       EXPR->X_op = O_absent; \
3796       ASARG = expr_parse_end; \
3797     } \
3798   while (0);
3799 		  switch (*++oparg)
3800 		    {
3801 		    case 'd': /* Xsd */
3802 		      ENCODE_UIMM_BIT_FIELD
3803 			(RD, ip, imm_expr, imm_reloc, asarg, 7, 11);
3804 		      continue;
3805 		    case 't': /* Xst */
3806 		      ENCODE_UIMM_BIT_FIELD
3807 			(RS2, ip, imm_expr, imm_reloc, asarg, 20, 24)
3808 		      continue;
3809 		    case 'O':
3810 		      switch (*++oparg)
3811 			{
3812 			case '2': /* XsO2 */
3813 			  ENCODE_UIMM_BIT_FIELD
3814 			    (XSO2, ip, imm_expr, imm_reloc, asarg, 26, 27);
3815 			  continue;
3816 			case '1': /* XsO1 */
3817 			  ENCODE_UIMM_BIT_FIELD
3818 			    (XSO1, ip, imm_expr, imm_reloc, asarg, 26, 26);
3819 			  continue;
3820 			}
3821 		    default:
3822 		      goto unknown_riscv_ip_operand;
3823 		    }
3824 #undef UIMM_BITFIELD_VAL
3825 #undef ENCODE_UIMM_BIT_FIELD
3826 		  break;
3827 
3828 		default:
3829 		  goto unknown_riscv_ip_operand;
3830 		}
3831 	      break;
3832 
3833 	    default:
3834 	    unknown_riscv_ip_operand:
3835 	      as_fatal (_("internal: unknown argument type `%s'"),
3836 			opargStart);
3837 	    }
3838 	  break;
3839 	}
3840       asarg = asargStart;
3841       insn_with_csr = false;
3842     }
3843 
3844  out:
3845   /* Restore the character we might have clobbered above.  */
3846   if (save_c)
3847     *(asargStart  - 1) = save_c;
3848 
3849   probing_insn_operands = false;
3850 
3851   return error;
3852 }
3853 
3854 /* Similar to riscv_ip, but assembles an instruction according to the
3855    hardcode values of .insn directive.  */
3856 
3857 static const char *
riscv_ip_hardcode(char * str,struct riscv_cl_insn * ip,expressionS * imm_expr,const char * error)3858 riscv_ip_hardcode (char *str,
3859 		   struct riscv_cl_insn *ip,
3860 		   expressionS *imm_expr,
3861 		   const char *error)
3862 {
3863   struct riscv_opcode *insn;
3864   insn_t values[2] = {0, 0};
3865   unsigned int num = 0;
3866 
3867   input_line_pointer = str;
3868   do
3869     {
3870       expression (imm_expr);
3871       switch (imm_expr->X_op)
3872 	{
3873 	case O_constant:
3874 	  values[num++] = (insn_t) imm_expr->X_add_number;
3875 	  break;
3876 	case O_big:
3877 	  /* Extract lower 32-bits of a big number.
3878 	     Assume that generic_bignum_to_int32 work on such number.  */
3879 	  values[num++] = (insn_t) generic_bignum_to_int32 ();
3880 	  break;
3881 	default:
3882 	  /* The first value isn't constant, so it should be
3883 	     .insn <type> <operands>.  We have been parsed it
3884 	     in the riscv_ip.  */
3885 	  if (num == 0)
3886 	    return error;
3887 	  return _("values must be constant");
3888 	}
3889     }
3890   while (*input_line_pointer++ == ',' && num < 2 && imm_expr->X_op != O_big);
3891 
3892   input_line_pointer--;
3893   if (*input_line_pointer != '\0')
3894     return _("unrecognized values");
3895 
3896   insn = XCNEW (struct riscv_opcode);
3897   insn->match = values[num - 1];
3898   create_insn (ip, insn);
3899   unsigned int bytes = riscv_insn_length (insn->match);
3900 
3901   if (num == 2 && values[0] != bytes)
3902     return _("value conflicts with instruction length");
3903 
3904   if (imm_expr->X_op == O_big)
3905     {
3906       unsigned int llen = 0;
3907       for (LITTLENUM_TYPE lval = generic_bignum[imm_expr->X_add_number - 1];
3908 	   lval != 0; llen++)
3909 	lval >>= BITS_PER_CHAR;
3910       unsigned int repr_bytes
3911 	  = (imm_expr->X_add_number - 1) * CHARS_PER_LITTLENUM + llen;
3912       if (bytes < repr_bytes)
3913 	return _("value conflicts with instruction length");
3914       for (num = 0; num < imm_expr->X_add_number - 1; ++num)
3915 	number_to_chars_littleendian (
3916 	    ip->insn_long_opcode + num * CHARS_PER_LITTLENUM,
3917 	    generic_bignum[num],
3918 	    CHARS_PER_LITTLENUM);
3919       if (llen != 0)
3920 	number_to_chars_littleendian (
3921 	    ip->insn_long_opcode + num * CHARS_PER_LITTLENUM,
3922 	    generic_bignum[num],
3923 	    llen);
3924       memset(ip->insn_long_opcode + repr_bytes, 0, bytes - repr_bytes);
3925       return NULL;
3926     }
3927 
3928   if (bytes < sizeof(values[0]) && values[num - 1] >> (8 * bytes) != 0)
3929     return _("value conflicts with instruction length");
3930 
3931   return NULL;
3932 }
3933 
3934 void
md_assemble(char * str)3935 md_assemble (char *str)
3936 {
3937   struct riscv_cl_insn insn;
3938   expressionS imm_expr;
3939   bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
3940 
3941   /* The architecture and privileged elf attributes should be set
3942      before assembling.  */
3943   if (!start_assemble)
3944     {
3945       start_assemble = true;
3946 
3947       riscv_set_abi_by_arch ();
3948       if (!riscv_set_default_priv_spec (NULL))
3949        return;
3950     }
3951 
3952   riscv_mapping_state (MAP_INSN, 0, false/* fr_align_code */);
3953 
3954   const struct riscv_ip_error error = riscv_ip (str, &insn, &imm_expr,
3955 						&imm_reloc, op_hash);
3956 
3957   if (error.msg)
3958     {
3959       if (error.missing_ext)
3960 	as_bad ("%s `%s', extension `%s' required", error.msg,
3961 		error.statement, error.missing_ext);
3962       else
3963 	as_bad ("%s `%s'", error.msg, error.statement);
3964       return;
3965     }
3966 
3967   if (insn.insn_mo->pinfo == INSN_MACRO)
3968     macro (&insn, &imm_expr, &imm_reloc);
3969   else
3970     append_insn (&insn, &imm_expr, imm_reloc);
3971 }
3972 
3973 const char *
md_atof(int type,char * litP,int * sizeP)3974 md_atof (int type, char *litP, int *sizeP)
3975 {
3976   return ieee_md_atof (type, litP, sizeP, target_big_endian);
3977 }
3978 
3979 void
md_number_to_chars(char * buf,valueT val,int n)3980 md_number_to_chars (char *buf, valueT val, int n)
3981 {
3982   if (target_big_endian)
3983     number_to_chars_bigendian (buf, val, n);
3984   else
3985     number_to_chars_littleendian (buf, val, n);
3986 }
3987 
3988 const char *md_shortopts = "O::g::G:";
3989 
3990 enum options
3991 {
3992   OPTION_MARCH = OPTION_MD_BASE,
3993   OPTION_PIC,
3994   OPTION_NO_PIC,
3995   OPTION_MABI,
3996   OPTION_RELAX,
3997   OPTION_NO_RELAX,
3998   OPTION_ARCH_ATTR,
3999   OPTION_NO_ARCH_ATTR,
4000   OPTION_CSR_CHECK,
4001   OPTION_NO_CSR_CHECK,
4002   OPTION_MISA_SPEC,
4003   OPTION_MPRIV_SPEC,
4004   OPTION_BIG_ENDIAN,
4005   OPTION_LITTLE_ENDIAN,
4006   OPTION_END_OF_ENUM
4007 };
4008 
4009 struct option md_longopts[] =
4010 {
4011   {"march", required_argument, NULL, OPTION_MARCH},
4012   {"fPIC", no_argument, NULL, OPTION_PIC},
4013   {"fpic", no_argument, NULL, OPTION_PIC},
4014   {"fno-pic", no_argument, NULL, OPTION_NO_PIC},
4015   {"mabi", required_argument, NULL, OPTION_MABI},
4016   {"mrelax", no_argument, NULL, OPTION_RELAX},
4017   {"mno-relax", no_argument, NULL, OPTION_NO_RELAX},
4018   {"march-attr", no_argument, NULL, OPTION_ARCH_ATTR},
4019   {"mno-arch-attr", no_argument, NULL, OPTION_NO_ARCH_ATTR},
4020   {"mcsr-check", no_argument, NULL, OPTION_CSR_CHECK},
4021   {"mno-csr-check", no_argument, NULL, OPTION_NO_CSR_CHECK},
4022   {"misa-spec", required_argument, NULL, OPTION_MISA_SPEC},
4023   {"mpriv-spec", required_argument, NULL, OPTION_MPRIV_SPEC},
4024   {"mbig-endian", no_argument, NULL, OPTION_BIG_ENDIAN},
4025   {"mlittle-endian", no_argument, NULL, OPTION_LITTLE_ENDIAN},
4026 
4027   {NULL, no_argument, NULL, 0}
4028 };
4029 size_t md_longopts_size = sizeof (md_longopts);
4030 
4031 int
md_parse_option(int c,const char * arg)4032 md_parse_option (int c, const char *arg)
4033 {
4034   switch (c)
4035     {
4036     case OPTION_MARCH:
4037       default_arch_with_ext = arg;
4038       break;
4039 
4040     case OPTION_NO_PIC:
4041       riscv_opts.pic = false;
4042       break;
4043 
4044     case OPTION_PIC:
4045       riscv_opts.pic = true;
4046       break;
4047 
4048     case OPTION_MABI:
4049       if (strcmp (arg, "ilp32") == 0)
4050 	riscv_set_abi (32, FLOAT_ABI_SOFT, false);
4051       else if (strcmp (arg, "ilp32e") == 0)
4052 	riscv_set_abi (32, FLOAT_ABI_SOFT, true);
4053       else if (strcmp (arg, "ilp32f") == 0)
4054 	riscv_set_abi (32, FLOAT_ABI_SINGLE, false);
4055       else if (strcmp (arg, "ilp32d") == 0)
4056 	riscv_set_abi (32, FLOAT_ABI_DOUBLE, false);
4057       else if (strcmp (arg, "ilp32q") == 0)
4058 	riscv_set_abi (32, FLOAT_ABI_QUAD, false);
4059       else if (strcmp (arg, "lp64") == 0)
4060 	riscv_set_abi (64, FLOAT_ABI_SOFT, false);
4061       else if (strcmp (arg, "lp64e") == 0)
4062 	riscv_set_abi (64, FLOAT_ABI_SOFT, true);
4063       else if (strcmp (arg, "lp64f") == 0)
4064 	riscv_set_abi (64, FLOAT_ABI_SINGLE, false);
4065       else if (strcmp (arg, "lp64d") == 0)
4066 	riscv_set_abi (64, FLOAT_ABI_DOUBLE, false);
4067       else if (strcmp (arg, "lp64q") == 0)
4068 	riscv_set_abi (64, FLOAT_ABI_QUAD, false);
4069       else
4070 	return 0;
4071       explicit_mabi = true;
4072       break;
4073 
4074     case OPTION_RELAX:
4075       riscv_opts.relax = true;
4076       break;
4077 
4078     case OPTION_NO_RELAX:
4079       riscv_opts.relax = false;
4080       break;
4081 
4082     case OPTION_ARCH_ATTR:
4083       riscv_opts.arch_attr = true;
4084       break;
4085 
4086     case OPTION_NO_ARCH_ATTR:
4087       riscv_opts.arch_attr = false;
4088       break;
4089 
4090     case OPTION_CSR_CHECK:
4091       riscv_opts.csr_check = true;
4092       break;
4093 
4094     case OPTION_NO_CSR_CHECK:
4095       riscv_opts.csr_check = false;
4096       break;
4097 
4098     case OPTION_MISA_SPEC:
4099       return riscv_set_default_isa_spec (arg);
4100 
4101     case OPTION_MPRIV_SPEC:
4102       return riscv_set_default_priv_spec (arg);
4103 
4104     case OPTION_BIG_ENDIAN:
4105       target_big_endian = 1;
4106       break;
4107 
4108     case OPTION_LITTLE_ENDIAN:
4109       target_big_endian = 0;
4110       break;
4111 
4112     default:
4113       return 0;
4114     }
4115 
4116   return 1;
4117 }
4118 
4119 void
riscv_after_parse_args(void)4120 riscv_after_parse_args (void)
4121 {
4122   /* The --with-arch is optional for now, so we still need to set the xlen
4123      according to the default_arch, which is set by the --target.  */
4124   if (xlen == 0)
4125     {
4126       if (strcmp (default_arch, "riscv32") == 0)
4127 	xlen = 32;
4128       else if (strcmp (default_arch, "riscv64") == 0)
4129 	xlen = 64;
4130       else
4131 	as_bad ("unknown default architecture `%s'", default_arch);
4132     }
4133 
4134   /* Set default specs.  */
4135   if (default_isa_spec == ISA_SPEC_CLASS_NONE)
4136     riscv_set_default_isa_spec (DEFAULT_RISCV_ISA_SPEC);
4137   if (default_priv_spec == PRIV_SPEC_CLASS_NONE)
4138     riscv_set_default_priv_spec (DEFAULT_RISCV_PRIV_SPEC);
4139 
4140   riscv_set_arch (default_arch_with_ext);
4141 
4142   /* If the CIE to be produced has not been overridden on the command line,
4143      then produce version 3 by default.  This allows us to use the full
4144      range of registers in a .cfi_return_column directive.  */
4145   if (flag_dwarf_cie_version == -1)
4146     flag_dwarf_cie_version = 3;
4147 }
4148 
riscv_parse_name(const char * name,struct expressionS * ep,enum expr_mode mode)4149 bool riscv_parse_name (const char *name, struct expressionS *ep,
4150 		       enum expr_mode mode)
4151 {
4152   unsigned int regno;
4153   symbolS *sym;
4154 
4155   if (!probing_insn_operands)
4156     return false;
4157 
4158   gas_assert (mode == expr_normal);
4159 
4160   regno = reg_lookup_internal (name, RCLASS_GPR);
4161   if (regno == (unsigned int)-1)
4162     return false;
4163 
4164   if (symbol_find (name) != NULL)
4165     return false;
4166 
4167   /* Create a symbol without adding it to the symbol table yet.
4168      Insertion will happen only once we commit to using the insn
4169      we're probing operands for.  */
4170   for (sym = deferred_sym_rootP; sym; sym = symbol_next (sym))
4171     if (strcmp (name, S_GET_NAME (sym)) == 0)
4172       break;
4173   if (!sym)
4174     {
4175       for (sym = orphan_sym_rootP; sym; sym = symbol_next (sym))
4176 	if (strcmp (name, S_GET_NAME (sym)) == 0)
4177 	  {
4178 	    symbol_remove (sym, &orphan_sym_rootP, &orphan_sym_lastP);
4179 	    break;
4180 	  }
4181       if (!sym)
4182 	sym = symbol_create (name, undefined_section,
4183 			     &zero_address_frag, 0);
4184 
4185       symbol_append (sym, deferred_sym_lastP, &deferred_sym_rootP,
4186 		     &deferred_sym_lastP);
4187     }
4188 
4189   ep->X_op = O_symbol;
4190   ep->X_add_symbol = sym;
4191   ep->X_add_number = 0;
4192 
4193   return true;
4194 }
4195 
4196 long
md_pcrel_from(fixS * fixP)4197 md_pcrel_from (fixS *fixP)
4198 {
4199   return fixP->fx_where + fixP->fx_frag->fr_address;
4200 }
4201 
4202 /* Apply a fixup to the object file.  */
4203 
4204 void
md_apply_fix(fixS * fixP,valueT * valP,segT seg ATTRIBUTE_UNUSED)4205 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
4206 {
4207   unsigned int subtype;
4208   bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
4209   bool relaxable = false;
4210   offsetT loc;
4211   segT sub_segment;
4212 
4213   /* Remember value for tc_gen_reloc.  */
4214   fixP->fx_addnumber = *valP;
4215 
4216   switch (fixP->fx_r_type)
4217     {
4218     case BFD_RELOC_RISCV_HI20:
4219     case BFD_RELOC_RISCV_LO12_I:
4220     case BFD_RELOC_RISCV_LO12_S:
4221       bfd_putl32 (riscv_apply_const_reloc (fixP->fx_r_type, *valP)
4222 		  | bfd_getl32 (buf), buf);
4223       if (fixP->fx_addsy == NULL)
4224 	fixP->fx_done = true;
4225       relaxable = true;
4226       break;
4227 
4228     case BFD_RELOC_RISCV_GOT_HI20:
4229       /* R_RISCV_GOT_HI20 and the following R_RISCV_LO12_I are relaxable
4230 	 only if it is created as a result of la or lga assembler macros. */
4231       if (fixP->tc_fix_data.source_macro == M_LA
4232 	  || fixP->tc_fix_data.source_macro == M_LGA)
4233 	relaxable = true;
4234       break;
4235 
4236     case BFD_RELOC_RISCV_ADD8:
4237     case BFD_RELOC_RISCV_ADD16:
4238     case BFD_RELOC_RISCV_ADD32:
4239     case BFD_RELOC_RISCV_ADD64:
4240     case BFD_RELOC_RISCV_SUB6:
4241     case BFD_RELOC_RISCV_SUB8:
4242     case BFD_RELOC_RISCV_SUB16:
4243     case BFD_RELOC_RISCV_SUB32:
4244     case BFD_RELOC_RISCV_SUB64:
4245     case BFD_RELOC_RISCV_RELAX:
4246     /* cvt_frag_to_fill () has called output_leb128 ().  */
4247     case BFD_RELOC_RISCV_SET_ULEB128:
4248     case BFD_RELOC_RISCV_SUB_ULEB128:
4249       break;
4250 
4251     case BFD_RELOC_RISCV_TPREL_HI20:
4252     case BFD_RELOC_RISCV_TPREL_LO12_I:
4253     case BFD_RELOC_RISCV_TPREL_LO12_S:
4254     case BFD_RELOC_RISCV_TPREL_ADD:
4255       relaxable = true;
4256       /* Fall through.  */
4257 
4258     case BFD_RELOC_RISCV_TLS_GOT_HI20:
4259     case BFD_RELOC_RISCV_TLS_GD_HI20:
4260     case BFD_RELOC_RISCV_TLS_DTPREL32:
4261     case BFD_RELOC_RISCV_TLS_DTPREL64:
4262       if (fixP->fx_addsy != NULL)
4263 	S_SET_THREAD_LOCAL (fixP->fx_addsy);
4264       else
4265 	as_bad_where (fixP->fx_file, fixP->fx_line,
4266 		      _("TLS relocation against a constant"));
4267       break;
4268 
4269     case BFD_RELOC_32:
4270       /* Use pc-relative relocation for FDE initial location.
4271 	 The symbol address in .eh_frame may be adjusted in
4272 	 _bfd_elf_discard_section_eh_frame, and the content of
4273 	 .eh_frame will be adjusted in _bfd_elf_write_section_eh_frame.
4274 	 Therefore, we cannot insert a relocation whose addend symbol is
4275 	 in .eh_frame.  Othrewise, the value may be adjusted twice.  */
4276       if (fixP->fx_addsy && fixP->fx_subsy
4277 	  && (sub_segment = S_GET_SEGMENT (fixP->fx_subsy))
4278 	  && strcmp (sub_segment->name, ".eh_frame") == 0
4279 	  && S_GET_VALUE (fixP->fx_subsy)
4280 	     == fixP->fx_frag->fr_address + fixP->fx_where)
4281 	{
4282 	  fixP->fx_r_type = BFD_RELOC_RISCV_32_PCREL;
4283 	  fixP->fx_subsy = NULL;
4284 	  break;
4285 	}
4286       /* Fall through.  */
4287     case BFD_RELOC_64:
4288     case BFD_RELOC_16:
4289     case BFD_RELOC_8:
4290     case BFD_RELOC_RISCV_CFA:
4291       if (fixP->fx_addsy && fixP->fx_subsy)
4292 	{
4293 	  fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
4294 	  fixP->fx_next->fx_addsy = fixP->fx_subsy;
4295 	  fixP->fx_next->fx_subsy = NULL;
4296 	  fixP->fx_next->fx_offset = 0;
4297 	  fixP->fx_subsy = NULL;
4298 
4299 	  switch (fixP->fx_r_type)
4300 	    {
4301 	    case BFD_RELOC_64:
4302 	      fixP->fx_r_type = BFD_RELOC_RISCV_ADD64;
4303 	      fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB64;
4304 	      break;
4305 
4306 	    case BFD_RELOC_32:
4307 	      fixP->fx_r_type = BFD_RELOC_RISCV_ADD32;
4308 	      fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
4309 	      break;
4310 
4311 	    case BFD_RELOC_16:
4312 	      fixP->fx_r_type = BFD_RELOC_RISCV_ADD16;
4313 	      fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
4314 	      break;
4315 
4316 	    case BFD_RELOC_8:
4317 	      fixP->fx_r_type = BFD_RELOC_RISCV_ADD8;
4318 	      fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
4319 	      break;
4320 
4321 	    case BFD_RELOC_RISCV_CFA:
4322 	      /* Load the byte to get the subtype.  */
4323 	      subtype = bfd_get_8 (NULL, &((fragS *) (fixP->fx_frag->fr_opcode))->fr_literal[fixP->fx_where]);
4324 	      loc = fixP->fx_frag->fr_fix - (subtype & 7);
4325 	      switch (subtype)
4326 		{
4327 		case DW_CFA_advance_loc1:
4328 		  fixP->fx_where = loc + 1;
4329 		  fixP->fx_next->fx_where = loc + 1;
4330 		  fixP->fx_r_type = BFD_RELOC_RISCV_SET8;
4331 		  fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
4332 		  break;
4333 
4334 		case DW_CFA_advance_loc2:
4335 		  fixP->fx_size = 2;
4336 		  fixP->fx_next->fx_size = 2;
4337 		  fixP->fx_where = loc + 1;
4338 		  fixP->fx_next->fx_where = loc + 1;
4339 		  fixP->fx_r_type = BFD_RELOC_RISCV_SET16;
4340 		  fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
4341 		  break;
4342 
4343 		case DW_CFA_advance_loc4:
4344 		  fixP->fx_size = 4;
4345 		  fixP->fx_next->fx_size = 4;
4346 		  fixP->fx_where = loc;
4347 		  fixP->fx_next->fx_where = loc;
4348 		  fixP->fx_r_type = BFD_RELOC_RISCV_SET32;
4349 		  fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
4350 		  break;
4351 
4352 		default:
4353 		  if (subtype < 0x80 && (subtype & 0x40))
4354 		    {
4355 		      /* DW_CFA_advance_loc */
4356 		      fixP->fx_frag = (fragS *) fixP->fx_frag->fr_opcode;
4357 		      fixP->fx_next->fx_frag = fixP->fx_frag;
4358 		      fixP->fx_r_type = BFD_RELOC_RISCV_SET6;
4359 		      fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB6;
4360 		    }
4361 		  else
4362 		    as_fatal (_("internal: bad CFA value #%d"), subtype);
4363 		  break;
4364 		}
4365 	      break;
4366 
4367 	    default:
4368 	      /* This case is unreachable.  */
4369 	      abort ();
4370 	    }
4371 	}
4372       /* Fall through.  */
4373 
4374     case BFD_RELOC_RVA:
4375       /* If we are deleting this reloc entry, we must fill in the
4376 	 value now.  This can happen if we have a .word which is not
4377 	 resolved when it appears but is later defined.  */
4378       if (fixP->fx_addsy == NULL)
4379 	{
4380 	  gas_assert (fixP->fx_size <= sizeof (valueT));
4381 	  md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
4382 	  fixP->fx_done = 1;
4383 	}
4384       break;
4385 
4386     case BFD_RELOC_RISCV_JMP:
4387       if (fixP->fx_addsy)
4388 	{
4389 	  /* Fill in a tentative value to improve objdump readability.  */
4390 	  bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4391 	  bfd_vma delta = target - md_pcrel_from (fixP);
4392 	  bfd_putl32 (bfd_getl32 (buf) | ENCODE_JTYPE_IMM (delta), buf);
4393 	}
4394       break;
4395 
4396     case BFD_RELOC_12_PCREL:
4397       if (fixP->fx_addsy)
4398 	{
4399 	  /* Fill in a tentative value to improve objdump readability.  */
4400 	  bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4401 	  bfd_vma delta = target - md_pcrel_from (fixP);
4402 	  bfd_putl32 (bfd_getl32 (buf) | ENCODE_BTYPE_IMM (delta), buf);
4403 	}
4404       break;
4405 
4406     case BFD_RELOC_RISCV_RVC_BRANCH:
4407       if (fixP->fx_addsy)
4408 	{
4409 	  /* Fill in a tentative value to improve objdump readability.  */
4410 	  bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4411 	  bfd_vma delta = target - md_pcrel_from (fixP);
4412 	  bfd_putl16 (bfd_getl16 (buf) | ENCODE_CBTYPE_IMM (delta), buf);
4413 	}
4414       break;
4415 
4416     case BFD_RELOC_RISCV_RVC_JUMP:
4417       if (fixP->fx_addsy)
4418 	{
4419 	  /* Fill in a tentative value to improve objdump readability.  */
4420 	  bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4421 	  bfd_vma delta = target - md_pcrel_from (fixP);
4422 	  bfd_putl16 (bfd_getl16 (buf) | ENCODE_CJTYPE_IMM (delta), buf);
4423 	}
4424       break;
4425 
4426     case BFD_RELOC_RISCV_CALL:
4427     case BFD_RELOC_RISCV_CALL_PLT:
4428       relaxable = true;
4429       break;
4430 
4431     case BFD_RELOC_RISCV_PCREL_HI20:
4432       /* Record and evaluate the pcrel_hi relocation with local symbol.
4433 	 Fill in a tentative value to improve objdump readability for -mrelax,
4434 	 and set fx_done for -mno-relax.  */
4435       if (fixP->fx_addsy
4436 	  && S_IS_LOCAL (fixP->fx_addsy)
4437 	  && S_GET_SEGMENT (fixP->fx_addsy) == seg)
4438 	{
4439 	  bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4440 	  bfd_vma value = target - md_pcrel_from (fixP);
4441 
4442 	  /* Record PCREL_HI20.  */
4443 	  if (!riscv_record_pcrel_fixup (riscv_pcrel_hi_fixup_hash,
4444 					 md_pcrel_from (fixP),
4445 					 fixP->fx_addsy,
4446 					 target))
4447 	    as_warn (_("too many pcrel_hi"));
4448 
4449 	  bfd_putl32 (bfd_getl32 (buf)
4450 		      | ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)),
4451 		      buf);
4452 	  if (!riscv_opts.relax)
4453 	    fixP->fx_done = 1;
4454 	}
4455       relaxable = true;
4456       break;
4457 
4458     case BFD_RELOC_RISCV_PCREL_LO12_S:
4459     case BFD_RELOC_RISCV_PCREL_LO12_I:
4460       /* Resolve the pcrel_lo relocation with local symbol.
4461 	 Fill in a tentative value to improve objdump readability for -mrelax,
4462 	 and set fx_done for -mno-relax.  */
4463       {
4464 	bfd_vma location_pcrel_hi = S_GET_VALUE (fixP->fx_addsy) + *valP;
4465 	riscv_pcrel_hi_fixup search = {location_pcrel_hi, 0, 0};
4466 	riscv_pcrel_hi_fixup *entry = htab_find (riscv_pcrel_hi_fixup_hash,
4467 						 &search);
4468 	if (entry && entry->symbol
4469 	    && S_IS_LOCAL (entry->symbol)
4470 	    && S_GET_SEGMENT (entry->symbol) == seg)
4471 	  {
4472 	    bfd_vma target = entry->target;
4473 	    bfd_vma value = target - entry->address;
4474 	    bfd_putl32 (bfd_getl32 (buf) | ENCODE_ITYPE_IMM (value), buf);
4475 	    /* Relaxations should never be enabled by `.option relax'.  */
4476 	    if (!riscv_opts.relax)
4477 	      fixP->fx_done = 1;
4478 	  }
4479       }
4480       relaxable = true;
4481       break;
4482 
4483     case BFD_RELOC_RISCV_ALIGN:
4484       break;
4485 
4486     default:
4487       /* We ignore generic BFD relocations we don't know about.  */
4488       if (bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type) != NULL)
4489 	as_fatal (_("internal: bad relocation #%d"), fixP->fx_r_type);
4490     }
4491 
4492   if (fixP->fx_subsy != NULL)
4493     as_bad_subtract (fixP);
4494 
4495   /* Add an R_RISCV_RELAX reloc if the reloc is relaxable.  */
4496   if (relaxable && fixP->fx_tcbit && fixP->fx_addsy != NULL)
4497     {
4498       fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
4499       fixP->fx_next->fx_addsy = fixP->fx_next->fx_subsy = NULL;
4500       fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_RELAX;
4501       fixP->fx_next->fx_size = 0;
4502     }
4503 }
4504 
4505 /* Because the value of .cfi_remember_state may changed after relaxation,
4506    we insert a fix to relocate it again in link-time.  */
4507 
4508 void
riscv_pre_output_hook(void)4509 riscv_pre_output_hook (void)
4510 {
4511   const frchainS *frch;
4512   segT s;
4513 
4514   /* Save the current segment info.  */
4515   segT seg = now_seg;
4516   subsegT subseg = now_subseg;
4517 
4518   for (s = stdoutput->sections; s; s = s->next)
4519     for (frch = seg_info (s)->frchainP; frch; frch = frch->frch_next)
4520       {
4521 	fragS *frag;
4522 
4523 	for (frag = frch->frch_root; frag; frag = frag->fr_next)
4524 	  {
4525 	    if (frag->fr_type == rs_cfa)
4526 	      {
4527 		expressionS exp;
4528 		expressionS *symval;
4529 
4530 		symval = symbol_get_value_expression (frag->fr_symbol);
4531 		exp.X_op = O_subtract;
4532 		exp.X_add_symbol = symval->X_add_symbol;
4533 		exp.X_add_number = 0;
4534 		exp.X_op_symbol = symval->X_op_symbol;
4535 
4536 		/* We must set the segment before creating a frag after all
4537 		   frag chains have been chained together.  */
4538 		subseg_set (s, frch->frch_subseg);
4539 
4540 		fix_new_exp (frag, (int) frag->fr_offset, 1, &exp, 0,
4541 			     BFD_RELOC_RISCV_CFA);
4542 	      }
4543 	  }
4544       }
4545 
4546   /* Restore the original segment info.  */
4547   subseg_set (seg, subseg);
4548 }
4549 
4550 /* Handle the .option pseudo-op.  */
4551 
4552 static void
s_riscv_option(int x ATTRIBUTE_UNUSED)4553 s_riscv_option (int x ATTRIBUTE_UNUSED)
4554 {
4555   char *name = input_line_pointer, ch;
4556 
4557   while (!is_end_of_line[(unsigned char) *input_line_pointer])
4558     ++input_line_pointer;
4559   ch = *input_line_pointer;
4560   *input_line_pointer = '\0';
4561 
4562   if (strcmp (name, "rvc") == 0)
4563     {
4564       riscv_update_subset (&riscv_rps_as, "+c");
4565       riscv_reset_subsets_list_arch_str ();
4566       riscv_set_rvc (true);
4567     }
4568   else if (strcmp (name, "norvc") == 0)
4569     {
4570       riscv_update_subset (&riscv_rps_as, "-c");
4571       riscv_reset_subsets_list_arch_str ();
4572       riscv_set_rvc (false);
4573     }
4574   else if (strcmp (name, "pic") == 0)
4575     riscv_opts.pic = true;
4576   else if (strcmp (name, "nopic") == 0)
4577     riscv_opts.pic = false;
4578   else if (strcmp (name, "relax") == 0)
4579     riscv_opts.relax = true;
4580   else if (strcmp (name, "norelax") == 0)
4581     riscv_opts.relax = false;
4582   else if (strcmp (name, "csr-check") == 0)
4583     riscv_opts.csr_check = true;
4584   else if (strcmp (name, "no-csr-check") == 0)
4585     riscv_opts.csr_check = false;
4586   else if (strncmp (name, "arch,", 5) == 0)
4587     {
4588       name += 5;
4589       if (ISSPACE (*name) && *name != '\0')
4590 	name++;
4591       riscv_update_subset (&riscv_rps_as, name);
4592       riscv_reset_subsets_list_arch_str ();
4593 
4594       riscv_set_rvc (false);
4595       if (riscv_subset_supports (&riscv_rps_as, "c")
4596 	  || riscv_subset_supports (&riscv_rps_as, "zca"))
4597 	riscv_set_rvc (true);
4598 
4599       if (riscv_subset_supports (&riscv_rps_as, "ztso"))
4600 	riscv_set_tso ();
4601     }
4602   else if (strcmp (name, "push") == 0)
4603     {
4604       struct riscv_option_stack *s;
4605 
4606       s = XNEW (struct riscv_option_stack);
4607       s->next = riscv_opts_stack;
4608       s->options = riscv_opts;
4609       s->subset_list = riscv_rps_as.subset_list;
4610       riscv_opts_stack = s;
4611       riscv_rps_as.subset_list = riscv_copy_subset_list (s->subset_list);
4612     }
4613   else if (strcmp (name, "pop") == 0)
4614     {
4615       struct riscv_option_stack *s;
4616 
4617       s = riscv_opts_stack;
4618       if (s == NULL)
4619 	as_bad (_(".option pop with no .option push"));
4620       else
4621 	{
4622 	  riscv_subset_list_t *release_subsets = riscv_rps_as.subset_list;
4623 	  riscv_opts_stack = s->next;
4624 	  riscv_opts = s->options;
4625 	  riscv_rps_as.subset_list = s->subset_list;
4626 	  riscv_release_subset_list (release_subsets);
4627 	  free (s);
4628 	}
4629     }
4630   else
4631     {
4632       as_warn (_("unrecognized .option directive: %s"), name);
4633     }
4634   *input_line_pointer = ch;
4635   demand_empty_rest_of_line ();
4636 }
4637 
4638 /* Handle the .dtprelword and .dtpreldword pseudo-ops.  They generate
4639    a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
4640    use in DWARF debug information.  */
4641 
4642 static void
s_dtprel(int bytes)4643 s_dtprel (int bytes)
4644 {
4645   expressionS ex;
4646   char *p;
4647 
4648   expression (&ex);
4649 
4650   if (ex.X_op != O_symbol)
4651     {
4652       as_bad (_("unsupported use of %s"), (bytes == 8
4653 					   ? ".dtpreldword"
4654 					   : ".dtprelword"));
4655       ignore_rest_of_line ();
4656     }
4657 
4658   p = frag_more (bytes);
4659   md_number_to_chars (p, 0, bytes);
4660   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, false,
4661 	       (bytes == 8
4662 		? BFD_RELOC_RISCV_TLS_DTPREL64
4663 		: BFD_RELOC_RISCV_TLS_DTPREL32));
4664 
4665   demand_empty_rest_of_line ();
4666 }
4667 
4668 static void
riscv_make_nops(char * buf,bfd_vma bytes)4669 riscv_make_nops (char *buf, bfd_vma bytes)
4670 {
4671   bfd_vma i = 0;
4672 
4673   /* RISC-V instructions cannot begin or end on odd addresses, so this case
4674      means we are not within a valid instruction sequence.  It is thus safe
4675      to use a zero byte, even though that is not a valid instruction.  */
4676   if (bytes % 2 == 1)
4677     buf[i++] = 0;
4678 
4679   /* Use at most one 2-byte NOP.  */
4680   if ((bytes - i) % 4 == 2)
4681     {
4682       number_to_chars_littleendian (buf + i, RVC_NOP, 2);
4683       i += 2;
4684     }
4685 
4686   /* Fill the remainder with 4-byte NOPs.  */
4687   for ( ; i < bytes; i += 4)
4688     number_to_chars_littleendian (buf + i, RISCV_NOP, 4);
4689 }
4690 
4691 /* Called from md_do_align.  Used to create an alignment frag in a
4692    code section by emitting a worst-case NOP sequence that the linker
4693    will later relax to the correct number of NOPs.  We can't compute
4694    the correct alignment now because of other linker relaxations.  */
4695 
4696 bool
riscv_frag_align_code(int n)4697 riscv_frag_align_code (int n)
4698 {
4699   bfd_vma bytes = (bfd_vma) 1 << n;
4700   bfd_vma insn_alignment = riscv_opts.rvc ? 2 : 4;
4701   bfd_vma worst_case_bytes = bytes - insn_alignment;
4702   char *nops;
4703   expressionS ex;
4704 
4705   /* If we are moving to a smaller alignment than the instruction size, then no
4706      alignment is required. */
4707   if (bytes <= insn_alignment)
4708     return true;
4709 
4710   /* When not relaxing, riscv_handle_align handles code alignment.  */
4711   if (!riscv_opts.relax)
4712     return false;
4713 
4714   /* Maybe we should use frag_var to create a new rs_align_code fragment,
4715      rather than just use frag_more to handle an alignment here?  So that we
4716      don't need to call riscv_mapping_state again later, and then only need
4717      to check frag->fr_type to see if it is frag_align_code.  */
4718   nops = frag_more (worst_case_bytes);
4719 
4720   ex.X_op = O_constant;
4721   ex.X_add_number = worst_case_bytes;
4722 
4723   riscv_make_nops (nops, worst_case_bytes);
4724 
4725   fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
4726 	       &ex, false, BFD_RELOC_RISCV_ALIGN);
4727 
4728   riscv_mapping_state (MAP_INSN, worst_case_bytes, true/* fr_align_code */);
4729 
4730   /* We need to start a new frag after the alignment which may be removed by
4731      the linker, to prevent the assembler from computing static offsets.
4732      This is necessary to get correct EH info.  */
4733   frag_wane (frag_now);
4734   frag_new (0);
4735 
4736   return true;
4737 }
4738 
4739 /* Implement HANDLE_ALIGN.  */
4740 
4741 void
riscv_handle_align(fragS * fragP)4742 riscv_handle_align (fragS *fragP)
4743 {
4744   switch (fragP->fr_type)
4745     {
4746     case rs_align_code:
4747       /* When relaxing, riscv_frag_align_code handles code alignment.  */
4748       if (!riscv_opts.relax)
4749 	{
4750 	  bfd_signed_vma bytes = (fragP->fr_next->fr_address
4751 				  - fragP->fr_address - fragP->fr_fix);
4752 	  /* We have 4 byte uncompressed nops.  */
4753 	  bfd_signed_vma size = 4;
4754 	  bfd_signed_vma excess = bytes % size;
4755 	  bfd_boolean odd_padding = (excess % 2 == 1);
4756 	  char *p = fragP->fr_literal + fragP->fr_fix;
4757 
4758 	  if (bytes <= 0)
4759 	    break;
4760 
4761 	  /* Insert zeros or compressed nops to get 4 byte alignment.  */
4762 	  if (excess)
4763 	    {
4764 	      if (odd_padding)
4765 		riscv_add_odd_padding_symbol (fragP);
4766 	      riscv_make_nops (p, excess);
4767 	      fragP->fr_fix += excess;
4768 	      p += excess;
4769 	    }
4770 
4771 	  /* The frag will be changed to `rs_fill` later.  The function
4772 	     `write_contents` will try to fill the remaining spaces
4773 	     according to the patterns we give.  In this case, we give
4774 	     a 4 byte uncompressed nop as the pattern, and set the size
4775 	     of the pattern into `fr_var`.  The nop will be output to the
4776 	     file `fr_offset` times.  However, `fr_offset` could be zero
4777 	     if we don't need to pad the boundary finally.  */
4778 	  riscv_make_nops (p, size);
4779 	  fragP->fr_var = size;
4780 	}
4781       break;
4782 
4783     default:
4784       break;
4785     }
4786 }
4787 
4788 /* This usually called from frag_var.  */
4789 
4790 void
riscv_init_frag(fragS * fragP,int max_chars)4791 riscv_init_frag (fragS * fragP, int max_chars)
4792 {
4793   /* Do not add mapping symbol to debug sections.  */
4794   if (bfd_section_flags (now_seg) & SEC_DEBUGGING)
4795     return;
4796 
4797   switch (fragP->fr_type)
4798     {
4799     case rs_fill:
4800     case rs_align:
4801     case rs_align_test:
4802       riscv_mapping_state (MAP_DATA, max_chars, false/* fr_align_code */);
4803       break;
4804     case rs_align_code:
4805       riscv_mapping_state (MAP_INSN, max_chars, true/* fr_align_code */);
4806       break;
4807     default:
4808       break;
4809     }
4810 }
4811 
4812 int
md_estimate_size_before_relax(fragS * fragp,asection * segtype)4813 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
4814 {
4815   return (fragp->fr_var = relaxed_branch_length (fragp, segtype, false));
4816 }
4817 
4818 /* Translate internal representation of relocation info to BFD target
4819    format.  */
4820 
4821 arelent *
tc_gen_reloc(asection * section ATTRIBUTE_UNUSED,fixS * fixp)4822 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
4823 {
4824   arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
4825 
4826   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
4827   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
4828   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
4829   reloc->addend = fixp->fx_addnumber;
4830 
4831   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
4832   if (reloc->howto == NULL)
4833     {
4834       if ((fixp->fx_r_type == BFD_RELOC_16 || fixp->fx_r_type == BFD_RELOC_8)
4835 	  && fixp->fx_addsy != NULL && fixp->fx_subsy != NULL)
4836 	{
4837 	  /* We don't have R_RISCV_8/16, but for this special case,
4838 	     we can use R_RISCV_ADD8/16 with R_RISCV_SUB8/16.  */
4839 	  return reloc;
4840 	}
4841 
4842       as_bad_where (fixp->fx_file, fixp->fx_line,
4843 		    _("cannot represent %s relocation in object file"),
4844 		    bfd_get_reloc_code_name (fixp->fx_r_type));
4845       return NULL;
4846     }
4847 
4848   return reloc;
4849 }
4850 
4851 int
riscv_relax_frag(asection * sec,fragS * fragp,long stretch ATTRIBUTE_UNUSED)4852 riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
4853 {
4854   if (RELAX_BRANCH_P (fragp->fr_subtype))
4855     {
4856       offsetT old_var = fragp->fr_var;
4857       fragp->fr_var = relaxed_branch_length (fragp, sec, true);
4858       return fragp->fr_var - old_var;
4859     }
4860 
4861   return 0;
4862 }
4863 
4864 /* Expand far branches to multi-instruction sequences.  */
4865 
4866 static void
md_convert_frag_branch(fragS * fragp)4867 md_convert_frag_branch (fragS *fragp)
4868 {
4869   bfd_byte *buf;
4870   expressionS exp;
4871   fixS *fixp;
4872   insn_t insn;
4873   int rs1, reloc;
4874 
4875   buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
4876 
4877   exp.X_op = O_symbol;
4878   exp.X_add_symbol = fragp->fr_symbol;
4879   exp.X_add_number = fragp->fr_offset;
4880 
4881   gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
4882 
4883   if (RELAX_BRANCH_RVC (fragp->fr_subtype))
4884     {
4885       switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
4886 	{
4887 	  case 8:
4888 	  case 4:
4889 	    /* Expand the RVC branch into a RISC-V one.  */
4890 	    insn = bfd_getl16 (buf);
4891 	    rs1 = 8 + ((insn >> OP_SH_CRS1S) & OP_MASK_CRS1S);
4892 	    if ((insn & MASK_C_J) == MATCH_C_J)
4893 	      insn = MATCH_JAL;
4894 	    else if ((insn & MASK_C_JAL) == MATCH_C_JAL)
4895 	      insn = MATCH_JAL | (X_RA << OP_SH_RD);
4896 	    else if ((insn & MASK_C_BEQZ) == MATCH_C_BEQZ)
4897 	      insn = MATCH_BEQ | (rs1 << OP_SH_RS1);
4898 	    else if ((insn & MASK_C_BNEZ) == MATCH_C_BNEZ)
4899 	      insn = MATCH_BNE | (rs1 << OP_SH_RS1);
4900 	    else
4901 	      abort ();
4902 	    bfd_putl32 (insn, buf);
4903 	    break;
4904 
4905 	  case 6:
4906 	    /* Invert the branch condition.  Branch over the jump.  */
4907 	    insn = bfd_getl16 (buf);
4908 	    insn ^= MATCH_C_BEQZ ^ MATCH_C_BNEZ;
4909 	    insn |= ENCODE_CBTYPE_IMM (6);
4910 	    bfd_putl16 (insn, buf);
4911 	    buf += 2;
4912 	    goto jump;
4913 
4914 	  case 2:
4915 	    /* Just keep the RVC branch.  */
4916 	    reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
4917 		    ? BFD_RELOC_RISCV_RVC_JUMP : BFD_RELOC_RISCV_RVC_BRANCH;
4918 	    fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
4919 				2, &exp, false, reloc);
4920 	    buf += 2;
4921 	    goto done;
4922 
4923 	  default:
4924 	    abort ();
4925 	}
4926     }
4927 
4928   switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
4929     {
4930     case 8:
4931       gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
4932 
4933       /* Invert the branch condition.  Branch over the jump.  */
4934       insn = bfd_getl32 (buf);
4935       insn ^= MATCH_BEQ ^ MATCH_BNE;
4936       insn |= ENCODE_BTYPE_IMM (8);
4937       bfd_putl32 (insn, buf);
4938       buf += 4;
4939 
4940     jump:
4941       /* Jump to the target.  */
4942       fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
4943 			  4, &exp, false, BFD_RELOC_RISCV_JMP);
4944       bfd_putl32 (MATCH_JAL, buf);
4945       buf += 4;
4946       break;
4947 
4948     case 4:
4949       reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
4950 	      ? BFD_RELOC_RISCV_JMP : BFD_RELOC_12_PCREL;
4951       fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
4952 			  4, &exp, false, reloc);
4953       buf += 4;
4954       break;
4955 
4956     default:
4957       abort ();
4958     }
4959 
4960  done:
4961   fixp->fx_file = fragp->fr_file;
4962   fixp->fx_line = fragp->fr_line;
4963 
4964   gas_assert (buf == (bfd_byte *)fragp->fr_literal
4965 	      + fragp->fr_fix + fragp->fr_var);
4966 
4967   fragp->fr_fix += fragp->fr_var;
4968 }
4969 
4970 /* Relax a machine dependent frag.  This returns the amount by which
4971    the current size of the frag should change.  */
4972 
4973 void
md_convert_frag(bfd * abfd ATTRIBUTE_UNUSED,segT asec ATTRIBUTE_UNUSED,fragS * fragp)4974 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
4975 		 fragS *fragp)
4976 {
4977   gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
4978   md_convert_frag_branch (fragp);
4979 }
4980 
4981 void
md_show_usage(FILE * stream)4982 md_show_usage (FILE *stream)
4983 {
4984   fprintf (stream, _("\
4985 RISC-V options:\n\
4986   -fpic or -fPIC              generate position-independent code\n\
4987   -fno-pic                    don't generate position-independent code (default)\n\
4988   -march=ISA                  set the RISC-V architecture\n\
4989   -misa-spec=ISAspec          set the RISC-V ISA spec (2.2, 20190608, 20191213)\n\
4990   -mpriv-spec=PRIVspec        set the RISC-V privilege spec (1.9.1, 1.10, 1.11, 1.12)\n\
4991   -mabi=ABI                   set the RISC-V ABI\n\
4992   -mrelax                     enable relax (default)\n\
4993   -mno-relax                  disable relax\n\
4994   -march-attr                 generate RISC-V arch attribute\n\
4995   -mno-arch-attr              don't generate RISC-V arch attribute\n\
4996   -mcsr-check                 enable the csr ISA and privilege spec version checks\n\
4997   -mno-csr-check              disable the csr ISA and privilege spec version checks (default)\n\
4998   -mbig-endian                assemble for big-endian\n\
4999   -mlittle-endian             assemble for little-endian\n\
5000 "));
5001 }
5002 
5003 /* Standard calling conventions leave the CFA at SP on entry.  */
5004 
5005 void
riscv_cfi_frame_initial_instructions(void)5006 riscv_cfi_frame_initial_instructions (void)
5007 {
5008   cfi_add_CFA_def_cfa_register (X_SP);
5009 }
5010 
5011 int
tc_riscv_regname_to_dw2regnum(char * regname)5012 tc_riscv_regname_to_dw2regnum (char *regname)
5013 {
5014   int reg;
5015 
5016   if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
5017     return reg;
5018 
5019   if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
5020     return reg + 32;
5021 
5022   if ((reg = reg_lookup_internal (regname, RCLASS_VECR)) >= 0)
5023     return reg + 96;
5024 
5025   /* CSRs are numbered 4096 -> 8191.  */
5026   if ((reg = reg_lookup_internal (regname, RCLASS_CSR)) >= 0)
5027     return reg + 4096;
5028 
5029   as_bad (_("unknown register `%s'"), regname);
5030   return -1;
5031 }
5032 
5033 void
riscv_elf_final_processing(void)5034 riscv_elf_final_processing (void)
5035 {
5036   riscv_set_abi_by_arch ();
5037   riscv_release_subset_list (riscv_rps_as.subset_list);
5038   elf_elfheader (stdoutput)->e_flags |= elf_flags;
5039 }
5040 
5041 /* Parse the .sleb128 and .uleb128 pseudos.  Only allow constant expressions,
5042    since these directives break relaxation when used with symbol deltas.  */
5043 
5044 static void
s_riscv_leb128(int sign)5045 s_riscv_leb128 (int sign)
5046 {
5047   expressionS exp;
5048   char *save_in = input_line_pointer;
5049 
5050   expression (&exp);
5051   if (sign && exp.X_op != O_constant)
5052     as_bad (_("non-constant .sleb128 is not supported"));
5053   else if (!sign && exp.X_op != O_constant && exp.X_op != O_subtract)
5054     as_bad (_(".uleb128 only supports constant or subtract expressions"));
5055 
5056   demand_empty_rest_of_line ();
5057 
5058   input_line_pointer = save_in;
5059   return s_leb128 (sign);
5060 }
5061 
5062 /* Parse the .insn directive.  There are three formats,
5063    Format 1: .insn <type> <operand1>, <operand2>, ...
5064    Format 2: .insn <length>, <value>
5065    Format 3: .insn <value>.  */
5066 
5067 static void
s_riscv_insn(int x ATTRIBUTE_UNUSED)5068 s_riscv_insn (int x ATTRIBUTE_UNUSED)
5069 {
5070   char *str = input_line_pointer;
5071   struct riscv_cl_insn insn;
5072   expressionS imm_expr;
5073   bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
5074   char save_c;
5075 
5076   while (!is_end_of_line[(unsigned char) *input_line_pointer])
5077     ++input_line_pointer;
5078 
5079   save_c = *input_line_pointer;
5080   *input_line_pointer = '\0';
5081 
5082   riscv_mapping_state (MAP_INSN, 0, false/* fr_align_code */);
5083 
5084   struct riscv_ip_error error = riscv_ip (str, &insn, &imm_expr,
5085 				&imm_reloc, insn_type_hash);
5086   if (error.msg)
5087     {
5088       char *save_in = input_line_pointer;
5089       error.msg = riscv_ip_hardcode (str, &insn, &imm_expr, error.msg);
5090       input_line_pointer = save_in;
5091     }
5092 
5093   if (error.msg)
5094     {
5095       if (error.missing_ext)
5096 	as_bad ("%s `%s', extension `%s' required", error.msg, error.statement,
5097 		error.missing_ext);
5098       else
5099 	as_bad ("%s `%s'", error.msg, error.statement);
5100     }
5101   else
5102     {
5103       gas_assert (insn.insn_mo->pinfo != INSN_MACRO);
5104       append_insn (&insn, &imm_expr, imm_reloc);
5105     }
5106 
5107   *input_line_pointer = save_c;
5108   demand_empty_rest_of_line ();
5109 }
5110 
5111 /* Update architecture and privileged elf attributes.  If we don't set
5112    them, then try to output the default ones.  */
5113 
5114 static void
riscv_write_out_attrs(void)5115 riscv_write_out_attrs (void)
5116 {
5117   const char *arch_str, *priv_str, *p;
5118   /* versions[0]: major version.
5119      versions[1]: minor version.
5120      versions[2]: revision version.  */
5121   unsigned versions[3] = {0}, number = 0;
5122   unsigned int i;
5123 
5124   /* Re-write architecture elf attribute.  */
5125   arch_str = riscv_rps_as.subset_list->arch_str;
5126   if (!bfd_elf_add_proc_attr_string (stdoutput, Tag_RISCV_arch, arch_str))
5127     as_fatal (_("error adding attribute: %s"),
5128 	      bfd_errmsg (bfd_get_error ()));
5129 
5130   /* For the file without any instruction, we don't set the default_priv_spec
5131      according to the privileged elf attributes since the md_assemble isn't
5132      called.  */
5133   if (!start_assemble
5134       && !riscv_set_default_priv_spec (NULL))
5135     return;
5136 
5137   /* If we already have set privileged elf attributes, then no need to do
5138      anything.  Otherwise, don't generate or update them when no CSR and
5139      privileged instructions are used.  */
5140   if (!explicit_priv_attr)
5141     return;
5142 
5143   RISCV_GET_PRIV_SPEC_NAME (priv_str, default_priv_spec);
5144   p = priv_str;
5145   for (i = 0; *p; ++p)
5146     {
5147       if (*p == '.' && i < 3)
5148        {
5149          versions[i++] = number;
5150          number = 0;
5151        }
5152       else if (ISDIGIT (*p))
5153        number = (number * 10) + (*p - '0');
5154       else
5155        {
5156          as_bad (_("internal: bad RISC-V privileged spec (%s)"), priv_str);
5157          return;
5158        }
5159     }
5160   versions[i] = number;
5161 
5162   /* Re-write privileged elf attributes.  */
5163   if (!bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec,
5164 				  versions[0])
5165       || !bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_minor,
5166 				     versions[1])
5167       || !bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_revision,
5168 				     versions[2]))
5169     as_fatal (_("error adding attribute: %s"),
5170 	      bfd_errmsg (bfd_get_error ()));
5171 }
5172 
5173 /* Add the default contents for the .riscv.attributes section.  */
5174 
5175 static void
riscv_set_public_attributes(void)5176 riscv_set_public_attributes (void)
5177 {
5178   if (riscv_opts.arch_attr || explicit_attr)
5179     riscv_write_out_attrs ();
5180 }
5181 
5182 /* Scan uleb128 subtraction expressions and insert fixups for them.
5183    e.g., .uleb128 .L1 - .L0
5184    Because relaxation may change the value of the subtraction, we
5185    must resolve them at link-time.  */
5186 
5187 static void
riscv_insert_uleb128_fixes(bfd * abfd ATTRIBUTE_UNUSED,asection * sec,void * xxx ATTRIBUTE_UNUSED)5188 riscv_insert_uleb128_fixes (bfd *abfd ATTRIBUTE_UNUSED,
5189 			    asection *sec, void *xxx ATTRIBUTE_UNUSED)
5190 {
5191   segment_info_type *seginfo = seg_info (sec);
5192   struct frag *fragP;
5193 
5194   subseg_set (sec, 0);
5195 
5196   for (fragP = seginfo->frchainP->frch_root;
5197        fragP; fragP = fragP->fr_next)
5198     {
5199       expressionS *exp, *exp_dup;
5200 
5201       if (fragP->fr_type != rs_leb128  || fragP->fr_symbol == NULL)
5202 	continue;
5203 
5204       exp = symbol_get_value_expression (fragP->fr_symbol);
5205 
5206       if (exp->X_op != O_subtract)
5207 	continue;
5208 
5209       /* Only unsigned leb128 can be handled.  */
5210       gas_assert (fragP->fr_subtype == 0);
5211       exp_dup = xmemdup (exp, sizeof (*exp), sizeof (*exp));
5212       exp_dup->X_op = O_symbol;
5213       exp_dup->X_op_symbol = NULL;
5214 
5215       /* Insert relocations to resolve the subtraction at link-time.
5216 	 Emit the SET relocation first in riscv.  */
5217       exp_dup->X_add_symbol = exp->X_add_symbol;
5218       fix_new_exp (fragP, fragP->fr_fix, 0,
5219 		   exp_dup, 0, BFD_RELOC_RISCV_SET_ULEB128);
5220       exp_dup->X_add_symbol = exp->X_op_symbol;
5221       exp_dup->X_add_number = 0; /* Set addend of SUB_ULEB128 to zero.  */
5222       fix_new_exp (fragP, fragP->fr_fix, 0,
5223 		   exp_dup, 0, BFD_RELOC_RISCV_SUB_ULEB128);
5224       free ((void *) exp_dup);
5225     }
5226 }
5227 
5228 /* Called after all assembly has been done.  */
5229 
5230 void
riscv_md_finish(void)5231 riscv_md_finish (void)
5232 {
5233   riscv_set_public_attributes ();
5234   if (riscv_opts.relax)
5235     bfd_map_over_sections (stdoutput, riscv_insert_uleb128_fixes, NULL);
5236 }
5237 
5238 /* Called just before the assembler exits.  */
5239 
5240 void
riscv_md_end(void)5241 riscv_md_end (void)
5242 {
5243   htab_delete (riscv_pcrel_hi_fixup_hash);
5244 }
5245 
5246 /* Adjust the symbol table.  */
5247 
5248 void
riscv_adjust_symtab(void)5249 riscv_adjust_symtab (void)
5250 {
5251   bfd_map_over_sections (stdoutput, riscv_check_mapping_symbols, (char *) 0);
5252   elf_adjust_symtab ();
5253 }
5254 
5255 /* Given a symbolic attribute NAME, return the proper integer value.
5256    Returns -1 if the attribute is not known.  */
5257 
5258 int
riscv_convert_symbolic_attribute(const char * name)5259 riscv_convert_symbolic_attribute (const char *name)
5260 {
5261   static const struct
5262   {
5263     const char *name;
5264     const int tag;
5265   }
5266   attribute_table[] =
5267   {
5268     /* When you modify this table you should
5269        also modify the list in doc/c-riscv.texi.  */
5270 #define T(tag) {#tag, Tag_RISCV_##tag}, {"Tag_RISCV_" #tag, Tag_RISCV_##tag}
5271     T(arch),
5272     T(priv_spec),
5273     T(priv_spec_minor),
5274     T(priv_spec_revision),
5275     T(unaligned_access),
5276     T(stack_align),
5277 #undef T
5278   };
5279 
5280   if (name == NULL)
5281     return -1;
5282 
5283   unsigned int i;
5284   for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
5285     if (strcmp (name, attribute_table[i].name) == 0)
5286       return attribute_table[i].tag;
5287 
5288   return -1;
5289 }
5290 
5291 /* Parse a .attribute directive.  */
5292 
5293 static void
s_riscv_attribute(int ignored ATTRIBUTE_UNUSED)5294 s_riscv_attribute (int ignored ATTRIBUTE_UNUSED)
5295 {
5296   int tag = obj_elf_vendor_attribute (OBJ_ATTR_PROC);
5297   unsigned old_xlen;
5298   obj_attribute *attr;
5299 
5300   explicit_attr = true;
5301   switch (tag)
5302     {
5303     case Tag_RISCV_arch:
5304       old_xlen = xlen;
5305       attr = elf_known_obj_attributes_proc (stdoutput);
5306       if (!start_assemble)
5307 	riscv_set_arch (attr[Tag_RISCV_arch].s);
5308       else
5309 	as_fatal (_("architecture elf attributes must set before "
5310 		    "any instructions"));
5311 
5312       if (old_xlen != xlen)
5313 	{
5314 	  /* We must re-init bfd again if xlen is changed.  */
5315 	  unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
5316 	  bfd_find_target (riscv_target_format (), stdoutput);
5317 
5318 	  if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
5319 	    as_warn (_("could not set architecture and machine"));
5320 	}
5321       break;
5322 
5323     case Tag_RISCV_priv_spec:
5324     case Tag_RISCV_priv_spec_minor:
5325     case Tag_RISCV_priv_spec_revision:
5326       if (start_assemble)
5327        as_fatal (_("privileged elf attributes must set before "
5328 		   "any instructions"));
5329       break;
5330 
5331     default:
5332       break;
5333     }
5334 }
5335 
5336 /* Mark symbol that it follows a variant CC convention.  */
5337 
5338 static void
s_variant_cc(int ignored ATTRIBUTE_UNUSED)5339 s_variant_cc (int ignored ATTRIBUTE_UNUSED)
5340 {
5341   char *name;
5342   char c;
5343   symbolS *sym;
5344   asymbol *bfdsym;
5345   elf_symbol_type *elfsym;
5346 
5347   c = get_symbol_name (&name);
5348   if (!*name)
5349     as_bad (_("missing symbol name for .variant_cc directive"));
5350   sym = symbol_find_or_make (name);
5351   restore_line_pointer (c);
5352   demand_empty_rest_of_line ();
5353 
5354   bfdsym = symbol_get_bfdsym (sym);
5355   elfsym = elf_symbol_from (bfdsym);
5356   gas_assert (elfsym);
5357   elfsym->internal_elf_sym.st_other |= STO_RISCV_VARIANT_CC;
5358 }
5359 
5360 /* Same as elf_copy_symbol_attributes, but without copying st_other.
5361    This is needed so RISC-V specific st_other values can be independently
5362    specified for an IFUNC resolver (that is called by the dynamic linker)
5363    and the symbol it resolves (aliased to the resolver).  In particular,
5364    if a function symbol has special st_other value set via directives,
5365    then attaching an IFUNC resolver to that symbol should not override
5366    the st_other setting.  Requiring the directive on the IFUNC resolver
5367    symbol would be unexpected and problematic in C code, where the two
5368    symbols appear as two independent function declarations.  */
5369 
5370 void
riscv_elf_copy_symbol_attributes(symbolS * dest,symbolS * src)5371 riscv_elf_copy_symbol_attributes (symbolS *dest, symbolS *src)
5372 {
5373   struct elf_obj_sy *srcelf = symbol_get_obj (src);
5374   struct elf_obj_sy *destelf = symbol_get_obj (dest);
5375   /* If size is unset, copy size from src.  Because we don't track whether
5376      .size has been used, we can't differentiate .size dest, 0 from the case
5377      where dest's size is unset.  */
5378   if (!destelf->size && S_GET_SIZE (dest) == 0)
5379     {
5380       if (srcelf->size)
5381 	{
5382 	  destelf->size = XNEW (expressionS);
5383 	  *destelf->size = *srcelf->size;
5384 	}
5385       S_SET_SIZE (dest, S_GET_SIZE (src));
5386     }
5387 }
5388 
5389 /* RISC-V pseudo-ops table.  */
5390 static const pseudo_typeS riscv_pseudo_table[] =
5391 {
5392   {"option", s_riscv_option, 0},
5393   {"half", cons, 2},
5394   {"word", cons, 4},
5395   {"dword", cons, 8},
5396   {"dtprelword", s_dtprel, 4},
5397   {"dtpreldword", s_dtprel, 8},
5398   {"uleb128", s_riscv_leb128, 0},
5399   {"sleb128", s_riscv_leb128, 1},
5400   {"insn", s_riscv_insn, 0},
5401   {"attribute", s_riscv_attribute, 0},
5402   {"variant_cc", s_variant_cc, 0},
5403   {"float16", float_cons, 'h'},
5404 
5405   { NULL, NULL, 0 },
5406 };
5407 
5408 void
riscv_pop_insert(void)5409 riscv_pop_insert (void)
5410 {
5411   extern void pop_insert (const pseudo_typeS *);
5412 
5413   pop_insert (riscv_pseudo_table);
5414 }
5415