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