]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gas/config/tc-riscv.c
RISC-V: Don't generate branch/jump relocation if symbol is local when no-relax.
[thirdparty/binutils-gdb.git] / gas / config / tc-riscv.c
CommitLineData
e23eba97 1/* tc-riscv.c -- RISC-V assembler
fd67aa11 2 Copyright (C) 2011-2024 Free Software Foundation, Inc.
e23eba97
NC
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
1080bf78 32#include "bfd/elfxx-riscv.h"
e23eba97
NC
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. */
40struct riscv_cl_insn
41{
42 /* The opcode's entry in riscv_opcodes. */
43 const struct riscv_opcode *insn_mo;
44
634001bb
TO
45 /* The encoded instruction bits
46 (first bits enough to extract instruction length on a long opcode). */
e23eba97
NC
47 insn_t insn_opcode;
48
634001bb
TO
49 /* The long encoded instruction bits ([0] is non-zero on a long opcode). */
50 char insn_long_opcode[RISCV_MAX_INSN_LEN];
51
e23eba97
NC
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
bf69326f
RU
62/* The identifier of the assembler macro we are expanding, if any. */
63static int source_macro = -1;
64
3d73d29e
NC
65/* All RISC-V CSR belong to one of these classes. */
66enum riscv_csr_class
67{
68 CSR_CLASS_NONE,
69
70 CSR_CLASS_I,
65e4a99a
NC
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 */
c625f4ed
NC
75 CSR_CLASS_DEBUG, /* debug CSR */
76 CSR_CLASS_H, /* hypervisor */
77 CSR_CLASS_H_32, /* hypervisor, rv32 only */
ac8df5a1
CM
78 CSR_CLASS_SMAIA, /* Smaia */
79 CSR_CLASS_SMAIA_32, /* Smaia, rv32 only */
a303646f
TO
80 CSR_CLASS_SMCNTRPMF, /* Smcntrpmf */
81 CSR_CLASS_SMCNTRPMF_32, /* Smcntrpmf, rv32 only */
6af47b08 82 CSR_CLASS_SMSTATEEN, /* Smstateen only */
6af47b08 83 CSR_CLASS_SMSTATEEN_32, /* Smstateen RV32 only */
ac8df5a1
CM
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 */
15253318
TO
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) */
713f3708
TO
91 CSR_CLASS_SSCOFPMF, /* Sscofpmf only */
92 CSR_CLASS_SSCOFPMF_32, /* Sscofpmf RV32 only */
766077c1
TO
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) */
6fdd02bb 97 CSR_CLASS_XTHEADVECTOR, /* xtheadvector only */
3d73d29e
NC
98};
99
100/* This structure holds all restricted conditions for a CSR. */
101struct 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
a63375ac 114 aborted in the current version, then it should be PRIV_SPEC_CLASS_DRAFT. */
3d73d29e
NC
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
e4028336
PN
121/* This structure contains information about errors that occur within the
122 riscv_ip function */
123struct 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
e23eba97
NC
135#ifndef DEFAULT_ARCH
136#define DEFAULT_ARCH "riscv64"
137#endif
138
2dc8dd17
JW
139#ifndef DEFAULT_RISCV_ATTR
140#define DEFAULT_RISCV_ATTR 0
141#endif
142
8f595e9b 143/* Let riscv_after_parse_args set the default value according to xlen. */
8f595e9b
NC
144#ifndef DEFAULT_RISCV_ARCH_WITH_EXT
145#define DEFAULT_RISCV_ARCH_WITH_EXT NULL
146#endif
147
dcd709e0 148/* Need to sync the version with RISC-V compiler. */
8f595e9b 149#ifndef DEFAULT_RISCV_ISA_SPEC
aed44286 150#define DEFAULT_RISCV_ISA_SPEC "20191213"
8f595e9b
NC
151#endif
152
153#ifndef DEFAULT_RISCV_PRIV_SPEC
154#define DEFAULT_RISCV_PRIV_SPEC "1.11"
155#endif
156
e23eba97 157static const char default_arch[] = DEFAULT_ARCH;
8f595e9b 158static const char *default_arch_with_ext = DEFAULT_RISCV_ARCH_WITH_EXT;
3d73d29e
NC
159static enum riscv_spec_class default_isa_spec = ISA_SPEC_CLASS_NONE;
160static enum riscv_spec_class default_priv_spec = PRIV_SPEC_CLASS_NONE;
e23eba97 161
dcd709e0
NC
162static unsigned xlen = 0; /* The width of an x-register. */
163static unsigned abi_xlen = 0; /* The width of a pointer in the ABI. */
5b7c81bd 164static bool rve_abi = false;
1942a048
NC
165enum float_abi
166{
6e1605e4
NC
167 FLOAT_ABI_DEFAULT = -1,
168 FLOAT_ABI_SOFT,
169 FLOAT_ABI_SINGLE,
170 FLOAT_ABI_DOUBLE,
171 FLOAT_ABI_QUAD
172};
173static enum float_abi float_abi = FLOAT_ABI_DEFAULT;
e23eba97 174
2922d21d 175#define LOAD_ADDRESS_INSN (abi_xlen == 64 ? "ld" : "lw")
e23eba97
NC
176#define ADD32_INSN (xlen == 64 ? "addiw" : "addi")
177
178static unsigned elf_flags = 0;
179
7a29ee29
JB
180static bool probing_insn_operands;
181
dcd709e0
NC
182/* Set the default_isa_spec. Return 0 if the spec isn't supported.
183 Otherwise, return 1. */
8f595e9b
NC
184
185static int
186riscv_set_default_isa_spec (const char *s)
187{
3d73d29e
NC
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)
8f595e9b 191 {
b800637e
NC
192 as_bad ("unknown default ISA spec `%s' set by "
193 "-misa-spec or --with-isa-spec", s);
8f595e9b
NC
194 return 0;
195 }
196 else
197 default_isa_spec = class;
198 return 1;
199}
200
dcd709e0
NC
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. */
8f595e9b
NC
204
205static int
206riscv_set_default_priv_spec (const char *s)
207{
3d73d29e 208 enum riscv_spec_class class = PRIV_SPEC_CLASS_NONE;
8f595e9b
NC
209 unsigned major, minor, revision;
210 obj_attribute *attr;
8f595e9b 211
3d73d29e
NC
212 RISCV_GET_PRIV_SPEC_CLASS (s, class);
213 if (class != PRIV_SPEC_CLASS_NONE)
8f595e9b
NC
214 {
215 default_priv_spec = class;
216 return 1;
217 }
218
219 if (s != NULL)
220 {
b800637e
NC
221 as_bad (_("unknown default privileged spec `%s' set by "
222 "-mpriv-spec or --with-priv-spec"), s);
8f595e9b
NC
223 return 0;
224 }
225
dcd709e0 226 /* Set the default_priv_spec by the privileged elf attributes. */
8f595e9b
NC
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;
3d73d29e
NC
231 /* Version 0.0.0 is the default value and meningless. */
232 if (major == 0 && minor == 0 && revision == 0)
233 return 1;
8f595e9b 234
3d73d29e
NC
235 riscv_get_priv_spec_class_from_numbers (major, minor, revision, &class);
236 if (class != PRIV_SPEC_CLASS_NONE)
237 {
8f595e9b 238 default_priv_spec = class;
8f595e9b
NC
239 return 1;
240 }
241
dcd709e0 242 /* Still can not find the privileged spec class. */
b800637e
NC
243 as_bad (_("unknown default privileged spec `%d.%d.%d' set by "
244 "privileged elf attributes"), major, minor, revision);
8f595e9b
NC
245 return 0;
246}
247
e23eba97 248/* This is the set of options which the .option pseudo-op may modify. */
e23eba97
NC
249struct riscv_set_options
250{
251 int pic; /* Generate position-independent code. */
252 int rvc; /* Generate RVC code. */
45f76423 253 int relax; /* Emit relocs the linker is allowed to relax. */
dcd709e0 254 int arch_attr; /* Emit architecture and privileged elf attributes. */
2ca89224 255 int csr_check; /* Enable the CSR checking. */
e23eba97
NC
256};
257
258static struct riscv_set_options riscv_opts =
259{
dcd709e0
NC
260 0, /* pic */
261 0, /* rvc */
dcd709e0 262 1, /* relax */
2dc8dd17 263 DEFAULT_RISCV_ATTR, /* arch_attr */
dcd709e0 264 0, /* csr_check */
e23eba97
NC
265};
266
437e2ff1
NC
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
e23eba97 270static void
5b7c81bd 271riscv_set_rvc (bool rvc_value)
e23eba97
NC
272{
273 if (rvc_value)
274 elf_flags |= EF_RISCV_RVC;
275
276 riscv_opts.rvc = rvc_value;
277}
278
96462b01
S
279/* Turn on the tso flag for elf_flags once we have enabled ztso extension. */
280
281static void
0242db99 282riscv_set_tso (void)
96462b01
S
283{
284 elf_flags |= EF_RISCV_TSO;
285}
286
f5cb31a8
JB
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. */
f786c359 291static riscv_parse_subset_t riscv_rps_as =
43135d3b 292{
d3ffd7f7
NC
293 NULL, /* subset_list, we will set it later once
294 riscv_opts_stack is created or updated. */
f786c359
NC
295 as_bad, /* error_handler. */
296 &xlen, /* xlen. */
297 &default_isa_spec, /* isa_spec. */
298 true, /* check_unknown_prefixed_ext. */
299};
43135d3b 300
40f1a1a4
NC
301/* Update the architecture string in the subset_list. */
302
303static void
304riscv_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
d3ffd7f7
NC
312/* This structure is used to hold a stack of .option values. */
313struct 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
320static struct riscv_option_stack *riscv_opts_stack = NULL;
321
2922d21d 322/* Set which ISA and extensions are available. */
e23eba97 323
e23eba97 324static void
2922d21d 325riscv_set_arch (const char *s)
e23eba97 326{
c9f27991
NC
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 }
7f999549 333
f5cb31a8 334 if (riscv_rps_as.subset_list == NULL)
d3ffd7f7 335 {
f5cb31a8
JB
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;
40f1a1a4 339 riscv_rps_as.subset_list->arch_str = NULL;
d3ffd7f7 340 }
f5cb31a8 341 riscv_release_subset_list (riscv_rps_as.subset_list);
f786c359 342 riscv_parse_subset (&riscv_rps_as, s);
40f1a1a4 343 riscv_reset_subsets_list_arch_str ();
28b2963f 344
28b2963f 345 riscv_set_rvc (false);
b5c37946
SJ
346 if (riscv_subset_supports (&riscv_rps_as, "c")
347 || riscv_subset_supports (&riscv_rps_as, "zca"))
28b2963f 348 riscv_set_rvc (true);
96462b01
S
349
350 if (riscv_subset_supports (&riscv_rps_as, "ztso"))
351 riscv_set_tso ();
e23eba97
NC
352}
353
dcd709e0 354/* Indicate -mabi option is explictly set. */
5b7c81bd 355static bool explicit_mabi = false;
6e1605e4 356
437e2ff1
NC
357/* Set the abi information. */
358
6e1605e4 359static void
5b7c81bd 360riscv_set_abi (unsigned new_xlen, enum float_abi new_float_abi, bool rve)
6e1605e4
NC
361{
362 abi_xlen = new_xlen;
363 float_abi = new_float_abi;
364 rve_abi = rve;
365}
366
dcd709e0
NC
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. */
6e1605e4
NC
369
370static void
371riscv_set_abi_by_arch (void)
372{
373 if (!explicit_mabi)
374 {
f786c359 375 if (riscv_subset_supports (&riscv_rps_as, "q"))
5b7c81bd 376 riscv_set_abi (xlen, FLOAT_ABI_QUAD, false);
f786c359 377 else if (riscv_subset_supports (&riscv_rps_as, "d"))
5b7c81bd 378 riscv_set_abi (xlen, FLOAT_ABI_DOUBLE, false);
f786c359 379 else if (riscv_subset_supports (&riscv_rps_as, "e"))
5d0ed830 380 riscv_set_abi (xlen, FLOAT_ABI_SOFT, true);
6e1605e4 381 else
5b7c81bd 382 riscv_set_abi (xlen, FLOAT_ABI_SOFT, false);
6e1605e4
NC
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);
5d0ed830 391
f786c359 392 if (riscv_subset_supports (&riscv_rps_as, "e") && !rve_abi)
6674b23f 393 as_bad ("only ilp32e/lp64e ABI are supported for e extension");
5d0ed830
NC
394
395 if (float_abi == FLOAT_ABI_SINGLE
f786c359 396 && !riscv_subset_supports (&riscv_rps_as, "f"))
5d0ed830
NC
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
f786c359 400 && !riscv_subset_supports (&riscv_rps_as, "d"))
5d0ed830
NC
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
f786c359 404 && !riscv_subset_supports (&riscv_rps_as, "q"))
5d0ed830
NC
405 as_bad ("ilp32q/lp64q ABI can't be used when q extension "
406 "isn't supported");
6e1605e4
NC
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
e23eba97 417/* Handle of the OPCODE hash table. */
629310ab 418static htab_t op_hash = NULL;
e23eba97 419
0e35537d 420/* Handle of the type of .insn hash table. */
629310ab 421static htab_t insn_type_hash = NULL;
0e35537d 422
e23eba97 423/* This array holds the chars that always start a comment. If the
dcd709e0 424 pre-processor is disabled, these aren't very useful. */
e23eba97
NC
425const 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'
dcd709e0
NC
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
e23eba97 432 first line of the input file. This is because the compiler outputs
dcd709e0
NC
433 #NO_APP at the beginning of its output.
434
435 Also note that C style comments are always supported. */
e23eba97
NC
436const char line_comment_chars[] = "#";
437
438/* This array holds machine specific line separator characters. */
439const char line_separator_chars[] = ";";
440
dcd709e0 441/* Chars that can be used to separate mant from exp in floating point nums. */
e23eba97
NC
442const char EXP_CHARS[] = "eE";
443
dcd709e0
NC
444/* Chars that mean this number is a floating point constant.
445 As in 0f12.456 or 0d1.2345e12. */
035784e3 446const char FLT_CHARS[] = "rRsSfFdDxXpPhH";
e23eba97 447
2dc8dd17 448/* Indicate we are already assemble any instructions or not. */
5b7c81bd 449static bool start_assemble = false;
2dc8dd17 450
f9a6a8f0 451/* Indicate ELF attributes are explicitly set. */
5b7c81bd 452static bool explicit_attr = false;
2dc8dd17 453
f9a6a8f0 454/* Indicate CSR or priv instructions are explicitly used. */
5b7c81bd 455static bool explicit_priv_attr = false;
3fc6c3dc 456
6eb099ae 457static char *expr_parse_end;
437e2ff1 458
e23eba97
NC
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
8b7419c4
CM
486#define INSERT_IMM(n, s, INSN, VALUE) \
487 INSERT_BITS ((INSN).insn_opcode, VALUE, (1ULL<<n) - 1, s)
488
e23eba97
NC
489/* Determine if an instruction matches an opcode. */
490#define OPCODE_MATCHES(OPCODE, OP) \
491 (((OPCODE) & MASK_##OP) == MATCH_##OP)
492
9b9b1092
NC
493/* Create a new mapping symbol for the transition to STATE. */
494
495static void
496make_mapping_symbol (enum riscv_seg_mstate state,
497 valueT value,
40f1a1a4 498 fragS *frag,
d918451a
NC
499 const char *arch_str,
500 bool odd_data_padding)
9b9b1092
NC
501{
502 const char *name;
615d4f41 503 char *buff = NULL;
9b9b1092
NC
504 switch (state)
505 {
506 case MAP_DATA:
507 name = "$d";
508 break;
509 case MAP_INSN:
d918451a 510 if (arch_str != NULL)
40f1a1a4 511 {
d918451a 512 size_t size = strlen (arch_str) + 3; /* "$x" + '\0' */
40f1a1a4 513 buff = xmalloc (size);
d918451a 514 snprintf (buff, size, "$x%s", arch_str);
40f1a1a4
NC
515 name = buff;
516 }
517 else
518 name = "$x";
9b9b1092
NC
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);
d918451a 526 if (arch_str != NULL)
40f1a1a4
NC
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 }
9b9b1092
NC
532
533 /* If .fill or other data filling directive generates zero sized data,
40f1a1a4
NC
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;
d918451a 540 symbolS *removed = NULL;
9b9b1092
NC
541 if (value == 0)
542 {
40f1a1a4 543 if (first != NULL)
9b9b1092 544 {
40f1a1a4
NC
545 know (S_GET_VALUE (first) == S_GET_VALUE (symbol)
546 && first == last);
9b9b1092 547 /* Remove the old one. */
d918451a 548 removed = first;
9b9b1092
NC
549 }
550 frag->tc_frag_data.first_map_symbol = symbol;
551 }
40f1a1a4 552 else if (last != NULL)
9b9b1092
NC
553 {
554 /* The mapping symbols should be added in offset order. */
40f1a1a4 555 know (S_GET_VALUE (last) <= S_GET_VALUE (symbol));
9b9b1092 556 /* Remove the old one. */
40f1a1a4 557 if (S_GET_VALUE (last) == S_GET_VALUE (symbol))
d918451a 558 removed = last;
9b9b1092
NC
559 }
560 frag->tc_frag_data.last_map_symbol = symbol;
d918451a
NC
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);
9b9b1092
NC
575}
576
577/* Set the mapping state for frag_now. */
578
579void
580riscv_mapping_state (enum riscv_seg_mstate to_state,
40f1a1a4 581 int max_chars,
3190ebcb 582 bool fr_align_code)
9b9b1092
NC
583{
584 enum riscv_seg_mstate from_state =
585 seg_info (now_seg)->tc_segment_info_data.map_state;
40f1a1a4 586 bool reset_seg_arch_str = false;
9b9b1092
NC
587
588 if (!SEG_NORMAL (now_seg)
40f1a1a4 589 /* For now we only add the mapping symbols to text sections.
9b9b1092
NC
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
40f1a1a4
NC
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
3190ebcb 607 && !fr_align_code
40f1a1a4
NC
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;
40f1a1a4
NC
612 }
613 else if (from_state == to_state)
9b9b1092
NC
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;
d918451a
NC
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 */);
9b9b1092
NC
622}
623
624/* Add the odd bytes of paddings for riscv_handle_align. */
625
626static void
627riscv_add_odd_padding_symbol (fragS *frag)
628{
629 /* If there was already a mapping symbol, it should be
40f1a1a4
NC
630 removed in the make_mapping_symbol.
631
d918451a
NC
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 */);
9b9b1092
NC
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
642static void
643riscv_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 {
40f1a1a4
NC
671 symbolS *next_first = next->tc_frag_data.first_map_symbol;
672 if (next_first != NULL)
9b9b1092
NC
673 {
674 /* The last mapping symbol overlaps with another one
40f1a1a4
NC
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. */
d918451a
NC
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);
9b9b1092
NC
685 break;
686 }
687
688 if (next->fr_next == NULL)
689 {
40f1a1a4
NC
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. */
9b9b1092
NC
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
e23eba97
NC
710/* The default target format to use. */
711
712const char *
713riscv_target_format (void)
714{
fbc09e7a
MC
715 if (target_big_endian)
716 return xlen == 64 ? "elf64-bigriscv" : "elf32-bigriscv";
717 else
718 return xlen == 64 ? "elf64-littleriscv" : "elf32-littleriscv";
e23eba97
NC
719}
720
721/* Return the length of instruction INSN. */
722
723static inline unsigned int
724insn_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
731static void
732create_insn (struct riscv_cl_insn *insn, const struct riscv_opcode *mo)
733{
734 insn->insn_mo = mo;
735 insn->insn_opcode = mo->match;
634001bb 736 insn->insn_long_opcode[0] = 0;
e23eba97
NC
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
744static void
745install_insn (const struct riscv_cl_insn *insn)
746{
747 char *f = insn->frag->fr_literal + insn->where;
634001bb
TO
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));
e23eba97
NC
752}
753
754/* Move INSN to offset WHERE in FRAG. Adjust the fixups accordingly
755 and install the opcode in the new location. */
756
757static void
758move_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
772static void
773add_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
779static void
780add_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
792static unsigned
793relaxed_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)
01156111 809 && !S_IS_WEAK (fragp->fr_symbol)
e23eba97
NC
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
0e35537d
JW
830/* Information about an opcode name, mnemonics and its value. */
831struct opcode_name_t
832{
833 const char *name;
834 unsigned int val;
835};
836
837/* List for all supported opcode name. */
838static 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},
f8ad70a1 867 {"OP_V", 0x57},
0e35537d
JW
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. */
629310ab 884static htab_t opcode_names_hash = NULL;
0e35537d
JW
885
886/* Initialization for hash table of opcode name. */
dcd709e0 887
0e35537d
JW
888static void
889init_opcode_names_hash (void)
890{
0e35537d
JW
891 const struct opcode_name_t *opcode;
892
893 for (opcode = &opcode_name_list[0]; opcode->name != NULL; ++opcode)
fe0e921f 894 if (str_hash_insert (opcode_names_hash, opcode->name, opcode, 0) != NULL)
b800637e 895 as_fatal (_("internal: duplicate %s"), opcode->name);
0e35537d
JW
896}
897
dcd709e0
NC
898/* Find `s` is a valid opcode name or not, return the opcode name info
899 if found. */
900
0e35537d
JW
901static const struct opcode_name_t *
902opcode_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
629310ab 919 o = (struct opcode_name_t *) str_hash_find (opcode_names_hash, *s);
0e35537d
JW
920
921 /* Advance to next token if one was recognized. */
922 if (o)
923 *s = e;
924
925 *e = save_c;
6eb099ae 926 expr_parse_end = e;
0e35537d
JW
927
928 return o;
929}
930
437e2ff1 931/* All RISC-V registers belong to one of these classes. */
e23eba97
NC
932enum reg_class
933{
934 RCLASS_GPR,
935 RCLASS_FPR,
65e4a99a
NC
936 RCLASS_VECR,
937 RCLASS_VECM,
8f595e9b
NC
938 RCLASS_MAX,
939
940 RCLASS_CSR
e23eba97
NC
941};
942
629310ab
ML
943static htab_t reg_names_hash = NULL;
944static htab_t csr_extra_hash = NULL;
e23eba97
NC
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
951static void
952hash_reg_name (enum reg_class class, const char *name, unsigned n)
953{
954 void *hash = ENCODE_REG_HASH (class, n);
fe0e921f 955 if (str_hash_insert (reg_names_hash, name, hash, 0) != NULL)
b800637e 956 as_fatal (_("internal: duplicate %s"), name);
e23eba97
NC
957}
958
959static void
02a63525 960hash_reg_names (enum reg_class class, const char names[][NRC], unsigned n)
e23eba97
NC
961{
962 unsigned i;
963
964 for (i = 0; i < n; i++)
965 hash_reg_name (class, names[i], i);
966}
967
8f595e9b 968/* Init hash table csr_extra_hash to handle CSR. */
dcd709e0 969
8f595e9b
NC
970static void
971riscv_init_csr_hash (const char *name,
3d73d29e
NC
972 unsigned address,
973 enum riscv_csr_class class,
974 enum riscv_spec_class define_version,
975 enum riscv_spec_class abort_version)
8f595e9b
NC
976{
977 struct riscv_csr_extra *entry, *pre_entry;
5b7c81bd 978 bool need_enrty = true;
8f595e9b
NC
979
980 pre_entry = NULL;
629310ab 981 entry = (struct riscv_csr_extra *) str_hash_find (csr_extra_hash, name);
8f595e9b
NC
982 while (need_enrty && entry != NULL)
983 {
984 if (entry->csr_class == class
1942a048
NC
985 && entry->address == address
986 && entry->define_version == define_version
987 && entry->abort_version == abort_version)
5b7c81bd 988 need_enrty = false;
8f595e9b
NC
989 pre_entry = entry;
990 entry = entry->next;
991 }
1942a048 992
dcd709e0 993 /* Duplicate CSR. */
8f595e9b
NC
994 if (!need_enrty)
995 return;
bd0cf5a6 996
7bfc4db2 997 entry = notes_alloc (sizeof (*entry));
8f595e9b
NC
998 entry->csr_class = class;
999 entry->address = address;
1000 entry->define_version = define_version;
1001 entry->abort_version = abort_version;
5c505568 1002 entry->next = NULL;
8f595e9b 1003
8f595e9b 1004 if (pre_entry == NULL)
fe0e921f 1005 str_hash_insert (csr_extra_hash, name, entry, 0);
8f595e9b
NC
1006 else
1007 pre_entry->next = entry;
1008}
bd0cf5a6 1009
dcd709e0
NC
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. */
bd0cf5a6 1019
08ccfccf
NC
1020static unsigned int
1021riscv_csr_address (const char *csr_name,
1022 struct riscv_csr_extra *entry)
bd0cf5a6 1023{
08ccfccf
NC
1024 struct riscv_csr_extra *saved_entry = entry;
1025 enum riscv_csr_class csr_class = entry->csr_class;
df0a549e 1026 bool need_check_version = false;
39590abd
TO
1027 bool is_rv32_only = false;
1028 bool is_h_required = false;
df0a549e 1029 const char* extension = NULL;
8f595e9b 1030
8f595e9b 1031 switch (csr_class)
bd0cf5a6 1032 {
08ccfccf 1033 case CSR_CLASS_I_32:
39590abd 1034 is_rv32_only = true;
df0a549e
PN
1035 /* Fall through. */
1036 case CSR_CLASS_I:
1037 need_check_version = true;
1038 extension = "i";
08ccfccf 1039 break;
c625f4ed 1040 case CSR_CLASS_H_32:
39590abd 1041 is_rv32_only = true;
c625f4ed
NC
1042 /* Fall through. */
1043 case CSR_CLASS_H:
1044 extension = "h";
1045 break;
8f595e9b 1046 case CSR_CLASS_F:
df0a549e 1047 extension = "f";
8f595e9b 1048 break;
3d1cafa0 1049 case CSR_CLASS_ZKR:
df0a549e 1050 extension = "zkr";
3d1cafa0 1051 break;
65e4a99a 1052 case CSR_CLASS_V:
1daabcc7 1053 extension = "zve32x";
65e4a99a 1054 break;
ac8df5a1
CM
1055 case CSR_CLASS_SMAIA_32:
1056 is_rv32_only = true;
1057 /* Fall through. */
1058 case CSR_CLASS_SMAIA:
1059 extension = "smaia";
1060 break;
a303646f
TO
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;
6af47b08 1068 case CSR_CLASS_SMSTATEEN_32:
c509db05
TO
1069 is_rv32_only = true;
1070 /* Fall through. */
1071 case CSR_CLASS_SMSTATEEN:
6af47b08
TO
1072 extension = "smstateen";
1073 break;
ac8df5a1
CM
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;
15253318 1084 case CSR_CLASS_SSSTATEEN_AND_H_32:
c509db05
TO
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:
15253318
TO
1091 extension = "ssstateen";
1092 break;
713f3708
TO
1093 case CSR_CLASS_SSCOFPMF_32:
1094 is_rv32_only = true;
1095 /* Fall through. */
1096 case CSR_CLASS_SSCOFPMF:
1097 extension = "sscofpmf";
1098 break;
766077c1
TO
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;
08ccfccf 1109 case CSR_CLASS_DEBUG:
8f595e9b 1110 break;
6fdd02bb
JM
1111 case CSR_CLASS_XTHEADVECTOR:
1112 extension = "xtheadvector";
1113 break;
8f595e9b
NC
1114 default:
1115 as_bad (_("internal: bad RISC-V CSR class (0x%x)"), csr_class);
bd0cf5a6
NC
1116 }
1117
df0a549e
PN
1118 if (riscv_opts.csr_check)
1119 {
39590abd 1120 if (is_rv32_only && xlen != 32)
df0a549e 1121 as_warn (_("invalid CSR `%s', needs rv32i extension"), csr_name);
39590abd
TO
1122 if (is_h_required && !riscv_subset_supports (&riscv_rps_as, "h"))
1123 as_warn (_("invalid CSR `%s', needs `h' extension"), csr_name);
df0a549e
PN
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 }
8f595e9b
NC
1130
1131 while (entry != NULL)
bd0cf5a6 1132 {
08ccfccf
NC
1133 if (!need_check_version
1134 || (default_priv_spec >= entry->define_version
1135 && default_priv_spec < entry->abort_version))
8f595e9b 1136 {
dcd709e0 1137 /* Find the CSR according to the specific version. */
08ccfccf 1138 return entry->address;
8f595e9b
NC
1139 }
1140 entry = entry->next;
1141 }
bd0cf5a6 1142
dcd709e0
NC
1143 /* Can not find the CSR address from the chosen privileged version,
1144 so use the newly defined value. */
8f595e9b
NC
1145 if (riscv_opts.csr_check)
1146 {
3d73d29e
NC
1147 const char *priv_name = NULL;
1148 RISCV_GET_PRIV_SPEC_NAME (priv_name, default_priv_spec);
8f595e9b 1149 if (priv_name != NULL)
b800637e 1150 as_warn (_("invalid CSR `%s' for the privileged spec `%s'"),
8f595e9b 1151 csr_name, priv_name);
bd0cf5a6 1152 }
08ccfccf
NC
1153
1154 return saved_entry->address;
bd0cf5a6
NC
1155}
1156
dcd709e0
NC
1157/* Return -1 if the CSR has never been defined. Otherwise, return
1158 the address. */
bd0cf5a6 1159
8f595e9b 1160static unsigned int
bd0cf5a6
NC
1161reg_csr_lookup_internal (const char *s)
1162{
1163 struct riscv_csr_extra *r =
629310ab 1164 (struct riscv_csr_extra *) str_hash_find (csr_extra_hash, s);
bd0cf5a6
NC
1165
1166 if (r == NULL)
8f595e9b 1167 return -1U;
bd0cf5a6 1168
08ccfccf 1169 return riscv_csr_address (s, r);
bd0cf5a6
NC
1170}
1171
e23eba97
NC
1172static unsigned int
1173reg_lookup_internal (const char *s, enum reg_class class)
1174{
8f595e9b
NC
1175 void *r;
1176
1177 if (class == RCLASS_CSR)
1178 return reg_csr_lookup_internal (s);
e23eba97 1179
629310ab 1180 r = str_hash_find (reg_names_hash, s);
e23eba97
NC
1181 if (r == NULL || DECODE_REG_CLASS (r) != class)
1182 return -1;
7f999549 1183
f786c359 1184 if (riscv_subset_supports (&riscv_rps_as, "e")
edc77c59
NC
1185 && class == RCLASS_GPR
1186 && DECODE_REG_NUM (r) > 15)
7f999549
JW
1187 return -1;
1188
e23eba97
NC
1189 return DECODE_REG_NUM (r);
1190}
1191
5b7c81bd 1192static bool
e23eba97
NC
1193reg_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
5b7c81bd 1220static bool
e23eba97
NC
1221arg_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
bfb218e3 1226 if (len == 0)
5b7c81bd 1227 return false;
bfb218e3 1228
e23eba97 1229 for (i = 0; i < size; i++)
207cc92d
LX
1230 if (array[i] != NULL && strncmp (array[i], *s, len) == 0
1231 && array[i][len] == '\0')
e23eba97
NC
1232 {
1233 *regnop = i;
1234 *s += len;
5b7c81bd 1235 return true;
e23eba97
NC
1236 }
1237
5b7c81bd 1238 return false;
e23eba97
NC
1239}
1240
1f3fc45b
CM
1241static bool
1242flt_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
437e2ff1 1256#define USE_BITS(mask,shift) (used_bits |= ((insn_t)(mask) << (shift)))
8b7419c4
CM
1257#define USE_IMM(n, s) \
1258 (used_bits |= ((insn_t)((1ull<<n)-1) << (s)))
437e2ff1 1259
e23eba97
NC
1260/* For consistency checking, verify that all bits are specified either
1261 by the match/mask part of the instruction definition, or by the
83029f7f
TO
1262 operand list. The `length` could be the actual instruction length or
1263 0 for auto-detection. */
0e35537d 1264
5b7c81bd 1265static bool
0e35537d 1266validate_riscv_insn (const struct riscv_opcode *opc, int length)
e23eba97 1267{
437e2ff1 1268 const char *oparg, *opargStart;
e23eba97 1269 insn_t used_bits = opc->mask;
0e35537d
JW
1270 int insn_width;
1271 insn_t required_bits;
1272
1273 if (length == 0)
83029f7f
TO
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;
0e35537d 1279
83029f7f 1280 required_bits = ((insn_t)~0ULL) >> (64 - insn_width);
e23eba97
NC
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);
5b7c81bd 1286 return false;
e23eba97
NC
1287 }
1288
437e2ff1
NC
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 {
65e4a99a
NC
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;
437e2ff1
NC
1336 }
1337 break;
0e35537d 1338 default:
437e2ff1
NC
1339 goto unknown_validate_operand;
1340 }
a63375ac 1341 break; /* end RVC */
65e4a99a
NC
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;
c8cb3734 1361 case 'l': used_bits |= ENCODE_RVV_VI_UIMM6 (-1U); break;
65e4a99a 1362 case 'm': USE_BITS (OP_MASK_VMASK, OP_SH_VMASK); break;
c1ecdee7
TO
1363 case 'M': break; /* Macro operand, must be a mask register. */
1364 case 'T': break; /* Macro operand, must be a vector register. */
65e4a99a
NC
1365 default:
1366 goto unknown_validate_operand;
1367 }
a63375ac 1368 break; /* end RVV */
437e2ff1
NC
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. */
c1ecdee7 1376 case 'c': break; /* Macro operand, must be symbol or constant. */
437e2ff1
NC
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;
3d1cafa0 1380 case 'y': USE_BITS (OP_MASK_BS, OP_SH_BS); break;
1381 case 'Y': USE_BITS (OP_MASK_RNUM, OP_SH_RNUM); break;
437e2ff1
NC
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 {
6de11ff6
NC
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;
437e2ff1
NC
1415 }
1416 break;
1417 case 'O': /* Opcode for .insn directive. */
1418 switch (*++oparg)
1419 {
6de11ff6
NC
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;
437e2ff1
NC
1424 }
1425 break;
6de11ff6 1426 case 'W': /* Various operands for standard z extensions. */
54bca63b
TO
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;
1f3fc45b
CM
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;
b5c37946
SJ
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;
54bca63b
TO
1457 default:
1458 goto unknown_validate_operand;
1459 }
1460 break;
6de11ff6
NC
1461 case 'X': /* Vendor-specific operands. */
1462 switch (*++oparg)
1463 {
1464 case 't': /* Vendor-specific (T-head) operands. */
8b7419c4 1465 {
6de11ff6
NC
1466 size_t n;
1467 size_t s;
1468 switch (*++oparg)
1469 {
6a95962e
JM
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;
6de11ff6
NC
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:
8b7419c4 1496 goto unknown_validate_operand;
6de11ff6 1497 }
8b7419c4 1498 }
6de11ff6 1499 break;
ccb388ca
MB
1500 case 'c': /* Vendor-specific (CORE-V) operands. */
1501 switch (*++oparg)
1502 {
d1bd9787
MB
1503 case '2':
1504 /* ls2[4:0] */
1505 used_bits |= ENCODE_CV_IS2_UIMM5 (-1U);
1506 break;
ccb388ca
MB
1507 case '3':
1508 used_bits |= ENCODE_CV_IS3_UIMM5 (-1U);
1509 break;
1510 default:
1511 goto unknown_validate_operand;
1512 }
1513 break;
248bf6de
NC
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;
6de11ff6
NC
1532 default:
1533 goto unknown_validate_operand;
1534 }
8b7419c4 1535 break;
437e2ff1
NC
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
e23eba97
NC
1545 if (used_bits != required_bits)
1546 {
b800637e 1547 as_bad (_("internal: bad RISC-V opcode "
6b84c098
TO
1548 "(bits %#llx undefined or invalid): %s %s"),
1549 (unsigned long long)(used_bits ^ required_bits),
e23eba97 1550 opc->name, opc->args);
5b7c81bd 1551 return false;
e23eba97 1552 }
5b7c81bd 1553 return true;
e23eba97
NC
1554}
1555
437e2ff1
NC
1556#undef USE_BITS
1557
e23eba97
NC
1558struct percent_op_match
1559{
1560 const char *str;
1561 bfd_reloc_code_real_type reloc;
1562};
1563
dcd709e0
NC
1564/* Common hash table initialization function for instruction and .insn
1565 directive. */
1566
629310ab 1567static htab_t
0e35537d 1568init_opcode_hash (const struct riscv_opcode *opcodes,
5b7c81bd 1569 bool insn_directive_p)
e23eba97
NC
1570{
1571 int i = 0;
0e35537d 1572 int length;
629310ab 1573 htab_t hash = str_htab_create ();
0e35537d 1574 while (opcodes[i].name)
e23eba97 1575 {
0e35537d 1576 const char *name = opcodes[i].name;
fe0e921f 1577 if (str_hash_insert (hash, name, &opcodes[i], 0) != NULL)
b800637e 1578 as_fatal (_("internal: duplicate %s"), name);
e23eba97
NC
1579
1580 do
1581 {
0e35537d 1582 if (opcodes[i].pinfo != INSN_MACRO)
e23eba97 1583 {
0e35537d
JW
1584 if (insn_directive_p)
1585 length = ((name[0] == 'c') ? 2 : 4);
1586 else
dcd709e0 1587 length = 0; /* Let assembler determine the length. */
0e35537d 1588 if (!validate_riscv_insn (&opcodes[i], length))
b800637e
NC
1589 as_fatal (_("internal: broken assembler. "
1590 "No assembly attempted"));
e23eba97 1591 }
0e35537d
JW
1592 else
1593 gas_assert (!insn_directive_p);
e23eba97
NC
1594 ++i;
1595 }
0e35537d 1596 while (opcodes[i].name && !strcmp (opcodes[i].name, name));
e23eba97
NC
1597 }
1598
0e35537d
JW
1599 return hash;
1600}
1601
dff565fc
LX
1602/* Record all PC-relative high-part relocation that we have encountered to
1603 help us resolve the corresponding low-part relocation later. */
1604typedef 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. */
1612static htab_t riscv_pcrel_hi_fixup_hash;
1613
1614/* Get the key of a entry from the pcrel_hi hash table. */
1615
1616static hashval_t
1617riscv_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
1625static int
1626riscv_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
1634static bool
1635riscv_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
0e35537d
JW
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
1654void
1655md_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))
b800637e 1660 as_warn (_("could not set architecture and machine"));
0e35537d 1661
5b7c81bd
AM
1662 op_hash = init_opcode_hash (riscv_opcodes, false);
1663 insn_type_hash = init_opcode_hash (riscv_insn_types, true);
0e35537d 1664
629310ab 1665 reg_names_hash = str_htab_create ();
e23eba97
NC
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);
65e4a99a
NC
1670 hash_reg_names (RCLASS_VECR, riscv_vecr_names_numeric, NVECR);
1671 hash_reg_names (RCLASS_VECM, riscv_vecm_names_numeric, NVECM);
b9c04e5a
JW
1672 /* Add "fp" as an alias for "s0". */
1673 hash_reg_name (RCLASS_GPR, "fp", 8);
1674
bd0cf5a6 1675 /* Create and insert CSR hash tables. */
629310ab 1676 csr_extra_hash = str_htab_create ();
8f595e9b
NC
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);
e23eba97
NC
1681#include "opcode/riscv-opc.h"
1682#undef DECLARE_CSR
1683
629310ab 1684 opcode_names_hash = str_htab_create ();
bd0cf5a6
NC
1685 init_opcode_names_hash ();
1686
dff565fc
LX
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
e23eba97
NC
1692 /* Set the default alignment for the text section. */
1693 record_alignment (text_section, riscv_opts.rvc ? 1 : 2);
1694}
1695
45f76423
AW
1696static insn_t
1697riscv_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
e23eba97
NC
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
1722static void
1723append_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
1d65abb5 1732 gas_assert (address_expr);
e23eba97
NC
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;
8c07e983 1737 int best_case = insn_length (ip);
e23eba97 1738 unsigned worst_case = relaxed_branch_length (NULL, NULL, 0);
743f5cfc
JW
1739
1740 if (now_seg == absolute_section)
1741 {
1742 as_bad (_("relaxable branches not supported in absolute section"));
1743 return;
1744 }
1745
e23eba97
NC
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 }
45f76423 1752 else
e23eba97 1753 {
45f76423
AW
1754 howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
1755 if (howto == NULL)
579f0281 1756 as_bad (_("internal: unsupported RISC-V relocation number %d"),
b800637e 1757 reloc_type);
e23eba97 1758
45f76423
AW
1759 ip->fixp = fix_new_exp (ip->frag, ip->where,
1760 bfd_get_reloc_size (howto),
5b7c81bd 1761 address_expr, false, reloc_type);
e23eba97 1762
45f76423 1763 ip->fixp->fx_tcbit = riscv_opts.relax;
bf69326f 1764 ip->fixp->tc_fix_data.source_macro = source_macro;
e23eba97 1765 }
e23eba97
NC
1766 }
1767
e23eba97 1768 add_fixed_insn (ip);
f77bb6c5
JW
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. */
b1b11e92 1774 if (reloc_type == BFD_RELOC_RISCV_HI20
f77bb6c5
JW
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 }
e23eba97
NC
1782}
1783
1784/* Build an instruction created by a macro expansion. This is passed
dcd709e0
NC
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. */
e23eba97
NC
1788
1789static void
1790macro_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;
437e2ff1 1796 const char *fmtStart;
e23eba97
NC
1797
1798 va_start (args, fmt);
1799
1800 r = BFD_RELOC_UNUSED;
629310ab 1801 mo = (struct riscv_opcode *) str_hash_find (op_hash, name);
e23eba97
NC
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);
437e2ff1 1811 for (;; ++fmt)
e23eba97 1812 {
437e2ff1
NC
1813 fmtStart = fmt;
1814 switch (*fmt)
e23eba97 1815 {
65e4a99a
NC
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
e23eba97
NC
1849 case 'd':
1850 INSERT_OPERAND (RD, insn, va_arg (args, int));
1851 continue;
e23eba97
NC
1852 case 's':
1853 INSERT_OPERAND (RS1, insn, va_arg (args, int));
1854 continue;
e23eba97
NC
1855 case 't':
1856 INSERT_OPERAND (RS2, insn, va_arg (args, int));
1857 continue;
1858
e23eba97
NC
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:
65e4a99a 1871 unknown_macro_argument:
437e2ff1 1872 as_fatal (_("internal: invalid macro argument `%s'"), fmtStart);
e23eba97
NC
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
db3b6ecc
KC
1882/* Build an instruction created by a macro expansion. Like md_assemble but
1883 accept a printf-style format string and arguments. */
1884
1885static void
1886md_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)
b800637e 1897 as_fatal (_("internal: vasprintf failed"));
db3b6ecc
KC
1898
1899 md_assemble (buf);
1900 free(buf);
1901
1902 va_end (ap);
1903}
1904
e23eba97
NC
1905/* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
1906 unset. */
dcd709e0 1907
e23eba97
NC
1908static void
1909normalize_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
ca2fd32c
JW
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. */
e23eba97
NC
1921
1922static void
ca2fd32c 1923check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex,
5b7c81bd 1924 bool maybe_csr)
e23eba97
NC
1925{
1926 if (ex->X_op == O_big)
1927 as_bad (_("unsupported large constant"));
ca2fd32c
JW
1928 else if (maybe_csr && ex->X_op == O_symbol)
1929 as_bad (_("unknown CSR `%s'"),
1930 S_GET_NAME (ex->X_add_symbol));
e23eba97 1931 else if (ex->X_op != O_constant)
b800637e 1932 as_bad (_("instruction %s requires absolute expression"),
e23eba97
NC
1933 ip->insn_mo->name);
1934 normalize_constant_expr (ex);
1935}
1936
1937static symbolS *
1938make_internal_label (void)
1939{
e01e1cee
AM
1940 return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg, frag_now,
1941 frag_now_fix ());
e23eba97
NC
1942}
1943
1944/* Load an entry from the GOT. */
dcd709e0 1945
e23eba97
NC
1946static void
1947pcrel_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
1961static void
1962pcrel_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
1969static void
1970pcrel_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. */
dcd709e0 1978
e23eba97
NC
1979static void
1980riscv_call (int destreg, int tempreg, expressionS *ep,
1981 bfd_reloc_code_real_type reloc)
1982{
b1b11e92
AM
1983 /* Ensure the jalr is emitted to the same frag as the auipc. */
1984 frag_grow (8);
e23eba97
NC
1985 macro_build (ep, "auipc", "d,u", tempreg, reloc);
1986 macro_build (NULL, "jalr", "d,s", destreg, tempreg);
b1b11e92
AM
1987 /* See comment at end of append_insn. */
1988 frag_wane (frag_now);
1989 frag_new (0);
e23eba97
NC
1990}
1991
1992/* Load an integer constant into a register. */
1993
1994static void
1995load_const (int reg, expressionS *ep)
1996{
1997 int shift = RISCV_IMM_BITS;
4f7cc141 1998 bfd_vma upper_imm, sign = (bfd_vma) 1 << (RISCV_IMM_BITS - 1);
e23eba97 1999 expressionS upper = *ep, lower = *ep;
4f7cc141 2000 lower.X_add_number = ((ep->X_add_number & (sign + sign - 1)) ^ sign) - sign;
e23eba97
NC
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
1d65abb5 2009 if (xlen > 32 && !IS_SEXT_32BIT_NUM (ep->X_add_number))
e23eba97
NC
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;
1d65abb5 2016 load_const (reg, &upper);
e23eba97 2017
db3b6ecc 2018 md_assemblef ("slli x%d, x%d, 0x%x", reg, reg, shift);
e23eba97 2019 if (lower.X_add_number != 0)
b8281767
AM
2020 md_assemblef ("addi x%d, x%d, %" PRId64, reg, reg,
2021 (int64_t) lower.X_add_number);
e23eba97
NC
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 {
db3b6ecc
KC
2030 /* Discard low part and zero-extend upper immediate. */
2031 upper_imm = ((uint32_t)upper.X_add_number >> shift);
2032
b8281767 2033 md_assemblef ("lui x%d, 0x%" PRIx64, reg, (uint64_t) upper_imm);
e23eba97
NC
2034 hi_reg = reg;
2035 }
2036
2037 if (lower.X_add_number != 0 || hi_reg == 0)
b8281767
AM
2038 md_assemblef ("%s x%d, x%d, %" PRId64, ADD32_INSN, reg, hi_reg,
2039 (int64_t) lower.X_add_number);
e23eba97
NC
2040 }
2041}
2042
c2137f55
NC
2043/* Zero extend and sign extend byte/half-word/word. */
2044
2045static void
5b7c81bd 2046riscv_ext (int destreg, int srcreg, unsigned shift, bool sign)
c2137f55 2047{
eb5e952f
JB
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);
c2137f55
NC
2051}
2052
65e4a99a
NC
2053/* Expand RISC-V Vector macros into one or more instructions. */
2054
2055static void
2056vector_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;
d4868004 2063 const char *vmslt_vx = ip->insn_mo->match ? "vmsltu.vx" : "vmslt.vx";
65e4a99a
NC
2064 int mask = ip->insn_mo->mask;
2065
2066 switch (mask)
2067 {
2068 case M_VMSGE:
2069 if (vm)
2070 {
2071 /* Unmasked. */
d4868004 2072 macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vd, vs2, vs1, -1);
65e4a99a
NC
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 {
d4868004 2081 macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vtemp, vs2, vs1, -1);
65e4a99a
NC
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. */
d4868004 2087 macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vtemp, vs2, vs1, -1);
65e4a99a
NC
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. */
d4868004 2096 macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vd, vs2, vs1, vm);
65e4a99a
NC
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
e23eba97 2108/* Expand RISC-V assembly macros into one or more instructions. */
2652cfad 2109
e23eba97
NC
2110static void
2111macro (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
bf69326f
RU
2119 source_macro = mask;
2120
e23eba97
NC
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:
ec2260af 2129 case M_LGA:
e23eba97
NC
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);
ec2260af
JW
2136 /* Global PIC symbol. */
2137 else if ((riscv_opts.pic && mask == M_LA)
2138 || mask == M_LGA)
e23eba97
NC
2139 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
2140 BFD_RELOC_RISCV_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
ec2260af
JW
2141 /* Local PIC symbol, or any non-PIC symbol. */
2142 else
e23eba97
NC
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
c76820a0
JB
2157 case M_Lx:
2158 pcrel_load (rd, rd, imm_expr, ip->insn_mo->name,
e23eba97
NC
2159 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2160 break;
2161
c76820a0
JB
2162 case M_FLx:
2163 pcrel_load (rd, rs1, imm_expr, ip->insn_mo->name,
e23eba97
NC
2164 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2165 break;
2166
c76820a0
JB
2167 case M_Sx_FSx:
2168 pcrel_store (rs2, rs1, imm_expr, ip->insn_mo->name,
e4bec45d
JB
2169 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
2170 break;
2171
e23eba97
NC
2172 case M_CALL:
2173 riscv_call (rd, rs1, imm_expr, *imm_reloc);
2174 break;
2175
eb5e952f
JB
2176 case M_EXTH:
2177 riscv_ext (rd, rs1, xlen - 16, *ip->insn_mo->name == 's');
c2137f55
NC
2178 break;
2179
2180 case M_ZEXTW:
5b7c81bd 2181 riscv_ext (rd, rs1, xlen - 32, false);
c2137f55
NC
2182 break;
2183
2184 case M_SEXTB:
5b7c81bd 2185 riscv_ext (rd, rs1, xlen - 8, true);
c2137f55
NC
2186 break;
2187
65e4a99a 2188 case M_VMSGE:
65e4a99a
NC
2189 vector_macro (ip);
2190 break;
2191
e23eba97 2192 default:
b800637e 2193 as_bad (_("internal: macro %s not implemented"), ip->insn_mo->name);
e23eba97
NC
2194 break;
2195 }
bf69326f
RU
2196
2197 source_macro = -1;
e23eba97
NC
2198}
2199
2200static const struct percent_op_match percent_op_utype[] =
2201{
85bd4bfb
JB
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},
e23eba97
NC
2208 {0, 0}
2209};
2210
2211static const struct percent_op_match percent_op_itype[] =
2212{
85bd4bfb
JB
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},
e23eba97
NC
2216 {0, 0}
2217};
2218
2219static const struct percent_op_match percent_op_stype[] =
2220{
85bd4bfb
JB
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},
e23eba97
NC
2224 {0, 0}
2225};
2226
2227static const struct percent_op_match percent_op_rtype[] =
2228{
85bd4bfb 2229 {"tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
e23eba97
NC
2230 {0, 0}
2231};
2232
f50fabe4
JW
2233static const struct percent_op_match percent_op_null[] =
2234{
2235 {0, 0}
2236};
2237
e23eba97
NC
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
5b7c81bd 2242static bool
e23eba97
NC
2243parse_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++)
85bd4bfb 2247 if (strncasecmp (*str + 1, percent_op->str, strlen (percent_op->str)) == 0)
e23eba97 2248 {
85bd4bfb 2249 size_t len = 1 + strlen (percent_op->str);
e23eba97 2250
654dfab0
JB
2251 while (ISSPACE ((*str)[len]))
2252 ++len;
2253 if ((*str)[len] != '(')
e23eba97
NC
2254 continue;
2255
85bd4bfb 2256 *str += len;
e23eba97
NC
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. */
45f76423
AW
2261 if (*reloc != BFD_RELOC_UNUSED
2262 && !bfd_reloc_type_lookup (stdoutput, *reloc))
e23eba97 2263 {
b800637e
NC
2264 as_bad ("internal: relocation %s isn't supported by the "
2265 "current ABI", percent_op->str);
e23eba97
NC
2266 *reloc = BFD_RELOC_UNUSED;
2267 }
5b7c81bd 2268 return true;
e23eba97 2269 }
5b7c81bd 2270 return false;
e23eba97
NC
2271}
2272
2273static void
2274my_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);
6eb099ae 2281 expr_parse_end = input_line_pointer;
e23eba97
NC
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
6eb099ae
AM
2289 On exit, EXPR_PARSE_END points to the first character after the
2290 expression. */
e23eba97
NC
2291
2292static size_t
2293my_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;
7a29ee29
JB
2297 unsigned crux_depth, str_depth;
2298 bool orig_probing = probing_insn_operands;
e23eba97
NC
2299 char *crux;
2300
e23eba97 2301 /* Search for the start of the main expression.
dcd709e0
NC
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. */
e23eba97
NC
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
a5e756e6
JB
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
7a29ee29
JB
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
e23eba97 2338 my_getExpression (ep, crux);
6eb099ae 2339 str = expr_parse_end;
e23eba97 2340
7a29ee29
JB
2341 probing_insn_operands = orig_probing;
2342
e23eba97
NC
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
6eb099ae 2351 expr_parse_end = str;
e23eba97
NC
2352
2353 return reloc_index;
2354}
2355
0e35537d 2356/* Parse opcode name, could be an mnemonics or number. */
dcd709e0 2357
0e35537d
JW
2358static size_t
2359my_getOpcodeExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
408ab016 2360 char *str)
0e35537d
JW
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
408ab016 2371 return my_getSmallExpression (ep, reloc, str, percent_op_null);
0e35537d
JW
2372}
2373
65e4a99a 2374/* Parse string STR as a vsetvli operand. Store the expression in *EP.
6eb099ae
AM
2375 On exit, EXPR_PARSE_END points to the first character after the
2376 expression. */
65e4a99a
NC
2377
2378static void
2379my_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);
6eb099ae 2426 expr_parse_end = str;
65e4a99a
NC
2427 }
2428 else
2429 {
2430 my_getExpression (ep, str);
6eb099ae 2431 str = expr_parse_end;
65e4a99a
NC
2432 }
2433}
2434
6a95962e
JM
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
2439static void
2440my_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
f0531ed6 2488/* Detect and handle implicitly zero load-store offsets. For example,
437e2ff1 2489 "lw t0, (t1)" is shorthand for "lw t0, 0(t1)". Return true if such
f0531ed6
JW
2490 an implicit offset was detected. */
2491
5b7c81bd 2492static bool
89424b1d 2493riscv_handle_implicit_zero_offset (expressionS *ep, const char *s)
f0531ed6
JW
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 {
89424b1d
MR
2499 ep->X_op = O_constant;
2500 ep->X_add_number = 0;
5b7c81bd 2501 return true;
f0531ed6
JW
2502 }
2503
5b7c81bd 2504 return false;
f0531ed6
JW
2505}
2506
54b2aec1 2507/* All RISC-V CSR instructions belong to one of these classes. */
54b2aec1
NC
2508enum 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
2518static enum csr_insn_type
2519riscv_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
5b7c81bd 2538static bool
54b2aec1
NC
2539riscv_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))
5b7c81bd 2551 return false;
54b2aec1 2552
5b7c81bd 2553 return true;
54b2aec1
NC
2554}
2555
437e2ff1 2556/* Return true if it is a privileged instruction. Otherwise, return false.
1a79004f
NC
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
5b7c81bd 2569static bool
1a79004f
NC
2570riscv_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
dcd709e0 2577 check it here to keep the compatible. */
1a79004f
NC
2578 || ((insn ^ MATCH_SFENCE_VM) & MASK_SFENCE_VM) == 0);
2579}
2580
7a29ee29
JB
2581static symbolS *deferred_sym_rootP;
2582static symbolS *deferred_sym_lastP;
2583/* Since symbols can't easily be freed, try to recycle ones which weren't
2584 committed. */
2585static symbolS *orphan_sym_rootP;
2586static symbolS *orphan_sym_lastP;
2587
e23eba97
NC
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
e4028336 2592static struct riscv_ip_error
e23eba97 2593riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
629310ab 2594 bfd_reloc_code_real_type *imm_reloc, htab_t hash)
e23eba97 2595{
437e2ff1
NC
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;
e23eba97 2601 struct riscv_opcode *insn;
e23eba97 2602 unsigned int regno;
e23eba97 2603 const struct percent_op_match *p;
e4028336
PN
2604 struct riscv_ip_error error;
2605 error.msg = "unrecognized opcode";
2606 error.statement = str;
2607 error.missing_ext = NULL;
54b2aec1 2608 /* Indicate we are assembling instruction with CSR. */
5b7c81bd 2609 bool insn_with_csr = false;
e23eba97
NC
2610
2611 /* Parse the name of the instruction. Terminate the string if whitespace
629310ab 2612 is found so that str_hash_find only sees the name part of the string. */
437e2ff1
NC
2613 for (asarg = str; *asarg!= '\0'; ++asarg)
2614 if (ISSPACE (*asarg))
e23eba97 2615 {
437e2ff1
NC
2616 save_c = *asarg;
2617 *asarg++ = '\0';
e23eba97
NC
2618 break;
2619 }
2620
629310ab 2621 insn = (struct riscv_opcode *) str_hash_find (hash, str);
e23eba97 2622
7a29ee29
JB
2623 probing_insn_operands = true;
2624
437e2ff1 2625 asargStart = asarg;
e23eba97
NC
2626 for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
2627 {
1080bf78
JW
2628 if ((insn->xlen_requirement != 0) && (xlen != insn->xlen_requirement))
2629 continue;
2630
f786c359 2631 if (!riscv_multi_subset_supports (&riscv_rps_as, insn->insn_class))
e4028336
PN
2632 {
2633 error.missing_ext = riscv_multi_subset_supports_ext (&riscv_rps_as,
2634 insn->insn_class);
2635 continue;
2636 }
e23eba97 2637
65e4a99a 2638 /* Reset error message of the previous round. */
e4028336
PN
2639 error.msg = _("illegal operands");
2640 error.missing_ext = NULL;
7a29ee29
JB
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
e23eba97 2652 create_insn (ip, insn);
e23eba97
NC
2653
2654 imm_expr->X_op = O_absent;
2655 *imm_reloc = BFD_RELOC_UNUSED;
b33e94cf 2656 p = percent_op_null;
e23eba97 2657
437e2ff1 2658 for (oparg = insn->args;; ++oparg)
e23eba97 2659 {
437e2ff1
NC
2660 opargStart = oparg;
2661 asarg += strspn (asarg, " \t");
2662 switch (*oparg)
e23eba97 2663 {
dcd709e0 2664 case '\0': /* End of args. */
27b33966
JB
2665 if (insn->match_func && !insn->match_func (insn, ip->insn_opcode))
2666 break;
2667
e23eba97
NC
2668 if (insn->pinfo != INSN_MACRO)
2669 {
0e35537d
JW
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)
e23eba97 2675 break;
54b2aec1 2676
1a79004f 2677 if (riscv_is_priv_insn (ip->insn_opcode))
5b7c81bd 2678 explicit_priv_attr = true;
1a79004f 2679
54b2aec1
NC
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)
437e2ff1 2689 *(asargStart - 1) = save_c;
b800637e 2690 as_warn (_("read-only CSR is written `%s'"), str);
5b7c81bd 2691 insn_with_csr = false;
54b2aec1 2692 }
65e4a99a
NC
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 {
e4028336 2700 error.msg = _("illegal opcode for zve32x");
65e4a99a
NC
2701 break;
2702 }
e23eba97 2703 }
437e2ff1 2704 if (*asarg != '\0')
e23eba97 2705 break;
7a29ee29 2706
e23eba97 2707 /* Successful assembly. */
e4028336 2708 error.msg = NULL;
5b7c81bd 2709 insn_with_csr = false;
7a29ee29
JB
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 }
e23eba97
NC
2722 goto out;
2723
2724 case 'C': /* RVC */
437e2ff1 2725 switch (*++oparg)
e23eba97 2726 {
dcd709e0 2727 case 's': /* RS1 x8-x15. */
437e2ff1 2728 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
e23eba97
NC
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. */
437e2ff1 2734 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
e23eba97
NC
2735 || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
2736 break;
2737 continue;
dcd709e0 2738 case 't': /* RS2 x8-x15. */
437e2ff1 2739 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
e23eba97
NC
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. */
437e2ff1 2745 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
e23eba97
NC
2746 || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
2747 break;
2748 continue;
2749 case 'U': /* RS1, constrained to equal RD. */
437e2ff1 2750 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
e23eba97
NC
2751 || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
2752 break;
2753 continue;
2754 case 'V': /* RS2 */
437e2ff1 2755 if (!reg_lookup (&asarg, RCLASS_GPR, &regno))
e23eba97
NC
2756 break;
2757 INSERT_OPERAND (CRS2, *ip, regno);
2758 continue;
2759 case 'c': /* RS1, constrained to equal sp. */
437e2ff1 2760 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
e23eba97
NC
2761 || regno != X_SP)
2762 break;
2763 continue;
dcd709e0 2764 case 'z': /* RS2, constrained to equal x0. */
437e2ff1 2765 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
ca0bc150
JW
2766 || regno != 0)
2767 break;
2768 continue;
768589d1 2769 case '>': /* Shift amount, 0 - (XLEN-1). */
437e2ff1 2770 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2771 || imm_expr->X_op != O_constant
768589d1 2772 || (unsigned long) imm_expr->X_add_number >= xlen)
e23eba97 2773 break;
5a9f5403 2774 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
dc1e8a47 2775 rvc_imm_done:
6eb099ae 2776 asarg = expr_parse_end;
e23eba97
NC
2777 imm_expr->X_op = O_absent;
2778 continue;
5a9f5403 2779 case '5':
437e2ff1 2780 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2781 || imm_expr->X_op != O_constant
5a9f5403 2782 || imm_expr->X_add_number < 0
169ec512 2783 || imm_expr->X_add_number >= 32
5a9f5403 2784 || !VALID_CLTYPE_IMM ((valueT) imm_expr->X_add_number))
e23eba97 2785 break;
0257c2ff 2786 ip->insn_opcode |= ENCODE_CLTYPE_IMM (imm_expr->X_add_number);
e23eba97 2787 goto rvc_imm_done;
5a9f5403 2788 case '6':
437e2ff1 2789 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
0e35537d 2790 || imm_expr->X_op != O_constant
0e35537d 2791 || imm_expr->X_add_number < 0
5a9f5403
NC
2792 || imm_expr->X_add_number >= 64
2793 || !VALID_CSSTYPE_IMM ((valueT) imm_expr->X_add_number))
0e35537d 2794 break;
0257c2ff 2795 ip->insn_opcode |= ENCODE_CSSTYPE_IMM (imm_expr->X_add_number);
0e35537d 2796 goto rvc_imm_done;
5a9f5403 2797 case '8':
437e2ff1 2798 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2799 || imm_expr->X_op != O_constant
5a9f5403
NC
2800 || imm_expr->X_add_number < 0
2801 || imm_expr->X_add_number >= 256
2802 || !VALID_CIWTYPE_IMM ((valueT) imm_expr->X_add_number))
e23eba97 2803 break;
0257c2ff 2804 ip->insn_opcode |= ENCODE_CIWTYPE_IMM (imm_expr->X_add_number);
e23eba97
NC
2805 goto rvc_imm_done;
2806 case 'j':
437e2ff1 2807 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97
NC
2808 || imm_expr->X_op != O_constant
2809 || imm_expr->X_add_number == 0
5a9f5403 2810 || !VALID_CITYPE_IMM ((valueT) imm_expr->X_add_number))
e23eba97 2811 break;
5a9f5403 2812 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
e23eba97
NC
2813 goto rvc_imm_done;
2814 case 'k':
437e2ff1 2815 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
f0531ed6 2816 continue;
437e2ff1 2817 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2818 || imm_expr->X_op != O_constant
5a9f5403 2819 || !VALID_CLTYPE_LW_IMM ((valueT) imm_expr->X_add_number))
e23eba97 2820 break;
5a9f5403 2821 ip->insn_opcode |= ENCODE_CLTYPE_LW_IMM (imm_expr->X_add_number);
e23eba97
NC
2822 goto rvc_imm_done;
2823 case 'l':
437e2ff1 2824 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
f0531ed6 2825 continue;
437e2ff1 2826 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2827 || imm_expr->X_op != O_constant
5a9f5403 2828 || !VALID_CLTYPE_LD_IMM ((valueT) imm_expr->X_add_number))
e23eba97 2829 break;
5a9f5403 2830 ip->insn_opcode |= ENCODE_CLTYPE_LD_IMM (imm_expr->X_add_number);
e23eba97
NC
2831 goto rvc_imm_done;
2832 case 'm':
437e2ff1 2833 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
f0531ed6 2834 continue;
437e2ff1 2835 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2836 || imm_expr->X_op != O_constant
5a9f5403 2837 || !VALID_CITYPE_LWSP_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2838 break;
2839 ip->insn_opcode |=
5a9f5403 2840 ENCODE_CITYPE_LWSP_IMM (imm_expr->X_add_number);
e23eba97
NC
2841 goto rvc_imm_done;
2842 case 'n':
437e2ff1 2843 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
f0531ed6 2844 continue;
437e2ff1 2845 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2846 || imm_expr->X_op != O_constant
5a9f5403 2847 || !VALID_CITYPE_LDSP_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2848 break;
2849 ip->insn_opcode |=
5a9f5403 2850 ENCODE_CITYPE_LDSP_IMM (imm_expr->X_add_number);
e23eba97 2851 goto rvc_imm_done;
b416fe87 2852 case 'o':
437e2ff1 2853 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
b416fe87 2854 || imm_expr->X_op != O_constant
21a186f2
JW
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'. */
5a9f5403 2858 || !VALID_CITYPE_IMM ((valueT) imm_expr->X_add_number))
b416fe87 2859 break;
5a9f5403 2860 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
b416fe87 2861 goto rvc_imm_done;
e23eba97 2862 case 'K':
437e2ff1 2863 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2864 || imm_expr->X_op != O_constant
169ec512 2865 || imm_expr->X_add_number == 0
5a9f5403 2866 || !VALID_CIWTYPE_ADDI4SPN_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2867 break;
2868 ip->insn_opcode |=
5a9f5403 2869 ENCODE_CIWTYPE_ADDI4SPN_IMM (imm_expr->X_add_number);
e23eba97
NC
2870 goto rvc_imm_done;
2871 case 'L':
437e2ff1 2872 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2873 || imm_expr->X_op != O_constant
5a9f5403 2874 || !VALID_CITYPE_ADDI16SP_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2875 break;
2876 ip->insn_opcode |=
5a9f5403 2877 ENCODE_CITYPE_ADDI16SP_IMM (imm_expr->X_add_number);
e23eba97
NC
2878 goto rvc_imm_done;
2879 case 'M':
437e2ff1 2880 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
f0531ed6 2881 continue;
437e2ff1 2882 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2883 || imm_expr->X_op != O_constant
5a9f5403 2884 || !VALID_CSSTYPE_SWSP_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2885 break;
2886 ip->insn_opcode |=
5a9f5403 2887 ENCODE_CSSTYPE_SWSP_IMM (imm_expr->X_add_number);
e23eba97
NC
2888 goto rvc_imm_done;
2889 case 'N':
437e2ff1 2890 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
f0531ed6 2891 continue;
437e2ff1 2892 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97 2893 || imm_expr->X_op != O_constant
5a9f5403 2894 || !VALID_CSSTYPE_SDSP_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2895 break;
2896 ip->insn_opcode |=
5a9f5403 2897 ENCODE_CSSTYPE_SDSP_IMM (imm_expr->X_add_number);
e23eba97
NC
2898 goto rvc_imm_done;
2899 case 'u':
2900 p = percent_op_utype;
437e2ff1 2901 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
e23eba97 2902 break;
dc1e8a47 2903 rvc_lui:
e23eba97
NC
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;
5a9f5403 2911 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
e23eba97
NC
2912 goto rvc_imm_done;
2913 case 'v':
437e2ff1 2914 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e23eba97
NC
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;
0e35537d 2926 case 'S': /* Floating-point RS1 x8-x15. */
437e2ff1 2927 if (!reg_lookup (&asarg, RCLASS_FPR, &regno)
0e35537d
JW
2928 || !(regno >= 8 && regno <= 15))
2929 break;
2930 INSERT_OPERAND (CRS1S, *ip, regno % 8);
2931 continue;
e23eba97 2932 case 'D': /* Floating-point RS2 x8-x15. */
437e2ff1 2933 if (!reg_lookup (&asarg, RCLASS_FPR, &regno)
e23eba97
NC
2934 || !(regno >= 8 && regno <= 15))
2935 break;
2936 INSERT_OPERAND (CRS2S, *ip, regno % 8);
2937 continue;
2938 case 'T': /* Floating-point RS2. */
437e2ff1 2939 if (!reg_lookup (&asarg, RCLASS_FPR, &regno))
e23eba97
NC
2940 break;
2941 INSERT_OPERAND (CRS2, *ip, regno);
2942 continue;
0e35537d 2943 case 'F':
437e2ff1 2944 switch (*++oparg)
0e35537d 2945 {
4765cd61 2946 case '6':
437e2ff1 2947 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
4765cd61
JW
2948 || imm_expr->X_op != O_constant
2949 || imm_expr->X_add_number < 0
2950 || imm_expr->X_add_number >= 64)
2951 {
b800637e 2952 as_bad (_("bad value for compressed funct6 "
b215cdf5 2953 "field, value must be 0...63"));
4765cd61
JW
2954 break;
2955 }
4765cd61
JW
2956 INSERT_OPERAND (CFUNCT6, *ip, imm_expr->X_add_number);
2957 imm_expr->X_op = O_absent;
6eb099ae 2958 asarg = expr_parse_end;
4765cd61 2959 continue;
1942a048 2960
0e35537d 2961 case '4':
437e2ff1 2962 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
0e35537d
JW
2963 || imm_expr->X_op != O_constant
2964 || imm_expr->X_add_number < 0
2965 || imm_expr->X_add_number >= 16)
2966 {
b800637e
NC
2967 as_bad (_("bad value for compressed funct4 "
2968 "field, value must be 0...15"));
0e35537d
JW
2969 break;
2970 }
0e35537d
JW
2971 INSERT_OPERAND (CFUNCT4, *ip, imm_expr->X_add_number);
2972 imm_expr->X_op = O_absent;
6eb099ae 2973 asarg = expr_parse_end;
0e35537d 2974 continue;
1942a048 2975
0e35537d 2976 case '3':
437e2ff1 2977 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
0e35537d
JW
2978 || imm_expr->X_op != O_constant
2979 || imm_expr->X_add_number < 0
2980 || imm_expr->X_add_number >= 8)
2981 {
b800637e
NC
2982 as_bad (_("bad value for compressed funct3 "
2983 "field, value must be 0...7"));
0e35537d
JW
2984 break;
2985 }
2986 INSERT_OPERAND (CFUNCT3, *ip, imm_expr->X_add_number);
2987 imm_expr->X_op = O_absent;
6eb099ae 2988 asarg = expr_parse_end;
0e35537d 2989 continue;
1942a048 2990
4765cd61 2991 case '2':
437e2ff1 2992 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
4765cd61
JW
2993 || imm_expr->X_op != O_constant
2994 || imm_expr->X_add_number < 0
2995 || imm_expr->X_add_number >= 4)
2996 {
b800637e
NC
2997 as_bad (_("bad value for compressed funct2 "
2998 "field, value must be 0...3"));
4765cd61
JW
2999 break;
3000 }
3001 INSERT_OPERAND (CFUNCT2, *ip, imm_expr->X_add_number);
3002 imm_expr->X_op = O_absent;
6eb099ae 3003 asarg = expr_parse_end;
4765cd61 3004 continue;
1942a048 3005
0e35537d 3006 default:
437e2ff1 3007 goto unknown_riscv_ip_operand;
0e35537d
JW
3008 }
3009 break;
3010
e23eba97 3011 default:
437e2ff1 3012 goto unknown_riscv_ip_operand;
e23eba97 3013 }
a63375ac 3014 break; /* end RVC */
e23eba97 3015
65e4a99a
NC
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;
6eb099ae 3095 asarg = expr_parse_end;
65e4a99a
NC
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;
6eb099ae 3107 asarg = expr_parse_end;
65e4a99a
NC
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;
6eb099ae 3119 asarg = expr_parse_end;
65e4a99a
NC
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;
6eb099ae 3131 asarg = expr_parse_end;
65e4a99a
NC
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;
6eb099ae 3143 asarg = expr_parse_end;
65e4a99a
NC
3144 continue;
3145
c8cb3734
CM
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
65e4a99a
NC
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 }
a63375ac 3192 break; /* end RVV */
65e4a99a 3193
e23eba97 3194 case ',':
437e2ff1 3195 if (*asarg++ == *oparg)
e23eba97 3196 continue;
437e2ff1 3197 asarg--;
e23eba97
NC
3198 break;
3199
3200 case '(':
3201 case ')':
3202 case '[':
3203 case ']':
437e2ff1 3204 if (*asarg++ == *oparg)
e23eba97
NC
3205 continue;
3206 break;
3207
dcd709e0 3208 case '<': /* Shift amount, 0 - 31. */
437e2ff1 3209 my_getExpression (imm_expr, asarg);
5b7c81bd 3210 check_absolute_expr (ip, imm_expr, false);
e23eba97 3211 if ((unsigned long) imm_expr->X_add_number > 31)
a6eeb20a
CM
3212 as_bad (_("improper shift amount (%"PRIu64")"),
3213 imm_expr->X_add_number);
e23eba97
NC
3214 INSERT_OPERAND (SHAMTW, *ip, imm_expr->X_add_number);
3215 imm_expr->X_op = O_absent;
6eb099ae 3216 asarg = expr_parse_end;
e23eba97
NC
3217 continue;
3218
dcd709e0 3219 case '>': /* Shift amount, 0 - (XLEN-1). */
437e2ff1 3220 my_getExpression (imm_expr, asarg);
5b7c81bd 3221 check_absolute_expr (ip, imm_expr, false);
e23eba97 3222 if ((unsigned long) imm_expr->X_add_number >= xlen)
a6eeb20a
CM
3223 as_bad (_("improper shift amount (%"PRIu64")"),
3224 imm_expr->X_add_number);
e23eba97
NC
3225 INSERT_OPERAND (SHAMT, *ip, imm_expr->X_add_number);
3226 imm_expr->X_op = O_absent;
6eb099ae 3227 asarg = expr_parse_end;
e23eba97
NC
3228 continue;
3229
dcd709e0 3230 case 'Z': /* CSRRxI immediate. */
437e2ff1 3231 my_getExpression (imm_expr, asarg);
5b7c81bd 3232 check_absolute_expr (ip, imm_expr, false);
e23eba97 3233 if ((unsigned long) imm_expr->X_add_number > 31)
a6eeb20a
CM
3234 as_bad (_("improper CSRxI immediate (%"PRIu64")"),
3235 imm_expr->X_add_number);
e23eba97
NC
3236 INSERT_OPERAND (RS1, *ip, imm_expr->X_add_number);
3237 imm_expr->X_op = O_absent;
6eb099ae 3238 asarg = expr_parse_end;
e23eba97
NC
3239 continue;
3240
dcd709e0 3241 case 'E': /* Control register. */
5b7c81bd
AM
3242 insn_with_csr = true;
3243 explicit_priv_attr = true;
437e2ff1 3244 if (reg_lookup (&asarg, RCLASS_CSR, &regno))
e23eba97
NC
3245 INSERT_OPERAND (CSR, *ip, regno);
3246 else
3247 {
437e2ff1 3248 my_getExpression (imm_expr, asarg);
5b7c81bd 3249 check_absolute_expr (ip, imm_expr, true);
e23eba97 3250 if ((unsigned long) imm_expr->X_add_number > 0xfff)
a6eeb20a
CM
3251 as_bad (_("improper CSR address (%"PRIu64")"),
3252 imm_expr->X_add_number);
e23eba97
NC
3253 INSERT_OPERAND (CSR, *ip, imm_expr->X_add_number);
3254 imm_expr->X_op = O_absent;
6eb099ae 3255 asarg = expr_parse_end;
e23eba97
NC
3256 }
3257 continue;
3258
dcd709e0 3259 case 'm': /* Rounding mode. */
437e2ff1
NC
3260 if (arg_lookup (&asarg, riscv_rm,
3261 ARRAY_SIZE (riscv_rm), &regno))
e23eba97
NC
3262 {
3263 INSERT_OPERAND (RM, *ip, regno);
3264 continue;
3265 }
3266 break;
3267
3268 case 'P':
dcd709e0 3269 case 'Q': /* Fence predecessor/successor. */
437e2ff1
NC
3270 if (arg_lookup (&asarg, riscv_pred_succ,
3271 ARRAY_SIZE (riscv_pred_succ), &regno))
e23eba97 3272 {
437e2ff1 3273 if (*oparg == 'P')
e23eba97
NC
3274 INSERT_OPERAND (PRED, *ip, regno);
3275 else
3276 INSERT_OPERAND (SUCC, *ip, regno);
3277 continue;
3278 }
3279 break;
3280
dcd709e0
NC
3281 case 'd': /* Destination register. */
3282 case 's': /* Source register. */
3283 case 't': /* Target register. */
3284 case 'r': /* RS3 */
437e2ff1 3285 if (reg_lookup (&asarg, RCLASS_GPR, &regno))
e23eba97 3286 {
437e2ff1
NC
3287 char c = *oparg;
3288 if (*asarg == ' ')
3289 ++asarg;
e23eba97
NC
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;
0e35537d
JW
3304 case 'r':
3305 INSERT_OPERAND (RS3, *ip, regno);
3306 break;
e23eba97
NC
3307 }
3308 continue;
3309 }
3310 break;
3311
dcd709e0
NC
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. */
de83e514 3317 if (reg_lookup (&asarg,
3318 (riscv_subset_supports (&riscv_rps_as, "zfinx")
3319 ? RCLASS_GPR : RCLASS_FPR), &regno))
e23eba97 3320 {
437e2ff1
NC
3321 char c = *oparg;
3322 if (*asarg == ' ')
3323 ++asarg;
e23eba97
NC
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);
dcd709e0 3334 /* Fall through. */
e23eba97
NC
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 }
e23eba97
NC
3344 break;
3345
3346 case 'I':
437e2ff1 3347 my_getExpression (imm_expr, asarg);
e23eba97
NC
3348 if (imm_expr->X_op != O_big
3349 && imm_expr->X_op != O_constant)
3350 break;
3351 normalize_constant_expr (imm_expr);
6eb099ae 3352 asarg = expr_parse_end;
e23eba97
NC
3353 continue;
3354
3355 case 'A':
437e2ff1 3356 my_getExpression (imm_expr, asarg);
e23eba97
NC
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;
6eb099ae 3362 asarg = expr_parse_end;
e23eba97
NC
3363 continue;
3364
160d1b3d 3365 case 'B':
437e2ff1 3366 my_getExpression (imm_expr, asarg);
160d1b3d
SH
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;
6eb099ae 3373 asarg = expr_parse_end;
160d1b3d
SH
3374 continue;
3375
e23eba97 3376 case 'j': /* Sign-extended immediate. */
e23eba97 3377 p = percent_op_itype;
f50fabe4 3378 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
e23eba97
NC
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;
dcd709e0
NC
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. */
e23eba97 3392 p = percent_op_rtype;
f50fabe4 3393 goto alu_op;
dcd709e0 3394 case '0': /* AMO displacement, which must be zero. */
dc1e8a47 3395 load_store:
437e2ff1 3396 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
e23eba97 3397 continue;
dc1e8a47 3398 alu_op:
e23eba97
NC
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. */
437e2ff1 3402 if (!my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
e23eba97
NC
3403 {
3404 normalize_constant_expr (imm_expr);
3405 if (imm_expr->X_op != O_constant
437e2ff1
NC
3406 || (*oparg == '0' && imm_expr->X_add_number != 0)
3407 || (*oparg == '1')
e23eba97
NC
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 }
6eb099ae 3412 asarg = expr_parse_end;
e23eba97
NC
3413 continue;
3414
dcd709e0 3415 case 'p': /* PC-relative offset. */
dc1e8a47 3416 branch:
e23eba97 3417 *imm_reloc = BFD_RELOC_12_PCREL;
437e2ff1 3418 my_getExpression (imm_expr, asarg);
6eb099ae 3419 asarg = expr_parse_end;
e23eba97
NC
3420 continue;
3421
dcd709e0 3422 case 'u': /* Upper 20 bits. */
e23eba97 3423 p = percent_op_utype;
437e2ff1 3424 if (!my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
e23eba97 3425 {
4288405d
JW
3426 if (imm_expr->X_op != O_constant)
3427 break;
3428
e23eba97
NC
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 }
6eb099ae 3436 asarg = expr_parse_end;
e23eba97
NC
3437 continue;
3438
dcd709e0 3439 case 'a': /* 20-bit PC-relative offset. */
dc1e8a47 3440 jump:
437e2ff1 3441 my_getExpression (imm_expr, asarg);
6eb099ae 3442 asarg = expr_parse_end;
e23eba97
NC
3443 *imm_reloc = BFD_RELOC_RISCV_JMP;
3444 continue;
3445
3446 case 'c':
437e2ff1 3447 my_getExpression (imm_expr, asarg);
6eb099ae 3448 asarg = expr_parse_end;
437e2ff1 3449 if (strcmp (asarg, "@plt") == 0)
70f35d72
NC
3450 asarg += 4;
3451 *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
e23eba97 3452 continue;
1942a048 3453
0e35537d 3454 case 'O':
437e2ff1 3455 switch (*++oparg)
0e35537d
JW
3456 {
3457 case '4':
408ab016 3458 if (my_getOpcodeExpression (imm_expr, imm_reloc, asarg)
0e35537d
JW
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 }
0e35537d
JW
3469 INSERT_OPERAND (OP, *ip, imm_expr->X_add_number);
3470 imm_expr->X_op = O_absent;
6eb099ae 3471 asarg = expr_parse_end;
0e35537d 3472 continue;
1942a048 3473
0e35537d 3474 case '2':
408ab016 3475 if (my_getOpcodeExpression (imm_expr, imm_reloc, asarg)
0e35537d
JW
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 }
0e35537d
JW
3484 INSERT_OPERAND (OP2, *ip, imm_expr->X_add_number);
3485 imm_expr->X_op = O_absent;
6eb099ae 3486 asarg = expr_parse_end;
0e35537d 3487 continue;
1942a048 3488
0e35537d 3489 default:
437e2ff1 3490 goto unknown_riscv_ip_operand;
0e35537d
JW
3491 }
3492 break;
3493
3494 case 'F':
437e2ff1 3495 switch (*++oparg)
0e35537d
JW
3496 {
3497 case '7':
437e2ff1 3498 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
0e35537d
JW
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 }
0e35537d
JW
3507 INSERT_OPERAND (FUNCT7, *ip, imm_expr->X_add_number);
3508 imm_expr->X_op = O_absent;
6eb099ae 3509 asarg = expr_parse_end;
0e35537d 3510 continue;
1942a048 3511
0e35537d 3512 case '3':
437e2ff1 3513 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
0e35537d
JW
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 }
0e35537d
JW
3522 INSERT_OPERAND (FUNCT3, *ip, imm_expr->X_add_number);
3523 imm_expr->X_op = O_absent;
6eb099ae 3524 asarg = expr_parse_end;
0e35537d 3525 continue;
1942a048 3526
0e35537d 3527 case '2':
437e2ff1 3528 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
0e35537d
JW
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 }
0e35537d
JW
3537 INSERT_OPERAND (FUNCT2, *ip, imm_expr->X_add_number);
3538 imm_expr->X_op = O_absent;
6eb099ae 3539 asarg = expr_parse_end;
0e35537d
JW
3540 continue;
3541
3542 default:
437e2ff1 3543 goto unknown_riscv_ip_operand;
0e35537d
JW
3544 }
3545 break;
e23eba97 3546
3d1cafa0 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;
6eb099ae 3555 asarg = expr_parse_end;
3d1cafa0 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;
6eb099ae 3566 asarg = expr_parse_end;
3d1cafa0 3567 continue;
3568
e925c834 3569 case 'z':
437e2ff1 3570 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
e925c834
JW
3571 || imm_expr->X_op != O_constant
3572 || imm_expr->X_add_number != 0)
3573 break;
6eb099ae 3574 asarg = expr_parse_end;
e925c834
JW
3575 imm_expr->X_op = O_absent;
3576 continue;
3577
6de11ff6 3578 case 'W': /* Various operands for standard z extensions. */
54bca63b
TO
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;
6de11ff6 3605
1f3fc45b
CM
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;
b5c37946
SJ
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;
b5c37946
SJ
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;
b5c37946
SJ
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;
b5c37946
SJ
3669 default:
3670 goto unknown_riscv_ip_operand;
3671 }
3672 break;
6de11ff6 3673
54bca63b
TO
3674 default:
3675 goto unknown_riscv_ip_operand;
3676 }
3677 break;
3b374308 3678
6de11ff6
NC
3679 case 'X': /* Vendor-specific operands. */
3680 switch (*++oparg)
3681 {
3682 case 't': /* Vendor-specific (T-head) operands. */
8b7419c4 3683 {
6de11ff6
NC
3684 size_t n;
3685 size_t s;
3686 bool sign;
3687 switch (*++oparg)
3688 {
6a95962e
JM
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
6de11ff6
NC
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:
8b7419c4 3745 goto unknown_riscv_ip_operand;
6de11ff6 3746 }
8b7419c4 3747 }
6de11ff6
NC
3748 break;
3749
ccb388ca
MB
3750 case 'c': /* Vendor-specific (CORE-V) operands. */
3751 switch (*++oparg)
3752 {
d1bd9787
MB
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;
ccb388ca
MB
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
248bf6de
NC
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
6de11ff6
NC
3828 default:
3829 goto unknown_riscv_ip_operand;
3830 }
8b7419c4 3831 break;
54bca63b 3832
e23eba97 3833 default:
437e2ff1
NC
3834 unknown_riscv_ip_operand:
3835 as_fatal (_("internal: unknown argument type `%s'"),
3836 opargStart);
e23eba97
NC
3837 }
3838 break;
3839 }
437e2ff1 3840 asarg = asargStart;
5b7c81bd 3841 insn_with_csr = false;
e23eba97
NC
3842 }
3843
dc1e8a47 3844 out:
e23eba97
NC
3845 /* Restore the character we might have clobbered above. */
3846 if (save_c)
437e2ff1 3847 *(asargStart - 1) = save_c;
e23eba97 3848
7a29ee29
JB
3849 probing_insn_operands = false;
3850
e23eba97
NC
3851 return error;
3852}
3853
a262b82f
NC
3854/* Similar to riscv_ip, but assembles an instruction according to the
3855 hardcode values of .insn directive. */
3856
3857static const char *
3858riscv_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);
bb996692 3871 switch (imm_expr->X_op)
a262b82f 3872 {
bb996692
JB
3873 case O_constant:
3874 values[num++] = (insn_t) imm_expr->X_add_number;
3875 break;
3876 case O_big:
634001bb
TO
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 ();
bb996692
JB
3880 break;
3881 default:
a262b82f
NC
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 }
a262b82f 3889 }
bb996692 3890 while (*input_line_pointer++ == ',' && num < 2 && imm_expr->X_op != O_big);
a262b82f
NC
3891
3892 input_line_pointer--;
3893 if (*input_line_pointer != '\0')
3894 return _("unrecognized values");
3895
cf2ab5ef 3896 insn = XCNEW (struct riscv_opcode);
a262b82f
NC
3897 insn->match = values[num - 1];
3898 create_insn (ip, insn);
3899 unsigned int bytes = riscv_insn_length (insn->match);
bb996692
JB
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 {
634001bb
TO
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)
bb996692 3913 return _("value conflicts with instruction length");
634001bb
TO
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);
bb996692
JB
3925 return NULL;
3926 }
3927
3928 if (bytes < sizeof(values[0]) && values[num - 1] >> (8 * bytes) != 0)
a262b82f
NC
3929 return _("value conflicts with instruction length");
3930
3931 return NULL;
3932}
3933
e23eba97
NC
3934void
3935md_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
dcd709e0
NC
3941 /* The architecture and privileged elf attributes should be set
3942 before assembling. */
8f595e9b
NC
3943 if (!start_assemble)
3944 {
5b7c81bd 3945 start_assemble = true;
e23eba97 3946
dcd709e0 3947 riscv_set_abi_by_arch ();
8f595e9b
NC
3948 if (!riscv_set_default_priv_spec (NULL))
3949 return;
3950 }
3951
3190ebcb 3952 riscv_mapping_state (MAP_INSN, 0, false/* fr_align_code */);
9b9b1092 3953
e4028336
PN
3954 const struct riscv_ip_error error = riscv_ip (str, &insn, &imm_expr,
3955 &imm_reloc, op_hash);
2dc8dd17 3956
e4028336 3957 if (error.msg)
e23eba97 3958 {
e4028336
PN
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);
e23eba97
NC
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
3973const char *
3974md_atof (int type, char *litP, int *sizeP)
3975{
71a75b51 3976 return ieee_md_atof (type, litP, sizeP, target_big_endian);
e23eba97
NC
3977}
3978
3979void
3980md_number_to_chars (char *buf, valueT val, int n)
3981{
fbc09e7a
MC
3982 if (target_big_endian)
3983 number_to_chars_bigendian (buf, val, n);
3984 else
3985 number_to_chars_littleendian (buf, val, n);
e23eba97
NC
3986}
3987
3988const char *md_shortopts = "O::g::G:";
3989
3990enum options
3991{
2922d21d 3992 OPTION_MARCH = OPTION_MD_BASE,
e23eba97
NC
3993 OPTION_PIC,
3994 OPTION_NO_PIC,
2922d21d 3995 OPTION_MABI,
71060565
JW
3996 OPTION_RELAX,
3997 OPTION_NO_RELAX,
2dc8dd17
JW
3998 OPTION_ARCH_ATTR,
3999 OPTION_NO_ARCH_ATTR,
2ca89224
NC
4000 OPTION_CSR_CHECK,
4001 OPTION_NO_CSR_CHECK,
8f595e9b
NC
4002 OPTION_MISA_SPEC,
4003 OPTION_MPRIV_SPEC,
fbc09e7a
MC
4004 OPTION_BIG_ENDIAN,
4005 OPTION_LITTLE_ENDIAN,
e23eba97
NC
4006 OPTION_END_OF_ENUM
4007};
4008
4009struct option md_longopts[] =
4010{
e23eba97
NC
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},
2922d21d 4015 {"mabi", required_argument, NULL, OPTION_MABI},
71060565
JW
4016 {"mrelax", no_argument, NULL, OPTION_RELAX},
4017 {"mno-relax", no_argument, NULL, OPTION_NO_RELAX},
2dc8dd17
JW
4018 {"march-attr", no_argument, NULL, OPTION_ARCH_ATTR},
4019 {"mno-arch-attr", no_argument, NULL, OPTION_NO_ARCH_ATTR},
2ca89224
NC
4020 {"mcsr-check", no_argument, NULL, OPTION_CSR_CHECK},
4021 {"mno-csr-check", no_argument, NULL, OPTION_NO_CSR_CHECK},
8f595e9b
NC
4022 {"misa-spec", required_argument, NULL, OPTION_MISA_SPEC},
4023 {"mpriv-spec", required_argument, NULL, OPTION_MPRIV_SPEC},
fbc09e7a
MC
4024 {"mbig-endian", no_argument, NULL, OPTION_BIG_ENDIAN},
4025 {"mlittle-endian", no_argument, NULL, OPTION_LITTLE_ENDIAN},
e23eba97
NC
4026
4027 {NULL, no_argument, NULL, 0}
4028};
4029size_t md_longopts_size = sizeof (md_longopts);
4030
e23eba97
NC
4031int
4032md_parse_option (int c, const char *arg)
4033{
4034 switch (c)
4035 {
e23eba97 4036 case OPTION_MARCH:
8f595e9b 4037 default_arch_with_ext = arg;
e23eba97
NC
4038 break;
4039
4040 case OPTION_NO_PIC:
5b7c81bd 4041 riscv_opts.pic = false;
e23eba97
NC
4042 break;
4043
4044 case OPTION_PIC:
5b7c81bd 4045 riscv_opts.pic = true;
e23eba97
NC
4046 break;
4047
2922d21d
AW
4048 case OPTION_MABI:
4049 if (strcmp (arg, "ilp32") == 0)
5b7c81bd 4050 riscv_set_abi (32, FLOAT_ABI_SOFT, false);
7f999549 4051 else if (strcmp (arg, "ilp32e") == 0)
5b7c81bd 4052 riscv_set_abi (32, FLOAT_ABI_SOFT, true);
2922d21d 4053 else if (strcmp (arg, "ilp32f") == 0)
5b7c81bd 4054 riscv_set_abi (32, FLOAT_ABI_SINGLE, false);
2922d21d 4055 else if (strcmp (arg, "ilp32d") == 0)
5b7c81bd 4056 riscv_set_abi (32, FLOAT_ABI_DOUBLE, false);
2922d21d 4057 else if (strcmp (arg, "ilp32q") == 0)
5b7c81bd 4058 riscv_set_abi (32, FLOAT_ABI_QUAD, false);
2922d21d 4059 else if (strcmp (arg, "lp64") == 0)
5b7c81bd 4060 riscv_set_abi (64, FLOAT_ABI_SOFT, false);
6674b23f
TO
4061 else if (strcmp (arg, "lp64e") == 0)
4062 riscv_set_abi (64, FLOAT_ABI_SOFT, true);
2922d21d 4063 else if (strcmp (arg, "lp64f") == 0)
5b7c81bd 4064 riscv_set_abi (64, FLOAT_ABI_SINGLE, false);
2922d21d 4065 else if (strcmp (arg, "lp64d") == 0)
5b7c81bd 4066 riscv_set_abi (64, FLOAT_ABI_DOUBLE, false);
2922d21d 4067 else if (strcmp (arg, "lp64q") == 0)
5b7c81bd 4068 riscv_set_abi (64, FLOAT_ABI_QUAD, false);
2922d21d
AW
4069 else
4070 return 0;
5b7c81bd 4071 explicit_mabi = true;
2922d21d
AW
4072 break;
4073
71060565 4074 case OPTION_RELAX:
5b7c81bd 4075 riscv_opts.relax = true;
71060565
JW
4076 break;
4077
4078 case OPTION_NO_RELAX:
5b7c81bd 4079 riscv_opts.relax = false;
71060565
JW
4080 break;
4081
2dc8dd17 4082 case OPTION_ARCH_ATTR:
5b7c81bd 4083 riscv_opts.arch_attr = true;
2dc8dd17
JW
4084 break;
4085
4086 case OPTION_NO_ARCH_ATTR:
5b7c81bd 4087 riscv_opts.arch_attr = false;
2dc8dd17
JW
4088 break;
4089
2ca89224 4090 case OPTION_CSR_CHECK:
5b7c81bd 4091 riscv_opts.csr_check = true;
2ca89224
NC
4092 break;
4093
4094 case OPTION_NO_CSR_CHECK:
5b7c81bd 4095 riscv_opts.csr_check = false;
2ca89224
NC
4096 break;
4097
8f595e9b
NC
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
fbc09e7a
MC
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
e23eba97
NC
4112 default:
4113 return 0;
4114 }
4115
4116 return 1;
4117}
4118
4119void
4120riscv_after_parse_args (void)
4121{
dcd709e0
NC
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. */
e23eba97
NC
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 }
8f595e9b 4133
dcd709e0 4134 /* Set default specs. */
8f595e9b
NC
4135 if (default_isa_spec == ISA_SPEC_CLASS_NONE)
4136 riscv_set_default_isa_spec (DEFAULT_RISCV_ISA_SPEC);
dcd709e0
NC
4137 if (default_priv_spec == PRIV_SPEC_CLASS_NONE)
4138 riscv_set_default_priv_spec (DEFAULT_RISCV_PRIV_SPEC);
2922d21d 4139
8f595e9b 4140 riscv_set_arch (default_arch_with_ext);
2922d21d 4141
0ac2b354
AB
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;
e23eba97
NC
4147}
4148
7a29ee29
JB
4149bool 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
e23eba97
NC
4196long
4197md_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
4204void
4205md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
4206{
45f76423 4207 unsigned int subtype;
e23eba97 4208 bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
5b7c81bd 4209 bool relaxable = false;
c1b465c9 4210 offsetT loc;
a6cbf936 4211 segT sub_segment;
e23eba97
NC
4212
4213 /* Remember value for tc_gen_reloc. */
4214 fixP->fx_addnumber = *valP;
4215
4216 switch (fixP->fx_r_type)
4217 {
e23eba97
NC
4218 case BFD_RELOC_RISCV_HI20:
4219 case BFD_RELOC_RISCV_LO12_I:
4220 case BFD_RELOC_RISCV_LO12_S:
45f76423
AW
4221 bfd_putl32 (riscv_apply_const_reloc (fixP->fx_r_type, *valP)
4222 | bfd_getl32 (buf), buf);
a5ec5e3f 4223 if (fixP->fx_addsy == NULL)
5b7c81bd
AM
4224 fixP->fx_done = true;
4225 relaxable = true;
45f76423
AW
4226 break;
4227
4228 case BFD_RELOC_RISCV_GOT_HI20:
bf69326f
RU
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
e23eba97
NC
4236 case BFD_RELOC_RISCV_ADD8:
4237 case BFD_RELOC_RISCV_ADD16:
4238 case BFD_RELOC_RISCV_ADD32:
4239 case BFD_RELOC_RISCV_ADD64:
45f76423 4240 case BFD_RELOC_RISCV_SUB6:
e23eba97
NC
4241 case BFD_RELOC_RISCV_SUB8:
4242 case BFD_RELOC_RISCV_SUB16:
4243 case BFD_RELOC_RISCV_SUB32:
4244 case BFD_RELOC_RISCV_SUB64:
45f76423 4245 case BFD_RELOC_RISCV_RELAX:
f1cd8b94
KLC
4246 /* cvt_frag_to_fill () has called output_leb128 (). */
4247 case BFD_RELOC_RISCV_SET_ULEB128:
4248 case BFD_RELOC_RISCV_SUB_ULEB128:
45f76423
AW
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:
5b7c81bd 4255 relaxable = true;
45f76423
AW
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:
e294484e
AW
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"));
e23eba97
NC
4267 break;
4268
e23eba97 4269 case BFD_RELOC_32:
a6cbf936
KLC
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
dcd709e0 4275 in .eh_frame. Othrewise, the value may be adjusted twice. */
a6cbf936
KLC
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:
e23eba97
NC
4288 case BFD_RELOC_16:
4289 case BFD_RELOC_8:
45f76423 4290 case BFD_RELOC_RISCV_CFA:
e23eba97
NC
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;
073808ed 4319 break;
e23eba97 4320
45f76423
AW
4321 case BFD_RELOC_RISCV_CFA:
4322 /* Load the byte to get the subtype. */
c1b465c9
KLC
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);
45f76423
AW
4325 switch (subtype)
4326 {
4327 case DW_CFA_advance_loc1:
c1b465c9
KLC
4328 fixP->fx_where = loc + 1;
4329 fixP->fx_next->fx_where = loc + 1;
45f76423
AW
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;
45f76423 4336 fixP->fx_next->fx_size = 2;
c1b465c9
KLC
4337 fixP->fx_where = loc + 1;
4338 fixP->fx_next->fx_where = loc + 1;
45f76423
AW
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;
45f76423 4345 fixP->fx_next->fx_size = 4;
c1b465c9
KLC
4346 fixP->fx_where = loc;
4347 fixP->fx_next->fx_where = loc;
45f76423
AW
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 */
2aece2ba
KLC
4356 fixP->fx_frag = (fragS *) fixP->fx_frag->fr_opcode;
4357 fixP->fx_next->fx_frag = fixP->fx_frag;
45f76423
AW
4358 fixP->fx_r_type = BFD_RELOC_RISCV_SET6;
4359 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB6;
4360 }
4361 else
b800637e 4362 as_fatal (_("internal: bad CFA value #%d"), subtype);
45f76423
AW
4363 break;
4364 }
4365 break;
4366
e23eba97
NC
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);
5a9f5403 4392 bfd_putl32 (bfd_getl32 (buf) | ENCODE_JTYPE_IMM (delta), buf);
af514e5f
NC
4393 if (!riscv_opts.relax && S_IS_LOCAL (fixP->fx_addsy))
4394 fixP->fx_done = 1;
e23eba97
NC
4395 }
4396 break;
4397
4398 case BFD_RELOC_12_PCREL:
4399 if (fixP->fx_addsy)
4400 {
4401 /* Fill in a tentative value to improve objdump readability. */
4402 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4403 bfd_vma delta = target - md_pcrel_from (fixP);
5a9f5403 4404 bfd_putl32 (bfd_getl32 (buf) | ENCODE_BTYPE_IMM (delta), buf);
af514e5f
NC
4405 if (!riscv_opts.relax && S_IS_LOCAL (fixP->fx_addsy))
4406 fixP->fx_done = 1;
e23eba97
NC
4407 }
4408 break;
4409
4410 case BFD_RELOC_RISCV_RVC_BRANCH:
4411 if (fixP->fx_addsy)
4412 {
4413 /* Fill in a tentative value to improve objdump readability. */
4414 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4415 bfd_vma delta = target - md_pcrel_from (fixP);
5a9f5403 4416 bfd_putl16 (bfd_getl16 (buf) | ENCODE_CBTYPE_IMM (delta), buf);
af514e5f
NC
4417 if (!riscv_opts.relax && S_IS_LOCAL (fixP->fx_addsy))
4418 fixP->fx_done = 1;
e23eba97
NC
4419 }
4420 break;
4421
4422 case BFD_RELOC_RISCV_RVC_JUMP:
4423 if (fixP->fx_addsy)
4424 {
4425 /* Fill in a tentative value to improve objdump readability. */
4426 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4427 bfd_vma delta = target - md_pcrel_from (fixP);
5a9f5403 4428 bfd_putl16 (bfd_getl16 (buf) | ENCODE_CJTYPE_IMM (delta), buf);
af514e5f
NC
4429 if (!riscv_opts.relax && S_IS_LOCAL (fixP->fx_addsy))
4430 fixP->fx_done = 1;
e23eba97
NC
4431 }
4432 break;
4433
e23eba97
NC
4434 case BFD_RELOC_RISCV_CALL:
4435 case BFD_RELOC_RISCV_CALL_PLT:
5b7c81bd 4436 relaxable = true;
45f76423
AW
4437 break;
4438
9d06997a 4439 case BFD_RELOC_RISCV_PCREL_HI20:
dff565fc
LX
4440 /* Record and evaluate the pcrel_hi relocation with local symbol.
4441 Fill in a tentative value to improve objdump readability for -mrelax,
4442 and set fx_done for -mno-relax. */
4443 if (fixP->fx_addsy
4444 && S_IS_LOCAL (fixP->fx_addsy)
4445 && S_GET_SEGMENT (fixP->fx_addsy) == seg)
4446 {
4447 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4448 bfd_vma value = target - md_pcrel_from (fixP);
4449
4450 /* Record PCREL_HI20. */
4451 if (!riscv_record_pcrel_fixup (riscv_pcrel_hi_fixup_hash,
4452 md_pcrel_from (fixP),
4453 fixP->fx_addsy,
4454 target))
4455 as_warn (_("too many pcrel_hi"));
4456
14f2724f
NC
4457 bfd_putl32 (bfd_getl32 (buf)
4458 | ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)),
4459 buf);
4460 if (!riscv_opts.relax)
4461 fixP->fx_done = 1;
dff565fc
LX
4462 }
4463 relaxable = true;
4464 break;
4465
45f76423
AW
4466 case BFD_RELOC_RISCV_PCREL_LO12_S:
4467 case BFD_RELOC_RISCV_PCREL_LO12_I:
dff565fc
LX
4468 /* Resolve the pcrel_lo relocation with local symbol.
4469 Fill in a tentative value to improve objdump readability for -mrelax,
4470 and set fx_done for -mno-relax. */
4471 {
4472 bfd_vma location_pcrel_hi = S_GET_VALUE (fixP->fx_addsy) + *valP;
4473 riscv_pcrel_hi_fixup search = {location_pcrel_hi, 0, 0};
4474 riscv_pcrel_hi_fixup *entry = htab_find (riscv_pcrel_hi_fixup_hash,
4475 &search);
4476 if (entry && entry->symbol
4477 && S_IS_LOCAL (entry->symbol)
4478 && S_GET_SEGMENT (entry->symbol) == seg)
4479 {
4480 bfd_vma target = entry->target;
4481 bfd_vma value = target - entry->address;
4482 bfd_putl32 (bfd_getl32 (buf) | ENCODE_ITYPE_IMM (value), buf);
4483 /* Relaxations should never be enabled by `.option relax'. */
4484 if (!riscv_opts.relax)
4485 fixP->fx_done = 1;
4486 }
4487 }
88420300 4488 relaxable = true;
9d06997a
PD
4489 break;
4490
e23eba97
NC
4491 case BFD_RELOC_RISCV_ALIGN:
4492 break;
4493
4494 default:
4495 /* We ignore generic BFD relocations we don't know about. */
4496 if (bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type) != NULL)
b800637e 4497 as_fatal (_("internal: bad relocation #%d"), fixP->fx_r_type);
e23eba97 4498 }
45f76423 4499
e294484e 4500 if (fixP->fx_subsy != NULL)
4bf09429 4501 as_bad_subtract (fixP);
e294484e 4502
45f76423
AW
4503 /* Add an R_RISCV_RELAX reloc if the reloc is relaxable. */
4504 if (relaxable && fixP->fx_tcbit && fixP->fx_addsy != NULL)
4505 {
4506 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
4507 fixP->fx_next->fx_addsy = fixP->fx_next->fx_subsy = NULL;
4508 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_RELAX;
b1b11e92 4509 fixP->fx_next->fx_size = 0;
45f76423
AW
4510 }
4511}
4512
4513/* Because the value of .cfi_remember_state may changed after relaxation,
4514 we insert a fix to relocate it again in link-time. */
4515
4516void
4517riscv_pre_output_hook (void)
4518{
4519 const frchainS *frch;
72393fd1
JW
4520 segT s;
4521
4522 /* Save the current segment info. */
4523 segT seg = now_seg;
4524 subsegT subseg = now_subseg;
45f76423
AW
4525
4526 for (s = stdoutput->sections; s; s = s->next)
4527 for (frch = seg_info (s)->frchainP; frch; frch = frch->frch_next)
4528 {
7cb7b948 4529 fragS *frag;
45f76423
AW
4530
4531 for (frag = frch->frch_root; frag; frag = frag->fr_next)
4532 {
4533 if (frag->fr_type == rs_cfa)
4534 {
45f76423 4535 expressionS exp;
8d1015a8 4536 expressionS *symval;
45f76423 4537
8d1015a8 4538 symval = symbol_get_value_expression (frag->fr_symbol);
45f76423 4539 exp.X_op = O_subtract;
8d1015a8 4540 exp.X_add_symbol = symval->X_add_symbol;
45f76423 4541 exp.X_add_number = 0;
8d1015a8 4542 exp.X_op_symbol = symval->X_op_symbol;
45f76423 4543
72393fd1
JW
4544 /* We must set the segment before creating a frag after all
4545 frag chains have been chained together. */
4546 subseg_set (s, frch->frch_subseg);
4547
c1b465c9 4548 fix_new_exp (frag, (int) frag->fr_offset, 1, &exp, 0,
45f76423
AW
4549 BFD_RELOC_RISCV_CFA);
4550 }
4551 }
4552 }
72393fd1
JW
4553
4554 /* Restore the original segment info. */
4555 subseg_set (seg, subseg);
e23eba97
NC
4556}
4557
e23eba97
NC
4558/* Handle the .option pseudo-op. */
4559
4560static void
4561s_riscv_option (int x ATTRIBUTE_UNUSED)
4562{
4563 char *name = input_line_pointer, ch;
4564
4565 while (!is_end_of_line[(unsigned char) *input_line_pointer])
4566 ++input_line_pointer;
4567 ch = *input_line_pointer;
4568 *input_line_pointer = '\0';
4569
4570 if (strcmp (name, "rvc") == 0)
edc77c59 4571 {
d3ffd7f7 4572 riscv_update_subset (&riscv_rps_as, "+c");
40f1a1a4 4573 riscv_reset_subsets_list_arch_str ();
edc77c59
NC
4574 riscv_set_rvc (true);
4575 }
e23eba97 4576 else if (strcmp (name, "norvc") == 0)
edc77c59 4577 {
d3ffd7f7 4578 riscv_update_subset (&riscv_rps_as, "-c");
40f1a1a4 4579 riscv_reset_subsets_list_arch_str ();
edc77c59
NC
4580 riscv_set_rvc (false);
4581 }
e23eba97 4582 else if (strcmp (name, "pic") == 0)
5b7c81bd 4583 riscv_opts.pic = true;
e23eba97 4584 else if (strcmp (name, "nopic") == 0)
5b7c81bd 4585 riscv_opts.pic = false;
45f76423 4586 else if (strcmp (name, "relax") == 0)
5b7c81bd 4587 riscv_opts.relax = true;
45f76423 4588 else if (strcmp (name, "norelax") == 0)
5b7c81bd 4589 riscv_opts.relax = false;
2ca89224 4590 else if (strcmp (name, "csr-check") == 0)
5b7c81bd 4591 riscv_opts.csr_check = true;
2ca89224 4592 else if (strcmp (name, "no-csr-check") == 0)
5b7c81bd 4593 riscv_opts.csr_check = false;
d3ffd7f7
NC
4594 else if (strncmp (name, "arch,", 5) == 0)
4595 {
4596 name += 5;
4597 if (ISSPACE (*name) && *name != '\0')
4598 name++;
4599 riscv_update_subset (&riscv_rps_as, name);
40f1a1a4 4600 riscv_reset_subsets_list_arch_str ();
e7e599a1
NC
4601
4602 riscv_set_rvc (false);
b5c37946
SJ
4603 if (riscv_subset_supports (&riscv_rps_as, "c")
4604 || riscv_subset_supports (&riscv_rps_as, "zca"))
e7e599a1 4605 riscv_set_rvc (true);
acab2a68
TO
4606
4607 if (riscv_subset_supports (&riscv_rps_as, "ztso"))
4608 riscv_set_tso ();
d3ffd7f7 4609 }
e23eba97
NC
4610 else if (strcmp (name, "push") == 0)
4611 {
4612 struct riscv_option_stack *s;
4613
d3ffd7f7 4614 s = XNEW (struct riscv_option_stack);
e23eba97
NC
4615 s->next = riscv_opts_stack;
4616 s->options = riscv_opts;
f5cb31a8 4617 s->subset_list = riscv_rps_as.subset_list;
e23eba97 4618 riscv_opts_stack = s;
f5cb31a8 4619 riscv_rps_as.subset_list = riscv_copy_subset_list (s->subset_list);
e23eba97
NC
4620 }
4621 else if (strcmp (name, "pop") == 0)
4622 {
4623 struct riscv_option_stack *s;
4624
4625 s = riscv_opts_stack;
4626 if (s == NULL)
4627 as_bad (_(".option pop with no .option push"));
4628 else
4629 {
f5cb31a8 4630 riscv_subset_list_t *release_subsets = riscv_rps_as.subset_list;
e23eba97 4631 riscv_opts_stack = s->next;
d3ffd7f7 4632 riscv_opts = s->options;
f5cb31a8 4633 riscv_rps_as.subset_list = s->subset_list;
d3ffd7f7 4634 riscv_release_subset_list (release_subsets);
e23eba97
NC
4635 free (s);
4636 }
4637 }
4638 else
4639 {
c84b3d7e 4640 as_warn (_("unrecognized .option directive: %s"), name);
e23eba97
NC
4641 }
4642 *input_line_pointer = ch;
4643 demand_empty_rest_of_line ();
4644}
4645
4646/* Handle the .dtprelword and .dtpreldword pseudo-ops. They generate
4647 a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
4648 use in DWARF debug information. */
4649
4650static void
4651s_dtprel (int bytes)
4652{
4653 expressionS ex;
4654 char *p;
4655
4656 expression (&ex);
4657
4658 if (ex.X_op != O_symbol)
4659 {
b800637e 4660 as_bad (_("unsupported use of %s"), (bytes == 8
e23eba97
NC
4661 ? ".dtpreldword"
4662 : ".dtprelword"));
4663 ignore_rest_of_line ();
4664 }
4665
4666 p = frag_more (bytes);
4667 md_number_to_chars (p, 0, bytes);
5b7c81bd 4668 fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, false,
e23eba97
NC
4669 (bytes == 8
4670 ? BFD_RELOC_RISCV_TLS_DTPREL64
4671 : BFD_RELOC_RISCV_TLS_DTPREL32));
4672
4673 demand_empty_rest_of_line ();
4674}
4675
e23eba97 4676static void
d115ab8e 4677riscv_make_nops (char *buf, bfd_vma bytes)
e23eba97 4678{
d115ab8e 4679 bfd_vma i = 0;
e23eba97 4680
e5b737de
AW
4681 /* RISC-V instructions cannot begin or end on odd addresses, so this case
4682 means we are not within a valid instruction sequence. It is thus safe
4683 to use a zero byte, even though that is not a valid instruction. */
4684 if (bytes % 2 == 1)
4685 buf[i++] = 0;
4686
4687 /* Use at most one 2-byte NOP. */
4688 if ((bytes - i) % 4 == 2)
e23eba97 4689 {
fbc09e7a 4690 number_to_chars_littleendian (buf + i, RVC_NOP, 2);
d115ab8e 4691 i += 2;
e23eba97
NC
4692 }
4693
e5b737de 4694 /* Fill the remainder with 4-byte NOPs. */
d115ab8e 4695 for ( ; i < bytes; i += 4)
fbc09e7a 4696 number_to_chars_littleendian (buf + i, RISCV_NOP, 4);
d115ab8e 4697}
e23eba97 4698
d115ab8e
AW
4699/* Called from md_do_align. Used to create an alignment frag in a
4700 code section by emitting a worst-case NOP sequence that the linker
4701 will later relax to the correct number of NOPs. We can't compute
4702 the correct alignment now because of other linker relaxations. */
4703
5b7c81bd 4704bool
d115ab8e
AW
4705riscv_frag_align_code (int n)
4706{
e5b737de 4707 bfd_vma bytes = (bfd_vma) 1 << n;
36877bfb
JW
4708 bfd_vma insn_alignment = riscv_opts.rvc ? 2 : 4;
4709 bfd_vma worst_case_bytes = bytes - insn_alignment;
4710 char *nops;
ed0816bd 4711 expressionS ex;
d115ab8e 4712
36877bfb
JW
4713 /* If we are moving to a smaller alignment than the instruction size, then no
4714 alignment is required. */
4715 if (bytes <= insn_alignment)
5b7c81bd 4716 return true;
36877bfb 4717
d115ab8e
AW
4718 /* When not relaxing, riscv_handle_align handles code alignment. */
4719 if (!riscv_opts.relax)
5b7c81bd 4720 return false;
e23eba97 4721
40f1a1a4
NC
4722 /* Maybe we should use frag_var to create a new rs_align_code fragment,
4723 rather than just use frag_more to handle an alignment here? So that we
4724 don't need to call riscv_mapping_state again later, and then only need
4725 to check frag->fr_type to see if it is frag_align_code. */
e80ae190
JW
4726 nops = frag_more (worst_case_bytes);
4727
ed0816bd
PD
4728 ex.X_op = O_constant;
4729 ex.X_add_number = worst_case_bytes;
d115ab8e 4730
ed0816bd 4731 riscv_make_nops (nops, worst_case_bytes);
e23eba97 4732
ed0816bd 4733 fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
5b7c81bd 4734 &ex, false, BFD_RELOC_RISCV_ALIGN);
e23eba97 4735
3190ebcb 4736 riscv_mapping_state (MAP_INSN, worst_case_bytes, true/* fr_align_code */);
9b9b1092 4737
cb2562f5
LX
4738 /* We need to start a new frag after the alignment which may be removed by
4739 the linker, to prevent the assembler from computing static offsets.
4740 This is necessary to get correct EH info. */
4741 frag_wane (frag_now);
4742 frag_new (0);
4743
5b7c81bd 4744 return true;
d115ab8e 4745}
e23eba97 4746
d115ab8e
AW
4747/* Implement HANDLE_ALIGN. */
4748
4749void
4750riscv_handle_align (fragS *fragP)
4751{
4752 switch (fragP->fr_type)
4753 {
4754 case rs_align_code:
4755 /* When relaxing, riscv_frag_align_code handles code alignment. */
4756 if (!riscv_opts.relax)
4757 {
e80ae190
JW
4758 bfd_signed_vma bytes = (fragP->fr_next->fr_address
4759 - fragP->fr_address - fragP->fr_fix);
4760 /* We have 4 byte uncompressed nops. */
4761 bfd_signed_vma size = 4;
4762 bfd_signed_vma excess = bytes % size;
9b9b1092 4763 bfd_boolean odd_padding = (excess % 2 == 1);
e80ae190
JW
4764 char *p = fragP->fr_literal + fragP->fr_fix;
4765
4766 if (bytes <= 0)
d115ab8e
AW
4767 break;
4768
e80ae190
JW
4769 /* Insert zeros or compressed nops to get 4 byte alignment. */
4770 if (excess)
4771 {
9b9b1092
NC
4772 if (odd_padding)
4773 riscv_add_odd_padding_symbol (fragP);
e80ae190
JW
4774 riscv_make_nops (p, excess);
4775 fragP->fr_fix += excess;
4776 p += excess;
4777 }
4778
9b9b1092
NC
4779 /* The frag will be changed to `rs_fill` later. The function
4780 `write_contents` will try to fill the remaining spaces
4781 according to the patterns we give. In this case, we give
4782 a 4 byte uncompressed nop as the pattern, and set the size
4783 of the pattern into `fr_var`. The nop will be output to the
4784 file `fr_offset` times. However, `fr_offset` could be zero
4785 if we don't need to pad the boundary finally. */
e80ae190
JW
4786 riscv_make_nops (p, size);
4787 fragP->fr_var = size;
d115ab8e
AW
4788 }
4789 break;
4790
4791 default:
4792 break;
4793 }
e23eba97
NC
4794}
4795
9b9b1092
NC
4796/* This usually called from frag_var. */
4797
4798void
4799riscv_init_frag (fragS * fragP, int max_chars)
4800{
4801 /* Do not add mapping symbol to debug sections. */
4802 if (bfd_section_flags (now_seg) & SEC_DEBUGGING)
4803 return;
4804
4805 switch (fragP->fr_type)
4806 {
4807 case rs_fill:
4808 case rs_align:
4809 case rs_align_test:
3190ebcb 4810 riscv_mapping_state (MAP_DATA, max_chars, false/* fr_align_code */);
9b9b1092
NC
4811 break;
4812 case rs_align_code:
3190ebcb 4813 riscv_mapping_state (MAP_INSN, max_chars, true/* fr_align_code */);
9b9b1092
NC
4814 break;
4815 default:
4816 break;
4817 }
4818}
4819
e23eba97
NC
4820int
4821md_estimate_size_before_relax (fragS *fragp, asection *segtype)
4822{
5b7c81bd 4823 return (fragp->fr_var = relaxed_branch_length (fragp, segtype, false));
e23eba97
NC
4824}
4825
4826/* Translate internal representation of relocation info to BFD target
4827 format. */
4828
4829arelent *
4830tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
4831{
4832 arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
4833
4834 reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
4835 *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
4836 reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
4837 reloc->addend = fixp->fx_addnumber;
4838
4839 reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
4840 if (reloc->howto == NULL)
4841 {
4842 if ((fixp->fx_r_type == BFD_RELOC_16 || fixp->fx_r_type == BFD_RELOC_8)
4843 && fixp->fx_addsy != NULL && fixp->fx_subsy != NULL)
4844 {
4845 /* We don't have R_RISCV_8/16, but for this special case,
4846 we can use R_RISCV_ADD8/16 with R_RISCV_SUB8/16. */
4847 return reloc;
4848 }
4849
4850 as_bad_where (fixp->fx_file, fixp->fx_line,
4851 _("cannot represent %s relocation in object file"),
4852 bfd_get_reloc_code_name (fixp->fx_r_type));
4853 return NULL;
4854 }
4855
4856 return reloc;
4857}
4858
4859int
4860riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
4861{
4862 if (RELAX_BRANCH_P (fragp->fr_subtype))
4863 {
4864 offsetT old_var = fragp->fr_var;
5b7c81bd 4865 fragp->fr_var = relaxed_branch_length (fragp, sec, true);
e23eba97
NC
4866 return fragp->fr_var - old_var;
4867 }
4868
4869 return 0;
4870}
4871
4872/* Expand far branches to multi-instruction sequences. */
4873
4874static void
4875md_convert_frag_branch (fragS *fragp)
4876{
4877 bfd_byte *buf;
4878 expressionS exp;
4879 fixS *fixp;
4880 insn_t insn;
4881 int rs1, reloc;
4882
4883 buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
4884
4885 exp.X_op = O_symbol;
4886 exp.X_add_symbol = fragp->fr_symbol;
4887 exp.X_add_number = fragp->fr_offset;
4888
4889 gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
4890
4891 if (RELAX_BRANCH_RVC (fragp->fr_subtype))
4892 {
4893 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
4894 {
4895 case 8:
4896 case 4:
4897 /* Expand the RVC branch into a RISC-V one. */
4898 insn = bfd_getl16 (buf);
4899 rs1 = 8 + ((insn >> OP_SH_CRS1S) & OP_MASK_CRS1S);
4900 if ((insn & MASK_C_J) == MATCH_C_J)
4901 insn = MATCH_JAL;
4902 else if ((insn & MASK_C_JAL) == MATCH_C_JAL)
4903 insn = MATCH_JAL | (X_RA << OP_SH_RD);
4904 else if ((insn & MASK_C_BEQZ) == MATCH_C_BEQZ)
4905 insn = MATCH_BEQ | (rs1 << OP_SH_RS1);
4906 else if ((insn & MASK_C_BNEZ) == MATCH_C_BNEZ)
4907 insn = MATCH_BNE | (rs1 << OP_SH_RS1);
4908 else
4909 abort ();
4910 bfd_putl32 (insn, buf);
4911 break;
4912
4913 case 6:
4914 /* Invert the branch condition. Branch over the jump. */
4915 insn = bfd_getl16 (buf);
4916 insn ^= MATCH_C_BEQZ ^ MATCH_C_BNEZ;
5a9f5403 4917 insn |= ENCODE_CBTYPE_IMM (6);
e23eba97
NC
4918 bfd_putl16 (insn, buf);
4919 buf += 2;
4920 goto jump;
4921
4922 case 2:
4923 /* Just keep the RVC branch. */
4924 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
4925 ? BFD_RELOC_RISCV_RVC_JUMP : BFD_RELOC_RISCV_RVC_BRANCH;
4926 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
5b7c81bd 4927 2, &exp, false, reloc);
e23eba97
NC
4928 buf += 2;
4929 goto done;
4930
4931 default:
1d65abb5 4932 abort ();
e23eba97
NC
4933 }
4934 }
4935
4936 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
4937 {
4938 case 8:
4939 gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
4940
4941 /* Invert the branch condition. Branch over the jump. */
4942 insn = bfd_getl32 (buf);
4943 insn ^= MATCH_BEQ ^ MATCH_BNE;
5a9f5403 4944 insn |= ENCODE_BTYPE_IMM (8);
fbc09e7a 4945 bfd_putl32 (insn, buf);
e23eba97
NC
4946 buf += 4;
4947
dc1e8a47 4948 jump:
e23eba97
NC
4949 /* Jump to the target. */
4950 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
5b7c81bd 4951 4, &exp, false, BFD_RELOC_RISCV_JMP);
fbc09e7a 4952 bfd_putl32 (MATCH_JAL, buf);
e23eba97
NC
4953 buf += 4;
4954 break;
4955
4956 case 4:
4957 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
4958 ? BFD_RELOC_RISCV_JMP : BFD_RELOC_12_PCREL;
4959 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
5b7c81bd 4960 4, &exp, false, reloc);
e23eba97
NC
4961 buf += 4;
4962 break;
4963
4964 default:
4965 abort ();
4966 }
4967
dc1e8a47 4968 done:
e23eba97
NC
4969 fixp->fx_file = fragp->fr_file;
4970 fixp->fx_line = fragp->fr_line;
4971
4972 gas_assert (buf == (bfd_byte *)fragp->fr_literal
4973 + fragp->fr_fix + fragp->fr_var);
4974
4975 fragp->fr_fix += fragp->fr_var;
4976}
4977
4978/* Relax a machine dependent frag. This returns the amount by which
4979 the current size of the frag should change. */
4980
4981void
4982md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
4983 fragS *fragp)
4984{
4985 gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
4986 md_convert_frag_branch (fragp);
4987}
4988
4989void
4990md_show_usage (FILE *stream)
4991{
4992 fprintf (stream, _("\
4993RISC-V options:\n\
437e2ff1 4994 -fpic or -fPIC generate position-independent code\n\
8f595e9b
NC
4995 -fno-pic don't generate position-independent code (default)\n\
4996 -march=ISA set the RISC-V architecture\n\
4997 -misa-spec=ISAspec set the RISC-V ISA spec (2.2, 20190608, 20191213)\n\
86d39e66 4998 -mpriv-spec=PRIVspec set the RISC-V privilege spec (1.9.1, 1.10, 1.11, 1.12)\n\
8f595e9b
NC
4999 -mabi=ABI set the RISC-V ABI\n\
5000 -mrelax enable relax (default)\n\
5001 -mno-relax disable relax\n\
5002 -march-attr generate RISC-V arch attribute\n\
5003 -mno-arch-attr don't generate RISC-V arch attribute\n\
437e2ff1
NC
5004 -mcsr-check enable the csr ISA and privilege spec version checks\n\
5005 -mno-csr-check disable the csr ISA and privilege spec version checks (default)\n\
5006 -mbig-endian assemble for big-endian\n\
5007 -mlittle-endian assemble for little-endian\n\
e23eba97
NC
5008"));
5009}
5010
5011/* Standard calling conventions leave the CFA at SP on entry. */
dcd709e0 5012
e23eba97
NC
5013void
5014riscv_cfi_frame_initial_instructions (void)
5015{
5016 cfi_add_CFA_def_cfa_register (X_SP);
5017}
5018
5019int
5020tc_riscv_regname_to_dw2regnum (char *regname)
5021{
5022 int reg;
5023
5024 if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
5025 return reg;
5026
5027 if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
5028 return reg + 32;
5029
7b4f2407
TO
5030 if ((reg = reg_lookup_internal (regname, RCLASS_VECR)) >= 0)
5031 return reg + 96;
5032
4762fe62
AB
5033 /* CSRs are numbered 4096 -> 8191. */
5034 if ((reg = reg_lookup_internal (regname, RCLASS_CSR)) >= 0)
5035 return reg + 4096;
5036
e23eba97
NC
5037 as_bad (_("unknown register `%s'"), regname);
5038 return -1;
5039}
5040
5041void
5042riscv_elf_final_processing (void)
5043{
6e1605e4 5044 riscv_set_abi_by_arch ();
40f1a1a4 5045 riscv_release_subset_list (riscv_rps_as.subset_list);
e23eba97 5046 elf_elfheader (stdoutput)->e_flags |= elf_flags;
e23eba97
NC
5047}
5048
5049/* Parse the .sleb128 and .uleb128 pseudos. Only allow constant expressions,
5050 since these directives break relaxation when used with symbol deltas. */
5051
5052static void
5053s_riscv_leb128 (int sign)
5054{
5055 expressionS exp;
5056 char *save_in = input_line_pointer;
5057
5058 expression (&exp);
f1cd8b94
KLC
5059 if (sign && exp.X_op != O_constant)
5060 as_bad (_("non-constant .sleb128 is not supported"));
5061 else if (!sign && exp.X_op != O_constant && exp.X_op != O_subtract)
5062 as_bad (_(".uleb128 only supports constant or subtract expressions"));
5063
e23eba97
NC
5064 demand_empty_rest_of_line ();
5065
5066 input_line_pointer = save_in;
5067 return s_leb128 (sign);
5068}
5069
a262b82f
NC
5070/* Parse the .insn directive. There are three formats,
5071 Format 1: .insn <type> <operand1>, <operand2>, ...
5072 Format 2: .insn <length>, <value>
5073 Format 3: .insn <value>. */
0e35537d
JW
5074
5075static void
5076s_riscv_insn (int x ATTRIBUTE_UNUSED)
5077{
5078 char *str = input_line_pointer;
5079 struct riscv_cl_insn insn;
5080 expressionS imm_expr;
5081 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
5082 char save_c;
5083
5084 while (!is_end_of_line[(unsigned char) *input_line_pointer])
5085 ++input_line_pointer;
5086
5087 save_c = *input_line_pointer;
5088 *input_line_pointer = '\0';
5089
3190ebcb 5090 riscv_mapping_state (MAP_INSN, 0, false/* fr_align_code */);
9b9b1092 5091
e4028336 5092 struct riscv_ip_error error = riscv_ip (str, &insn, &imm_expr,
0e35537d 5093 &imm_reloc, insn_type_hash);
e4028336 5094 if (error.msg)
0e35537d 5095 {
a262b82f 5096 char *save_in = input_line_pointer;
e4028336 5097 error.msg = riscv_ip_hardcode (str, &insn, &imm_expr, error.msg);
a262b82f 5098 input_line_pointer = save_in;
0e35537d 5099 }
a262b82f 5100
e4028336
PN
5101 if (error.msg)
5102 {
5103 if (error.missing_ext)
5104 as_bad ("%s `%s', extension `%s' required", error.msg, error.statement,
5105 error.missing_ext);
5106 else
5107 as_bad ("%s `%s'", error.msg, error.statement);
5108 }
634001bb 5109 else
0e35537d
JW
5110 {
5111 gas_assert (insn.insn_mo->pinfo != INSN_MACRO);
5112 append_insn (&insn, &imm_expr, imm_reloc);
5113 }
5114
5115 *input_line_pointer = save_c;
5116 demand_empty_rest_of_line ();
5117}
5118
dcd709e0
NC
5119/* Update architecture and privileged elf attributes. If we don't set
5120 them, then try to output the default ones. */
2dc8dd17
JW
5121
5122static void
8f595e9b 5123riscv_write_out_attrs (void)
2dc8dd17 5124{
8f595e9b 5125 const char *arch_str, *priv_str, *p;
dcd709e0
NC
5126 /* versions[0]: major version.
5127 versions[1]: minor version.
5128 versions[2]: revision version. */
8f595e9b
NC
5129 unsigned versions[3] = {0}, number = 0;
5130 unsigned int i;
2dc8dd17 5131
dcd709e0 5132 /* Re-write architecture elf attribute. */
40f1a1a4 5133 arch_str = riscv_rps_as.subset_list->arch_str;
a1d1634d
AM
5134 if (!bfd_elf_add_proc_attr_string (stdoutput, Tag_RISCV_arch, arch_str))
5135 as_fatal (_("error adding attribute: %s"),
5136 bfd_errmsg (bfd_get_error ()));
8f595e9b
NC
5137
5138 /* For the file without any instruction, we don't set the default_priv_spec
dcd709e0
NC
5139 according to the privileged elf attributes since the md_assemble isn't
5140 called. */
8f595e9b
NC
5141 if (!start_assemble
5142 && !riscv_set_default_priv_spec (NULL))
5143 return;
5144
dcd709e0
NC
5145 /* If we already have set privileged elf attributes, then no need to do
5146 anything. Otherwise, don't generate or update them when no CSR and
5147 privileged instructions are used. */
1a79004f 5148 if (!explicit_priv_attr)
3fc6c3dc
NC
5149 return;
5150
3d73d29e 5151 RISCV_GET_PRIV_SPEC_NAME (priv_str, default_priv_spec);
8f595e9b
NC
5152 p = priv_str;
5153 for (i = 0; *p; ++p)
5154 {
5155 if (*p == '.' && i < 3)
5156 {
5157 versions[i++] = number;
5158 number = 0;
5159 }
5160 else if (ISDIGIT (*p))
5161 number = (number * 10) + (*p - '0');
5162 else
5163 {
b800637e 5164 as_bad (_("internal: bad RISC-V privileged spec (%s)"), priv_str);
8f595e9b
NC
5165 return;
5166 }
5167 }
5168 versions[i] = number;
5169
dcd709e0 5170 /* Re-write privileged elf attributes. */
a1d1634d
AM
5171 if (!bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec,
5172 versions[0])
5173 || !bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_minor,
5174 versions[1])
5175 || !bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_revision,
5176 versions[2]))
5177 as_fatal (_("error adding attribute: %s"),
5178 bfd_errmsg (bfd_get_error ()));
2dc8dd17
JW
5179}
5180
dcd709e0 5181/* Add the default contents for the .riscv.attributes section. */
2dc8dd17
JW
5182
5183static void
5184riscv_set_public_attributes (void)
5185{
8f595e9b
NC
5186 if (riscv_opts.arch_attr || explicit_attr)
5187 riscv_write_out_attrs ();
2dc8dd17
JW
5188}
5189
f1cd8b94
KLC
5190/* Scan uleb128 subtraction expressions and insert fixups for them.
5191 e.g., .uleb128 .L1 - .L0
5192 Because relaxation may change the value of the subtraction, we
5193 must resolve them at link-time. */
5194
5195static void
5196riscv_insert_uleb128_fixes (bfd *abfd ATTRIBUTE_UNUSED,
5197 asection *sec, void *xxx ATTRIBUTE_UNUSED)
5198{
5199 segment_info_type *seginfo = seg_info (sec);
5200 struct frag *fragP;
5201
5202 subseg_set (sec, 0);
5203
5204 for (fragP = seginfo->frchainP->frch_root;
5205 fragP; fragP = fragP->fr_next)
5206 {
5207 expressionS *exp, *exp_dup;
5208
5209 if (fragP->fr_type != rs_leb128 || fragP->fr_symbol == NULL)
5210 continue;
5211
5212 exp = symbol_get_value_expression (fragP->fr_symbol);
5213
5214 if (exp->X_op != O_subtract)
5215 continue;
5216
5217 /* Only unsigned leb128 can be handled. */
5218 gas_assert (fragP->fr_subtype == 0);
5219 exp_dup = xmemdup (exp, sizeof (*exp), sizeof (*exp));
5220 exp_dup->X_op = O_symbol;
5221 exp_dup->X_op_symbol = NULL;
5222
5223 /* Insert relocations to resolve the subtraction at link-time.
5224 Emit the SET relocation first in riscv. */
5225 exp_dup->X_add_symbol = exp->X_add_symbol;
5226 fix_new_exp (fragP, fragP->fr_fix, 0,
5227 exp_dup, 0, BFD_RELOC_RISCV_SET_ULEB128);
5228 exp_dup->X_add_symbol = exp->X_op_symbol;
2029e139 5229 exp_dup->X_add_number = 0; /* Set addend of SUB_ULEB128 to zero. */
f1cd8b94
KLC
5230 fix_new_exp (fragP, fragP->fr_fix, 0,
5231 exp_dup, 0, BFD_RELOC_RISCV_SUB_ULEB128);
dc63d568 5232 free ((void *) exp_dup);
f1cd8b94
KLC
5233 }
5234}
5235
2dc8dd17
JW
5236/* Called after all assembly has been done. */
5237
5238void
ed2917de 5239riscv_md_finish (void)
2dc8dd17
JW
5240{
5241 riscv_set_public_attributes ();
f1cd8b94
KLC
5242 if (riscv_opts.relax)
5243 bfd_map_over_sections (stdoutput, riscv_insert_uleb128_fixes, NULL);
2dc8dd17
JW
5244}
5245
dff565fc
LX
5246/* Called just before the assembler exits. */
5247
5248void
5249riscv_md_end (void)
5250{
5251 htab_delete (riscv_pcrel_hi_fixup_hash);
5252}
5253
9b9b1092
NC
5254/* Adjust the symbol table. */
5255
5256void
5257riscv_adjust_symtab (void)
5258{
5259 bfd_map_over_sections (stdoutput, riscv_check_mapping_symbols, (char *) 0);
5260 elf_adjust_symtab ();
5261}
5262
2dc8dd17
JW
5263/* Given a symbolic attribute NAME, return the proper integer value.
5264 Returns -1 if the attribute is not known. */
5265
5266int
5267riscv_convert_symbolic_attribute (const char *name)
5268{
5269 static const struct
5270 {
1942a048
NC
5271 const char *name;
5272 const int tag;
2dc8dd17
JW
5273 }
5274 attribute_table[] =
1942a048
NC
5275 {
5276 /* When you modify this table you should
5277 also modify the list in doc/c-riscv.texi. */
5278#define T(tag) {#tag, Tag_RISCV_##tag}, {"Tag_RISCV_" #tag, Tag_RISCV_##tag}
5279 T(arch),
5280 T(priv_spec),
5281 T(priv_spec_minor),
5282 T(priv_spec_revision),
5283 T(unaligned_access),
5284 T(stack_align),
2dc8dd17 5285#undef T
1942a048 5286 };
2dc8dd17
JW
5287
5288 if (name == NULL)
5289 return -1;
5290
1942a048 5291 unsigned int i;
2dc8dd17
JW
5292 for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
5293 if (strcmp (name, attribute_table[i].name) == 0)
5294 return attribute_table[i].tag;
5295
5296 return -1;
5297}
5298
5299/* Parse a .attribute directive. */
5300
5301static void
5302s_riscv_attribute (int ignored ATTRIBUTE_UNUSED)
5303{
5304 int tag = obj_elf_vendor_attribute (OBJ_ATTR_PROC);
8f595e9b
NC
5305 unsigned old_xlen;
5306 obj_attribute *attr;
2dc8dd17 5307
5b7c81bd 5308 explicit_attr = true;
8f595e9b 5309 switch (tag)
2dc8dd17 5310 {
8f595e9b
NC
5311 case Tag_RISCV_arch:
5312 old_xlen = xlen;
2dc8dd17
JW
5313 attr = elf_known_obj_attributes_proc (stdoutput);
5314 if (!start_assemble)
5315 riscv_set_arch (attr[Tag_RISCV_arch].s);
5316 else
b800637e
NC
5317 as_fatal (_("architecture elf attributes must set before "
5318 "any instructions"));
2dc8dd17
JW
5319
5320 if (old_xlen != xlen)
5321 {
5322 /* We must re-init bfd again if xlen is changed. */
5323 unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
5324 bfd_find_target (riscv_target_format (), stdoutput);
5325
5326 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
b800637e 5327 as_warn (_("could not set architecture and machine"));
2dc8dd17 5328 }
8f595e9b
NC
5329 break;
5330
5331 case Tag_RISCV_priv_spec:
5332 case Tag_RISCV_priv_spec_minor:
5333 case Tag_RISCV_priv_spec_revision:
5334 if (start_assemble)
b800637e
NC
5335 as_fatal (_("privileged elf attributes must set before "
5336 "any instructions"));
8f595e9b
NC
5337 break;
5338
5339 default:
5340 break;
2dc8dd17
JW
5341 }
5342}
5343
8155b853
NC
5344/* Mark symbol that it follows a variant CC convention. */
5345
5346static void
5347s_variant_cc (int ignored ATTRIBUTE_UNUSED)
5348{
5349 char *name;
5350 char c;
5351 symbolS *sym;
5352 asymbol *bfdsym;
5353 elf_symbol_type *elfsym;
5354
5355 c = get_symbol_name (&name);
5356 if (!*name)
5357 as_bad (_("missing symbol name for .variant_cc directive"));
5358 sym = symbol_find_or_make (name);
5359 restore_line_pointer (c);
5360 demand_empty_rest_of_line ();
5361
5362 bfdsym = symbol_get_bfdsym (sym);
5363 elfsym = elf_symbol_from (bfdsym);
5364 gas_assert (elfsym);
5365 elfsym->internal_elf_sym.st_other |= STO_RISCV_VARIANT_CC;
5366}
5367
5368/* Same as elf_copy_symbol_attributes, but without copying st_other.
5369 This is needed so RISC-V specific st_other values can be independently
5370 specified for an IFUNC resolver (that is called by the dynamic linker)
5371 and the symbol it resolves (aliased to the resolver). In particular,
5372 if a function symbol has special st_other value set via directives,
5373 then attaching an IFUNC resolver to that symbol should not override
5374 the st_other setting. Requiring the directive on the IFUNC resolver
5375 symbol would be unexpected and problematic in C code, where the two
5376 symbols appear as two independent function declarations. */
5377
5378void
5379riscv_elf_copy_symbol_attributes (symbolS *dest, symbolS *src)
5380{
5381 struct elf_obj_sy *srcelf = symbol_get_obj (src);
5382 struct elf_obj_sy *destelf = symbol_get_obj (dest);
a3a7f5e1
FS
5383 /* If size is unset, copy size from src. Because we don't track whether
5384 .size has been used, we can't differentiate .size dest, 0 from the case
5385 where dest's size is unset. */
5386 if (!destelf->size && S_GET_SIZE (dest) == 0)
8155b853 5387 {
a3a7f5e1
FS
5388 if (srcelf->size)
5389 {
5390 destelf->size = XNEW (expressionS);
5391 *destelf->size = *srcelf->size;
5392 }
5393 S_SET_SIZE (dest, S_GET_SIZE (src));
8155b853 5394 }
8155b853
NC
5395}
5396
dcd709e0 5397/* RISC-V pseudo-ops table. */
e23eba97
NC
5398static const pseudo_typeS riscv_pseudo_table[] =
5399{
e23eba97
NC
5400 {"option", s_riscv_option, 0},
5401 {"half", cons, 2},
5402 {"word", cons, 4},
5403 {"dword", cons, 8},
5404 {"dtprelword", s_dtprel, 4},
5405 {"dtpreldword", s_dtprel, 8},
e23eba97
NC
5406 {"uleb128", s_riscv_leb128, 0},
5407 {"sleb128", s_riscv_leb128, 1},
0e35537d 5408 {"insn", s_riscv_insn, 0},
2dc8dd17 5409 {"attribute", s_riscv_attribute, 0},
8155b853 5410 {"variant_cc", s_variant_cc, 0},
035784e3 5411 {"float16", float_cons, 'h'},
e23eba97
NC
5412
5413 { NULL, NULL, 0 },
5414};
5415
5416void
5417riscv_pop_insert (void)
5418{
5419 extern void pop_insert (const pseudo_typeS *);
5420
5421 pop_insert (riscv_pseudo_table);
5422}