]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gas/config/tc-riscv.c
as_bad_subtract
[thirdparty/binutils-gdb.git] / gas / config / tc-riscv.c
CommitLineData
e23eba97 1/* tc-riscv.c -- RISC-V assembler
250d07de 2 Copyright (C) 2011-2021 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
3d73d29e 32#include "bfd/cpu-riscv.h"
1080bf78 33#include "bfd/elfxx-riscv.h"
e23eba97
NC
34#include "elf/riscv.h"
35#include "opcode/riscv.h"
36
37#include <stdint.h>
38
39/* Information about an instruction, including its format, operands
40 and fixups. */
41struct riscv_cl_insn
42{
43 /* The opcode's entry in riscv_opcodes. */
44 const struct riscv_opcode *insn_mo;
45
46 /* The encoded instruction bits. */
47 insn_t insn_opcode;
48
49 /* The frag that contains the instruction. */
50 struct frag *frag;
51
52 /* The offset into FRAG of the first instruction byte. */
53 long where;
54
55 /* The relocs associated with the instruction, if any. */
56 fixS *fixp;
57};
58
3d73d29e
NC
59/* All RISC-V CSR belong to one of these classes. */
60enum riscv_csr_class
61{
62 CSR_CLASS_NONE,
63
64 CSR_CLASS_I,
65 CSR_CLASS_I_32, /* rv32 only */
66 CSR_CLASS_F, /* f-ext only */
67 CSR_CLASS_DEBUG /* debug CSR */
68};
69
70/* This structure holds all restricted conditions for a CSR. */
71struct riscv_csr_extra
72{
73 /* Class to which this CSR belongs. Used to decide whether or
74 not this CSR is legal in the current -march context. */
75 enum riscv_csr_class csr_class;
76
77 /* CSR may have differnet numbers in the previous priv spec. */
78 unsigned address;
79
80 /* Record the CSR is defined/valid in which versions. */
81 enum riscv_spec_class define_version;
82
83 /* Record the CSR is aborted/invalid from which versions. If it isn't
84 aborted in the current version, then it should be CSR_CLASS_VDRAFT. */
85 enum riscv_spec_class abort_version;
86
87 /* The CSR may have more than one setting. */
88 struct riscv_csr_extra *next;
89};
90
91/* All standard/Z* extensions defined in all supported ISA spec. */
92struct riscv_ext_version
93{
94 const char *name;
95 enum riscv_spec_class isa_spec_class;
96 int major_version;
97 int minor_version;
98};
99
100static const struct riscv_ext_version ext_version_table[] =
101{
102 {"e", ISA_SPEC_CLASS_20191213, 1, 9},
103 {"e", ISA_SPEC_CLASS_20190608, 1, 9},
104 {"e", ISA_SPEC_CLASS_2P2, 1, 9},
105
106 {"i", ISA_SPEC_CLASS_20191213, 2, 1},
107 {"i", ISA_SPEC_CLASS_20190608, 2, 1},
108 {"i", ISA_SPEC_CLASS_2P2, 2, 0},
109
110 {"m", ISA_SPEC_CLASS_20191213, 2, 0},
111 {"m", ISA_SPEC_CLASS_20190608, 2, 0},
112 {"m", ISA_SPEC_CLASS_2P2, 2, 0},
113
114 {"a", ISA_SPEC_CLASS_20191213, 2, 1},
115 {"a", ISA_SPEC_CLASS_20190608, 2, 0},
116 {"a", ISA_SPEC_CLASS_2P2, 2, 0},
117
118 {"f", ISA_SPEC_CLASS_20191213, 2, 2},
119 {"f", ISA_SPEC_CLASS_20190608, 2, 2},
120 {"f", ISA_SPEC_CLASS_2P2, 2, 0},
121
122 {"d", ISA_SPEC_CLASS_20191213, 2, 2},
123 {"d", ISA_SPEC_CLASS_20190608, 2, 2},
124 {"d", ISA_SPEC_CLASS_2P2, 2, 0},
125
126 {"q", ISA_SPEC_CLASS_20191213, 2, 2},
127 {"q", ISA_SPEC_CLASS_20190608, 2, 2},
128 {"q", ISA_SPEC_CLASS_2P2, 2, 0},
129
130 {"c", ISA_SPEC_CLASS_20191213, 2, 0},
131 {"c", ISA_SPEC_CLASS_20190608, 2, 0},
132 {"c", ISA_SPEC_CLASS_2P2, 2, 0},
133
134 {"zicsr", ISA_SPEC_CLASS_20191213, 2, 0},
135 {"zicsr", ISA_SPEC_CLASS_20190608, 2, 0},
136
137 {"zifencei", ISA_SPEC_CLASS_20191213, 2, 0},
138 {"zifencei", ISA_SPEC_CLASS_20190608, 2, 0},
139
140 {"zihintpause", ISA_SPEC_CLASS_DRAFT, 1, 0},
141
80d49d6a
KLC
142 {"zbb", ISA_SPEC_CLASS_DRAFT, 0, 93},
143 {"zba", ISA_SPEC_CLASS_DRAFT, 0, 93},
144 {"zbc", ISA_SPEC_CLASS_DRAFT, 0, 93},
145
3d73d29e
NC
146 /* Terminate the list. */
147 {NULL, 0, 0, 0}
148};
149
e23eba97
NC
150#ifndef DEFAULT_ARCH
151#define DEFAULT_ARCH "riscv64"
152#endif
153
2dc8dd17
JW
154#ifndef DEFAULT_RISCV_ATTR
155#define DEFAULT_RISCV_ATTR 0
156#endif
157
8f595e9b 158/* Let riscv_after_parse_args set the default value according to xlen. */
8f595e9b
NC
159#ifndef DEFAULT_RISCV_ARCH_WITH_EXT
160#define DEFAULT_RISCV_ARCH_WITH_EXT NULL
161#endif
162
dcd709e0 163/* Need to sync the version with RISC-V compiler. */
8f595e9b
NC
164#ifndef DEFAULT_RISCV_ISA_SPEC
165#define DEFAULT_RISCV_ISA_SPEC "2.2"
166#endif
167
168#ifndef DEFAULT_RISCV_PRIV_SPEC
169#define DEFAULT_RISCV_PRIV_SPEC "1.11"
170#endif
171
e23eba97 172static const char default_arch[] = DEFAULT_ARCH;
8f595e9b 173static const char *default_arch_with_ext = DEFAULT_RISCV_ARCH_WITH_EXT;
3d73d29e
NC
174static enum riscv_spec_class default_isa_spec = ISA_SPEC_CLASS_NONE;
175static enum riscv_spec_class default_priv_spec = PRIV_SPEC_CLASS_NONE;
e23eba97 176
dcd709e0
NC
177static unsigned xlen = 0; /* The width of an x-register. */
178static unsigned abi_xlen = 0; /* The width of a pointer in the ABI. */
5b7c81bd 179static bool rve_abi = false;
1942a048
NC
180enum float_abi
181{
6e1605e4
NC
182 FLOAT_ABI_DEFAULT = -1,
183 FLOAT_ABI_SOFT,
184 FLOAT_ABI_SINGLE,
185 FLOAT_ABI_DOUBLE,
186 FLOAT_ABI_QUAD
187};
188static enum float_abi float_abi = FLOAT_ABI_DEFAULT;
e23eba97 189
2922d21d 190#define LOAD_ADDRESS_INSN (abi_xlen == 64 ? "ld" : "lw")
e23eba97
NC
191#define ADD32_INSN (xlen == 64 ? "addiw" : "addi")
192
193static unsigned elf_flags = 0;
194
dcd709e0
NC
195/* Set the default_isa_spec. Return 0 if the spec isn't supported.
196 Otherwise, return 1. */
8f595e9b
NC
197
198static int
199riscv_set_default_isa_spec (const char *s)
200{
3d73d29e
NC
201 enum riscv_spec_class class = ISA_SPEC_CLASS_NONE;
202 RISCV_GET_ISA_SPEC_CLASS (s, class);
203 if (class == ISA_SPEC_CLASS_NONE)
8f595e9b 204 {
b800637e
NC
205 as_bad ("unknown default ISA spec `%s' set by "
206 "-misa-spec or --with-isa-spec", s);
8f595e9b
NC
207 return 0;
208 }
209 else
210 default_isa_spec = class;
211 return 1;
212}
213
dcd709e0
NC
214/* Set the default_priv_spec. Find the privileged elf attributes when
215 the input string is NULL. Return 0 if the spec isn't supported.
216 Otherwise, return 1. */
8f595e9b
NC
217
218static int
219riscv_set_default_priv_spec (const char *s)
220{
3d73d29e 221 enum riscv_spec_class class = PRIV_SPEC_CLASS_NONE;
8f595e9b
NC
222 unsigned major, minor, revision;
223 obj_attribute *attr;
8f595e9b 224
3d73d29e
NC
225 RISCV_GET_PRIV_SPEC_CLASS (s, class);
226 if (class != PRIV_SPEC_CLASS_NONE)
8f595e9b
NC
227 {
228 default_priv_spec = class;
229 return 1;
230 }
231
232 if (s != NULL)
233 {
b800637e
NC
234 as_bad (_("unknown default privileged spec `%s' set by "
235 "-mpriv-spec or --with-priv-spec"), s);
8f595e9b
NC
236 return 0;
237 }
238
dcd709e0 239 /* Set the default_priv_spec by the privileged elf attributes. */
8f595e9b
NC
240 attr = elf_known_obj_attributes_proc (stdoutput);
241 major = (unsigned) attr[Tag_RISCV_priv_spec].i;
242 minor = (unsigned) attr[Tag_RISCV_priv_spec_minor].i;
243 revision = (unsigned) attr[Tag_RISCV_priv_spec_revision].i;
3d73d29e
NC
244 /* Version 0.0.0 is the default value and meningless. */
245 if (major == 0 && minor == 0 && revision == 0)
246 return 1;
8f595e9b 247
3d73d29e
NC
248 riscv_get_priv_spec_class_from_numbers (major, minor, revision, &class);
249 if (class != PRIV_SPEC_CLASS_NONE)
250 {
8f595e9b 251 default_priv_spec = class;
8f595e9b
NC
252 return 1;
253 }
254
dcd709e0 255 /* Still can not find the privileged spec class. */
b800637e
NC
256 as_bad (_("unknown default privileged spec `%d.%d.%d' set by "
257 "privileged elf attributes"), major, minor, revision);
8f595e9b
NC
258 return 0;
259}
260
e23eba97 261/* This is the set of options which the .option pseudo-op may modify. */
e23eba97
NC
262struct riscv_set_options
263{
264 int pic; /* Generate position-independent code. */
265 int rvc; /* Generate RVC code. */
7f999549 266 int rve; /* Generate RVE code. */
45f76423 267 int relax; /* Emit relocs the linker is allowed to relax. */
dcd709e0 268 int arch_attr; /* Emit architecture and privileged elf attributes. */
2ca89224 269 int csr_check; /* Enable the CSR checking. */
e23eba97
NC
270};
271
272static struct riscv_set_options riscv_opts =
273{
dcd709e0
NC
274 0, /* pic */
275 0, /* rvc */
276 0, /* rve */
277 1, /* relax */
2dc8dd17 278 DEFAULT_RISCV_ATTR, /* arch_attr */
dcd709e0 279 0, /* csr_check */
e23eba97
NC
280};
281
282static void
5b7c81bd 283riscv_set_rvc (bool rvc_value)
e23eba97
NC
284{
285 if (rvc_value)
286 elf_flags |= EF_RISCV_RVC;
287
288 riscv_opts.rvc = rvc_value;
289}
290
7f999549 291static void
5b7c81bd 292riscv_set_rve (bool rve_value)
7f999549
JW
293{
294 riscv_opts.rve = rve_value;
295}
296
1080bf78 297static riscv_subset_list_t riscv_subsets;
e23eba97 298
5b7c81bd 299static bool
1080bf78 300riscv_subset_supports (const char *feature)
e23eba97 301{
dfe92496
NC
302 struct riscv_subset_t *subset;
303
1080bf78 304 if (riscv_opts.rvc && (strcasecmp (feature, "c") == 0))
5b7c81bd 305 return true;
e23eba97 306
dfe92496 307 return riscv_lookup_subset (&riscv_subsets, feature, &subset);
e23eba97
NC
308}
309
5b7c81bd 310static bool
7e9ad3a3 311riscv_multi_subset_supports (enum riscv_insn_class insn_class)
43135d3b 312{
7e9ad3a3
JW
313 switch (insn_class)
314 {
315 case INSN_CLASS_I: return riscv_subset_supports ("i");
316 case INSN_CLASS_C: return riscv_subset_supports ("c");
317 case INSN_CLASS_A: return riscv_subset_supports ("a");
318 case INSN_CLASS_M: return riscv_subset_supports ("m");
319 case INSN_CLASS_F: return riscv_subset_supports ("f");
320 case INSN_CLASS_D: return riscv_subset_supports ("d");
729a5353 321 case INSN_CLASS_Q: return riscv_subset_supports ("q");
7e9ad3a3
JW
322
323 case INSN_CLASS_F_AND_C:
729a5353
NC
324 return (riscv_subset_supports ("f")
325 && riscv_subset_supports ("c"));
326 case INSN_CLASS_D_AND_C:
327 return (riscv_subset_supports ("d")
328 && riscv_subset_supports ("c"));
43135d3b 329
729a5353
NC
330 case INSN_CLASS_ZICSR:
331 return riscv_subset_supports ("zicsr");
332 case INSN_CLASS_ZIFENCEI:
333 return riscv_subset_supports ("zifencei");
aa881ecd
PT
334 case INSN_CLASS_ZIHINTPAUSE:
335 return riscv_subset_supports ("zihintpause");
43135d3b 336
80d49d6a
KLC
337 case INSN_CLASS_ZBB:
338 return riscv_subset_supports ("zbb");
339
340 case INSN_CLASS_ZBA:
341 return riscv_subset_supports ("zba");
342
343 case INSN_CLASS_ZBC:
344 return riscv_subset_supports ("zbc");
345
7e9ad3a3 346 default:
b800637e 347 as_fatal ("internal: unreachable");
5b7c81bd 348 return false;
7e9ad3a3 349 }
43135d3b
JW
350}
351
8f595e9b 352/* Handle of the extension with version hash table. */
629310ab 353static htab_t ext_version_hash = NULL;
8f595e9b 354
629310ab 355static htab_t
3d73d29e 356init_ext_version_hash (void)
8f595e9b 357{
3d73d29e 358 const struct riscv_ext_version *table = ext_version_table;
629310ab 359 htab_t hash = str_htab_create ();
3d73d29e 360 int i = 0;
8f595e9b
NC
361
362 while (table[i].name)
363 {
364 const char *name = table[i].name;
fe0e921f 365 if (str_hash_insert (hash, name, &table[i], 0) != NULL)
b800637e 366 as_fatal (_("internal: duplicate %s"), name);
8f595e9b
NC
367
368 i++;
369 while (table[i].name
1942a048 370 && strcmp (table[i].name, name) == 0)
8f595e9b
NC
371 i++;
372 }
373
374 return hash;
375}
376
377static void
378riscv_get_default_ext_version (const char *name,
7ef19aa6
NC
379 int *major_version,
380 int *minor_version)
8f595e9b
NC
381{
382 struct riscv_ext_version *ext;
383
8f595e9b
NC
384 if (name == NULL || default_isa_spec == ISA_SPEC_CLASS_NONE)
385 return;
386
629310ab 387 ext = (struct riscv_ext_version *) str_hash_find (ext_version_hash, name);
8f595e9b 388 while (ext
7ef19aa6
NC
389 && ext->name
390 && strcmp (ext->name, name) == 0)
8f595e9b 391 {
2652cfad
CXW
392 if (ext->isa_spec_class == ISA_SPEC_CLASS_DRAFT
393 || ext->isa_spec_class == default_isa_spec)
7ef19aa6
NC
394 {
395 *major_version = ext->major_version;
396 *minor_version = ext->minor_version;
397 return;
398 }
8f595e9b
NC
399 ext++;
400 }
401}
402
2922d21d 403/* Set which ISA and extensions are available. */
e23eba97 404
e23eba97 405static void
2922d21d 406riscv_set_arch (const char *s)
e23eba97 407{
1080bf78
JW
408 riscv_parse_subset_t rps;
409 rps.subset_list = &riscv_subsets;
7ef19aa6 410 rps.error_handler = as_bad;
1080bf78 411 rps.xlen = &xlen;
8f595e9b 412 rps.get_default_version = riscv_get_default_ext_version;
fe1f847d 413 rps.check_unknown_prefixed_ext = true;
8f595e9b
NC
414
415 if (s == NULL)
416 return;
7f999549 417
1080bf78
JW
418 riscv_release_subset_list (&riscv_subsets);
419 riscv_parse_subset (&rps, s);
28b2963f
NC
420
421 /* To support .option rvc and rve. */
422 riscv_set_rvc (false);
423 if (riscv_subset_supports ("c"))
424 riscv_set_rvc (true);
425 riscv_set_rve (false);
426 if (riscv_subset_supports ("e"))
427 riscv_set_rve (true);
e23eba97
NC
428}
429
dcd709e0 430/* Indicate -mabi option is explictly set. */
5b7c81bd 431static bool explicit_mabi = false;
6e1605e4
NC
432
433static void
5b7c81bd 434riscv_set_abi (unsigned new_xlen, enum float_abi new_float_abi, bool rve)
6e1605e4
NC
435{
436 abi_xlen = new_xlen;
437 float_abi = new_float_abi;
438 rve_abi = rve;
439}
440
dcd709e0
NC
441/* If the -mabi option isn't set, then set the abi according to the
442 ISA string. Otherwise, check if there is any conflict. */
6e1605e4
NC
443
444static void
445riscv_set_abi_by_arch (void)
446{
447 if (!explicit_mabi)
448 {
449 if (riscv_subset_supports ("q"))
5b7c81bd 450 riscv_set_abi (xlen, FLOAT_ABI_QUAD, false);
6e1605e4 451 else if (riscv_subset_supports ("d"))
5b7c81bd 452 riscv_set_abi (xlen, FLOAT_ABI_DOUBLE, false);
5d0ed830
NC
453 else if (riscv_subset_supports ("e"))
454 riscv_set_abi (xlen, FLOAT_ABI_SOFT, true);
6e1605e4 455 else
5b7c81bd 456 riscv_set_abi (xlen, FLOAT_ABI_SOFT, false);
6e1605e4
NC
457 }
458 else
459 {
460 gas_assert (abi_xlen != 0 && xlen != 0 && float_abi != FLOAT_ABI_DEFAULT);
461 if (abi_xlen > xlen)
462 as_bad ("can't have %d-bit ABI on %d-bit ISA", abi_xlen, xlen);
463 else if (abi_xlen < xlen)
464 as_bad ("%d-bit ABI not yet supported on %d-bit ISA", abi_xlen, xlen);
5d0ed830
NC
465
466 if (riscv_subset_supports ("e") && !rve_abi)
467 as_bad ("only the ilp32e ABI is supported for e extension");
468
469 if (float_abi == FLOAT_ABI_SINGLE
470 && !riscv_subset_supports ("f"))
471 as_bad ("ilp32f/lp64f ABI can't be used when f extension "
472 "isn't supported");
473 else if (float_abi == FLOAT_ABI_DOUBLE
474 && !riscv_subset_supports ("d"))
475 as_bad ("ilp32d/lp64d ABI can't be used when d extension "
476 "isn't supported");
477 else if (float_abi == FLOAT_ABI_QUAD
478 && !riscv_subset_supports ("q"))
479 as_bad ("ilp32q/lp64q ABI can't be used when q extension "
480 "isn't supported");
6e1605e4
NC
481 }
482
483 /* Update the EF_RISCV_FLOAT_ABI field of elf_flags. */
484 elf_flags &= ~EF_RISCV_FLOAT_ABI;
485 elf_flags |= float_abi << 1;
486
487 if (rve_abi)
488 elf_flags |= EF_RISCV_RVE;
489}
490
e23eba97 491/* Handle of the OPCODE hash table. */
629310ab 492static htab_t op_hash = NULL;
e23eba97 493
0e35537d 494/* Handle of the type of .insn hash table. */
629310ab 495static htab_t insn_type_hash = NULL;
0e35537d 496
e23eba97 497/* This array holds the chars that always start a comment. If the
dcd709e0 498 pre-processor is disabled, these aren't very useful. */
e23eba97
NC
499const char comment_chars[] = "#";
500
501/* This array holds the chars that only start a comment at the beginning of
502 a line. If the line seems to have the form '# 123 filename'
dcd709e0
NC
503 .line and .file directives will appear in the pre-processed output
504
505 Note that input_file.c hand checks for '#' at the beginning of the
e23eba97 506 first line of the input file. This is because the compiler outputs
dcd709e0
NC
507 #NO_APP at the beginning of its output.
508
509 Also note that C style comments are always supported. */
e23eba97
NC
510const char line_comment_chars[] = "#";
511
512/* This array holds machine specific line separator characters. */
513const char line_separator_chars[] = ";";
514
dcd709e0 515/* Chars that can be used to separate mant from exp in floating point nums. */
e23eba97
NC
516const char EXP_CHARS[] = "eE";
517
dcd709e0
NC
518/* Chars that mean this number is a floating point constant.
519 As in 0f12.456 or 0d1.2345e12. */
e23eba97
NC
520const char FLT_CHARS[] = "rRsSfFdDxXpP";
521
2dc8dd17 522/* Indicate we are already assemble any instructions or not. */
5b7c81bd 523static bool start_assemble = false;
2dc8dd17 524
f9a6a8f0 525/* Indicate ELF attributes are explicitly set. */
5b7c81bd 526static bool explicit_attr = false;
2dc8dd17 527
f9a6a8f0 528/* Indicate CSR or priv instructions are explicitly used. */
5b7c81bd 529static bool explicit_priv_attr = false;
3fc6c3dc 530
e23eba97
NC
531/* Macros for encoding relaxation state for RVC branches and far jumps. */
532#define RELAX_BRANCH_ENCODE(uncond, rvc, length) \
533 ((relax_substateT) \
534 (0xc0000000 \
535 | ((uncond) ? 1 : 0) \
536 | ((rvc) ? 2 : 0) \
537 | ((length) << 2)))
538#define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
539#define RELAX_BRANCH_LENGTH(i) (((i) >> 2) & 0xF)
540#define RELAX_BRANCH_RVC(i) (((i) & 2) != 0)
541#define RELAX_BRANCH_UNCOND(i) (((i) & 1) != 0)
542
543/* Is the given value a sign-extended 32-bit value? */
544#define IS_SEXT_32BIT_NUM(x) \
545 (((x) &~ (offsetT) 0x7fffffff) == 0 \
546 || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
547
548/* Is the given value a zero-extended 32-bit value? Or a negated one? */
549#define IS_ZEXT_32BIT_NUM(x) \
550 (((x) &~ (offsetT) 0xffffffff) == 0 \
551 || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
552
553/* Change INSN's opcode so that the operand given by FIELD has value VALUE.
554 INSN is a riscv_cl_insn structure and VALUE is evaluated exactly once. */
555#define INSERT_OPERAND(FIELD, INSN, VALUE) \
556 INSERT_BITS ((INSN).insn_opcode, VALUE, OP_MASK_##FIELD, OP_SH_##FIELD)
557
558/* Determine if an instruction matches an opcode. */
559#define OPCODE_MATCHES(OPCODE, OP) \
560 (((OPCODE) & MASK_##OP) == MATCH_##OP)
561
562static char *expr_end;
563
564/* The default target format to use. */
565
566const char *
567riscv_target_format (void)
568{
fbc09e7a
MC
569 if (target_big_endian)
570 return xlen == 64 ? "elf64-bigriscv" : "elf32-bigriscv";
571 else
572 return xlen == 64 ? "elf64-littleriscv" : "elf32-littleriscv";
e23eba97
NC
573}
574
575/* Return the length of instruction INSN. */
576
577static inline unsigned int
578insn_length (const struct riscv_cl_insn *insn)
579{
580 return riscv_insn_length (insn->insn_opcode);
581}
582
583/* Initialise INSN from opcode entry MO. Leave its position unspecified. */
584
585static void
586create_insn (struct riscv_cl_insn *insn, const struct riscv_opcode *mo)
587{
588 insn->insn_mo = mo;
589 insn->insn_opcode = mo->match;
590 insn->frag = NULL;
591 insn->where = 0;
592 insn->fixp = NULL;
593}
594
595/* Install INSN at the location specified by its "frag" and "where" fields. */
596
597static void
598install_insn (const struct riscv_cl_insn *insn)
599{
600 char *f = insn->frag->fr_literal + insn->where;
fbc09e7a 601 number_to_chars_littleendian (f, insn->insn_opcode, insn_length (insn));
e23eba97
NC
602}
603
604/* Move INSN to offset WHERE in FRAG. Adjust the fixups accordingly
605 and install the opcode in the new location. */
606
607static void
608move_insn (struct riscv_cl_insn *insn, fragS *frag, long where)
609{
610 insn->frag = frag;
611 insn->where = where;
612 if (insn->fixp != NULL)
613 {
614 insn->fixp->fx_frag = frag;
615 insn->fixp->fx_where = where;
616 }
617 install_insn (insn);
618}
619
620/* Add INSN to the end of the output. */
621
622static void
623add_fixed_insn (struct riscv_cl_insn *insn)
624{
625 char *f = frag_more (insn_length (insn));
626 move_insn (insn, frag_now, f - frag_now->fr_literal);
627}
628
629static void
630add_relaxed_insn (struct riscv_cl_insn *insn, int max_chars, int var,
631 relax_substateT subtype, symbolS *symbol, offsetT offset)
632{
633 frag_grow (max_chars);
634 move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
635 frag_var (rs_machine_dependent, max_chars, var,
636 subtype, symbol, offset, NULL);
637}
638
639/* Compute the length of a branch sequence, and adjust the stored length
640 accordingly. If FRAGP is NULL, the worst-case length is returned. */
641
642static unsigned
643relaxed_branch_length (fragS *fragp, asection *sec, int update)
644{
645 int jump, rvc, length = 8;
646
647 if (!fragp)
648 return length;
649
650 jump = RELAX_BRANCH_UNCOND (fragp->fr_subtype);
651 rvc = RELAX_BRANCH_RVC (fragp->fr_subtype);
652 length = RELAX_BRANCH_LENGTH (fragp->fr_subtype);
653
654 /* Assume jumps are in range; the linker will catch any that aren't. */
655 length = jump ? 4 : 8;
656
657 if (fragp->fr_symbol != NULL
658 && S_IS_DEFINED (fragp->fr_symbol)
01156111 659 && !S_IS_WEAK (fragp->fr_symbol)
e23eba97
NC
660 && sec == S_GET_SEGMENT (fragp->fr_symbol))
661 {
662 offsetT val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
663 bfd_vma rvc_range = jump ? RVC_JUMP_REACH : RVC_BRANCH_REACH;
664 val -= fragp->fr_address + fragp->fr_fix;
665
666 if (rvc && (bfd_vma)(val + rvc_range/2) < rvc_range)
667 length = 2;
668 else if ((bfd_vma)(val + RISCV_BRANCH_REACH/2) < RISCV_BRANCH_REACH)
669 length = 4;
670 else if (!jump && rvc)
671 length = 6;
672 }
673
674 if (update)
675 fragp->fr_subtype = RELAX_BRANCH_ENCODE (jump, rvc, length);
676
677 return length;
678}
679
0e35537d
JW
680/* Information about an opcode name, mnemonics and its value. */
681struct opcode_name_t
682{
683 const char *name;
684 unsigned int val;
685};
686
687/* List for all supported opcode name. */
688static const struct opcode_name_t opcode_name_list[] =
689{
690 {"C0", 0x0},
691 {"C1", 0x1},
692 {"C2", 0x2},
693
694 {"LOAD", 0x03},
695 {"LOAD_FP", 0x07},
696 {"CUSTOM_0", 0x0b},
697 {"MISC_MEM", 0x0f},
698 {"OP_IMM", 0x13},
699 {"AUIPC", 0x17},
700 {"OP_IMM_32", 0x1b},
701 /* 48b 0x1f. */
702
703 {"STORE", 0x23},
704 {"STORE_FP", 0x27},
705 {"CUSTOM_1", 0x2b},
706 {"AMO", 0x2f},
707 {"OP", 0x33},
708 {"LUI", 0x37},
709 {"OP_32", 0x3b},
710 /* 64b 0x3f. */
711
712 {"MADD", 0x43},
713 {"MSUB", 0x47},
714 {"NMADD", 0x4f},
715 {"NMSUB", 0x4b},
716 {"OP_FP", 0x53},
717 /*reserved 0x57. */
718 {"CUSTOM_2", 0x5b},
719 /* 48b 0x5f. */
720
721 {"BRANCH", 0x63},
722 {"JALR", 0x67},
723 /*reserved 0x5b. */
724 {"JAL", 0x6f},
725 {"SYSTEM", 0x73},
726 /*reserved 0x77. */
727 {"CUSTOM_3", 0x7b},
728 /* >80b 0x7f. */
729
730 {NULL, 0}
731};
732
733/* Hash table for lookup opcode name. */
629310ab 734static htab_t opcode_names_hash = NULL;
0e35537d
JW
735
736/* Initialization for hash table of opcode name. */
dcd709e0 737
0e35537d
JW
738static void
739init_opcode_names_hash (void)
740{
0e35537d
JW
741 const struct opcode_name_t *opcode;
742
743 for (opcode = &opcode_name_list[0]; opcode->name != NULL; ++opcode)
fe0e921f 744 if (str_hash_insert (opcode_names_hash, opcode->name, opcode, 0) != NULL)
b800637e 745 as_fatal (_("internal: duplicate %s"), opcode->name);
0e35537d
JW
746}
747
dcd709e0
NC
748/* Find `s` is a valid opcode name or not, return the opcode name info
749 if found. */
750
0e35537d
JW
751static const struct opcode_name_t *
752opcode_name_lookup (char **s)
753{
754 char *e;
755 char save_c;
756 struct opcode_name_t *o;
757
758 /* Find end of name. */
759 e = *s;
760 if (is_name_beginner (*e))
761 ++e;
762 while (is_part_of_name (*e))
763 ++e;
764
765 /* Terminate name. */
766 save_c = *e;
767 *e = '\0';
768
629310ab 769 o = (struct opcode_name_t *) str_hash_find (opcode_names_hash, *s);
0e35537d
JW
770
771 /* Advance to next token if one was recognized. */
772 if (o)
773 *s = e;
774
775 *e = save_c;
776 expr_end = e;
777
778 return o;
779}
780
e23eba97
NC
781enum reg_class
782{
783 RCLASS_GPR,
784 RCLASS_FPR,
8f595e9b
NC
785 RCLASS_MAX,
786
787 RCLASS_CSR
e23eba97
NC
788};
789
629310ab
ML
790static htab_t reg_names_hash = NULL;
791static htab_t csr_extra_hash = NULL;
e23eba97
NC
792
793#define ENCODE_REG_HASH(cls, n) \
794 ((void *)(uintptr_t)((n) * RCLASS_MAX + (cls) + 1))
795#define DECODE_REG_CLASS(hash) (((uintptr_t)(hash) - 1) % RCLASS_MAX)
796#define DECODE_REG_NUM(hash) (((uintptr_t)(hash) - 1) / RCLASS_MAX)
797
798static void
799hash_reg_name (enum reg_class class, const char *name, unsigned n)
800{
801 void *hash = ENCODE_REG_HASH (class, n);
fe0e921f 802 if (str_hash_insert (reg_names_hash, name, hash, 0) != NULL)
b800637e 803 as_fatal (_("internal: duplicate %s"), name);
e23eba97
NC
804}
805
806static void
807hash_reg_names (enum reg_class class, const char * const names[], unsigned n)
808{
809 unsigned i;
810
811 for (i = 0; i < n; i++)
812 hash_reg_name (class, names[i], i);
813}
814
8f595e9b 815/* Init hash table csr_extra_hash to handle CSR. */
dcd709e0 816
8f595e9b
NC
817static void
818riscv_init_csr_hash (const char *name,
3d73d29e
NC
819 unsigned address,
820 enum riscv_csr_class class,
821 enum riscv_spec_class define_version,
822 enum riscv_spec_class abort_version)
8f595e9b
NC
823{
824 struct riscv_csr_extra *entry, *pre_entry;
5b7c81bd 825 bool need_enrty = true;
8f595e9b
NC
826
827 pre_entry = NULL;
629310ab 828 entry = (struct riscv_csr_extra *) str_hash_find (csr_extra_hash, name);
8f595e9b
NC
829 while (need_enrty && entry != NULL)
830 {
831 if (entry->csr_class == class
1942a048
NC
832 && entry->address == address
833 && entry->define_version == define_version
834 && entry->abort_version == abort_version)
5b7c81bd 835 need_enrty = false;
8f595e9b
NC
836 pre_entry = entry;
837 entry = entry->next;
838 }
1942a048 839
dcd709e0 840 /* Duplicate CSR. */
8f595e9b
NC
841 if (!need_enrty)
842 return;
bd0cf5a6 843
8f595e9b
NC
844 entry = XNEW (struct riscv_csr_extra);
845 entry->csr_class = class;
846 entry->address = address;
847 entry->define_version = define_version;
848 entry->abort_version = abort_version;
5c505568 849 entry->next = NULL;
8f595e9b 850
8f595e9b 851 if (pre_entry == NULL)
fe0e921f 852 str_hash_insert (csr_extra_hash, name, entry, 0);
8f595e9b
NC
853 else
854 pre_entry->next = entry;
855}
bd0cf5a6 856
dcd709e0
NC
857/* Return the CSR address after checking the ISA dependency and
858 the privileged spec version.
859
860 There are one warning and two errors for CSR,
861
862 Invalid CSR: the CSR was defined, but isn't allowed for the current ISA
863 or the privileged spec, report warning only if -mcsr-check is set.
864 Unknown CSR: the CSR has never been defined, report error.
865 Improper CSR: the CSR number over the range (> 0xfff), report error. */
bd0cf5a6 866
08ccfccf
NC
867static unsigned int
868riscv_csr_address (const char *csr_name,
869 struct riscv_csr_extra *entry)
bd0cf5a6 870{
08ccfccf
NC
871 struct riscv_csr_extra *saved_entry = entry;
872 enum riscv_csr_class csr_class = entry->csr_class;
5b7c81bd
AM
873 bool need_check_version = true;
874 bool result = true;
8f595e9b 875
8f595e9b 876 switch (csr_class)
bd0cf5a6 877 {
8f595e9b
NC
878 case CSR_CLASS_I:
879 result = riscv_subset_supports ("i");
880 break;
08ccfccf
NC
881 case CSR_CLASS_I_32:
882 result = (xlen == 32 && riscv_subset_supports ("i"));
883 break;
8f595e9b
NC
884 case CSR_CLASS_F:
885 result = riscv_subset_supports ("f");
5b7c81bd 886 need_check_version = false;
8f595e9b 887 break;
08ccfccf 888 case CSR_CLASS_DEBUG:
5b7c81bd 889 need_check_version = false;
8f595e9b
NC
890 break;
891 default:
892 as_bad (_("internal: bad RISC-V CSR class (0x%x)"), csr_class);
bd0cf5a6
NC
893 }
894
08ccfccf 895 if (riscv_opts.csr_check && !result)
b800637e 896 as_warn (_("invalid CSR `%s' for the current ISA"), csr_name);
8f595e9b
NC
897
898 while (entry != NULL)
bd0cf5a6 899 {
08ccfccf
NC
900 if (!need_check_version
901 || (default_priv_spec >= entry->define_version
902 && default_priv_spec < entry->abort_version))
8f595e9b 903 {
dcd709e0 904 /* Find the CSR according to the specific version. */
08ccfccf 905 return entry->address;
8f595e9b
NC
906 }
907 entry = entry->next;
908 }
bd0cf5a6 909
dcd709e0
NC
910 /* Can not find the CSR address from the chosen privileged version,
911 so use the newly defined value. */
8f595e9b
NC
912 if (riscv_opts.csr_check)
913 {
3d73d29e
NC
914 const char *priv_name = NULL;
915 RISCV_GET_PRIV_SPEC_NAME (priv_name, default_priv_spec);
8f595e9b 916 if (priv_name != NULL)
b800637e 917 as_warn (_("invalid CSR `%s' for the privileged spec `%s'"),
8f595e9b 918 csr_name, priv_name);
bd0cf5a6 919 }
08ccfccf
NC
920
921 return saved_entry->address;
bd0cf5a6
NC
922}
923
dcd709e0
NC
924/* Return -1 if the CSR has never been defined. Otherwise, return
925 the address. */
bd0cf5a6 926
8f595e9b 927static unsigned int
bd0cf5a6
NC
928reg_csr_lookup_internal (const char *s)
929{
930 struct riscv_csr_extra *r =
629310ab 931 (struct riscv_csr_extra *) str_hash_find (csr_extra_hash, s);
bd0cf5a6
NC
932
933 if (r == NULL)
8f595e9b 934 return -1U;
bd0cf5a6 935
08ccfccf 936 return riscv_csr_address (s, r);
bd0cf5a6
NC
937}
938
e23eba97
NC
939static unsigned int
940reg_lookup_internal (const char *s, enum reg_class class)
941{
8f595e9b
NC
942 void *r;
943
944 if (class == RCLASS_CSR)
945 return reg_csr_lookup_internal (s);
e23eba97 946
629310ab 947 r = str_hash_find (reg_names_hash, s);
e23eba97
NC
948 if (r == NULL || DECODE_REG_CLASS (r) != class)
949 return -1;
7f999549
JW
950
951 if (riscv_opts.rve && class == RCLASS_GPR && DECODE_REG_NUM (r) > 15)
952 return -1;
953
e23eba97
NC
954 return DECODE_REG_NUM (r);
955}
956
5b7c81bd 957static bool
e23eba97
NC
958reg_lookup (char **s, enum reg_class class, unsigned int *regnop)
959{
960 char *e;
961 char save_c;
962 int reg = -1;
963
964 /* Find end of name. */
965 e = *s;
966 if (is_name_beginner (*e))
967 ++e;
968 while (is_part_of_name (*e))
969 ++e;
970
971 /* Terminate name. */
972 save_c = *e;
973 *e = '\0';
974
975 /* Look for the register. Advance to next token if one was recognized. */
976 if ((reg = reg_lookup_internal (*s, class)) >= 0)
977 *s = e;
978
979 *e = save_c;
980 if (regnop)
981 *regnop = reg;
982 return reg >= 0;
983}
984
5b7c81bd 985static bool
e23eba97
NC
986arg_lookup (char **s, const char *const *array, size_t size, unsigned *regnop)
987{
988 const char *p = strchr (*s, ',');
989 size_t i, len = p ? (size_t)(p - *s) : strlen (*s);
990
bfb218e3 991 if (len == 0)
5b7c81bd 992 return false;
bfb218e3 993
e23eba97
NC
994 for (i = 0; i < size; i++)
995 if (array[i] != NULL && strncmp (array[i], *s, len) == 0)
996 {
997 *regnop = i;
998 *s += len;
5b7c81bd 999 return true;
e23eba97
NC
1000 }
1001
5b7c81bd 1002 return false;
e23eba97
NC
1003}
1004
1005/* For consistency checking, verify that all bits are specified either
1006 by the match/mask part of the instruction definition, or by the
dcd709e0 1007 operand list. The `length` could be 0, 4 or 8, 0 for auto detection. */
0e35537d 1008
5b7c81bd 1009static bool
0e35537d 1010validate_riscv_insn (const struct riscv_opcode *opc, int length)
e23eba97
NC
1011{
1012 const char *p = opc->args;
1013 char c;
1014 insn_t used_bits = opc->mask;
0e35537d
JW
1015 int insn_width;
1016 insn_t required_bits;
1017
1018 if (length == 0)
1019 insn_width = 8 * riscv_insn_length (opc->match);
1020 else
1021 insn_width = 8 * length;
1022
1023 required_bits = ~0ULL >> (64 - insn_width);
e23eba97
NC
1024
1025 if ((used_bits & opc->match) != (opc->match & required_bits))
1026 {
1027 as_bad (_("internal: bad RISC-V opcode (mask error): %s %s"),
1028 opc->name, opc->args);
5b7c81bd 1029 return false;
e23eba97
NC
1030 }
1031
1032#define USE_BITS(mask,shift) (used_bits |= ((insn_t)(mask) << (shift)))
1033 while (*p)
1034 switch (c = *p++)
1035 {
1036 case 'C': /* RVC */
1037 switch (c = *p++)
1038 {
5a9f5403
NC
1039 case 'U': break; /* CRS1, constrained to equal RD. */
1040 case 'c': break; /* CRS1, constrained to equal sp. */
1041 case 'T': /* CRS2, floating point. */
1042 case 'V': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
1043 case 'S': /* CRS1S, floating point. */
e23eba97 1044 case 's': USE_BITS (OP_MASK_CRS1S, OP_SH_CRS1S); break;
5a9f5403
NC
1045 case 'w': break; /* CRS1S, constrained to equal RD. */
1046 case 'D': /* CRS2S, floating point. */
e23eba97 1047 case 't': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
5a9f5403
NC
1048 case 'x': break; /* CRS2S, constrained to equal RD. */
1049 case 'z': break; /* CRS2S, constrained to be x0. */
1050 case '>': /* CITYPE immediate, compressed shift. */
1051 case 'u': /* CITYPE immediate, compressed lui. */
1052 case 'v': /* CITYPE immediate, li to compressed lui. */
1053 case 'o': /* CITYPE immediate, allow zero. */
1054 case 'j': used_bits |= ENCODE_CITYPE_IMM (-1U); break;
1055 case 'L': used_bits |= ENCODE_CITYPE_ADDI16SP_IMM (-1U); break;
1056 case 'm': used_bits |= ENCODE_CITYPE_LWSP_IMM (-1U); break;
1057 case 'n': used_bits |= ENCODE_CITYPE_LDSP_IMM (-1U); break;
1058 case '6': used_bits |= ENCODE_CSSTYPE_IMM (-1U); break;
1059 case 'M': used_bits |= ENCODE_CSSTYPE_SWSP_IMM (-1U); break;
1060 case 'N': used_bits |= ENCODE_CSSTYPE_SDSP_IMM (-1U); break;
1061 case '8': used_bits |= ENCODE_CIWTYPE_IMM (-1U); break;
1062 case 'K': used_bits |= ENCODE_CIWTYPE_ADDI4SPN_IMM (-1U); break;
1063 /* CLTYPE and CSTYPE have the same immediate encoding. */
1064 case '5': used_bits |= ENCODE_CLTYPE_IMM (-1U); break;
1065 case 'k': used_bits |= ENCODE_CLTYPE_LW_IMM (-1U); break;
1066 case 'l': used_bits |= ENCODE_CLTYPE_LD_IMM (-1U); break;
1067 case 'p': used_bits |= ENCODE_CBTYPE_IMM (-1U); break;
1068 case 'a': used_bits |= ENCODE_CJTYPE_IMM (-1U); break;
1069 case 'F': /* Compressed funct for .insn directive. */
0e35537d
JW
1070 switch (c = *p++)
1071 {
4765cd61 1072 case '6': USE_BITS (OP_MASK_CFUNCT6, OP_SH_CFUNCT6); break;
0e35537d
JW
1073 case '4': USE_BITS (OP_MASK_CFUNCT4, OP_SH_CFUNCT4); break;
1074 case '3': USE_BITS (OP_MASK_CFUNCT3, OP_SH_CFUNCT3); break;
4765cd61 1075 case '2': USE_BITS (OP_MASK_CFUNCT2, OP_SH_CFUNCT2); break;
0e35537d 1076 default:
b800637e
NC
1077 as_bad (_("internal: bad RISC-V opcode "
1078 "(unknown operand type `CF%c'): %s %s"),
0e35537d 1079 c, opc->name, opc->args);
5b7c81bd 1080 return false;
0e35537d
JW
1081 }
1082 break;
e23eba97 1083 default:
b800637e
NC
1084 as_bad (_("internal: bad RISC-V opcode "
1085 "(unknown operand type `C%c'): %s %s"),
e23eba97 1086 c, opc->name, opc->args);
5b7c81bd 1087 return false;
e23eba97
NC
1088 }
1089 break;
1090 case ',': break;
1091 case '(': break;
1092 case ')': break;
1942a048
NC
1093 case '<': USE_BITS (OP_MASK_SHAMTW, OP_SH_SHAMTW); break;
1094 case '>': USE_BITS (OP_MASK_SHAMT, OP_SH_SHAMT); break;
5a9f5403
NC
1095 case 'A': break; /* Macro operand, must be symbol. */
1096 case 'B': break; /* Macro operand, must be symbol or constant. */
1097 case 'I': break; /* Macro operand, must be constant. */
1098 case 'D': /* RD, floating point. */
1942a048 1099 case 'd': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
5a9f5403
NC
1100 case 'Z': /* RS1, CSR number. */
1101 case 'S': /* RS1, floating point. */
1942a048 1102 case 's': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
5a9f5403
NC
1103 case 'U': /* RS1 and RS2 are the same, floating point. */
1104 USE_BITS (OP_MASK_RS1, OP_SH_RS1);
1105 /* Fall through. */
1106 case 'T': /* RS2, floating point. */
1942a048 1107 case 't': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
5a9f5403
NC
1108 case 'R': /* RS3, floating point. */
1109 case 'r': USE_BITS (OP_MASK_RS3, OP_SH_RS3); break;
1110 case 'm': USE_BITS (OP_MASK_RM, OP_SH_RM); break;
1111 case 'E': USE_BITS (OP_MASK_CSR, OP_SH_CSR); break;
1942a048
NC
1112 case 'P': USE_BITS (OP_MASK_PRED, OP_SH_PRED); break;
1113 case 'Q': USE_BITS (OP_MASK_SUCC, OP_SH_SUCC); break;
5a9f5403 1114 case 'o': /* ITYPE immediate, load displacement. */
1d65abb5 1115 case 'j': used_bits |= ENCODE_ITYPE_IMM (-1U); break;
5a9f5403
NC
1116 case 'a': used_bits |= ENCODE_JTYPE_IMM (-1U); break;
1117 case 'p': used_bits |= ENCODE_BTYPE_IMM (-1U); break;
1942a048
NC
1118 case 'q': used_bits |= ENCODE_STYPE_IMM (-1U); break;
1119 case 'u': used_bits |= ENCODE_UTYPE_IMM (-1U); break;
5a9f5403
NC
1120 case 'z': break; /* Zero immediate. */
1121 case '[': break; /* Unused operand. */
1122 case ']': break; /* Unused operand. */
1123 case '0': break; /* AMO displacement, must to zero. */
1124 case '1': break; /* Relaxation operand. */
dcd709e0 1125 case 'F': /* Funct for .insn directive. */
0e35537d
JW
1126 switch (c = *p++)
1127 {
1128 case '7': USE_BITS (OP_MASK_FUNCT7, OP_SH_FUNCT7); break;
1129 case '3': USE_BITS (OP_MASK_FUNCT3, OP_SH_FUNCT3); break;
1130 case '2': USE_BITS (OP_MASK_FUNCT2, OP_SH_FUNCT2); break;
1131 default:
b800637e
NC
1132 as_bad (_("internal: bad RISC-V opcode "
1133 "(unknown operand type `F%c'): %s %s"),
0e35537d 1134 c, opc->name, opc->args);
5b7c81bd 1135 return false;
0e35537d
JW
1136 }
1137 break;
dcd709e0 1138 case 'O': /* Opcode for .insn directive. */
0e35537d
JW
1139 switch (c = *p++)
1140 {
1141 case '4': USE_BITS (OP_MASK_OP, OP_SH_OP); break;
1142 case '2': USE_BITS (OP_MASK_OP2, OP_SH_OP2); break;
1143 default:
b800637e
NC
1144 as_bad (_("internal: bad RISC-V opcode "
1145 "(unknown operand type `F%c'): %s %s"),
0e35537d 1146 c, opc->name, opc->args);
5b7c81bd 1147 return false;
0e35537d
JW
1148 }
1149 break;
e23eba97
NC
1150 default:
1151 as_bad (_("internal: bad RISC-V opcode "
1152 "(unknown operand type `%c'): %s %s"),
1153 c, opc->name, opc->args);
5b7c81bd 1154 return false;
e23eba97
NC
1155 }
1156#undef USE_BITS
1157 if (used_bits != required_bits)
1158 {
b800637e
NC
1159 as_bad (_("internal: bad RISC-V opcode "
1160 "(bits 0x%lx undefined): %s %s"),
e23eba97
NC
1161 ~(unsigned long)(used_bits & required_bits),
1162 opc->name, opc->args);
5b7c81bd 1163 return false;
e23eba97 1164 }
5b7c81bd 1165 return true;
e23eba97
NC
1166}
1167
1168struct percent_op_match
1169{
1170 const char *str;
1171 bfd_reloc_code_real_type reloc;
1172};
1173
dcd709e0
NC
1174/* Common hash table initialization function for instruction and .insn
1175 directive. */
1176
629310ab 1177static htab_t
0e35537d 1178init_opcode_hash (const struct riscv_opcode *opcodes,
5b7c81bd 1179 bool insn_directive_p)
e23eba97
NC
1180{
1181 int i = 0;
0e35537d 1182 int length;
629310ab 1183 htab_t hash = str_htab_create ();
0e35537d 1184 while (opcodes[i].name)
e23eba97 1185 {
0e35537d 1186 const char *name = opcodes[i].name;
fe0e921f 1187 if (str_hash_insert (hash, name, &opcodes[i], 0) != NULL)
b800637e 1188 as_fatal (_("internal: duplicate %s"), name);
e23eba97
NC
1189
1190 do
1191 {
0e35537d 1192 if (opcodes[i].pinfo != INSN_MACRO)
e23eba97 1193 {
0e35537d
JW
1194 if (insn_directive_p)
1195 length = ((name[0] == 'c') ? 2 : 4);
1196 else
dcd709e0 1197 length = 0; /* Let assembler determine the length. */
0e35537d 1198 if (!validate_riscv_insn (&opcodes[i], length))
b800637e
NC
1199 as_fatal (_("internal: broken assembler. "
1200 "No assembly attempted"));
e23eba97 1201 }
0e35537d
JW
1202 else
1203 gas_assert (!insn_directive_p);
e23eba97
NC
1204 ++i;
1205 }
0e35537d 1206 while (opcodes[i].name && !strcmp (opcodes[i].name, name));
e23eba97
NC
1207 }
1208
0e35537d
JW
1209 return hash;
1210}
1211
1212/* This function is called once, at assembler startup time. It should set up
1213 all the tables, etc. that the MD part of the assembler will need. */
1214
1215void
1216md_begin (void)
1217{
1218 unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
1219
1220 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
b800637e 1221 as_warn (_("could not set architecture and machine"));
0e35537d 1222
5b7c81bd
AM
1223 op_hash = init_opcode_hash (riscv_opcodes, false);
1224 insn_type_hash = init_opcode_hash (riscv_insn_types, true);
0e35537d 1225
629310ab 1226 reg_names_hash = str_htab_create ();
e23eba97
NC
1227 hash_reg_names (RCLASS_GPR, riscv_gpr_names_numeric, NGPR);
1228 hash_reg_names (RCLASS_GPR, riscv_gpr_names_abi, NGPR);
1229 hash_reg_names (RCLASS_FPR, riscv_fpr_names_numeric, NFPR);
1230 hash_reg_names (RCLASS_FPR, riscv_fpr_names_abi, NFPR);
b9c04e5a
JW
1231 /* Add "fp" as an alias for "s0". */
1232 hash_reg_name (RCLASS_GPR, "fp", 8);
1233
bd0cf5a6 1234 /* Create and insert CSR hash tables. */
629310ab 1235 csr_extra_hash = str_htab_create ();
8f595e9b
NC
1236#define DECLARE_CSR(name, num, class, define_version, abort_version) \
1237 riscv_init_csr_hash (#name, num, class, define_version, abort_version);
1238#define DECLARE_CSR_ALIAS(name, num, class, define_version, abort_version) \
1239 DECLARE_CSR(name, num, class, define_version, abort_version);
e23eba97
NC
1240#include "opcode/riscv-opc.h"
1241#undef DECLARE_CSR
1242
629310ab 1243 opcode_names_hash = str_htab_create ();
bd0cf5a6
NC
1244 init_opcode_names_hash ();
1245
e23eba97
NC
1246 /* Set the default alignment for the text section. */
1247 record_alignment (text_section, riscv_opts.rvc ? 1 : 2);
1248}
1249
45f76423
AW
1250static insn_t
1251riscv_apply_const_reloc (bfd_reloc_code_real_type reloc_type, bfd_vma value)
1252{
1253 switch (reloc_type)
1254 {
1255 case BFD_RELOC_32:
1256 return value;
1257
1258 case BFD_RELOC_RISCV_HI20:
1259 return ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value));
1260
1261 case BFD_RELOC_RISCV_LO12_S:
1262 return ENCODE_STYPE_IMM (value);
1263
1264 case BFD_RELOC_RISCV_LO12_I:
1265 return ENCODE_ITYPE_IMM (value);
1266
1267 default:
1268 abort ();
1269 }
1270}
1271
e23eba97
NC
1272/* Output an instruction. IP is the instruction information.
1273 ADDRESS_EXPR is an operand of the instruction to be used with
1274 RELOC_TYPE. */
1275
1276static void
1277append_insn (struct riscv_cl_insn *ip, expressionS *address_expr,
1278 bfd_reloc_code_real_type reloc_type)
1279{
1280 dwarf2_emit_insn (0);
1281
1282 if (reloc_type != BFD_RELOC_UNUSED)
1283 {
1284 reloc_howto_type *howto;
1285
1d65abb5 1286 gas_assert (address_expr);
e23eba97
NC
1287 if (reloc_type == BFD_RELOC_12_PCREL
1288 || reloc_type == BFD_RELOC_RISCV_JMP)
1289 {
1290 int j = reloc_type == BFD_RELOC_RISCV_JMP;
1291 int best_case = riscv_insn_length (ip->insn_opcode);
1292 unsigned worst_case = relaxed_branch_length (NULL, NULL, 0);
743f5cfc
JW
1293
1294 if (now_seg == absolute_section)
1295 {
1296 as_bad (_("relaxable branches not supported in absolute section"));
1297 return;
1298 }
1299
e23eba97
NC
1300 add_relaxed_insn (ip, worst_case, best_case,
1301 RELAX_BRANCH_ENCODE (j, best_case == 2, worst_case),
1302 address_expr->X_add_symbol,
1303 address_expr->X_add_number);
1304 return;
1305 }
45f76423 1306 else
e23eba97 1307 {
45f76423
AW
1308 howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
1309 if (howto == NULL)
579f0281 1310 as_bad (_("internal: unsupported RISC-V relocation number %d"),
b800637e 1311 reloc_type);
e23eba97 1312
45f76423
AW
1313 ip->fixp = fix_new_exp (ip->frag, ip->where,
1314 bfd_get_reloc_size (howto),
5b7c81bd 1315 address_expr, false, reloc_type);
e23eba97 1316
45f76423 1317 ip->fixp->fx_tcbit = riscv_opts.relax;
e23eba97 1318 }
e23eba97
NC
1319 }
1320
e23eba97
NC
1321 add_fixed_insn (ip);
1322 install_insn (ip);
f77bb6c5
JW
1323
1324 /* We need to start a new frag after any instruction that can be
1325 optimized away or compressed by the linker during relaxation, to prevent
1326 the assembler from computing static offsets across such an instruction.
1327 This is necessary to get correct EH info. */
b1b11e92 1328 if (reloc_type == BFD_RELOC_RISCV_HI20
f77bb6c5
JW
1329 || reloc_type == BFD_RELOC_RISCV_PCREL_HI20
1330 || reloc_type == BFD_RELOC_RISCV_TPREL_HI20
1331 || reloc_type == BFD_RELOC_RISCV_TPREL_ADD)
1332 {
1333 frag_wane (frag_now);
1334 frag_new (0);
1335 }
e23eba97
NC
1336}
1337
1338/* Build an instruction created by a macro expansion. This is passed
dcd709e0
NC
1339 a pointer to the count of instructions created so far, an expression,
1340 the name of the instruction to build, an operand format string, and
1341 corresponding arguments. */
e23eba97
NC
1342
1343static void
1344macro_build (expressionS *ep, const char *name, const char *fmt, ...)
1345{
1346 const struct riscv_opcode *mo;
1347 struct riscv_cl_insn insn;
1348 bfd_reloc_code_real_type r;
1349 va_list args;
1350
1351 va_start (args, fmt);
1352
1353 r = BFD_RELOC_UNUSED;
629310ab 1354 mo = (struct riscv_opcode *) str_hash_find (op_hash, name);
e23eba97
NC
1355 gas_assert (mo);
1356
1357 /* Find a non-RVC variant of the instruction. append_insn will compress
1358 it if possible. */
1359 while (riscv_insn_length (mo->match) < 4)
1360 mo++;
1361 gas_assert (strcmp (name, mo->name) == 0);
1362
1363 create_insn (&insn, mo);
1364 for (;;)
1365 {
1366 switch (*fmt++)
1367 {
1368 case 'd':
1369 INSERT_OPERAND (RD, insn, va_arg (args, int));
1370 continue;
1371
1372 case 's':
1373 INSERT_OPERAND (RS1, insn, va_arg (args, int));
1374 continue;
1375
1376 case 't':
1377 INSERT_OPERAND (RS2, insn, va_arg (args, int));
1378 continue;
1379
e23eba97
NC
1380 case 'j':
1381 case 'u':
1382 case 'q':
1383 gas_assert (ep != NULL);
1384 r = va_arg (args, int);
1385 continue;
1386
1387 case '\0':
1388 break;
1389 case ',':
1390 continue;
1391 default:
b800637e 1392 as_fatal (_("internal: invalid macro"));
e23eba97
NC
1393 }
1394 break;
1395 }
1396 va_end (args);
1397 gas_assert (r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
1398
1399 append_insn (&insn, ep, r);
1400}
1401
db3b6ecc
KC
1402/* Build an instruction created by a macro expansion. Like md_assemble but
1403 accept a printf-style format string and arguments. */
1404
1405static void
1406md_assemblef (const char *format, ...)
1407{
1408 char *buf = NULL;
1409 va_list ap;
1410 int r;
1411
1412 va_start (ap, format);
1413
1414 r = vasprintf (&buf, format, ap);
1415
1416 if (r < 0)
b800637e 1417 as_fatal (_("internal: vasprintf failed"));
db3b6ecc
KC
1418
1419 md_assemble (buf);
1420 free(buf);
1421
1422 va_end (ap);
1423}
1424
e23eba97
NC
1425/* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
1426 unset. */
dcd709e0 1427
e23eba97
NC
1428static void
1429normalize_constant_expr (expressionS *ex)
1430{
1431 if (xlen > 32)
1432 return;
1433 if ((ex->X_op == O_constant || ex->X_op == O_symbol)
1434 && IS_ZEXT_32BIT_NUM (ex->X_add_number))
1435 ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
1436 - 0x80000000);
1437}
1438
ca2fd32c
JW
1439/* Fail if an expression EX is not a constant. IP is the instruction using EX.
1440 MAYBE_CSR is true if the symbol may be an unrecognized CSR name. */
e23eba97
NC
1441
1442static void
ca2fd32c 1443check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex,
5b7c81bd 1444 bool maybe_csr)
e23eba97
NC
1445{
1446 if (ex->X_op == O_big)
1447 as_bad (_("unsupported large constant"));
ca2fd32c
JW
1448 else if (maybe_csr && ex->X_op == O_symbol)
1449 as_bad (_("unknown CSR `%s'"),
1450 S_GET_NAME (ex->X_add_symbol));
e23eba97 1451 else if (ex->X_op != O_constant)
b800637e 1452 as_bad (_("instruction %s requires absolute expression"),
e23eba97
NC
1453 ip->insn_mo->name);
1454 normalize_constant_expr (ex);
1455}
1456
1457static symbolS *
1458make_internal_label (void)
1459{
e01e1cee
AM
1460 return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg, frag_now,
1461 frag_now_fix ());
e23eba97
NC
1462}
1463
1464/* Load an entry from the GOT. */
dcd709e0 1465
e23eba97
NC
1466static void
1467pcrel_access (int destreg, int tempreg, expressionS *ep,
1468 const char *lo_insn, const char *lo_pattern,
1469 bfd_reloc_code_real_type hi_reloc,
1470 bfd_reloc_code_real_type lo_reloc)
1471{
1472 expressionS ep2;
1473 ep2.X_op = O_symbol;
1474 ep2.X_add_symbol = make_internal_label ();
1475 ep2.X_add_number = 0;
1476
1477 macro_build (ep, "auipc", "d,u", tempreg, hi_reloc);
1478 macro_build (&ep2, lo_insn, lo_pattern, destreg, tempreg, lo_reloc);
1479}
1480
1481static void
1482pcrel_load (int destreg, int tempreg, expressionS *ep, const char *lo_insn,
1483 bfd_reloc_code_real_type hi_reloc,
1484 bfd_reloc_code_real_type lo_reloc)
1485{
1486 pcrel_access (destreg, tempreg, ep, lo_insn, "d,s,j", hi_reloc, lo_reloc);
1487}
1488
1489static void
1490pcrel_store (int srcreg, int tempreg, expressionS *ep, const char *lo_insn,
1491 bfd_reloc_code_real_type hi_reloc,
1492 bfd_reloc_code_real_type lo_reloc)
1493{
1494 pcrel_access (srcreg, tempreg, ep, lo_insn, "t,s,q", hi_reloc, lo_reloc);
1495}
1496
1497/* PC-relative function call using AUIPC/JALR, relaxed to JAL. */
dcd709e0 1498
e23eba97
NC
1499static void
1500riscv_call (int destreg, int tempreg, expressionS *ep,
1501 bfd_reloc_code_real_type reloc)
1502{
b1b11e92
AM
1503 /* Ensure the jalr is emitted to the same frag as the auipc. */
1504 frag_grow (8);
e23eba97
NC
1505 macro_build (ep, "auipc", "d,u", tempreg, reloc);
1506 macro_build (NULL, "jalr", "d,s", destreg, tempreg);
b1b11e92
AM
1507 /* See comment at end of append_insn. */
1508 frag_wane (frag_now);
1509 frag_new (0);
e23eba97
NC
1510}
1511
1512/* Load an integer constant into a register. */
1513
1514static void
1515load_const (int reg, expressionS *ep)
1516{
1517 int shift = RISCV_IMM_BITS;
4f7cc141 1518 bfd_vma upper_imm, sign = (bfd_vma) 1 << (RISCV_IMM_BITS - 1);
e23eba97 1519 expressionS upper = *ep, lower = *ep;
4f7cc141 1520 lower.X_add_number = ((ep->X_add_number & (sign + sign - 1)) ^ sign) - sign;
e23eba97
NC
1521 upper.X_add_number -= lower.X_add_number;
1522
1523 if (ep->X_op != O_constant)
1524 {
1525 as_bad (_("unsupported large constant"));
1526 return;
1527 }
1528
1d65abb5 1529 if (xlen > 32 && !IS_SEXT_32BIT_NUM (ep->X_add_number))
e23eba97
NC
1530 {
1531 /* Reduce to a signed 32-bit constant using SLLI and ADDI. */
1532 while (((upper.X_add_number >> shift) & 1) == 0)
1533 shift++;
1534
1535 upper.X_add_number = (int64_t) upper.X_add_number >> shift;
1d65abb5 1536 load_const (reg, &upper);
e23eba97 1537
db3b6ecc 1538 md_assemblef ("slli x%d, x%d, 0x%x", reg, reg, shift);
e23eba97 1539 if (lower.X_add_number != 0)
db3b6ecc
KC
1540 md_assemblef ("addi x%d, x%d, %" BFD_VMA_FMT "d", reg, reg,
1541 lower.X_add_number);
e23eba97
NC
1542 }
1543 else
1544 {
1545 /* Simply emit LUI and/or ADDI to build a 32-bit signed constant. */
1546 int hi_reg = 0;
1547
1548 if (upper.X_add_number != 0)
1549 {
db3b6ecc
KC
1550 /* Discard low part and zero-extend upper immediate. */
1551 upper_imm = ((uint32_t)upper.X_add_number >> shift);
1552
1553 md_assemblef ("lui x%d, 0x%" BFD_VMA_FMT "x", reg, upper_imm);
e23eba97
NC
1554 hi_reg = reg;
1555 }
1556
1557 if (lower.X_add_number != 0 || hi_reg == 0)
db3b6ecc
KC
1558 md_assemblef ("%s x%d, x%d, %" BFD_VMA_FMT "d", ADD32_INSN, reg, hi_reg,
1559 lower.X_add_number);
e23eba97
NC
1560 }
1561}
1562
c2137f55
NC
1563/* Zero extend and sign extend byte/half-word/word. */
1564
1565static void
5b7c81bd 1566riscv_ext (int destreg, int srcreg, unsigned shift, bool sign)
c2137f55
NC
1567{
1568 if (sign)
1569 {
1570 md_assemblef ("slli x%d, x%d, 0x%x", destreg, srcreg, shift);
1571 md_assemblef ("srai x%d, x%d, 0x%x", destreg, destreg, shift);
1572 }
1573 else
1574 {
1575 md_assemblef ("slli x%d, x%d, 0x%x", destreg, srcreg, shift);
1576 md_assemblef ("srli x%d, x%d, 0x%x", destreg, destreg, shift);
1577 }
1578}
1579
e23eba97 1580/* Expand RISC-V assembly macros into one or more instructions. */
2652cfad 1581
e23eba97
NC
1582static void
1583macro (struct riscv_cl_insn *ip, expressionS *imm_expr,
1584 bfd_reloc_code_real_type *imm_reloc)
1585{
1586 int rd = (ip->insn_opcode >> OP_SH_RD) & OP_MASK_RD;
1587 int rs1 = (ip->insn_opcode >> OP_SH_RS1) & OP_MASK_RS1;
1588 int rs2 = (ip->insn_opcode >> OP_SH_RS2) & OP_MASK_RS2;
1589 int mask = ip->insn_mo->mask;
1590
1591 switch (mask)
1592 {
1593 case M_LI:
1594 load_const (rd, imm_expr);
1595 break;
1596
1597 case M_LA:
1598 case M_LLA:
1599 /* Load the address of a symbol into a register. */
1600 if (!IS_SEXT_32BIT_NUM (imm_expr->X_add_number))
1601 as_bad (_("offset too large"));
1602
1603 if (imm_expr->X_op == O_constant)
1604 load_const (rd, imm_expr);
dcd709e0 1605 else if (riscv_opts.pic && mask == M_LA) /* Global PIC symbol. */
e23eba97
NC
1606 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
1607 BFD_RELOC_RISCV_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
dcd709e0 1608 else /* Local PIC symbol, or any non-PIC symbol. */
e23eba97
NC
1609 pcrel_load (rd, rd, imm_expr, "addi",
1610 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1611 break;
1612
1613 case M_LA_TLS_GD:
1614 pcrel_load (rd, rd, imm_expr, "addi",
1615 BFD_RELOC_RISCV_TLS_GD_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1616 break;
1617
1618 case M_LA_TLS_IE:
1619 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
1620 BFD_RELOC_RISCV_TLS_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1621 break;
1622
1623 case M_LB:
1624 pcrel_load (rd, rd, imm_expr, "lb",
1625 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1626 break;
1627
1628 case M_LBU:
1629 pcrel_load (rd, rd, imm_expr, "lbu",
1630 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1631 break;
1632
1633 case M_LH:
1634 pcrel_load (rd, rd, imm_expr, "lh",
1635 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1636 break;
1637
1638 case M_LHU:
1639 pcrel_load (rd, rd, imm_expr, "lhu",
1640 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1641 break;
1642
1643 case M_LW:
1644 pcrel_load (rd, rd, imm_expr, "lw",
1645 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1646 break;
1647
1648 case M_LWU:
1649 pcrel_load (rd, rd, imm_expr, "lwu",
1650 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1651 break;
1652
1653 case M_LD:
1654 pcrel_load (rd, rd, imm_expr, "ld",
1655 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1656 break;
1657
1658 case M_FLW:
1659 pcrel_load (rd, rs1, imm_expr, "flw",
1660 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1661 break;
1662
1663 case M_FLD:
1664 pcrel_load (rd, rs1, imm_expr, "fld",
1665 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1666 break;
1667
1668 case M_SB:
1669 pcrel_store (rs2, rs1, imm_expr, "sb",
1670 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1671 break;
1672
1673 case M_SH:
1674 pcrel_store (rs2, rs1, imm_expr, "sh",
1675 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1676 break;
1677
1678 case M_SW:
1679 pcrel_store (rs2, rs1, imm_expr, "sw",
1680 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1681 break;
1682
1683 case M_SD:
1684 pcrel_store (rs2, rs1, imm_expr, "sd",
1685 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1686 break;
1687
1688 case M_FSW:
1689 pcrel_store (rs2, rs1, imm_expr, "fsw",
1690 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1691 break;
1692
1693 case M_FSD:
1694 pcrel_store (rs2, rs1, imm_expr, "fsd",
1695 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1696 break;
1697
1698 case M_CALL:
1699 riscv_call (rd, rs1, imm_expr, *imm_reloc);
1700 break;
1701
c2137f55 1702 case M_ZEXTH:
5b7c81bd 1703 riscv_ext (rd, rs1, xlen - 16, false);
c2137f55
NC
1704 break;
1705
1706 case M_ZEXTW:
5b7c81bd 1707 riscv_ext (rd, rs1, xlen - 32, false);
c2137f55
NC
1708 break;
1709
1710 case M_SEXTB:
5b7c81bd 1711 riscv_ext (rd, rs1, xlen - 8, true);
c2137f55
NC
1712 break;
1713
1714 case M_SEXTH:
5b7c81bd 1715 riscv_ext (rd, rs1, xlen - 16, true);
c2137f55
NC
1716 break;
1717
e23eba97 1718 default:
b800637e 1719 as_bad (_("internal: macro %s not implemented"), ip->insn_mo->name);
e23eba97
NC
1720 break;
1721 }
1722}
1723
1724static const struct percent_op_match percent_op_utype[] =
1725{
1726 {"%tprel_hi", BFD_RELOC_RISCV_TPREL_HI20},
1727 {"%pcrel_hi", BFD_RELOC_RISCV_PCREL_HI20},
dee35d02 1728 {"%got_pcrel_hi", BFD_RELOC_RISCV_GOT_HI20},
e23eba97
NC
1729 {"%tls_ie_pcrel_hi", BFD_RELOC_RISCV_TLS_GOT_HI20},
1730 {"%tls_gd_pcrel_hi", BFD_RELOC_RISCV_TLS_GD_HI20},
1731 {"%hi", BFD_RELOC_RISCV_HI20},
1732 {0, 0}
1733};
1734
1735static const struct percent_op_match percent_op_itype[] =
1736{
1737 {"%lo", BFD_RELOC_RISCV_LO12_I},
1738 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_I},
1739 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_I},
1740 {0, 0}
1741};
1742
1743static const struct percent_op_match percent_op_stype[] =
1744{
1745 {"%lo", BFD_RELOC_RISCV_LO12_S},
1746 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_S},
1747 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_S},
1748 {0, 0}
1749};
1750
1751static const struct percent_op_match percent_op_rtype[] =
1752{
1753 {"%tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
1754 {0, 0}
1755};
1756
f50fabe4
JW
1757static const struct percent_op_match percent_op_null[] =
1758{
1759 {0, 0}
1760};
1761
e23eba97
NC
1762/* Return true if *STR points to a relocation operator. When returning true,
1763 move *STR over the operator and store its relocation code in *RELOC.
1764 Leave both *STR and *RELOC alone when returning false. */
1765
5b7c81bd 1766static bool
e23eba97
NC
1767parse_relocation (char **str, bfd_reloc_code_real_type *reloc,
1768 const struct percent_op_match *percent_op)
1769{
1770 for ( ; percent_op->str; percent_op++)
1771 if (strncasecmp (*str, percent_op->str, strlen (percent_op->str)) == 0)
1772 {
1773 int len = strlen (percent_op->str);
1774
1775 if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
1776 continue;
1777
1778 *str += strlen (percent_op->str);
1779 *reloc = percent_op->reloc;
1780
1781 /* Check whether the output BFD supports this relocation.
1782 If not, issue an error and fall back on something safe. */
45f76423
AW
1783 if (*reloc != BFD_RELOC_UNUSED
1784 && !bfd_reloc_type_lookup (stdoutput, *reloc))
e23eba97 1785 {
b800637e
NC
1786 as_bad ("internal: relocation %s isn't supported by the "
1787 "current ABI", percent_op->str);
e23eba97
NC
1788 *reloc = BFD_RELOC_UNUSED;
1789 }
5b7c81bd 1790 return true;
e23eba97 1791 }
5b7c81bd 1792 return false;
e23eba97
NC
1793}
1794
1795static void
1796my_getExpression (expressionS *ep, char *str)
1797{
1798 char *save_in;
1799
1800 save_in = input_line_pointer;
1801 input_line_pointer = str;
1802 expression (ep);
1803 expr_end = input_line_pointer;
1804 input_line_pointer = save_in;
1805}
1806
1807/* Parse string STR as a 16-bit relocatable operand. Store the
1808 expression in *EP and the relocation, if any, in RELOC.
1809 Return the number of relocation operators used (0 or 1).
1810
1811 On exit, EXPR_END points to the first character after the expression. */
1812
1813static size_t
1814my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1815 char *str, const struct percent_op_match *percent_op)
1816{
1817 size_t reloc_index;
1818 unsigned crux_depth, str_depth, regno;
1819 char *crux;
1820
8970c022
JW
1821 /* First, check for integer registers. No callers can accept a reg, but
1822 we need to avoid accidentally creating a useless undefined symbol below,
1823 if this is an instruction pattern that can't match. A glibc build fails
1824 if this is removed. */
e23eba97
NC
1825 if (reg_lookup (&str, RCLASS_GPR, &regno))
1826 {
1827 ep->X_op = O_register;
1828 ep->X_add_number = regno;
8970c022 1829 expr_end = str;
e23eba97
NC
1830 return 0;
1831 }
1832
1833 /* Search for the start of the main expression.
dcd709e0
NC
1834
1835 End the loop with CRUX pointing to the start of the main expression and
1836 with CRUX_DEPTH containing the number of open brackets at that point. */
e23eba97
NC
1837 reloc_index = -1;
1838 str_depth = 0;
1839 do
1840 {
1841 reloc_index++;
1842 crux = str;
1843 crux_depth = str_depth;
1844
1845 /* Skip over whitespace and brackets, keeping count of the number
1846 of brackets. */
1847 while (*str == ' ' || *str == '\t' || *str == '(')
1848 if (*str++ == '(')
1849 str_depth++;
1850 }
1851 while (*str == '%'
1852 && reloc_index < 1
1853 && parse_relocation (&str, reloc, percent_op));
1854
1855 my_getExpression (ep, crux);
1856 str = expr_end;
1857
1858 /* Match every open bracket. */
1859 while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
1860 if (*str++ == ')')
1861 crux_depth--;
1862
1863 if (crux_depth > 0)
1864 as_bad ("unclosed '('");
1865
1866 expr_end = str;
1867
1868 return reloc_index;
1869}
1870
0e35537d 1871/* Parse opcode name, could be an mnemonics or number. */
dcd709e0 1872
0e35537d
JW
1873static size_t
1874my_getOpcodeExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1875 char *str, const struct percent_op_match *percent_op)
1876{
1877 const struct opcode_name_t *o = opcode_name_lookup (&str);
1878
1879 if (o != NULL)
1880 {
1881 ep->X_op = O_constant;
1882 ep->X_add_number = o->val;
1883 return 0;
1884 }
1885
1886 return my_getSmallExpression (ep, reloc, str, percent_op);
1887}
1888
f0531ed6
JW
1889/* Detect and handle implicitly zero load-store offsets. For example,
1890 "lw t0, (t1)" is shorthand for "lw t0, 0(t1)". Return TRUE iff such
1891 an implicit offset was detected. */
1892
5b7c81bd 1893static bool
89424b1d 1894riscv_handle_implicit_zero_offset (expressionS *ep, const char *s)
f0531ed6
JW
1895{
1896 /* Check whether there is only a single bracketed expression left.
1897 If so, it must be the base register and the constant must be zero. */
1898 if (*s == '(' && strchr (s + 1, '(') == 0)
1899 {
89424b1d
MR
1900 ep->X_op = O_constant;
1901 ep->X_add_number = 0;
5b7c81bd 1902 return true;
f0531ed6
JW
1903 }
1904
5b7c81bd 1905 return false;
f0531ed6
JW
1906}
1907
54b2aec1 1908/* All RISC-V CSR instructions belong to one of these classes. */
54b2aec1
NC
1909enum csr_insn_type
1910{
1911 INSN_NOT_CSR,
1912 INSN_CSRRW,
1913 INSN_CSRRS,
1914 INSN_CSRRC
1915};
1916
1917/* Return which CSR instruction is checking. */
1918
1919static enum csr_insn_type
1920riscv_csr_insn_type (insn_t insn)
1921{
1922 if (((insn ^ MATCH_CSRRW) & MASK_CSRRW) == 0
1923 || ((insn ^ MATCH_CSRRWI) & MASK_CSRRWI) == 0)
1924 return INSN_CSRRW;
1925 else if (((insn ^ MATCH_CSRRS) & MASK_CSRRS) == 0
1926 || ((insn ^ MATCH_CSRRSI) & MASK_CSRRSI) == 0)
1927 return INSN_CSRRS;
1928 else if (((insn ^ MATCH_CSRRC) & MASK_CSRRC) == 0
1929 || ((insn ^ MATCH_CSRRCI) & MASK_CSRRCI) == 0)
1930 return INSN_CSRRC;
1931 else
1932 return INSN_NOT_CSR;
1933}
1934
1935/* CSRRW and CSRRWI always write CSR. CSRRS, CSRRC, CSRRSI and CSRRCI write
1936 CSR when RS1 isn't zero. The CSR is read only if the [11:10] bits of
1937 CSR address is 0x3. */
1938
5b7c81bd 1939static bool
54b2aec1
NC
1940riscv_csr_read_only_check (insn_t insn)
1941{
1942 int csr = (insn & (OP_MASK_CSR << OP_SH_CSR)) >> OP_SH_CSR;
1943 int rs1 = (insn & (OP_MASK_RS1 << OP_SH_RS1)) >> OP_SH_RS1;
1944 int readonly = (((csr & (0x3 << 10)) >> 10) == 0x3);
1945 enum csr_insn_type csr_insn = riscv_csr_insn_type (insn);
1946
1947 if (readonly
1948 && (((csr_insn == INSN_CSRRS
1949 || csr_insn == INSN_CSRRC)
1950 && rs1 != 0)
1951 || csr_insn == INSN_CSRRW))
5b7c81bd 1952 return false;
54b2aec1 1953
5b7c81bd 1954 return true;
54b2aec1
NC
1955}
1956
1a79004f
NC
1957/* Return True if it is a privileged instruction. Otherwise, return FALSE.
1958
1959 uret is actually a N-ext instruction. So it is better to regard it as
1960 an user instruction rather than the priv instruction.
1961
1962 hret is used to return from traps in H-mode. H-mode is removed since
1963 the v1.10 priv spec, but probably be added in the new hypervisor spec.
1964 Therefore, hret should be controlled by the hypervisor spec rather than
1965 priv spec in the future.
1966
1967 dret is defined in the debug spec, so it should be checked in the future,
1968 too. */
1969
5b7c81bd 1970static bool
1a79004f
NC
1971riscv_is_priv_insn (insn_t insn)
1972{
1973 return (((insn ^ MATCH_SRET) & MASK_SRET) == 0
1974 || ((insn ^ MATCH_MRET) & MASK_MRET) == 0
1975 || ((insn ^ MATCH_SFENCE_VMA) & MASK_SFENCE_VMA) == 0
1976 || ((insn ^ MATCH_WFI) & MASK_WFI) == 0
1977 /* The sfence.vm is dropped in the v1.10 priv specs, but we still need to
dcd709e0 1978 check it here to keep the compatible. */
1a79004f
NC
1979 || ((insn ^ MATCH_SFENCE_VM) & MASK_SFENCE_VM) == 0);
1980}
1981
e23eba97
NC
1982/* This routine assembles an instruction into its binary format. As a
1983 side effect, it sets the global variable imm_reloc to the type of
1984 relocation to do if one of the operands is an address expression. */
1985
1986static const char *
1987riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
629310ab 1988 bfd_reloc_code_real_type *imm_reloc, htab_t hash)
e23eba97
NC
1989{
1990 char *s;
1991 const char *args;
1992 char c = 0;
1993 struct riscv_opcode *insn;
1994 char *argsStart;
1995 unsigned int regno;
1996 char save_c = 0;
1997 int argnum;
1998 const struct percent_op_match *p;
1999 const char *error = "unrecognized opcode";
54b2aec1 2000 /* Indicate we are assembling instruction with CSR. */
5b7c81bd 2001 bool insn_with_csr = false;
e23eba97
NC
2002
2003 /* Parse the name of the instruction. Terminate the string if whitespace
629310ab 2004 is found so that str_hash_find only sees the name part of the string. */
e23eba97
NC
2005 for (s = str; *s != '\0'; ++s)
2006 if (ISSPACE (*s))
2007 {
2008 save_c = *s;
2009 *s++ = '\0';
2010 break;
2011 }
2012
629310ab 2013 insn = (struct riscv_opcode *) str_hash_find (hash, str);
e23eba97
NC
2014
2015 argsStart = s;
2016 for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
2017 {
1080bf78
JW
2018 if ((insn->xlen_requirement != 0) && (xlen != insn->xlen_requirement))
2019 continue;
2020
7e9ad3a3 2021 if (!riscv_multi_subset_supports (insn->insn_class))
e23eba97
NC
2022 continue;
2023
2024 create_insn (ip, insn);
2025 argnum = 1;
2026
2027 imm_expr->X_op = O_absent;
2028 *imm_reloc = BFD_RELOC_UNUSED;
2029 p = percent_op_itype;
2030
2031 for (args = insn->args;; ++args)
2032 {
2033 s += strspn (s, " \t");
2034 switch (*args)
2035 {
dcd709e0 2036 case '\0': /* End of args. */
e23eba97
NC
2037 if (insn->pinfo != INSN_MACRO)
2038 {
2039 if (!insn->match_func (insn, ip->insn_opcode))
2040 break;
0e35537d
JW
2041
2042 /* For .insn, insn->match and insn->mask are 0. */
2043 if (riscv_insn_length ((insn->match == 0 && insn->mask == 0)
2044 ? ip->insn_opcode
2045 : insn->match) == 2
2046 && !riscv_opts.rvc)
e23eba97 2047 break;
54b2aec1 2048
1a79004f 2049 if (riscv_is_priv_insn (ip->insn_opcode))
5b7c81bd 2050 explicit_priv_attr = true;
1a79004f 2051
54b2aec1
NC
2052 /* Check if we write a read-only CSR by the CSR
2053 instruction. */
2054 if (insn_with_csr
2055 && riscv_opts.csr_check
2056 && !riscv_csr_read_only_check (ip->insn_opcode))
2057 {
2058 /* Restore the character in advance, since we want to
2059 report the detailed warning message here. */
2060 if (save_c)
2061 *(argsStart - 1) = save_c;
b800637e 2062 as_warn (_("read-only CSR is written `%s'"), str);
5b7c81bd 2063 insn_with_csr = false;
54b2aec1 2064 }
e23eba97
NC
2065 }
2066 if (*s != '\0')
2067 break;
2068 /* Successful assembly. */
2069 error = NULL;
5b7c81bd 2070 insn_with_csr = false;
e23eba97
NC
2071 goto out;
2072
2073 case 'C': /* RVC */
2074 switch (*++args)
2075 {
dcd709e0 2076 case 's': /* RS1 x8-x15. */
e23eba97
NC
2077 if (!reg_lookup (&s, RCLASS_GPR, &regno)
2078 || !(regno >= 8 && regno <= 15))
2079 break;
2080 INSERT_OPERAND (CRS1S, *ip, regno % 8);
2081 continue;
2082 case 'w': /* RS1 x8-x15, constrained to equal RD x8-x15. */
2083 if (!reg_lookup (&s, RCLASS_GPR, &regno)
2084 || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
2085 break;
2086 continue;
dcd709e0 2087 case 't': /* RS2 x8-x15. */
e23eba97
NC
2088 if (!reg_lookup (&s, RCLASS_GPR, &regno)
2089 || !(regno >= 8 && regno <= 15))
2090 break;
2091 INSERT_OPERAND (CRS2S, *ip, regno % 8);
2092 continue;
2093 case 'x': /* RS2 x8-x15, constrained to equal RD x8-x15. */
2094 if (!reg_lookup (&s, RCLASS_GPR, &regno)
2095 || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
2096 break;
2097 continue;
2098 case 'U': /* RS1, constrained to equal RD. */
2099 if (!reg_lookup (&s, RCLASS_GPR, &regno)
2100 || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
2101 break;
2102 continue;
2103 case 'V': /* RS2 */
2104 if (!reg_lookup (&s, RCLASS_GPR, &regno))
2105 break;
2106 INSERT_OPERAND (CRS2, *ip, regno);
2107 continue;
2108 case 'c': /* RS1, constrained to equal sp. */
2109 if (!reg_lookup (&s, RCLASS_GPR, &regno)
2110 || regno != X_SP)
2111 break;
2112 continue;
dcd709e0 2113 case 'z': /* RS2, constrained to equal x0. */
ca0bc150
JW
2114 if (!reg_lookup (&s, RCLASS_GPR, &regno)
2115 || regno != 0)
2116 break;
2117 continue;
768589d1 2118 case '>': /* Shift amount, 0 - (XLEN-1). */
e23eba97
NC
2119 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2120 || imm_expr->X_op != O_constant
768589d1 2121 || (unsigned long) imm_expr->X_add_number >= xlen)
e23eba97 2122 break;
5a9f5403 2123 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
dc1e8a47 2124 rvc_imm_done:
e23eba97
NC
2125 s = expr_end;
2126 imm_expr->X_op = O_absent;
2127 continue;
5a9f5403 2128 case '5':
e23eba97
NC
2129 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2130 || imm_expr->X_op != O_constant
5a9f5403 2131 || imm_expr->X_add_number < 0
169ec512 2132 || imm_expr->X_add_number >= 32
5a9f5403 2133 || !VALID_CLTYPE_IMM ((valueT) imm_expr->X_add_number))
e23eba97 2134 break;
0257c2ff 2135 ip->insn_opcode |= ENCODE_CLTYPE_IMM (imm_expr->X_add_number);
e23eba97 2136 goto rvc_imm_done;
5a9f5403 2137 case '6':
0e35537d
JW
2138 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2139 || imm_expr->X_op != O_constant
0e35537d 2140 || imm_expr->X_add_number < 0
5a9f5403
NC
2141 || imm_expr->X_add_number >= 64
2142 || !VALID_CSSTYPE_IMM ((valueT) imm_expr->X_add_number))
0e35537d 2143 break;
0257c2ff 2144 ip->insn_opcode |= ENCODE_CSSTYPE_IMM (imm_expr->X_add_number);
0e35537d 2145 goto rvc_imm_done;
5a9f5403 2146 case '8':
e23eba97
NC
2147 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2148 || imm_expr->X_op != O_constant
5a9f5403
NC
2149 || imm_expr->X_add_number < 0
2150 || imm_expr->X_add_number >= 256
2151 || !VALID_CIWTYPE_IMM ((valueT) imm_expr->X_add_number))
e23eba97 2152 break;
0257c2ff 2153 ip->insn_opcode |= ENCODE_CIWTYPE_IMM (imm_expr->X_add_number);
e23eba97
NC
2154 goto rvc_imm_done;
2155 case 'j':
2156 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2157 || imm_expr->X_op != O_constant
2158 || imm_expr->X_add_number == 0
5a9f5403 2159 || !VALID_CITYPE_IMM ((valueT) imm_expr->X_add_number))
e23eba97 2160 break;
5a9f5403 2161 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
e23eba97
NC
2162 goto rvc_imm_done;
2163 case 'k':
f0531ed6
JW
2164 if (riscv_handle_implicit_zero_offset (imm_expr, s))
2165 continue;
e23eba97
NC
2166 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2167 || imm_expr->X_op != O_constant
5a9f5403 2168 || !VALID_CLTYPE_LW_IMM ((valueT) imm_expr->X_add_number))
e23eba97 2169 break;
5a9f5403 2170 ip->insn_opcode |= ENCODE_CLTYPE_LW_IMM (imm_expr->X_add_number);
e23eba97
NC
2171 goto rvc_imm_done;
2172 case 'l':
f0531ed6
JW
2173 if (riscv_handle_implicit_zero_offset (imm_expr, s))
2174 continue;
e23eba97
NC
2175 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2176 || imm_expr->X_op != O_constant
5a9f5403 2177 || !VALID_CLTYPE_LD_IMM ((valueT) imm_expr->X_add_number))
e23eba97 2178 break;
5a9f5403 2179 ip->insn_opcode |= ENCODE_CLTYPE_LD_IMM (imm_expr->X_add_number);
e23eba97
NC
2180 goto rvc_imm_done;
2181 case 'm':
f0531ed6
JW
2182 if (riscv_handle_implicit_zero_offset (imm_expr, s))
2183 continue;
e23eba97
NC
2184 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2185 || imm_expr->X_op != O_constant
5a9f5403 2186 || !VALID_CITYPE_LWSP_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2187 break;
2188 ip->insn_opcode |=
5a9f5403 2189 ENCODE_CITYPE_LWSP_IMM (imm_expr->X_add_number);
e23eba97
NC
2190 goto rvc_imm_done;
2191 case 'n':
f0531ed6
JW
2192 if (riscv_handle_implicit_zero_offset (imm_expr, s))
2193 continue;
e23eba97
NC
2194 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2195 || imm_expr->X_op != O_constant
5a9f5403 2196 || !VALID_CITYPE_LDSP_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2197 break;
2198 ip->insn_opcode |=
5a9f5403 2199 ENCODE_CITYPE_LDSP_IMM (imm_expr->X_add_number);
e23eba97 2200 goto rvc_imm_done;
b416fe87
KC
2201 case 'o':
2202 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2203 || imm_expr->X_op != O_constant
21a186f2
JW
2204 /* C.addiw, c.li, and c.andi allow zero immediate.
2205 C.addi allows zero immediate as hint. Otherwise this
2206 is same as 'j'. */
5a9f5403 2207 || !VALID_CITYPE_IMM ((valueT) imm_expr->X_add_number))
b416fe87 2208 break;
5a9f5403 2209 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
b416fe87 2210 goto rvc_imm_done;
e23eba97
NC
2211 case 'K':
2212 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2213 || imm_expr->X_op != O_constant
169ec512 2214 || imm_expr->X_add_number == 0
5a9f5403 2215 || !VALID_CIWTYPE_ADDI4SPN_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2216 break;
2217 ip->insn_opcode |=
5a9f5403 2218 ENCODE_CIWTYPE_ADDI4SPN_IMM (imm_expr->X_add_number);
e23eba97
NC
2219 goto rvc_imm_done;
2220 case 'L':
2221 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2222 || imm_expr->X_op != O_constant
5a9f5403 2223 || !VALID_CITYPE_ADDI16SP_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2224 break;
2225 ip->insn_opcode |=
5a9f5403 2226 ENCODE_CITYPE_ADDI16SP_IMM (imm_expr->X_add_number);
e23eba97
NC
2227 goto rvc_imm_done;
2228 case 'M':
f0531ed6
JW
2229 if (riscv_handle_implicit_zero_offset (imm_expr, s))
2230 continue;
e23eba97
NC
2231 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2232 || imm_expr->X_op != O_constant
5a9f5403 2233 || !VALID_CSSTYPE_SWSP_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2234 break;
2235 ip->insn_opcode |=
5a9f5403 2236 ENCODE_CSSTYPE_SWSP_IMM (imm_expr->X_add_number);
e23eba97
NC
2237 goto rvc_imm_done;
2238 case 'N':
f0531ed6
JW
2239 if (riscv_handle_implicit_zero_offset (imm_expr, s))
2240 continue;
e23eba97
NC
2241 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2242 || imm_expr->X_op != O_constant
5a9f5403 2243 || !VALID_CSSTYPE_SDSP_IMM ((valueT) imm_expr->X_add_number))
e23eba97
NC
2244 break;
2245 ip->insn_opcode |=
5a9f5403 2246 ENCODE_CSSTYPE_SDSP_IMM (imm_expr->X_add_number);
e23eba97
NC
2247 goto rvc_imm_done;
2248 case 'u':
2249 p = percent_op_utype;
2250 if (my_getSmallExpression (imm_expr, imm_reloc, s, p))
2251 break;
dc1e8a47 2252 rvc_lui:
e23eba97
NC
2253 if (imm_expr->X_op != O_constant
2254 || imm_expr->X_add_number <= 0
2255 || imm_expr->X_add_number >= RISCV_BIGIMM_REACH
2256 || (imm_expr->X_add_number >= RISCV_RVC_IMM_REACH / 2
2257 && (imm_expr->X_add_number <
2258 RISCV_BIGIMM_REACH - RISCV_RVC_IMM_REACH / 2)))
2259 break;
5a9f5403 2260 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
e23eba97
NC
2261 goto rvc_imm_done;
2262 case 'v':
2263 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2264 || (imm_expr->X_add_number & (RISCV_IMM_REACH - 1))
2265 || ((int32_t)imm_expr->X_add_number
2266 != imm_expr->X_add_number))
2267 break;
2268 imm_expr->X_add_number =
2269 ((uint32_t) imm_expr->X_add_number) >> RISCV_IMM_BITS;
2270 goto rvc_lui;
2271 case 'p':
2272 goto branch;
2273 case 'a':
2274 goto jump;
0e35537d
JW
2275 case 'S': /* Floating-point RS1 x8-x15. */
2276 if (!reg_lookup (&s, RCLASS_FPR, &regno)
2277 || !(regno >= 8 && regno <= 15))
2278 break;
2279 INSERT_OPERAND (CRS1S, *ip, regno % 8);
2280 continue;
e23eba97
NC
2281 case 'D': /* Floating-point RS2 x8-x15. */
2282 if (!reg_lookup (&s, RCLASS_FPR, &regno)
2283 || !(regno >= 8 && regno <= 15))
2284 break;
2285 INSERT_OPERAND (CRS2S, *ip, regno % 8);
2286 continue;
2287 case 'T': /* Floating-point RS2. */
2288 if (!reg_lookup (&s, RCLASS_FPR, &regno))
2289 break;
2290 INSERT_OPERAND (CRS2, *ip, regno);
2291 continue;
0e35537d
JW
2292 case 'F':
2293 switch (*++args)
2294 {
4765cd61
JW
2295 case '6':
2296 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2297 || imm_expr->X_op != O_constant
2298 || imm_expr->X_add_number < 0
2299 || imm_expr->X_add_number >= 64)
2300 {
b800637e
NC
2301 as_bad (_("bad value for compressed funct6 "
2302 "field, value must be 0...64"));
4765cd61
JW
2303 break;
2304 }
4765cd61
JW
2305 INSERT_OPERAND (CFUNCT6, *ip, imm_expr->X_add_number);
2306 imm_expr->X_op = O_absent;
2307 s = expr_end;
2308 continue;
1942a048 2309
0e35537d
JW
2310 case '4':
2311 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2312 || imm_expr->X_op != O_constant
2313 || imm_expr->X_add_number < 0
2314 || imm_expr->X_add_number >= 16)
2315 {
b800637e
NC
2316 as_bad (_("bad value for compressed funct4 "
2317 "field, value must be 0...15"));
0e35537d
JW
2318 break;
2319 }
0e35537d
JW
2320 INSERT_OPERAND (CFUNCT4, *ip, imm_expr->X_add_number);
2321 imm_expr->X_op = O_absent;
2322 s = expr_end;
2323 continue;
1942a048 2324
0e35537d
JW
2325 case '3':
2326 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2327 || imm_expr->X_op != O_constant
2328 || imm_expr->X_add_number < 0
2329 || imm_expr->X_add_number >= 8)
2330 {
b800637e
NC
2331 as_bad (_("bad value for compressed funct3 "
2332 "field, value must be 0...7"));
0e35537d
JW
2333 break;
2334 }
2335 INSERT_OPERAND (CFUNCT3, *ip, imm_expr->X_add_number);
2336 imm_expr->X_op = O_absent;
2337 s = expr_end;
2338 continue;
1942a048 2339
4765cd61
JW
2340 case '2':
2341 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2342 || imm_expr->X_op != O_constant
2343 || imm_expr->X_add_number < 0
2344 || imm_expr->X_add_number >= 4)
2345 {
b800637e
NC
2346 as_bad (_("bad value for compressed funct2 "
2347 "field, value must be 0...3"));
4765cd61
JW
2348 break;
2349 }
2350 INSERT_OPERAND (CFUNCT2, *ip, imm_expr->X_add_number);
2351 imm_expr->X_op = O_absent;
2352 s = expr_end;
2353 continue;
1942a048 2354
0e35537d 2355 default:
b800637e
NC
2356 as_bad (_("internal: unknown compressed funct "
2357 "field specifier `CF%c'"), *args);
0e35537d
JW
2358 }
2359 break;
2360
e23eba97 2361 default:
b800637e
NC
2362 as_bad (_("internal: unknown compressed field "
2363 "specifier `C%c'"), *args);
e23eba97
NC
2364 }
2365 break;
2366
2367 case ',':
2368 ++argnum;
2369 if (*s++ == *args)
2370 continue;
2371 s--;
2372 break;
2373
2374 case '(':
2375 case ')':
2376 case '[':
2377 case ']':
2378 if (*s++ == *args)
2379 continue;
2380 break;
2381
dcd709e0 2382 case '<': /* Shift amount, 0 - 31. */
e23eba97 2383 my_getExpression (imm_expr, s);
5b7c81bd 2384 check_absolute_expr (ip, imm_expr, false);
e23eba97 2385 if ((unsigned long) imm_expr->X_add_number > 31)
b800637e 2386 as_bad (_("improper shift amount (%lu)"),
94f78a77 2387 (unsigned long) imm_expr->X_add_number);
e23eba97
NC
2388 INSERT_OPERAND (SHAMTW, *ip, imm_expr->X_add_number);
2389 imm_expr->X_op = O_absent;
2390 s = expr_end;
2391 continue;
2392
dcd709e0 2393 case '>': /* Shift amount, 0 - (XLEN-1). */
e23eba97 2394 my_getExpression (imm_expr, s);
5b7c81bd 2395 check_absolute_expr (ip, imm_expr, false);
e23eba97 2396 if ((unsigned long) imm_expr->X_add_number >= xlen)
b800637e 2397 as_bad (_("improper shift amount (%lu)"),
94f78a77 2398 (unsigned long) imm_expr->X_add_number);
e23eba97
NC
2399 INSERT_OPERAND (SHAMT, *ip, imm_expr->X_add_number);
2400 imm_expr->X_op = O_absent;
2401 s = expr_end;
2402 continue;
2403
dcd709e0 2404 case 'Z': /* CSRRxI immediate. */
e23eba97 2405 my_getExpression (imm_expr, s);
5b7c81bd 2406 check_absolute_expr (ip, imm_expr, false);
e23eba97 2407 if ((unsigned long) imm_expr->X_add_number > 31)
b800637e 2408 as_bad (_("improper CSRxI immediate (%lu)"),
94f78a77 2409 (unsigned long) imm_expr->X_add_number);
e23eba97
NC
2410 INSERT_OPERAND (RS1, *ip, imm_expr->X_add_number);
2411 imm_expr->X_op = O_absent;
2412 s = expr_end;
2413 continue;
2414
dcd709e0 2415 case 'E': /* Control register. */
5b7c81bd
AM
2416 insn_with_csr = true;
2417 explicit_priv_attr = true;
e23eba97
NC
2418 if (reg_lookup (&s, RCLASS_CSR, &regno))
2419 INSERT_OPERAND (CSR, *ip, regno);
2420 else
2421 {
2422 my_getExpression (imm_expr, s);
5b7c81bd 2423 check_absolute_expr (ip, imm_expr, true);
e23eba97 2424 if ((unsigned long) imm_expr->X_add_number > 0xfff)
b800637e 2425 as_bad (_("improper CSR address (%lu)"),
94f78a77 2426 (unsigned long) imm_expr->X_add_number);
e23eba97
NC
2427 INSERT_OPERAND (CSR, *ip, imm_expr->X_add_number);
2428 imm_expr->X_op = O_absent;
2429 s = expr_end;
2430 }
2431 continue;
2432
dcd709e0 2433 case 'm': /* Rounding mode. */
e23eba97
NC
2434 if (arg_lookup (&s, riscv_rm, ARRAY_SIZE (riscv_rm), &regno))
2435 {
2436 INSERT_OPERAND (RM, *ip, regno);
2437 continue;
2438 }
2439 break;
2440
2441 case 'P':
dcd709e0 2442 case 'Q': /* Fence predecessor/successor. */
e23eba97
NC
2443 if (arg_lookup (&s, riscv_pred_succ, ARRAY_SIZE (riscv_pred_succ),
2444 &regno))
2445 {
2446 if (*args == 'P')
2447 INSERT_OPERAND (PRED, *ip, regno);
2448 else
2449 INSERT_OPERAND (SUCC, *ip, regno);
2450 continue;
2451 }
2452 break;
2453
dcd709e0
NC
2454 case 'd': /* Destination register. */
2455 case 's': /* Source register. */
2456 case 't': /* Target register. */
2457 case 'r': /* RS3 */
e23eba97
NC
2458 if (reg_lookup (&s, RCLASS_GPR, &regno))
2459 {
2460 c = *args;
2461 if (*s == ' ')
2462 ++s;
2463
2464 /* Now that we have assembled one operand, we use the args
2465 string to figure out where it goes in the instruction. */
2466 switch (c)
2467 {
2468 case 's':
2469 INSERT_OPERAND (RS1, *ip, regno);
2470 break;
2471 case 'd':
2472 INSERT_OPERAND (RD, *ip, regno);
2473 break;
2474 case 't':
2475 INSERT_OPERAND (RS2, *ip, regno);
2476 break;
0e35537d
JW
2477 case 'r':
2478 INSERT_OPERAND (RS3, *ip, regno);
2479 break;
e23eba97
NC
2480 }
2481 continue;
2482 }
2483 break;
2484
dcd709e0
NC
2485 case 'D': /* Floating point RD. */
2486 case 'S': /* Floating point RS1. */
2487 case 'T': /* Floating point RS2. */
2488 case 'U': /* Floating point RS1 and RS2. */
2489 case 'R': /* Floating point RS3. */
e23eba97
NC
2490 if (reg_lookup (&s, RCLASS_FPR, &regno))
2491 {
2492 c = *args;
2493 if (*s == ' ')
2494 ++s;
2495 switch (c)
2496 {
2497 case 'D':
2498 INSERT_OPERAND (RD, *ip, regno);
2499 break;
2500 case 'S':
2501 INSERT_OPERAND (RS1, *ip, regno);
2502 break;
2503 case 'U':
2504 INSERT_OPERAND (RS1, *ip, regno);
dcd709e0 2505 /* Fall through. */
e23eba97
NC
2506 case 'T':
2507 INSERT_OPERAND (RS2, *ip, regno);
2508 break;
2509 case 'R':
2510 INSERT_OPERAND (RS3, *ip, regno);
2511 break;
2512 }
2513 continue;
2514 }
e23eba97
NC
2515 break;
2516
2517 case 'I':
2518 my_getExpression (imm_expr, s);
2519 if (imm_expr->X_op != O_big
2520 && imm_expr->X_op != O_constant)
2521 break;
2522 normalize_constant_expr (imm_expr);
2523 s = expr_end;
2524 continue;
2525
2526 case 'A':
2527 my_getExpression (imm_expr, s);
2528 normalize_constant_expr (imm_expr);
2529 /* The 'A' format specifier must be a symbol. */
2530 if (imm_expr->X_op != O_symbol)
2531 break;
2532 *imm_reloc = BFD_RELOC_32;
2533 s = expr_end;
2534 continue;
2535
160d1b3d
SH
2536 case 'B':
2537 my_getExpression (imm_expr, s);
2538 normalize_constant_expr (imm_expr);
2539 /* The 'B' format specifier must be a symbol or a constant. */
2540 if (imm_expr->X_op != O_symbol && imm_expr->X_op != O_constant)
2541 break;
2542 if (imm_expr->X_op == O_symbol)
2543 *imm_reloc = BFD_RELOC_32;
2544 s = expr_end;
2545 continue;
2546
e23eba97 2547 case 'j': /* Sign-extended immediate. */
e23eba97 2548 p = percent_op_itype;
f50fabe4 2549 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
e23eba97
NC
2550 goto alu_op;
2551 case 'q': /* Store displacement. */
2552 p = percent_op_stype;
2553 *imm_reloc = BFD_RELOC_RISCV_LO12_S;
2554 goto load_store;
2555 case 'o': /* Load displacement. */
2556 p = percent_op_itype;
2557 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
2558 goto load_store;
dcd709e0
NC
2559 case '1':
2560 /* This is used for TLS, where the fourth operand is
2561 %tprel_add, to get a relocation applied to an add
2562 instruction, for relaxation to use. */
e23eba97 2563 p = percent_op_rtype;
f50fabe4 2564 goto alu_op;
dcd709e0 2565 case '0': /* AMO displacement, which must be zero. */
f50fabe4 2566 p = percent_op_null;
dc1e8a47 2567 load_store:
f0531ed6 2568 if (riscv_handle_implicit_zero_offset (imm_expr, s))
e23eba97 2569 continue;
dc1e8a47 2570 alu_op:
e23eba97
NC
2571 /* If this value won't fit into a 16 bit offset, then go
2572 find a macro that will generate the 32 bit offset
2573 code pattern. */
2574 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p))
2575 {
2576 normalize_constant_expr (imm_expr);
2577 if (imm_expr->X_op != O_constant
2578 || (*args == '0' && imm_expr->X_add_number != 0)
f50fabe4 2579 || (*args == '1')
e23eba97
NC
2580 || imm_expr->X_add_number >= (signed)RISCV_IMM_REACH/2
2581 || imm_expr->X_add_number < -(signed)RISCV_IMM_REACH/2)
2582 break;
2583 }
e23eba97
NC
2584 s = expr_end;
2585 continue;
2586
dcd709e0 2587 case 'p': /* PC-relative offset. */
dc1e8a47 2588 branch:
e23eba97
NC
2589 *imm_reloc = BFD_RELOC_12_PCREL;
2590 my_getExpression (imm_expr, s);
2591 s = expr_end;
2592 continue;
2593
dcd709e0 2594 case 'u': /* Upper 20 bits. */
e23eba97 2595 p = percent_op_utype;
4288405d 2596 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p))
e23eba97 2597 {
4288405d
JW
2598 if (imm_expr->X_op != O_constant)
2599 break;
2600
e23eba97
NC
2601 if (imm_expr->X_add_number < 0
2602 || imm_expr->X_add_number >= (signed)RISCV_BIGIMM_REACH)
2603 as_bad (_("lui expression not in range 0..1048575"));
2604
2605 *imm_reloc = BFD_RELOC_RISCV_HI20;
2606 imm_expr->X_add_number <<= RISCV_IMM_BITS;
2607 }
2608 s = expr_end;
2609 continue;
2610
dcd709e0 2611 case 'a': /* 20-bit PC-relative offset. */
dc1e8a47 2612 jump:
e23eba97
NC
2613 my_getExpression (imm_expr, s);
2614 s = expr_end;
2615 *imm_reloc = BFD_RELOC_RISCV_JMP;
2616 continue;
2617
2618 case 'c':
2619 my_getExpression (imm_expr, s);
2620 s = expr_end;
2621 if (strcmp (s, "@plt") == 0)
2622 {
2623 *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
2624 s += 4;
2625 }
2626 else
2627 *imm_reloc = BFD_RELOC_RISCV_CALL;
2628 continue;
1942a048 2629
0e35537d
JW
2630 case 'O':
2631 switch (*++args)
2632 {
2633 case '4':
2634 if (my_getOpcodeExpression (imm_expr, imm_reloc, s, p)
2635 || imm_expr->X_op != O_constant
2636 || imm_expr->X_add_number < 0
2637 || imm_expr->X_add_number >= 128
2638 || (imm_expr->X_add_number & 0x3) != 3)
2639 {
2640 as_bad (_("bad value for opcode field, "
2641 "value must be 0...127 and "
2642 "lower 2 bits must be 0x3"));
2643 break;
2644 }
0e35537d
JW
2645 INSERT_OPERAND (OP, *ip, imm_expr->X_add_number);
2646 imm_expr->X_op = O_absent;
2647 s = expr_end;
2648 continue;
1942a048 2649
0e35537d
JW
2650 case '2':
2651 if (my_getOpcodeExpression (imm_expr, imm_reloc, s, p)
2652 || imm_expr->X_op != O_constant
2653 || imm_expr->X_add_number < 0
2654 || imm_expr->X_add_number >= 3)
2655 {
2656 as_bad (_("bad value for opcode field, "
2657 "value must be 0...2"));
2658 break;
2659 }
0e35537d
JW
2660 INSERT_OPERAND (OP2, *ip, imm_expr->X_add_number);
2661 imm_expr->X_op = O_absent;
2662 s = expr_end;
2663 continue;
1942a048 2664
0e35537d 2665 default:
b800637e
NC
2666 as_bad (_("internal: unknown opcode field "
2667 "specifier `O%c'"), *args);
0e35537d
JW
2668 }
2669 break;
2670
2671 case 'F':
2672 switch (*++args)
2673 {
2674 case '7':
2675 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2676 || imm_expr->X_op != O_constant
2677 || imm_expr->X_add_number < 0
2678 || imm_expr->X_add_number >= 128)
2679 {
2680 as_bad (_("bad value for funct7 field, "
2681 "value must be 0...127"));
2682 break;
2683 }
0e35537d
JW
2684 INSERT_OPERAND (FUNCT7, *ip, imm_expr->X_add_number);
2685 imm_expr->X_op = O_absent;
2686 s = expr_end;
2687 continue;
1942a048 2688
0e35537d
JW
2689 case '3':
2690 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2691 || imm_expr->X_op != O_constant
2692 || imm_expr->X_add_number < 0
2693 || imm_expr->X_add_number >= 8)
2694 {
2695 as_bad (_("bad value for funct3 field, "
2696 "value must be 0...7"));
2697 break;
2698 }
0e35537d
JW
2699 INSERT_OPERAND (FUNCT3, *ip, imm_expr->X_add_number);
2700 imm_expr->X_op = O_absent;
2701 s = expr_end;
2702 continue;
1942a048 2703
0e35537d
JW
2704 case '2':
2705 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2706 || imm_expr->X_op != O_constant
2707 || imm_expr->X_add_number < 0
2708 || imm_expr->X_add_number >= 4)
2709 {
2710 as_bad (_("bad value for funct2 field, "
2711 "value must be 0...3"));
2712 break;
2713 }
0e35537d
JW
2714 INSERT_OPERAND (FUNCT2, *ip, imm_expr->X_add_number);
2715 imm_expr->X_op = O_absent;
2716 s = expr_end;
2717 continue;
2718
2719 default:
b800637e
NC
2720 as_bad (_("internal: unknown funct field "
2721 "specifier `F%c'\n"), *args);
0e35537d
JW
2722 }
2723 break;
e23eba97 2724
e925c834
JW
2725 case 'z':
2726 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2727 || imm_expr->X_op != O_constant
2728 || imm_expr->X_add_number != 0)
2729 break;
2730 s = expr_end;
2731 imm_expr->X_op = O_absent;
2732 continue;
2733
e23eba97 2734 default:
b800637e 2735 as_fatal (_("internal: unknown argument type `%c'"), *args);
e23eba97
NC
2736 }
2737 break;
2738 }
2739 s = argsStart;
2740 error = _("illegal operands");
5b7c81bd 2741 insn_with_csr = false;
e23eba97
NC
2742 }
2743
dc1e8a47 2744 out:
e23eba97
NC
2745 /* Restore the character we might have clobbered above. */
2746 if (save_c)
2747 *(argsStart - 1) = save_c;
2748
2749 return error;
2750}
2751
2752void
2753md_assemble (char *str)
2754{
2755 struct riscv_cl_insn insn;
2756 expressionS imm_expr;
2757 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
2758
dcd709e0
NC
2759 /* The architecture and privileged elf attributes should be set
2760 before assembling. */
8f595e9b
NC
2761 if (!start_assemble)
2762 {
5b7c81bd 2763 start_assemble = true;
e23eba97 2764
dcd709e0 2765 riscv_set_abi_by_arch ();
8f595e9b
NC
2766 if (!riscv_set_default_priv_spec (NULL))
2767 return;
2768 }
2769
2770 const char *error = riscv_ip (str, &insn, &imm_expr, &imm_reloc, op_hash);
2dc8dd17 2771
e23eba97
NC
2772 if (error)
2773 {
2774 as_bad ("%s `%s'", error, str);
2775 return;
2776 }
2777
2778 if (insn.insn_mo->pinfo == INSN_MACRO)
2779 macro (&insn, &imm_expr, &imm_reloc);
2780 else
2781 append_insn (&insn, &imm_expr, imm_reloc);
2782}
2783
2784const char *
2785md_atof (int type, char *litP, int *sizeP)
2786{
2787 return ieee_md_atof (type, litP, sizeP, TARGET_BYTES_BIG_ENDIAN);
2788}
2789
2790void
2791md_number_to_chars (char *buf, valueT val, int n)
2792{
fbc09e7a
MC
2793 if (target_big_endian)
2794 number_to_chars_bigendian (buf, val, n);
2795 else
2796 number_to_chars_littleendian (buf, val, n);
e23eba97
NC
2797}
2798
2799const char *md_shortopts = "O::g::G:";
2800
2801enum options
2802{
2922d21d 2803 OPTION_MARCH = OPTION_MD_BASE,
e23eba97
NC
2804 OPTION_PIC,
2805 OPTION_NO_PIC,
2922d21d 2806 OPTION_MABI,
71060565
JW
2807 OPTION_RELAX,
2808 OPTION_NO_RELAX,
2dc8dd17
JW
2809 OPTION_ARCH_ATTR,
2810 OPTION_NO_ARCH_ATTR,
2ca89224
NC
2811 OPTION_CSR_CHECK,
2812 OPTION_NO_CSR_CHECK,
8f595e9b
NC
2813 OPTION_MISA_SPEC,
2814 OPTION_MPRIV_SPEC,
fbc09e7a
MC
2815 OPTION_BIG_ENDIAN,
2816 OPTION_LITTLE_ENDIAN,
e23eba97
NC
2817 OPTION_END_OF_ENUM
2818};
2819
2820struct option md_longopts[] =
2821{
e23eba97
NC
2822 {"march", required_argument, NULL, OPTION_MARCH},
2823 {"fPIC", no_argument, NULL, OPTION_PIC},
2824 {"fpic", no_argument, NULL, OPTION_PIC},
2825 {"fno-pic", no_argument, NULL, OPTION_NO_PIC},
2922d21d 2826 {"mabi", required_argument, NULL, OPTION_MABI},
71060565
JW
2827 {"mrelax", no_argument, NULL, OPTION_RELAX},
2828 {"mno-relax", no_argument, NULL, OPTION_NO_RELAX},
2dc8dd17
JW
2829 {"march-attr", no_argument, NULL, OPTION_ARCH_ATTR},
2830 {"mno-arch-attr", no_argument, NULL, OPTION_NO_ARCH_ATTR},
2ca89224
NC
2831 {"mcsr-check", no_argument, NULL, OPTION_CSR_CHECK},
2832 {"mno-csr-check", no_argument, NULL, OPTION_NO_CSR_CHECK},
8f595e9b
NC
2833 {"misa-spec", required_argument, NULL, OPTION_MISA_SPEC},
2834 {"mpriv-spec", required_argument, NULL, OPTION_MPRIV_SPEC},
fbc09e7a
MC
2835 {"mbig-endian", no_argument, NULL, OPTION_BIG_ENDIAN},
2836 {"mlittle-endian", no_argument, NULL, OPTION_LITTLE_ENDIAN},
e23eba97
NC
2837
2838 {NULL, no_argument, NULL, 0}
2839};
2840size_t md_longopts_size = sizeof (md_longopts);
2841
e23eba97
NC
2842int
2843md_parse_option (int c, const char *arg)
2844{
2845 switch (c)
2846 {
e23eba97 2847 case OPTION_MARCH:
8f595e9b 2848 default_arch_with_ext = arg;
e23eba97
NC
2849 break;
2850
2851 case OPTION_NO_PIC:
5b7c81bd 2852 riscv_opts.pic = false;
e23eba97
NC
2853 break;
2854
2855 case OPTION_PIC:
5b7c81bd 2856 riscv_opts.pic = true;
e23eba97
NC
2857 break;
2858
2922d21d
AW
2859 case OPTION_MABI:
2860 if (strcmp (arg, "ilp32") == 0)
5b7c81bd 2861 riscv_set_abi (32, FLOAT_ABI_SOFT, false);
7f999549 2862 else if (strcmp (arg, "ilp32e") == 0)
5b7c81bd 2863 riscv_set_abi (32, FLOAT_ABI_SOFT, true);
2922d21d 2864 else if (strcmp (arg, "ilp32f") == 0)
5b7c81bd 2865 riscv_set_abi (32, FLOAT_ABI_SINGLE, false);
2922d21d 2866 else if (strcmp (arg, "ilp32d") == 0)
5b7c81bd 2867 riscv_set_abi (32, FLOAT_ABI_DOUBLE, false);
2922d21d 2868 else if (strcmp (arg, "ilp32q") == 0)
5b7c81bd 2869 riscv_set_abi (32, FLOAT_ABI_QUAD, false);
2922d21d 2870 else if (strcmp (arg, "lp64") == 0)
5b7c81bd 2871 riscv_set_abi (64, FLOAT_ABI_SOFT, false);
2922d21d 2872 else if (strcmp (arg, "lp64f") == 0)
5b7c81bd 2873 riscv_set_abi (64, FLOAT_ABI_SINGLE, false);
2922d21d 2874 else if (strcmp (arg, "lp64d") == 0)
5b7c81bd 2875 riscv_set_abi (64, FLOAT_ABI_DOUBLE, false);
2922d21d 2876 else if (strcmp (arg, "lp64q") == 0)
5b7c81bd 2877 riscv_set_abi (64, FLOAT_ABI_QUAD, false);
2922d21d
AW
2878 else
2879 return 0;
5b7c81bd 2880 explicit_mabi = true;
2922d21d
AW
2881 break;
2882
71060565 2883 case OPTION_RELAX:
5b7c81bd 2884 riscv_opts.relax = true;
71060565
JW
2885 break;
2886
2887 case OPTION_NO_RELAX:
5b7c81bd 2888 riscv_opts.relax = false;
71060565
JW
2889 break;
2890
2dc8dd17 2891 case OPTION_ARCH_ATTR:
5b7c81bd 2892 riscv_opts.arch_attr = true;
2dc8dd17
JW
2893 break;
2894
2895 case OPTION_NO_ARCH_ATTR:
5b7c81bd 2896 riscv_opts.arch_attr = false;
2dc8dd17
JW
2897 break;
2898
2ca89224 2899 case OPTION_CSR_CHECK:
5b7c81bd 2900 riscv_opts.csr_check = true;
2ca89224
NC
2901 break;
2902
2903 case OPTION_NO_CSR_CHECK:
5b7c81bd 2904 riscv_opts.csr_check = false;
2ca89224
NC
2905 break;
2906
8f595e9b
NC
2907 case OPTION_MISA_SPEC:
2908 return riscv_set_default_isa_spec (arg);
2909
2910 case OPTION_MPRIV_SPEC:
2911 return riscv_set_default_priv_spec (arg);
2912
fbc09e7a
MC
2913 case OPTION_BIG_ENDIAN:
2914 target_big_endian = 1;
2915 break;
2916
2917 case OPTION_LITTLE_ENDIAN:
2918 target_big_endian = 0;
2919 break;
2920
e23eba97
NC
2921 default:
2922 return 0;
2923 }
2924
2925 return 1;
2926}
2927
2928void
2929riscv_after_parse_args (void)
2930{
dcd709e0
NC
2931 /* The --with-arch is optional for now, so we still need to set the xlen
2932 according to the default_arch, which is set by the --target. */
e23eba97
NC
2933 if (xlen == 0)
2934 {
2935 if (strcmp (default_arch, "riscv32") == 0)
2936 xlen = 32;
2937 else if (strcmp (default_arch, "riscv64") == 0)
2938 xlen = 64;
2939 else
2940 as_bad ("unknown default architecture `%s'", default_arch);
2941 }
8f595e9b
NC
2942 if (default_arch_with_ext == NULL)
2943 default_arch_with_ext = xlen == 64 ? "rv64g" : "rv32g";
2944
2945 /* Initialize the hash table for extensions with default version. */
3d73d29e 2946 ext_version_hash = init_ext_version_hash ();
8f595e9b 2947
dcd709e0 2948 /* Set default specs. */
8f595e9b
NC
2949 if (default_isa_spec == ISA_SPEC_CLASS_NONE)
2950 riscv_set_default_isa_spec (DEFAULT_RISCV_ISA_SPEC);
dcd709e0
NC
2951 if (default_priv_spec == PRIV_SPEC_CLASS_NONE)
2952 riscv_set_default_priv_spec (DEFAULT_RISCV_PRIV_SPEC);
2922d21d 2953
8f595e9b 2954 riscv_set_arch (default_arch_with_ext);
2922d21d 2955
0ac2b354
AB
2956 /* If the CIE to be produced has not been overridden on the command line,
2957 then produce version 3 by default. This allows us to use the full
2958 range of registers in a .cfi_return_column directive. */
2959 if (flag_dwarf_cie_version == -1)
2960 flag_dwarf_cie_version = 3;
e23eba97
NC
2961}
2962
2963long
2964md_pcrel_from (fixS *fixP)
2965{
2966 return fixP->fx_where + fixP->fx_frag->fr_address;
2967}
2968
2969/* Apply a fixup to the object file. */
2970
2971void
2972md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
2973{
45f76423 2974 unsigned int subtype;
e23eba97 2975 bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
5b7c81bd 2976 bool relaxable = false;
c1b465c9 2977 offsetT loc;
a6cbf936 2978 segT sub_segment;
e23eba97
NC
2979
2980 /* Remember value for tc_gen_reloc. */
2981 fixP->fx_addnumber = *valP;
2982
2983 switch (fixP->fx_r_type)
2984 {
e23eba97
NC
2985 case BFD_RELOC_RISCV_HI20:
2986 case BFD_RELOC_RISCV_LO12_I:
2987 case BFD_RELOC_RISCV_LO12_S:
45f76423
AW
2988 bfd_putl32 (riscv_apply_const_reloc (fixP->fx_r_type, *valP)
2989 | bfd_getl32 (buf), buf);
a5ec5e3f 2990 if (fixP->fx_addsy == NULL)
5b7c81bd
AM
2991 fixP->fx_done = true;
2992 relaxable = true;
45f76423
AW
2993 break;
2994
2995 case BFD_RELOC_RISCV_GOT_HI20:
e23eba97
NC
2996 case BFD_RELOC_RISCV_ADD8:
2997 case BFD_RELOC_RISCV_ADD16:
2998 case BFD_RELOC_RISCV_ADD32:
2999 case BFD_RELOC_RISCV_ADD64:
45f76423 3000 case BFD_RELOC_RISCV_SUB6:
e23eba97
NC
3001 case BFD_RELOC_RISCV_SUB8:
3002 case BFD_RELOC_RISCV_SUB16:
3003 case BFD_RELOC_RISCV_SUB32:
3004 case BFD_RELOC_RISCV_SUB64:
45f76423
AW
3005 case BFD_RELOC_RISCV_RELAX:
3006 break;
3007
3008 case BFD_RELOC_RISCV_TPREL_HI20:
3009 case BFD_RELOC_RISCV_TPREL_LO12_I:
3010 case BFD_RELOC_RISCV_TPREL_LO12_S:
3011 case BFD_RELOC_RISCV_TPREL_ADD:
5b7c81bd 3012 relaxable = true;
45f76423
AW
3013 /* Fall through. */
3014
3015 case BFD_RELOC_RISCV_TLS_GOT_HI20:
3016 case BFD_RELOC_RISCV_TLS_GD_HI20:
3017 case BFD_RELOC_RISCV_TLS_DTPREL32:
3018 case BFD_RELOC_RISCV_TLS_DTPREL64:
e294484e
AW
3019 if (fixP->fx_addsy != NULL)
3020 S_SET_THREAD_LOCAL (fixP->fx_addsy);
3021 else
3022 as_bad_where (fixP->fx_file, fixP->fx_line,
3023 _("TLS relocation against a constant"));
e23eba97
NC
3024 break;
3025
e23eba97 3026 case BFD_RELOC_32:
a6cbf936
KLC
3027 /* Use pc-relative relocation for FDE initial location.
3028 The symbol address in .eh_frame may be adjusted in
3029 _bfd_elf_discard_section_eh_frame, and the content of
3030 .eh_frame will be adjusted in _bfd_elf_write_section_eh_frame.
3031 Therefore, we cannot insert a relocation whose addend symbol is
dcd709e0 3032 in .eh_frame. Othrewise, the value may be adjusted twice. */
a6cbf936
KLC
3033 if (fixP->fx_addsy && fixP->fx_subsy
3034 && (sub_segment = S_GET_SEGMENT (fixP->fx_subsy))
3035 && strcmp (sub_segment->name, ".eh_frame") == 0
3036 && S_GET_VALUE (fixP->fx_subsy)
3037 == fixP->fx_frag->fr_address + fixP->fx_where)
3038 {
3039 fixP->fx_r_type = BFD_RELOC_RISCV_32_PCREL;
3040 fixP->fx_subsy = NULL;
3041 break;
3042 }
3043 /* Fall through. */
3044 case BFD_RELOC_64:
e23eba97
NC
3045 case BFD_RELOC_16:
3046 case BFD_RELOC_8:
45f76423 3047 case BFD_RELOC_RISCV_CFA:
e23eba97
NC
3048 if (fixP->fx_addsy && fixP->fx_subsy)
3049 {
3050 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
3051 fixP->fx_next->fx_addsy = fixP->fx_subsy;
3052 fixP->fx_next->fx_subsy = NULL;
3053 fixP->fx_next->fx_offset = 0;
3054 fixP->fx_subsy = NULL;
3055
3056 switch (fixP->fx_r_type)
3057 {
3058 case BFD_RELOC_64:
3059 fixP->fx_r_type = BFD_RELOC_RISCV_ADD64;
3060 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB64;
3061 break;
3062
3063 case BFD_RELOC_32:
3064 fixP->fx_r_type = BFD_RELOC_RISCV_ADD32;
3065 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
3066 break;
3067
3068 case BFD_RELOC_16:
3069 fixP->fx_r_type = BFD_RELOC_RISCV_ADD16;
3070 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
3071 break;
3072
3073 case BFD_RELOC_8:
3074 fixP->fx_r_type = BFD_RELOC_RISCV_ADD8;
3075 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
073808ed 3076 break;
e23eba97 3077
45f76423
AW
3078 case BFD_RELOC_RISCV_CFA:
3079 /* Load the byte to get the subtype. */
c1b465c9
KLC
3080 subtype = bfd_get_8 (NULL, &((fragS *) (fixP->fx_frag->fr_opcode))->fr_literal[fixP->fx_where]);
3081 loc = fixP->fx_frag->fr_fix - (subtype & 7);
45f76423
AW
3082 switch (subtype)
3083 {
3084 case DW_CFA_advance_loc1:
c1b465c9
KLC
3085 fixP->fx_where = loc + 1;
3086 fixP->fx_next->fx_where = loc + 1;
45f76423
AW
3087 fixP->fx_r_type = BFD_RELOC_RISCV_SET8;
3088 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
3089 break;
3090
3091 case DW_CFA_advance_loc2:
3092 fixP->fx_size = 2;
45f76423 3093 fixP->fx_next->fx_size = 2;
c1b465c9
KLC
3094 fixP->fx_where = loc + 1;
3095 fixP->fx_next->fx_where = loc + 1;
45f76423
AW
3096 fixP->fx_r_type = BFD_RELOC_RISCV_SET16;
3097 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
3098 break;
3099
3100 case DW_CFA_advance_loc4:
3101 fixP->fx_size = 4;
45f76423 3102 fixP->fx_next->fx_size = 4;
c1b465c9
KLC
3103 fixP->fx_where = loc;
3104 fixP->fx_next->fx_where = loc;
45f76423
AW
3105 fixP->fx_r_type = BFD_RELOC_RISCV_SET32;
3106 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
3107 break;
3108
3109 default:
3110 if (subtype < 0x80 && (subtype & 0x40))
3111 {
3112 /* DW_CFA_advance_loc */
2aece2ba
KLC
3113 fixP->fx_frag = (fragS *) fixP->fx_frag->fr_opcode;
3114 fixP->fx_next->fx_frag = fixP->fx_frag;
45f76423
AW
3115 fixP->fx_r_type = BFD_RELOC_RISCV_SET6;
3116 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB6;
3117 }
3118 else
b800637e 3119 as_fatal (_("internal: bad CFA value #%d"), subtype);
45f76423
AW
3120 break;
3121 }
3122 break;
3123
e23eba97
NC
3124 default:
3125 /* This case is unreachable. */
3126 abort ();
3127 }
3128 }
3129 /* Fall through. */
3130
3131 case BFD_RELOC_RVA:
3132 /* If we are deleting this reloc entry, we must fill in the
3133 value now. This can happen if we have a .word which is not
3134 resolved when it appears but is later defined. */
3135 if (fixP->fx_addsy == NULL)
3136 {
3137 gas_assert (fixP->fx_size <= sizeof (valueT));
3138 md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
3139 fixP->fx_done = 1;
3140 }
3141 break;
3142
3143 case BFD_RELOC_RISCV_JMP:
3144 if (fixP->fx_addsy)
3145 {
3146 /* Fill in a tentative value to improve objdump readability. */
3147 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
3148 bfd_vma delta = target - md_pcrel_from (fixP);
5a9f5403 3149 bfd_putl32 (bfd_getl32 (buf) | ENCODE_JTYPE_IMM (delta), buf);
e23eba97
NC
3150 }
3151 break;
3152
3153 case BFD_RELOC_12_PCREL:
3154 if (fixP->fx_addsy)
3155 {
3156 /* Fill in a tentative value to improve objdump readability. */
3157 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
3158 bfd_vma delta = target - md_pcrel_from (fixP);
5a9f5403 3159 bfd_putl32 (bfd_getl32 (buf) | ENCODE_BTYPE_IMM (delta), buf);
e23eba97
NC
3160 }
3161 break;
3162
3163 case BFD_RELOC_RISCV_RVC_BRANCH:
3164 if (fixP->fx_addsy)
3165 {
3166 /* Fill in a tentative value to improve objdump readability. */
3167 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
3168 bfd_vma delta = target - md_pcrel_from (fixP);
5a9f5403 3169 bfd_putl16 (bfd_getl16 (buf) | ENCODE_CBTYPE_IMM (delta), buf);
e23eba97
NC
3170 }
3171 break;
3172
3173 case BFD_RELOC_RISCV_RVC_JUMP:
3174 if (fixP->fx_addsy)
3175 {
3176 /* Fill in a tentative value to improve objdump readability. */
3177 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
3178 bfd_vma delta = target - md_pcrel_from (fixP);
5a9f5403 3179 bfd_putl16 (bfd_getl16 (buf) | ENCODE_CJTYPE_IMM (delta), buf);
e23eba97
NC
3180 }
3181 break;
3182
e23eba97
NC
3183 case BFD_RELOC_RISCV_CALL:
3184 case BFD_RELOC_RISCV_CALL_PLT:
5b7c81bd 3185 relaxable = true;
45f76423
AW
3186 break;
3187
9d06997a 3188 case BFD_RELOC_RISCV_PCREL_HI20:
45f76423
AW
3189 case BFD_RELOC_RISCV_PCREL_LO12_S:
3190 case BFD_RELOC_RISCV_PCREL_LO12_I:
9d06997a
PD
3191 relaxable = riscv_opts.relax;
3192 break;
3193
e23eba97
NC
3194 case BFD_RELOC_RISCV_ALIGN:
3195 break;
3196
3197 default:
3198 /* We ignore generic BFD relocations we don't know about. */
3199 if (bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type) != NULL)
b800637e 3200 as_fatal (_("internal: bad relocation #%d"), fixP->fx_r_type);
e23eba97 3201 }
45f76423 3202
e294484e 3203 if (fixP->fx_subsy != NULL)
4bf09429 3204 as_bad_subtract (fixP);
e294484e 3205
45f76423
AW
3206 /* Add an R_RISCV_RELAX reloc if the reloc is relaxable. */
3207 if (relaxable && fixP->fx_tcbit && fixP->fx_addsy != NULL)
3208 {
3209 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
3210 fixP->fx_next->fx_addsy = fixP->fx_next->fx_subsy = NULL;
3211 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_RELAX;
b1b11e92 3212 fixP->fx_next->fx_size = 0;
45f76423
AW
3213 }
3214}
3215
3216/* Because the value of .cfi_remember_state may changed after relaxation,
3217 we insert a fix to relocate it again in link-time. */
3218
3219void
3220riscv_pre_output_hook (void)
3221{
3222 const frchainS *frch;
72393fd1
JW
3223 segT s;
3224
3225 /* Save the current segment info. */
3226 segT seg = now_seg;
3227 subsegT subseg = now_subseg;
45f76423
AW
3228
3229 for (s = stdoutput->sections; s; s = s->next)
3230 for (frch = seg_info (s)->frchainP; frch; frch = frch->frch_next)
3231 {
7cb7b948 3232 fragS *frag;
45f76423
AW
3233
3234 for (frag = frch->frch_root; frag; frag = frag->fr_next)
3235 {
3236 if (frag->fr_type == rs_cfa)
3237 {
45f76423 3238 expressionS exp;
8d1015a8 3239 expressionS *symval;
45f76423 3240
8d1015a8 3241 symval = symbol_get_value_expression (frag->fr_symbol);
45f76423 3242 exp.X_op = O_subtract;
8d1015a8 3243 exp.X_add_symbol = symval->X_add_symbol;
45f76423 3244 exp.X_add_number = 0;
8d1015a8 3245 exp.X_op_symbol = symval->X_op_symbol;
45f76423 3246
72393fd1
JW
3247 /* We must set the segment before creating a frag after all
3248 frag chains have been chained together. */
3249 subseg_set (s, frch->frch_subseg);
3250
c1b465c9 3251 fix_new_exp (frag, (int) frag->fr_offset, 1, &exp, 0,
45f76423
AW
3252 BFD_RELOC_RISCV_CFA);
3253 }
3254 }
3255 }
72393fd1
JW
3256
3257 /* Restore the original segment info. */
3258 subseg_set (seg, subseg);
e23eba97
NC
3259}
3260
3261/* This structure is used to hold a stack of .option values. */
e23eba97
NC
3262struct riscv_option_stack
3263{
3264 struct riscv_option_stack *next;
3265 struct riscv_set_options options;
3266};
3267
3268static struct riscv_option_stack *riscv_opts_stack;
3269
3270/* Handle the .option pseudo-op. */
3271
3272static void
3273s_riscv_option (int x ATTRIBUTE_UNUSED)
3274{
3275 char *name = input_line_pointer, ch;
3276
3277 while (!is_end_of_line[(unsigned char) *input_line_pointer])
3278 ++input_line_pointer;
3279 ch = *input_line_pointer;
3280 *input_line_pointer = '\0';
3281
3282 if (strcmp (name, "rvc") == 0)
5b7c81bd 3283 riscv_set_rvc (true);
e23eba97 3284 else if (strcmp (name, "norvc") == 0)
5b7c81bd 3285 riscv_set_rvc (false);
e23eba97 3286 else if (strcmp (name, "pic") == 0)
5b7c81bd 3287 riscv_opts.pic = true;
e23eba97 3288 else if (strcmp (name, "nopic") == 0)
5b7c81bd 3289 riscv_opts.pic = false;
45f76423 3290 else if (strcmp (name, "relax") == 0)
5b7c81bd 3291 riscv_opts.relax = true;
45f76423 3292 else if (strcmp (name, "norelax") == 0)
5b7c81bd 3293 riscv_opts.relax = false;
2ca89224 3294 else if (strcmp (name, "csr-check") == 0)
5b7c81bd 3295 riscv_opts.csr_check = true;
2ca89224 3296 else if (strcmp (name, "no-csr-check") == 0)
5b7c81bd 3297 riscv_opts.csr_check = false;
e23eba97
NC
3298 else if (strcmp (name, "push") == 0)
3299 {
3300 struct riscv_option_stack *s;
3301
3302 s = (struct riscv_option_stack *) xmalloc (sizeof *s);
3303 s->next = riscv_opts_stack;
3304 s->options = riscv_opts;
3305 riscv_opts_stack = s;
3306 }
3307 else if (strcmp (name, "pop") == 0)
3308 {
3309 struct riscv_option_stack *s;
3310
3311 s = riscv_opts_stack;
3312 if (s == NULL)
3313 as_bad (_(".option pop with no .option push"));
3314 else
3315 {
3316 riscv_opts = s->options;
3317 riscv_opts_stack = s->next;
3318 free (s);
3319 }
3320 }
3321 else
3322 {
b800637e 3323 as_warn (_("unrecognized .option directive: %s\n"), name);
e23eba97
NC
3324 }
3325 *input_line_pointer = ch;
3326 demand_empty_rest_of_line ();
3327}
3328
3329/* Handle the .dtprelword and .dtpreldword pseudo-ops. They generate
3330 a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
3331 use in DWARF debug information. */
3332
3333static void
3334s_dtprel (int bytes)
3335{
3336 expressionS ex;
3337 char *p;
3338
3339 expression (&ex);
3340
3341 if (ex.X_op != O_symbol)
3342 {
b800637e 3343 as_bad (_("unsupported use of %s"), (bytes == 8
e23eba97
NC
3344 ? ".dtpreldword"
3345 : ".dtprelword"));
3346 ignore_rest_of_line ();
3347 }
3348
3349 p = frag_more (bytes);
3350 md_number_to_chars (p, 0, bytes);
5b7c81bd 3351 fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, false,
e23eba97
NC
3352 (bytes == 8
3353 ? BFD_RELOC_RISCV_TLS_DTPREL64
3354 : BFD_RELOC_RISCV_TLS_DTPREL32));
3355
3356 demand_empty_rest_of_line ();
3357}
3358
3359/* Handle the .bss pseudo-op. */
3360
3361static void
3362s_bss (int ignore ATTRIBUTE_UNUSED)
3363{
3364 subseg_set (bss_section, 0);
3365 demand_empty_rest_of_line ();
3366}
3367
e23eba97 3368static void
d115ab8e 3369riscv_make_nops (char *buf, bfd_vma bytes)
e23eba97 3370{
d115ab8e 3371 bfd_vma i = 0;
e23eba97 3372
e5b737de
AW
3373 /* RISC-V instructions cannot begin or end on odd addresses, so this case
3374 means we are not within a valid instruction sequence. It is thus safe
3375 to use a zero byte, even though that is not a valid instruction. */
3376 if (bytes % 2 == 1)
3377 buf[i++] = 0;
3378
3379 /* Use at most one 2-byte NOP. */
3380 if ((bytes - i) % 4 == 2)
e23eba97 3381 {
fbc09e7a 3382 number_to_chars_littleendian (buf + i, RVC_NOP, 2);
d115ab8e 3383 i += 2;
e23eba97
NC
3384 }
3385
e5b737de 3386 /* Fill the remainder with 4-byte NOPs. */
d115ab8e 3387 for ( ; i < bytes; i += 4)
fbc09e7a 3388 number_to_chars_littleendian (buf + i, RISCV_NOP, 4);
d115ab8e 3389}
e23eba97 3390
d115ab8e
AW
3391/* Called from md_do_align. Used to create an alignment frag in a
3392 code section by emitting a worst-case NOP sequence that the linker
3393 will later relax to the correct number of NOPs. We can't compute
3394 the correct alignment now because of other linker relaxations. */
3395
5b7c81bd 3396bool
d115ab8e
AW
3397riscv_frag_align_code (int n)
3398{
e5b737de 3399 bfd_vma bytes = (bfd_vma) 1 << n;
36877bfb
JW
3400 bfd_vma insn_alignment = riscv_opts.rvc ? 2 : 4;
3401 bfd_vma worst_case_bytes = bytes - insn_alignment;
3402 char *nops;
ed0816bd 3403 expressionS ex;
d115ab8e 3404
36877bfb
JW
3405 /* If we are moving to a smaller alignment than the instruction size, then no
3406 alignment is required. */
3407 if (bytes <= insn_alignment)
5b7c81bd 3408 return true;
36877bfb 3409
d115ab8e
AW
3410 /* When not relaxing, riscv_handle_align handles code alignment. */
3411 if (!riscv_opts.relax)
5b7c81bd 3412 return false;
e23eba97 3413
e80ae190
JW
3414 nops = frag_more (worst_case_bytes);
3415
ed0816bd
PD
3416 ex.X_op = O_constant;
3417 ex.X_add_number = worst_case_bytes;
d115ab8e 3418
ed0816bd 3419 riscv_make_nops (nops, worst_case_bytes);
e23eba97 3420
ed0816bd 3421 fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
5b7c81bd 3422 &ex, false, BFD_RELOC_RISCV_ALIGN);
e23eba97 3423
5b7c81bd 3424 return true;
d115ab8e 3425}
e23eba97 3426
d115ab8e
AW
3427/* Implement HANDLE_ALIGN. */
3428
3429void
3430riscv_handle_align (fragS *fragP)
3431{
3432 switch (fragP->fr_type)
3433 {
3434 case rs_align_code:
3435 /* When relaxing, riscv_frag_align_code handles code alignment. */
3436 if (!riscv_opts.relax)
3437 {
e80ae190
JW
3438 bfd_signed_vma bytes = (fragP->fr_next->fr_address
3439 - fragP->fr_address - fragP->fr_fix);
3440 /* We have 4 byte uncompressed nops. */
3441 bfd_signed_vma size = 4;
3442 bfd_signed_vma excess = bytes % size;
3443 char *p = fragP->fr_literal + fragP->fr_fix;
3444
3445 if (bytes <= 0)
d115ab8e
AW
3446 break;
3447
e80ae190
JW
3448 /* Insert zeros or compressed nops to get 4 byte alignment. */
3449 if (excess)
3450 {
3451 riscv_make_nops (p, excess);
3452 fragP->fr_fix += excess;
3453 p += excess;
3454 }
3455
3456 /* Insert variable number of 4 byte uncompressed nops. */
3457 riscv_make_nops (p, size);
3458 fragP->fr_var = size;
d115ab8e
AW
3459 }
3460 break;
3461
3462 default:
3463 break;
3464 }
e23eba97
NC
3465}
3466
3467int
3468md_estimate_size_before_relax (fragS *fragp, asection *segtype)
3469{
5b7c81bd 3470 return (fragp->fr_var = relaxed_branch_length (fragp, segtype, false));
e23eba97
NC
3471}
3472
3473/* Translate internal representation of relocation info to BFD target
3474 format. */
3475
3476arelent *
3477tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
3478{
3479 arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
3480
3481 reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
3482 *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
3483 reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
3484 reloc->addend = fixp->fx_addnumber;
3485
3486 reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
3487 if (reloc->howto == NULL)
3488 {
3489 if ((fixp->fx_r_type == BFD_RELOC_16 || fixp->fx_r_type == BFD_RELOC_8)
3490 && fixp->fx_addsy != NULL && fixp->fx_subsy != NULL)
3491 {
3492 /* We don't have R_RISCV_8/16, but for this special case,
3493 we can use R_RISCV_ADD8/16 with R_RISCV_SUB8/16. */
3494 return reloc;
3495 }
3496
3497 as_bad_where (fixp->fx_file, fixp->fx_line,
3498 _("cannot represent %s relocation in object file"),
3499 bfd_get_reloc_code_name (fixp->fx_r_type));
3500 return NULL;
3501 }
3502
3503 return reloc;
3504}
3505
3506int
3507riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
3508{
3509 if (RELAX_BRANCH_P (fragp->fr_subtype))
3510 {
3511 offsetT old_var = fragp->fr_var;
5b7c81bd 3512 fragp->fr_var = relaxed_branch_length (fragp, sec, true);
e23eba97
NC
3513 return fragp->fr_var - old_var;
3514 }
3515
3516 return 0;
3517}
3518
3519/* Expand far branches to multi-instruction sequences. */
3520
3521static void
3522md_convert_frag_branch (fragS *fragp)
3523{
3524 bfd_byte *buf;
3525 expressionS exp;
3526 fixS *fixp;
3527 insn_t insn;
3528 int rs1, reloc;
3529
3530 buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
3531
3532 exp.X_op = O_symbol;
3533 exp.X_add_symbol = fragp->fr_symbol;
3534 exp.X_add_number = fragp->fr_offset;
3535
3536 gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
3537
3538 if (RELAX_BRANCH_RVC (fragp->fr_subtype))
3539 {
3540 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
3541 {
3542 case 8:
3543 case 4:
3544 /* Expand the RVC branch into a RISC-V one. */
3545 insn = bfd_getl16 (buf);
3546 rs1 = 8 + ((insn >> OP_SH_CRS1S) & OP_MASK_CRS1S);
3547 if ((insn & MASK_C_J) == MATCH_C_J)
3548 insn = MATCH_JAL;
3549 else if ((insn & MASK_C_JAL) == MATCH_C_JAL)
3550 insn = MATCH_JAL | (X_RA << OP_SH_RD);
3551 else if ((insn & MASK_C_BEQZ) == MATCH_C_BEQZ)
3552 insn = MATCH_BEQ | (rs1 << OP_SH_RS1);
3553 else if ((insn & MASK_C_BNEZ) == MATCH_C_BNEZ)
3554 insn = MATCH_BNE | (rs1 << OP_SH_RS1);
3555 else
3556 abort ();
3557 bfd_putl32 (insn, buf);
3558 break;
3559
3560 case 6:
3561 /* Invert the branch condition. Branch over the jump. */
3562 insn = bfd_getl16 (buf);
3563 insn ^= MATCH_C_BEQZ ^ MATCH_C_BNEZ;
5a9f5403 3564 insn |= ENCODE_CBTYPE_IMM (6);
e23eba97
NC
3565 bfd_putl16 (insn, buf);
3566 buf += 2;
3567 goto jump;
3568
3569 case 2:
3570 /* Just keep the RVC branch. */
3571 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
3572 ? BFD_RELOC_RISCV_RVC_JUMP : BFD_RELOC_RISCV_RVC_BRANCH;
3573 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
5b7c81bd 3574 2, &exp, false, reloc);
e23eba97
NC
3575 buf += 2;
3576 goto done;
3577
3578 default:
1d65abb5 3579 abort ();
e23eba97
NC
3580 }
3581 }
3582
3583 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
3584 {
3585 case 8:
3586 gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
3587
3588 /* Invert the branch condition. Branch over the jump. */
3589 insn = bfd_getl32 (buf);
3590 insn ^= MATCH_BEQ ^ MATCH_BNE;
5a9f5403 3591 insn |= ENCODE_BTYPE_IMM (8);
fbc09e7a 3592 bfd_putl32 (insn, buf);
e23eba97
NC
3593 buf += 4;
3594
dc1e8a47 3595 jump:
e23eba97
NC
3596 /* Jump to the target. */
3597 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
5b7c81bd 3598 4, &exp, false, BFD_RELOC_RISCV_JMP);
fbc09e7a 3599 bfd_putl32 (MATCH_JAL, buf);
e23eba97
NC
3600 buf += 4;
3601 break;
3602
3603 case 4:
3604 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
3605 ? BFD_RELOC_RISCV_JMP : BFD_RELOC_12_PCREL;
3606 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
5b7c81bd 3607 4, &exp, false, reloc);
e23eba97
NC
3608 buf += 4;
3609 break;
3610
3611 default:
3612 abort ();
3613 }
3614
dc1e8a47 3615 done:
e23eba97
NC
3616 fixp->fx_file = fragp->fr_file;
3617 fixp->fx_line = fragp->fr_line;
3618
3619 gas_assert (buf == (bfd_byte *)fragp->fr_literal
3620 + fragp->fr_fix + fragp->fr_var);
3621
3622 fragp->fr_fix += fragp->fr_var;
3623}
3624
3625/* Relax a machine dependent frag. This returns the amount by which
3626 the current size of the frag should change. */
3627
3628void
3629md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
3630 fragS *fragp)
3631{
3632 gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
3633 md_convert_frag_branch (fragp);
3634}
3635
3636void
3637md_show_usage (FILE *stream)
3638{
3639 fprintf (stream, _("\
3640RISC-V options:\n\
8f595e9b
NC
3641 -fpic generate position-independent code\n\
3642 -fno-pic don't generate position-independent code (default)\n\
3643 -march=ISA set the RISC-V architecture\n\
3644 -misa-spec=ISAspec set the RISC-V ISA spec (2.2, 20190608, 20191213)\n\
3645 -mpriv-spec=PRIVspec set the RISC-V privilege spec (1.9, 1.9.1, 1.10, 1.11)\n\
3646 -mabi=ABI set the RISC-V ABI\n\
3647 -mrelax enable relax (default)\n\
3648 -mno-relax disable relax\n\
3649 -march-attr generate RISC-V arch attribute\n\
3650 -mno-arch-attr don't generate RISC-V arch attribute\n\
e23eba97
NC
3651"));
3652}
3653
3654/* Standard calling conventions leave the CFA at SP on entry. */
dcd709e0 3655
e23eba97
NC
3656void
3657riscv_cfi_frame_initial_instructions (void)
3658{
3659 cfi_add_CFA_def_cfa_register (X_SP);
3660}
3661
3662int
3663tc_riscv_regname_to_dw2regnum (char *regname)
3664{
3665 int reg;
3666
3667 if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
3668 return reg;
3669
3670 if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
3671 return reg + 32;
3672
4762fe62
AB
3673 /* CSRs are numbered 4096 -> 8191. */
3674 if ((reg = reg_lookup_internal (regname, RCLASS_CSR)) >= 0)
3675 return reg + 4096;
3676
e23eba97
NC
3677 as_bad (_("unknown register `%s'"), regname);
3678 return -1;
3679}
3680
3681void
3682riscv_elf_final_processing (void)
3683{
6e1605e4 3684 riscv_set_abi_by_arch ();
e23eba97 3685 elf_elfheader (stdoutput)->e_flags |= elf_flags;
e23eba97
NC
3686}
3687
3688/* Parse the .sleb128 and .uleb128 pseudos. Only allow constant expressions,
3689 since these directives break relaxation when used with symbol deltas. */
3690
3691static void
3692s_riscv_leb128 (int sign)
3693{
3694 expressionS exp;
3695 char *save_in = input_line_pointer;
3696
3697 expression (&exp);
3698 if (exp.X_op != O_constant)
3699 as_bad (_("non-constant .%cleb128 is not supported"), sign ? 's' : 'u');
3700 demand_empty_rest_of_line ();
3701
3702 input_line_pointer = save_in;
3703 return s_leb128 (sign);
3704}
3705
0e35537d
JW
3706/* Parse the .insn directive. */
3707
3708static void
3709s_riscv_insn (int x ATTRIBUTE_UNUSED)
3710{
3711 char *str = input_line_pointer;
3712 struct riscv_cl_insn insn;
3713 expressionS imm_expr;
3714 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
3715 char save_c;
3716
3717 while (!is_end_of_line[(unsigned char) *input_line_pointer])
3718 ++input_line_pointer;
3719
3720 save_c = *input_line_pointer;
3721 *input_line_pointer = '\0';
3722
3723 const char *error = riscv_ip (str, &insn, &imm_expr,
3724 &imm_reloc, insn_type_hash);
3725
3726 if (error)
3727 {
3728 as_bad ("%s `%s'", error, str);
3729 }
3730 else
3731 {
3732 gas_assert (insn.insn_mo->pinfo != INSN_MACRO);
3733 append_insn (&insn, &imm_expr, imm_reloc);
3734 }
3735
3736 *input_line_pointer = save_c;
3737 demand_empty_rest_of_line ();
3738}
3739
dcd709e0
NC
3740/* Update architecture and privileged elf attributes. If we don't set
3741 them, then try to output the default ones. */
2dc8dd17
JW
3742
3743static void
8f595e9b 3744riscv_write_out_attrs (void)
2dc8dd17 3745{
8f595e9b 3746 const char *arch_str, *priv_str, *p;
dcd709e0
NC
3747 /* versions[0]: major version.
3748 versions[1]: minor version.
3749 versions[2]: revision version. */
8f595e9b
NC
3750 unsigned versions[3] = {0}, number = 0;
3751 unsigned int i;
2dc8dd17 3752
dcd709e0 3753 /* Re-write architecture elf attribute. */
8f595e9b 3754 arch_str = riscv_arch_str (xlen, &riscv_subsets);
2dc8dd17 3755 bfd_elf_add_proc_attr_string (stdoutput, Tag_RISCV_arch, arch_str);
1942a048 3756 xfree ((void *) arch_str);
8f595e9b
NC
3757
3758 /* For the file without any instruction, we don't set the default_priv_spec
dcd709e0
NC
3759 according to the privileged elf attributes since the md_assemble isn't
3760 called. */
8f595e9b
NC
3761 if (!start_assemble
3762 && !riscv_set_default_priv_spec (NULL))
3763 return;
3764
dcd709e0
NC
3765 /* If we already have set privileged elf attributes, then no need to do
3766 anything. Otherwise, don't generate or update them when no CSR and
3767 privileged instructions are used. */
1a79004f 3768 if (!explicit_priv_attr)
3fc6c3dc
NC
3769 return;
3770
3d73d29e 3771 RISCV_GET_PRIV_SPEC_NAME (priv_str, default_priv_spec);
8f595e9b
NC
3772 p = priv_str;
3773 for (i = 0; *p; ++p)
3774 {
3775 if (*p == '.' && i < 3)
3776 {
3777 versions[i++] = number;
3778 number = 0;
3779 }
3780 else if (ISDIGIT (*p))
3781 number = (number * 10) + (*p - '0');
3782 else
3783 {
b800637e 3784 as_bad (_("internal: bad RISC-V privileged spec (%s)"), priv_str);
8f595e9b
NC
3785 return;
3786 }
3787 }
3788 versions[i] = number;
3789
dcd709e0 3790 /* Re-write privileged elf attributes. */
8f595e9b
NC
3791 bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec, versions[0]);
3792 bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_minor, versions[1]);
3793 bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_revision, versions[2]);
2dc8dd17
JW
3794}
3795
dcd709e0 3796/* Add the default contents for the .riscv.attributes section. */
2dc8dd17
JW
3797
3798static void
3799riscv_set_public_attributes (void)
3800{
8f595e9b
NC
3801 if (riscv_opts.arch_attr || explicit_attr)
3802 riscv_write_out_attrs ();
2dc8dd17
JW
3803}
3804
3805/* Called after all assembly has been done. */
3806
3807void
3808riscv_md_end (void)
3809{
3810 riscv_set_public_attributes ();
3811}
3812
3813/* Given a symbolic attribute NAME, return the proper integer value.
3814 Returns -1 if the attribute is not known. */
3815
3816int
3817riscv_convert_symbolic_attribute (const char *name)
3818{
3819 static const struct
3820 {
1942a048
NC
3821 const char *name;
3822 const int tag;
2dc8dd17
JW
3823 }
3824 attribute_table[] =
1942a048
NC
3825 {
3826 /* When you modify this table you should
3827 also modify the list in doc/c-riscv.texi. */
3828#define T(tag) {#tag, Tag_RISCV_##tag}, {"Tag_RISCV_" #tag, Tag_RISCV_##tag}
3829 T(arch),
3830 T(priv_spec),
3831 T(priv_spec_minor),
3832 T(priv_spec_revision),
3833 T(unaligned_access),
3834 T(stack_align),
2dc8dd17 3835#undef T
1942a048 3836 };
2dc8dd17
JW
3837
3838 if (name == NULL)
3839 return -1;
3840
1942a048 3841 unsigned int i;
2dc8dd17
JW
3842 for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
3843 if (strcmp (name, attribute_table[i].name) == 0)
3844 return attribute_table[i].tag;
3845
3846 return -1;
3847}
3848
3849/* Parse a .attribute directive. */
3850
3851static void
3852s_riscv_attribute (int ignored ATTRIBUTE_UNUSED)
3853{
3854 int tag = obj_elf_vendor_attribute (OBJ_ATTR_PROC);
8f595e9b
NC
3855 unsigned old_xlen;
3856 obj_attribute *attr;
2dc8dd17 3857
5b7c81bd 3858 explicit_attr = true;
8f595e9b 3859 switch (tag)
2dc8dd17 3860 {
8f595e9b
NC
3861 case Tag_RISCV_arch:
3862 old_xlen = xlen;
2dc8dd17
JW
3863 attr = elf_known_obj_attributes_proc (stdoutput);
3864 if (!start_assemble)
3865 riscv_set_arch (attr[Tag_RISCV_arch].s);
3866 else
b800637e
NC
3867 as_fatal (_("architecture elf attributes must set before "
3868 "any instructions"));
2dc8dd17
JW
3869
3870 if (old_xlen != xlen)
3871 {
3872 /* We must re-init bfd again if xlen is changed. */
3873 unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
3874 bfd_find_target (riscv_target_format (), stdoutput);
3875
3876 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
b800637e 3877 as_warn (_("could not set architecture and machine"));
2dc8dd17 3878 }
8f595e9b
NC
3879 break;
3880
3881 case Tag_RISCV_priv_spec:
3882 case Tag_RISCV_priv_spec_minor:
3883 case Tag_RISCV_priv_spec_revision:
3884 if (start_assemble)
b800637e
NC
3885 as_fatal (_("privileged elf attributes must set before "
3886 "any instructions"));
8f595e9b
NC
3887 break;
3888
3889 default:
3890 break;
2dc8dd17
JW
3891 }
3892}
3893
dcd709e0 3894/* RISC-V pseudo-ops table. */
e23eba97
NC
3895static const pseudo_typeS riscv_pseudo_table[] =
3896{
e23eba97
NC
3897 {"option", s_riscv_option, 0},
3898 {"half", cons, 2},
3899 {"word", cons, 4},
3900 {"dword", cons, 8},
3901 {"dtprelword", s_dtprel, 4},
3902 {"dtpreldword", s_dtprel, 8},
3903 {"bss", s_bss, 0},
e23eba97
NC
3904 {"uleb128", s_riscv_leb128, 0},
3905 {"sleb128", s_riscv_leb128, 1},
0e35537d 3906 {"insn", s_riscv_insn, 0},
2dc8dd17 3907 {"attribute", s_riscv_attribute, 0},
e23eba97
NC
3908
3909 { NULL, NULL, 0 },
3910};
3911
3912void
3913riscv_pop_insert (void)
3914{
3915 extern void pop_insert (const pseudo_typeS *);
3916
3917 pop_insert (riscv_pseudo_table);
3918}