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