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