1 /* tc-riscv.c -- RISC-V assembler
2 Copyright 2011-2016 Free Software Foundation, Inc.
4 Contributed by Andrew Waterman (andrew@sifive.com).
7 This file is part of GAS.
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)
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.
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/>. */
26 #include "safe-ctype.h"
29 #include "dwarf2dbg.h"
30 #include "dw2gencfi.h"
31 #include "struc-symbol.h"
33 #include "elf/riscv.h"
34 #include "opcode/riscv.h"
38 /* Information about an instruction, including its format, operands
42 /* The opcode's entry in riscv_opcodes. */
43 const struct riscv_opcode *insn_mo;
45 /* The encoded instruction bits. */
48 /* The frag that contains the instruction. */
51 /* The offset into FRAG of the first instruction byte. */
54 /* The relocs associated with the instruction, if any. */
59 #define DEFAULT_ARCH "riscv64"
62 static const char default_arch[] = DEFAULT_ARCH;
64 unsigned xlen = 0; /* width of an x-register */
66 #define LOAD_ADDRESS_INSN (xlen == 64 ? "ld" : "lw")
67 #define ADD32_INSN (xlen == 64 ? "addiw" : "addi")
69 static unsigned elf_flags = 0;
71 /* This is the set of options which the .option pseudo-op may modify. */
73 struct riscv_set_options
75 int pic; /* Generate position-independent code. */
76 int rvc; /* Generate RVC code. */
79 static struct riscv_set_options riscv_opts =
86 riscv_set_rvc (bfd_boolean rvc_value)
89 elf_flags |= EF_RISCV_RVC;
91 riscv_opts.rvc = rvc_value;
98 struct riscv_subset *next;
101 static struct riscv_subset *riscv_subsets;
104 riscv_subset_supports (const char *feature)
106 struct riscv_subset *s;
108 unsigned xlen_required = strtoul (feature, &p, 10);
110 if (xlen_required && xlen != xlen_required)
113 for (s = riscv_subsets; s != NULL; s = s->next)
114 if (strcasecmp (s->name, p) == 0)
121 riscv_add_subset (const char *subset)
123 struct riscv_subset *s = xmalloc (sizeof *s);
125 s->name = xstrdup (subset);
126 s->next = riscv_subsets;
130 /* Set which ISA and extensions are available. Formally, ISA strings must
131 begin with RV32 or RV64, but we allow the prefix to be omitted.
133 FIXME: Version numbers are not supported yet. */
135 riscv_set_arch (const char *p)
137 const char *all_subsets = "IMAFDC";
138 const char *extension = NULL;
142 if (strncasecmp (p, "RV32", 4) == 0)
147 else if (strncasecmp (p, "RV64", 4) == 0)
152 else if (strncasecmp (p, "RV", 2) == 0)
165 for (i = 0; all_subsets[i] != '\0'; i++)
167 const char subset[] = {all_subsets[i], '\0'};
168 riscv_add_subset (subset);
173 as_fatal ("`I' must be the first ISA subset name specified (got %c)",
179 if (TOUPPER(*p) == 'X')
181 char *subset = xstrdup (p), *q = subset;
183 while (*++q != '\0' && *q != '_')
188 as_fatal ("only one eXtension is supported (found %s and %s)",
191 riscv_add_subset (subset);
192 p += strlen (subset);
197 else if ((all_subsets = strchr (all_subsets, *p)) != NULL)
199 const char subset[] = {*p, 0};
200 riscv_add_subset (subset);
201 if (TOUPPER(*p) == 'C')
207 as_fatal ("unsupported ISA subset %c", *p);
212 /* Override -m[no-]rvc setting if C was explicitly listed. */
213 riscv_set_rvc (TRUE);
217 /* Add RVC anyway. -m[no-]rvc toggles its availability. */
218 riscv_add_subset ("C");
222 /* Handle of the OPCODE hash table. */
223 static struct hash_control *op_hash = NULL;
225 /* This array holds the chars that always start a comment. If the
226 pre-processor is disabled, these aren't very useful */
227 const char comment_chars[] = "#";
229 /* This array holds the chars that only start a comment at the beginning of
230 a line. If the line seems to have the form '# 123 filename'
231 .line and .file directives will appear in the pre-processed output */
232 /* Note that input_file.c hand checks for '#' at the beginning of the
233 first line of the input file. This is because the compiler outputs
234 #NO_APP at the beginning of its output. */
235 /* Also note that C style comments are always supported. */
236 const char line_comment_chars[] = "#";
238 /* This array holds machine specific line separator characters. */
239 const char line_separator_chars[] = ";";
241 /* Chars that can be used to separate mant from exp in floating point nums */
242 const char EXP_CHARS[] = "eE";
244 /* Chars that mean this number is a floating point constant */
247 const char FLT_CHARS[] = "rRsSfFdDxXpP";
249 /* Macros for encoding relaxation state for RVC branches and far jumps. */
250 #define RELAX_BRANCH_ENCODE(uncond, rvc, length) \
253 | ((uncond) ? 1 : 0) \
256 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
257 #define RELAX_BRANCH_LENGTH(i) (((i) >> 2) & 0xF)
258 #define RELAX_BRANCH_RVC(i) (((i) & 2) != 0)
259 #define RELAX_BRANCH_UNCOND(i) (((i) & 1) != 0)
261 /* Is the given value a sign-extended 32-bit value? */
262 #define IS_SEXT_32BIT_NUM(x) \
263 (((x) &~ (offsetT) 0x7fffffff) == 0 \
264 || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
266 /* Is the given value a zero-extended 32-bit value? Or a negated one? */
267 #define IS_ZEXT_32BIT_NUM(x) \
268 (((x) &~ (offsetT) 0xffffffff) == 0 \
269 || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
271 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
272 INSN is a riscv_cl_insn structure and VALUE is evaluated exactly once. */
273 #define INSERT_OPERAND(FIELD, INSN, VALUE) \
274 INSERT_BITS ((INSN).insn_opcode, VALUE, OP_MASK_##FIELD, OP_SH_##FIELD)
276 /* Determine if an instruction matches an opcode. */
277 #define OPCODE_MATCHES(OPCODE, OP) \
278 (((OPCODE) & MASK_##OP) == MATCH_##OP)
280 static char *expr_end;
282 /* The default target format to use. */
285 riscv_target_format (void)
287 return xlen == 64 ? "elf64-littleriscv" : "elf32-littleriscv";
290 /* Return the length of instruction INSN. */
292 static inline unsigned int
293 insn_length (const struct riscv_cl_insn *insn)
295 return riscv_insn_length (insn->insn_opcode);
298 /* Initialise INSN from opcode entry MO. Leave its position unspecified. */
301 create_insn (struct riscv_cl_insn *insn, const struct riscv_opcode *mo)
304 insn->insn_opcode = mo->match;
310 /* Install INSN at the location specified by its "frag" and "where" fields. */
313 install_insn (const struct riscv_cl_insn *insn)
315 char *f = insn->frag->fr_literal + insn->where;
316 md_number_to_chars (f, insn->insn_opcode, insn_length (insn));
319 /* Move INSN to offset WHERE in FRAG. Adjust the fixups accordingly
320 and install the opcode in the new location. */
323 move_insn (struct riscv_cl_insn *insn, fragS *frag, long where)
327 if (insn->fixp != NULL)
329 insn->fixp->fx_frag = frag;
330 insn->fixp->fx_where = where;
335 /* Add INSN to the end of the output. */
338 add_fixed_insn (struct riscv_cl_insn *insn)
340 char *f = frag_more (insn_length (insn));
341 move_insn (insn, frag_now, f - frag_now->fr_literal);
345 add_relaxed_insn (struct riscv_cl_insn *insn, int max_chars, int var,
346 relax_substateT subtype, symbolS *symbol, offsetT offset)
348 frag_grow (max_chars);
349 move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
350 frag_var (rs_machine_dependent, max_chars, var,
351 subtype, symbol, offset, NULL);
354 /* Compute the length of a branch sequence, and adjust the stored length
355 accordingly. If FRAGP is NULL, the worst-case length is returned. */
358 relaxed_branch_length (fragS *fragp, asection *sec, int update)
360 int jump, rvc, length = 8;
365 jump = RELAX_BRANCH_UNCOND (fragp->fr_subtype);
366 rvc = RELAX_BRANCH_RVC (fragp->fr_subtype);
367 length = RELAX_BRANCH_LENGTH (fragp->fr_subtype);
369 /* Assume jumps are in range; the linker will catch any that aren't. */
370 length = jump ? 4 : 8;
372 if (fragp->fr_symbol != NULL
373 && S_IS_DEFINED (fragp->fr_symbol)
374 && sec == S_GET_SEGMENT (fragp->fr_symbol))
376 offsetT val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
377 bfd_vma rvc_range = jump ? RVC_JUMP_REACH : RVC_BRANCH_REACH;
378 val -= fragp->fr_address + fragp->fr_fix;
380 if (rvc && (bfd_vma)(val + rvc_range/2) < rvc_range)
382 else if ((bfd_vma)(val + RISCV_BRANCH_REACH/2) < RISCV_BRANCH_REACH)
384 else if (!jump && rvc)
389 fragp->fr_subtype = RELAX_BRANCH_ENCODE (jump, rvc, length);
408 static struct hash_control *reg_names_hash = NULL;
410 #define ENCODE_REG_HASH(cls, n) \
411 ((void *)(uintptr_t)((n) * RCLASS_MAX + (cls) + 1))
412 #define DECODE_REG_CLASS(hash) (((uintptr_t)(hash) - 1) % RCLASS_MAX)
413 #define DECODE_REG_NUM(hash) (((uintptr_t)(hash) - 1) / RCLASS_MAX)
416 hash_reg_name (enum reg_class class, const char *name, unsigned n)
418 void *hash = ENCODE_REG_HASH (class, n);
419 const char *retval = hash_insert (reg_names_hash, name, hash);
422 as_fatal (_("internal error: can't hash `%s': %s"), name, retval);
426 hash_reg_names (enum reg_class class, const char * const names[], unsigned n)
430 for (i = 0; i < n; i++)
431 hash_reg_name (class, names[i], i);
435 reg_lookup_internal (const char *s, enum reg_class class)
437 struct regname *r = (struct regname *) hash_find (reg_names_hash, s);
439 if (r == NULL || DECODE_REG_CLASS (r) != class)
441 return DECODE_REG_NUM (r);
445 reg_lookup (char **s, enum reg_class class, unsigned int *regnop)
451 /* Find end of name. */
453 if (is_name_beginner (*e))
455 while (is_part_of_name (*e))
458 /* Terminate name. */
462 /* Look for the register. Advance to next token if one was recognized. */
463 if ((reg = reg_lookup_internal (*s, class)) >= 0)
473 arg_lookup (char **s, const char *const *array, size_t size, unsigned *regnop)
475 const char *p = strchr (*s, ',');
476 size_t i, len = p ? (size_t)(p - *s) : strlen (*s);
478 for (i = 0; i < size; i++)
479 if (array[i] != NULL && strncmp (array[i], *s, len) == 0)
489 /* For consistency checking, verify that all bits are specified either
490 by the match/mask part of the instruction definition, or by the
493 validate_riscv_insn (const struct riscv_opcode *opc)
495 const char *p = opc->args;
497 insn_t used_bits = opc->mask;
498 int insn_width = 8 * riscv_insn_length (opc->match);
499 insn_t required_bits = ~0ULL >> (64 - insn_width);
501 if ((used_bits & opc->match) != (opc->match & required_bits))
503 as_bad (_("internal: bad RISC-V opcode (mask error): %s %s"),
504 opc->name, opc->args);
508 #define USE_BITS(mask,shift) (used_bits |= ((insn_t)(mask) << (shift)))
515 case 'a': used_bits |= ENCODE_RVC_J_IMM (-1U); break;
516 case 'c': break; /* RS1, constrained to equal sp */
517 case 'i': used_bits |= ENCODE_RVC_SIMM3(-1U); break;
518 case 'j': used_bits |= ENCODE_RVC_IMM (-1U); break;
519 case 'k': used_bits |= ENCODE_RVC_LW_IMM (-1U); break;
520 case 'l': used_bits |= ENCODE_RVC_LD_IMM (-1U); break;
521 case 'm': used_bits |= ENCODE_RVC_LWSP_IMM (-1U); break;
522 case 'n': used_bits |= ENCODE_RVC_LDSP_IMM (-1U); break;
523 case 'p': used_bits |= ENCODE_RVC_B_IMM (-1U); break;
524 case 's': USE_BITS (OP_MASK_CRS1S, OP_SH_CRS1S); break;
525 case 't': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
526 case 'u': used_bits |= ENCODE_RVC_IMM (-1U); break;
527 case 'v': used_bits |= ENCODE_RVC_IMM (-1U); break;
528 case 'w': break; /* RS1S, constrained to equal RD */
529 case 'x': break; /* RS2S, constrained to equal RD */
530 case 'K': used_bits |= ENCODE_RVC_ADDI4SPN_IMM (-1U); break;
531 case 'L': used_bits |= ENCODE_RVC_ADDI16SP_IMM (-1U); break;
532 case 'M': used_bits |= ENCODE_RVC_SWSP_IMM (-1U); break;
533 case 'N': used_bits |= ENCODE_RVC_SDSP_IMM (-1U); break;
534 case 'U': break; /* RS1, constrained to equal RD */
535 case 'V': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
536 case '<': used_bits |= ENCODE_RVC_IMM (-1U); break;
537 case '>': used_bits |= ENCODE_RVC_IMM (-1U); break;
538 case 'T': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
539 case 'D': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
541 as_bad (_("internal: bad RISC-V opcode (unknown operand type `C%c'): %s %s"),
542 c, opc->name, opc->args);
549 case '<': USE_BITS (OP_MASK_SHAMTW, OP_SH_SHAMTW); break;
550 case '>': USE_BITS (OP_MASK_SHAMT, OP_SH_SHAMT); break;
552 case 'D': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
553 case 'Z': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
554 case 'E': USE_BITS (OP_MASK_CSR, OP_SH_CSR); break;
556 case 'R': USE_BITS (OP_MASK_RS3, OP_SH_RS3); break;
557 case 'S': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
558 case 'U': USE_BITS (OP_MASK_RS1, OP_SH_RS1); /* fallthru */
559 case 'T': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
560 case 'd': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
561 case 'm': USE_BITS (OP_MASK_RM, OP_SH_RM); break;
562 case 's': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
563 case 't': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
564 case 'P': USE_BITS (OP_MASK_PRED, OP_SH_PRED); break;
565 case 'Q': USE_BITS (OP_MASK_SUCC, OP_SH_SUCC); break;
567 case 'j': used_bits |= ENCODE_ITYPE_IMM (-1U); break;
568 case 'a': used_bits |= ENCODE_UJTYPE_IMM (-1U); break;
569 case 'p': used_bits |= ENCODE_SBTYPE_IMM (-1U); break;
570 case 'q': used_bits |= ENCODE_STYPE_IMM (-1U); break;
571 case 'u': used_bits |= ENCODE_UTYPE_IMM (-1U); break;
576 as_bad (_("internal: bad RISC-V opcode "
577 "(unknown operand type `%c'): %s %s"),
578 c, opc->name, opc->args);
582 if (used_bits != required_bits)
584 as_bad (_("internal: bad RISC-V opcode (bits 0x%lx undefined): %s %s"),
585 ~(unsigned long)(used_bits & required_bits),
586 opc->name, opc->args);
592 struct percent_op_match
595 bfd_reloc_code_real_type reloc;
598 /* This function is called once, at assembler startup time. It should set up
599 all the tables, etc. that the MD part of the assembler will need. */
606 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, 0))
607 as_warn (_("Could not set architecture and machine"));
609 op_hash = hash_new ();
611 while (riscv_opcodes[i].name)
613 const char *name = riscv_opcodes[i].name;
614 const char *hash_error =
615 hash_insert (op_hash, name, (void *) &riscv_opcodes[i]);
619 fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
620 riscv_opcodes[i].name, hash_error);
621 /* Probably a memory allocation problem? Give up now. */
622 as_fatal (_("Broken assembler. No assembly attempted."));
627 if (riscv_opcodes[i].pinfo != INSN_MACRO)
629 if (!validate_riscv_insn (&riscv_opcodes[i]))
630 as_fatal (_("Broken assembler. No assembly attempted."));
634 while (riscv_opcodes[i].name && !strcmp (riscv_opcodes[i].name, name));
637 reg_names_hash = hash_new ();
638 hash_reg_names (RCLASS_GPR, riscv_gpr_names_numeric, NGPR);
639 hash_reg_names (RCLASS_GPR, riscv_gpr_names_abi, NGPR);
640 hash_reg_names (RCLASS_FPR, riscv_fpr_names_numeric, NFPR);
641 hash_reg_names (RCLASS_FPR, riscv_fpr_names_abi, NFPR);
643 #define DECLARE_CSR(name, num) hash_reg_name (RCLASS_CSR, #name, num);
644 #include "opcode/riscv-opc.h"
647 /* Set the default alignment for the text section. */
648 record_alignment (text_section, riscv_opts.rvc ? 1 : 2);
651 /* Output an instruction. IP is the instruction information.
652 ADDRESS_EXPR is an operand of the instruction to be used with
656 append_insn (struct riscv_cl_insn *ip, expressionS *address_expr,
657 bfd_reloc_code_real_type reloc_type)
659 dwarf2_emit_insn (0);
661 if (reloc_type != BFD_RELOC_UNUSED)
663 reloc_howto_type *howto;
665 gas_assert (address_expr);
666 if (reloc_type == BFD_RELOC_12_PCREL
667 || reloc_type == BFD_RELOC_RISCV_JMP)
669 int j = reloc_type == BFD_RELOC_RISCV_JMP;
670 int best_case = riscv_insn_length (ip->insn_opcode);
671 unsigned worst_case = relaxed_branch_length (NULL, NULL, 0);
672 add_relaxed_insn (ip, worst_case, best_case,
673 RELAX_BRANCH_ENCODE (j, best_case == 2, worst_case),
674 address_expr->X_add_symbol,
675 address_expr->X_add_number);
678 else if (address_expr->X_op == O_constant)
683 ip->insn_opcode |= address_expr->X_add_number;
686 case BFD_RELOC_RISCV_HI20:
688 insn_t imm = RISCV_CONST_HIGH_PART (address_expr->X_add_number);
689 ip->insn_opcode |= ENCODE_UTYPE_IMM (imm);
693 case BFD_RELOC_RISCV_LO12_S:
694 ip->insn_opcode |= ENCODE_STYPE_IMM (address_expr->X_add_number);
697 case BFD_RELOC_RISCV_LO12_I:
698 ip->insn_opcode |= ENCODE_ITYPE_IMM (address_expr->X_add_number);
706 howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
708 as_bad (_("Unsupported RISC-V relocation number %d"), reloc_type);
710 ip->fixp = fix_new_exp (ip->frag, ip->where,
711 bfd_get_reloc_size (howto),
712 address_expr, FALSE, reloc_type);
720 /* Build an instruction created by a macro expansion. This is passed
721 a pointer to the count of instructions created so far, an
722 expression, the name of the instruction to build, an operand format
723 string, and corresponding arguments. */
726 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
728 const struct riscv_opcode *mo;
729 struct riscv_cl_insn insn;
730 bfd_reloc_code_real_type r;
733 va_start (args, fmt);
735 r = BFD_RELOC_UNUSED;
736 mo = (struct riscv_opcode *) hash_find (op_hash, name);
739 /* Find a non-RVC variant of the instruction. append_insn will compress
741 while (riscv_insn_length (mo->match) < 4)
743 gas_assert (strcmp (name, mo->name) == 0);
745 create_insn (&insn, mo);
751 INSERT_OPERAND (RD, insn, va_arg (args, int));
755 INSERT_OPERAND (RS1, insn, va_arg (args, int));
759 INSERT_OPERAND (RS2, insn, va_arg (args, int));
763 INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
769 gas_assert (ep != NULL);
770 r = va_arg (args, int);
778 as_fatal (_("internal error: invalid macro"));
783 gas_assert (r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
785 append_insn (&insn, ep, r);
788 /* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
791 normalize_constant_expr (expressionS *ex)
795 if ((ex->X_op == O_constant || ex->X_op == O_symbol)
796 && IS_ZEXT_32BIT_NUM (ex->X_add_number))
797 ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
801 /* Fail if an expression is not a constant. */
804 check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex)
806 if (ex->X_op == O_big)
807 as_bad (_("unsupported large constant"));
808 else if (ex->X_op != O_constant)
809 as_bad (_("Instruction %s requires absolute expression"),
811 normalize_constant_expr (ex);
815 make_internal_label (void)
817 return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg,
818 (valueT) frag_now_fix (), frag_now);
821 /* Load an entry from the GOT. */
823 pcrel_access (int destreg, int tempreg, expressionS *ep,
824 const char *lo_insn, const char *lo_pattern,
825 bfd_reloc_code_real_type hi_reloc,
826 bfd_reloc_code_real_type lo_reloc)
830 ep2.X_add_symbol = make_internal_label ();
831 ep2.X_add_number = 0;
833 macro_build (ep, "auipc", "d,u", tempreg, hi_reloc);
834 macro_build (&ep2, lo_insn, lo_pattern, destreg, tempreg, lo_reloc);
838 pcrel_load (int destreg, int tempreg, expressionS *ep, const char *lo_insn,
839 bfd_reloc_code_real_type hi_reloc,
840 bfd_reloc_code_real_type lo_reloc)
842 pcrel_access (destreg, tempreg, ep, lo_insn, "d,s,j", hi_reloc, lo_reloc);
846 pcrel_store (int srcreg, int tempreg, expressionS *ep, const char *lo_insn,
847 bfd_reloc_code_real_type hi_reloc,
848 bfd_reloc_code_real_type lo_reloc)
850 pcrel_access (srcreg, tempreg, ep, lo_insn, "t,s,q", hi_reloc, lo_reloc);
853 /* PC-relative function call using AUIPC/JALR, relaxed to JAL. */
855 riscv_call (int destreg, int tempreg, expressionS *ep,
856 bfd_reloc_code_real_type reloc)
858 macro_build (ep, "auipc", "d,u", tempreg, reloc);
859 macro_build (NULL, "jalr", "d,s", destreg, tempreg);
862 /* Load an integer constant into a register. */
865 load_const (int reg, expressionS *ep)
867 int shift = RISCV_IMM_BITS;
868 expressionS upper = *ep, lower = *ep;
869 lower.X_add_number = (int32_t) ep->X_add_number << (32-shift) >> (32-shift);
870 upper.X_add_number -= lower.X_add_number;
872 if (ep->X_op != O_constant)
874 as_bad (_("unsupported large constant"));
878 if (xlen > 32 && !IS_SEXT_32BIT_NUM (ep->X_add_number))
880 /* Reduce to a signed 32-bit constant using SLLI and ADDI. */
881 while (((upper.X_add_number >> shift) & 1) == 0)
884 upper.X_add_number = (int64_t) upper.X_add_number >> shift;
885 load_const (reg, &upper);
887 macro_build (NULL, "slli", "d,s,>", reg, reg, shift);
888 if (lower.X_add_number != 0)
889 macro_build (&lower, "addi", "d,s,j", reg, reg, BFD_RELOC_RISCV_LO12_I);
893 /* Simply emit LUI and/or ADDI to build a 32-bit signed constant. */
896 if (upper.X_add_number != 0)
898 macro_build (ep, "lui", "d,u", reg, BFD_RELOC_RISCV_HI20);
902 if (lower.X_add_number != 0 || hi_reg == 0)
903 macro_build (ep, ADD32_INSN, "d,s,j", reg, hi_reg,
904 BFD_RELOC_RISCV_LO12_I);
908 /* Expand RISC-V assembly macros into one or more instructions. */
910 macro (struct riscv_cl_insn *ip, expressionS *imm_expr,
911 bfd_reloc_code_real_type *imm_reloc)
913 int rd = (ip->insn_opcode >> OP_SH_RD) & OP_MASK_RD;
914 int rs1 = (ip->insn_opcode >> OP_SH_RS1) & OP_MASK_RS1;
915 int rs2 = (ip->insn_opcode >> OP_SH_RS2) & OP_MASK_RS2;
916 int mask = ip->insn_mo->mask;
921 load_const (rd, imm_expr);
926 /* Load the address of a symbol into a register. */
927 if (!IS_SEXT_32BIT_NUM (imm_expr->X_add_number))
928 as_bad (_("offset too large"));
930 if (imm_expr->X_op == O_constant)
931 load_const (rd, imm_expr);
932 else if (riscv_opts.pic && mask == M_LA) /* Global PIC symbol */
933 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
934 BFD_RELOC_RISCV_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
935 else /* Local PIC symbol, or any non-PIC symbol */
936 pcrel_load (rd, rd, imm_expr, "addi",
937 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
941 pcrel_load (rd, rd, imm_expr, "addi",
942 BFD_RELOC_RISCV_TLS_GD_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
946 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
947 BFD_RELOC_RISCV_TLS_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
951 pcrel_load (rd, rd, imm_expr, "lb",
952 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
956 pcrel_load (rd, rd, imm_expr, "lbu",
957 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
961 pcrel_load (rd, rd, imm_expr, "lh",
962 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
966 pcrel_load (rd, rd, imm_expr, "lhu",
967 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
971 pcrel_load (rd, rd, imm_expr, "lw",
972 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
976 pcrel_load (rd, rd, imm_expr, "lwu",
977 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
981 pcrel_load (rd, rd, imm_expr, "ld",
982 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
986 pcrel_load (rd, rs1, imm_expr, "flw",
987 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
991 pcrel_load (rd, rs1, imm_expr, "fld",
992 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
996 pcrel_store (rs2, rs1, imm_expr, "sb",
997 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1001 pcrel_store (rs2, rs1, imm_expr, "sh",
1002 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1006 pcrel_store (rs2, rs1, imm_expr, "sw",
1007 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1011 pcrel_store (rs2, rs1, imm_expr, "sd",
1012 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1016 pcrel_store (rs2, rs1, imm_expr, "fsw",
1017 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1021 pcrel_store (rs2, rs1, imm_expr, "fsd",
1022 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1026 riscv_call (rd, rs1, imm_expr, *imm_reloc);
1030 as_bad (_("Macro %s not implemented"), ip->insn_mo->name);
1035 static const struct percent_op_match percent_op_utype[] =
1037 {"%tprel_hi", BFD_RELOC_RISCV_TPREL_HI20},
1038 {"%pcrel_hi", BFD_RELOC_RISCV_PCREL_HI20},
1039 {"%tls_ie_pcrel_hi", BFD_RELOC_RISCV_TLS_GOT_HI20},
1040 {"%tls_gd_pcrel_hi", BFD_RELOC_RISCV_TLS_GD_HI20},
1041 {"%hi", BFD_RELOC_RISCV_HI20},
1045 static const struct percent_op_match percent_op_itype[] =
1047 {"%lo", BFD_RELOC_RISCV_LO12_I},
1048 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_I},
1049 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_I},
1053 static const struct percent_op_match percent_op_stype[] =
1055 {"%lo", BFD_RELOC_RISCV_LO12_S},
1056 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_S},
1057 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_S},
1061 static const struct percent_op_match percent_op_rtype[] =
1063 {"%tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
1067 /* Return true if *STR points to a relocation operator. When returning true,
1068 move *STR over the operator and store its relocation code in *RELOC.
1069 Leave both *STR and *RELOC alone when returning false. */
1072 parse_relocation (char **str, bfd_reloc_code_real_type *reloc,
1073 const struct percent_op_match *percent_op)
1075 for ( ; percent_op->str; percent_op++)
1076 if (strncasecmp (*str, percent_op->str, strlen (percent_op->str)) == 0)
1078 int len = strlen (percent_op->str);
1080 if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
1083 *str += strlen (percent_op->str);
1084 *reloc = percent_op->reloc;
1086 /* Check whether the output BFD supports this relocation.
1087 If not, issue an error and fall back on something safe. */
1088 if (!bfd_reloc_type_lookup (stdoutput, percent_op->reloc))
1090 as_bad ("relocation %s isn't supported by the current ABI",
1092 *reloc = BFD_RELOC_UNUSED;
1100 my_getExpression (expressionS *ep, char *str)
1104 save_in = input_line_pointer;
1105 input_line_pointer = str;
1107 expr_end = input_line_pointer;
1108 input_line_pointer = save_in;
1111 /* Parse string STR as a 16-bit relocatable operand. Store the
1112 expression in *EP and the relocation, if any, in RELOC.
1113 Return the number of relocation operators used (0 or 1).
1115 On exit, EXPR_END points to the first character after the expression. */
1118 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1119 char *str, const struct percent_op_match *percent_op)
1122 unsigned crux_depth, str_depth, regno;
1125 /* First, check for integer registers. */
1126 if (reg_lookup (&str, RCLASS_GPR, ®no))
1128 ep->X_op = O_register;
1129 ep->X_add_number = regno;
1133 /* Search for the start of the main expression.
1134 End the loop with CRUX pointing to the start
1135 of the main expression and with CRUX_DEPTH containing the number
1136 of open brackets at that point. */
1143 crux_depth = str_depth;
1145 /* Skip over whitespace and brackets, keeping count of the number
1147 while (*str == ' ' || *str == '\t' || *str == '(')
1153 && parse_relocation (&str, reloc, percent_op));
1155 my_getExpression (ep, crux);
1158 /* Match every open bracket. */
1159 while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
1164 as_bad ("unclosed '('");
1171 /* This routine assembles an instruction into its binary format. As a
1172 side effect, it sets the global variable imm_reloc to the type of
1173 relocation to do if one of the operands is an address expression. */
1176 riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
1177 bfd_reloc_code_real_type *imm_reloc)
1182 struct riscv_opcode *insn;
1187 const struct percent_op_match *p;
1188 const char *error = "unrecognized opcode";
1190 /* Parse the name of the instruction. Terminate the string if whitespace
1191 is found so that hash_find only sees the name part of the string. */
1192 for (s = str; *s != '\0'; ++s)
1200 insn = (struct riscv_opcode *) hash_find (op_hash, str);
1203 for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
1205 if (!riscv_subset_supports (insn->subset))
1208 create_insn (ip, insn);
1211 imm_expr->X_op = O_absent;
1212 *imm_reloc = BFD_RELOC_UNUSED;
1213 p = percent_op_itype;
1215 for (args = insn->args;; ++args)
1217 s += strspn (s, " \t");
1220 case '\0': /* End of args. */
1221 if (insn->pinfo != INSN_MACRO)
1223 if (!insn->match_func (insn, ip->insn_opcode))
1225 if (riscv_insn_length (insn->match) == 2 && !riscv_opts.rvc)
1230 /* Successful assembly. */
1237 case 's': /* RS1 x8-x15 */
1238 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1239 || !(regno >= 8 && regno <= 15))
1241 INSERT_OPERAND (CRS1S, *ip, regno % 8);
1243 case 'w': /* RS1 x8-x15, constrained to equal RD x8-x15. */
1244 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1245 || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
1248 case 't': /* RS2 x8-x15 */
1249 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1250 || !(regno >= 8 && regno <= 15))
1252 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1254 case 'x': /* RS2 x8-x15, constrained to equal RD x8-x15. */
1255 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1256 || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
1259 case 'U': /* RS1, constrained to equal RD. */
1260 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1261 || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
1265 if (!reg_lookup (&s, RCLASS_GPR, ®no))
1267 INSERT_OPERAND (CRS2, *ip, regno);
1269 case 'c': /* RS1, constrained to equal sp. */
1270 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1275 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1276 || imm_expr->X_op != O_constant
1277 || imm_expr->X_add_number <= 0
1278 || imm_expr->X_add_number >= 64)
1280 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1283 imm_expr->X_op = O_absent;
1286 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1287 || imm_expr->X_op != O_constant
1288 || !VALID_RVC_IMM (imm_expr->X_add_number)
1289 || imm_expr->X_add_number <= 0
1290 || imm_expr->X_add_number >= 32)
1292 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1295 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1296 || imm_expr->X_op != O_constant
1297 || imm_expr->X_add_number == 0
1298 || !VALID_RVC_SIMM3 (imm_expr->X_add_number))
1300 ip->insn_opcode |= ENCODE_RVC_SIMM3 (imm_expr->X_add_number);
1303 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1304 || imm_expr->X_op != O_constant
1305 || imm_expr->X_add_number == 0
1306 || !VALID_RVC_IMM (imm_expr->X_add_number))
1308 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1311 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1312 || imm_expr->X_op != O_constant
1313 || !VALID_RVC_LW_IMM (imm_expr->X_add_number))
1315 ip->insn_opcode |= ENCODE_RVC_LW_IMM (imm_expr->X_add_number);
1318 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1319 || imm_expr->X_op != O_constant
1320 || !VALID_RVC_LD_IMM (imm_expr->X_add_number))
1322 ip->insn_opcode |= ENCODE_RVC_LD_IMM (imm_expr->X_add_number);
1325 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1326 || imm_expr->X_op != O_constant
1327 || !VALID_RVC_LWSP_IMM (imm_expr->X_add_number))
1330 ENCODE_RVC_LWSP_IMM (imm_expr->X_add_number);
1333 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1334 || imm_expr->X_op != O_constant
1335 || !VALID_RVC_LDSP_IMM (imm_expr->X_add_number))
1338 ENCODE_RVC_LDSP_IMM (imm_expr->X_add_number);
1341 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1342 || imm_expr->X_op != O_constant
1343 || !VALID_RVC_ADDI4SPN_IMM (imm_expr->X_add_number)
1344 || imm_expr->X_add_number == 0)
1347 ENCODE_RVC_ADDI4SPN_IMM (imm_expr->X_add_number);
1350 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1351 || imm_expr->X_op != O_constant
1352 || !VALID_RVC_ADDI16SP_IMM (imm_expr->X_add_number)
1353 || imm_expr->X_add_number == 0)
1356 ENCODE_RVC_ADDI16SP_IMM (imm_expr->X_add_number);
1359 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1360 || imm_expr->X_op != O_constant
1361 || !VALID_RVC_SWSP_IMM (imm_expr->X_add_number))
1364 ENCODE_RVC_SWSP_IMM (imm_expr->X_add_number);
1367 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1368 || imm_expr->X_op != O_constant
1369 || !VALID_RVC_SDSP_IMM (imm_expr->X_add_number))
1372 ENCODE_RVC_SDSP_IMM (imm_expr->X_add_number);
1375 p = percent_op_utype;
1376 if (my_getSmallExpression (imm_expr, imm_reloc, s, p))
1379 if (imm_expr->X_op != O_constant
1380 || imm_expr->X_add_number <= 0
1381 || imm_expr->X_add_number >= RISCV_BIGIMM_REACH
1382 || (imm_expr->X_add_number >= RISCV_RVC_IMM_REACH / 2
1383 && (imm_expr->X_add_number <
1384 RISCV_BIGIMM_REACH - RISCV_RVC_IMM_REACH / 2)))
1386 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1389 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1390 || (imm_expr->X_add_number & (RISCV_IMM_REACH - 1))
1391 || ((int32_t)imm_expr->X_add_number
1392 != imm_expr->X_add_number))
1394 imm_expr->X_add_number =
1395 ((uint32_t) imm_expr->X_add_number) >> RISCV_IMM_BITS;
1401 case 'D': /* Floating-point RS2 x8-x15. */
1402 if (!reg_lookup (&s, RCLASS_FPR, ®no)
1403 || !(regno >= 8 && regno <= 15))
1405 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1407 case 'T': /* Floating-point RS2. */
1408 if (!reg_lookup (&s, RCLASS_FPR, ®no))
1410 INSERT_OPERAND (CRS2, *ip, regno);
1413 as_bad (_("bad RVC field specifier 'C%c'\n"), *args);
1432 case '<': /* Shift amount, 0 - 31. */
1433 my_getExpression (imm_expr, s);
1434 check_absolute_expr (ip, imm_expr);
1435 if ((unsigned long) imm_expr->X_add_number > 31)
1436 as_warn (_("Improper shift amount (%lu)"),
1437 (unsigned long) imm_expr->X_add_number);
1438 INSERT_OPERAND (SHAMTW, *ip, imm_expr->X_add_number);
1439 imm_expr->X_op = O_absent;
1443 case '>': /* Shift amount, 0 - (XLEN-1). */
1444 my_getExpression (imm_expr, s);
1445 check_absolute_expr (ip, imm_expr);
1446 if ((unsigned long) imm_expr->X_add_number >= xlen)
1447 as_warn (_("Improper shift amount (%lu)"),
1448 (unsigned long) imm_expr->X_add_number);
1449 INSERT_OPERAND (SHAMT, *ip, imm_expr->X_add_number);
1450 imm_expr->X_op = O_absent;
1454 case 'Z': /* CSRRxI immediate. */
1455 my_getExpression (imm_expr, s);
1456 check_absolute_expr (ip, imm_expr);
1457 if ((unsigned long) imm_expr->X_add_number > 31)
1458 as_warn (_("Improper CSRxI immediate (%lu)"),
1459 (unsigned long) imm_expr->X_add_number);
1460 INSERT_OPERAND (RS1, *ip, imm_expr->X_add_number);
1461 imm_expr->X_op = O_absent;
1465 case 'E': /* Control register. */
1466 if (reg_lookup (&s, RCLASS_CSR, ®no))
1467 INSERT_OPERAND (CSR, *ip, regno);
1470 my_getExpression (imm_expr, s);
1471 check_absolute_expr (ip, imm_expr);
1472 if ((unsigned long) imm_expr->X_add_number > 0xfff)
1473 as_warn (_("Improper CSR address (%lu)"),
1474 (unsigned long) imm_expr->X_add_number);
1475 INSERT_OPERAND (CSR, *ip, imm_expr->X_add_number);
1476 imm_expr->X_op = O_absent;
1481 case 'm': /* Rounding mode. */
1482 if (arg_lookup (&s, riscv_rm, ARRAY_SIZE (riscv_rm), ®no))
1484 INSERT_OPERAND (RM, *ip, regno);
1490 case 'Q': /* Fence predecessor/successor. */
1491 if (arg_lookup (&s, riscv_pred_succ, ARRAY_SIZE (riscv_pred_succ),
1495 INSERT_OPERAND (PRED, *ip, regno);
1497 INSERT_OPERAND (SUCC, *ip, regno);
1502 case 'd': /* Destination register. */
1503 case 's': /* Source register. */
1504 case 't': /* Target register. */
1505 if (reg_lookup (&s, RCLASS_GPR, ®no))
1511 /* Now that we have assembled one operand, we use the args
1512 string to figure out where it goes in the instruction. */
1516 INSERT_OPERAND (RS1, *ip, regno);
1519 INSERT_OPERAND (RD, *ip, regno);
1522 INSERT_OPERAND (RS2, *ip, regno);
1529 case 'D': /* Floating point rd. */
1530 case 'S': /* Floating point rs1. */
1531 case 'T': /* Floating point rs2. */
1532 case 'U': /* Floating point rs1 and rs2. */
1533 case 'R': /* Floating point rs3. */
1534 if (reg_lookup (&s, RCLASS_FPR, ®no))
1542 INSERT_OPERAND (RD, *ip, regno);
1545 INSERT_OPERAND (RS1, *ip, regno);
1548 INSERT_OPERAND (RS1, *ip, regno);
1551 INSERT_OPERAND (RS2, *ip, regno);
1554 INSERT_OPERAND (RS3, *ip, regno);
1563 my_getExpression (imm_expr, s);
1564 if (imm_expr->X_op != O_big
1565 && imm_expr->X_op != O_constant)
1567 normalize_constant_expr (imm_expr);
1572 my_getExpression (imm_expr, s);
1573 normalize_constant_expr (imm_expr);
1574 /* The 'A' format specifier must be a symbol. */
1575 if (imm_expr->X_op != O_symbol)
1577 *imm_reloc = BFD_RELOC_32;
1581 case 'j': /* Sign-extended immediate. */
1582 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
1583 p = percent_op_itype;
1585 case 'q': /* Store displacement. */
1586 p = percent_op_stype;
1587 *imm_reloc = BFD_RELOC_RISCV_LO12_S;
1589 case 'o': /* Load displacement. */
1590 p = percent_op_itype;
1591 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
1593 case '0': /* AMO "displacement," which must be zero. */
1594 p = percent_op_rtype;
1595 *imm_reloc = BFD_RELOC_UNUSED;
1597 /* Check whether there is only a single bracketed expression
1598 left. If so, it must be the base register and the
1599 constant must be zero. */
1600 imm_expr->X_op = O_constant;
1601 imm_expr->X_add_number = 0;
1602 if (*s == '(' && strchr (s + 1, '(') == 0)
1605 /* If this value won't fit into a 16 bit offset, then go
1606 find a macro that will generate the 32 bit offset
1608 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p))
1610 normalize_constant_expr (imm_expr);
1611 if (imm_expr->X_op != O_constant
1612 || (*args == '0' && imm_expr->X_add_number != 0)
1613 || imm_expr->X_add_number >= (signed)RISCV_IMM_REACH/2
1614 || imm_expr->X_add_number < -(signed)RISCV_IMM_REACH/2)
1621 case 'p': /* PC-relative offset. */
1623 *imm_reloc = BFD_RELOC_12_PCREL;
1624 my_getExpression (imm_expr, s);
1628 case 'u': /* Upper 20 bits. */
1629 p = percent_op_utype;
1630 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p)
1631 && imm_expr->X_op == O_constant)
1633 if (imm_expr->X_add_number < 0
1634 || imm_expr->X_add_number >= (signed)RISCV_BIGIMM_REACH)
1635 as_bad (_("lui expression not in range 0..1048575"));
1637 *imm_reloc = BFD_RELOC_RISCV_HI20;
1638 imm_expr->X_add_number <<= RISCV_IMM_BITS;
1643 case 'a': /* 20-bit PC-relative offset. */
1645 my_getExpression (imm_expr, s);
1647 *imm_reloc = BFD_RELOC_RISCV_JMP;
1651 my_getExpression (imm_expr, s);
1653 if (strcmp (s, "@plt") == 0)
1655 *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
1659 *imm_reloc = BFD_RELOC_RISCV_CALL;
1663 as_fatal (_("internal error: bad argument type %c"), *args);
1668 error = _("illegal operands");
1672 /* Restore the character we might have clobbered above. */
1674 *(argsStart - 1) = save_c;
1680 md_assemble (char *str)
1682 struct riscv_cl_insn insn;
1683 expressionS imm_expr;
1684 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
1686 const char *error = riscv_ip (str, &insn, &imm_expr, &imm_reloc);
1690 as_bad ("%s `%s'", error, str);
1694 if (insn.insn_mo->pinfo == INSN_MACRO)
1695 macro (&insn, &imm_expr, &imm_reloc);
1697 append_insn (&insn, &imm_expr, imm_reloc);
1701 md_atof (int type, char *litP, int *sizeP)
1703 return ieee_md_atof (type, litP, sizeP, TARGET_BYTES_BIG_ENDIAN);
1707 md_number_to_chars (char *buf, valueT val, int n)
1709 number_to_chars_littleendian (buf, val, n);
1712 const char *md_shortopts = "O::g::G:";
1716 OPTION_M32 = OPTION_MD_BASE,
1728 struct option md_longopts[] =
1730 {"m32", no_argument, NULL, OPTION_M32},
1731 {"m64", no_argument, NULL, OPTION_M64},
1732 {"march", required_argument, NULL, OPTION_MARCH},
1733 {"fPIC", no_argument, NULL, OPTION_PIC},
1734 {"fpic", no_argument, NULL, OPTION_PIC},
1735 {"fno-pic", no_argument, NULL, OPTION_NO_PIC},
1736 {"mrvc", no_argument, NULL, OPTION_MRVC},
1737 {"mno-rvc", no_argument, NULL, OPTION_MNO_RVC},
1738 {"msoft-float", no_argument, NULL, OPTION_MSOFT_FLOAT},
1739 {"mhard-float", no_argument, NULL, OPTION_MHARD_FLOAT},
1741 {NULL, no_argument, NULL, 0}
1743 size_t md_longopts_size = sizeof (md_longopts);
1751 static enum float_mode float_mode = FLOAT_MODE_DEFAULT;
1754 md_parse_option (int c, const char *arg)
1759 riscv_set_rvc (TRUE);
1762 case OPTION_MNO_RVC:
1763 riscv_set_rvc (FALSE);
1766 case OPTION_MSOFT_FLOAT:
1767 float_mode = FLOAT_MODE_SOFT;
1770 case OPTION_MHARD_FLOAT:
1771 float_mode = FLOAT_MODE_HARD;
1783 riscv_set_arch (arg);
1787 riscv_opts.pic = FALSE;
1791 riscv_opts.pic = TRUE;
1802 riscv_after_parse_args (void)
1804 if (riscv_subsets == NULL)
1805 riscv_set_arch ("RVIMAFD");
1809 if (strcmp (default_arch, "riscv32") == 0)
1811 else if (strcmp (default_arch, "riscv64") == 0)
1814 as_bad ("unknown default architecture `%s'", default_arch);
1819 md_pcrel_from (fixS *fixP)
1821 return fixP->fx_where + fixP->fx_frag->fr_address;
1824 /* Apply a fixup to the object file. */
1827 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
1829 bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
1831 /* Remember value for tc_gen_reloc. */
1832 fixP->fx_addnumber = *valP;
1834 switch (fixP->fx_r_type)
1836 case BFD_RELOC_RISCV_TLS_GOT_HI20:
1837 case BFD_RELOC_RISCV_TLS_GD_HI20:
1838 case BFD_RELOC_RISCV_TLS_DTPREL32:
1839 case BFD_RELOC_RISCV_TLS_DTPREL64:
1840 case BFD_RELOC_RISCV_TPREL_HI20:
1841 case BFD_RELOC_RISCV_TPREL_LO12_I:
1842 case BFD_RELOC_RISCV_TPREL_LO12_S:
1843 case BFD_RELOC_RISCV_TPREL_ADD:
1844 S_SET_THREAD_LOCAL (fixP->fx_addsy);
1847 case BFD_RELOC_RISCV_GOT_HI20:
1848 case BFD_RELOC_RISCV_PCREL_HI20:
1849 case BFD_RELOC_RISCV_HI20:
1850 case BFD_RELOC_RISCV_LO12_I:
1851 case BFD_RELOC_RISCV_LO12_S:
1852 case BFD_RELOC_RISCV_ADD8:
1853 case BFD_RELOC_RISCV_ADD16:
1854 case BFD_RELOC_RISCV_ADD32:
1855 case BFD_RELOC_RISCV_ADD64:
1856 case BFD_RELOC_RISCV_SUB8:
1857 case BFD_RELOC_RISCV_SUB16:
1858 case BFD_RELOC_RISCV_SUB32:
1859 case BFD_RELOC_RISCV_SUB64:
1860 gas_assert (fixP->fx_addsy != NULL);
1861 /* Nothing needed to do. The value comes from the reloc entry. */
1868 if (fixP->fx_addsy && fixP->fx_subsy)
1870 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
1871 fixP->fx_next->fx_addsy = fixP->fx_subsy;
1872 fixP->fx_next->fx_subsy = NULL;
1873 fixP->fx_next->fx_offset = 0;
1874 fixP->fx_subsy = NULL;
1876 switch (fixP->fx_r_type)
1879 fixP->fx_r_type = BFD_RELOC_RISCV_ADD64;
1880 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB64;
1884 fixP->fx_r_type = BFD_RELOC_RISCV_ADD32;
1885 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
1889 fixP->fx_r_type = BFD_RELOC_RISCV_ADD16;
1890 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
1894 fixP->fx_r_type = BFD_RELOC_RISCV_ADD8;
1895 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
1899 /* This case is unreachable. */
1906 /* If we are deleting this reloc entry, we must fill in the
1907 value now. This can happen if we have a .word which is not
1908 resolved when it appears but is later defined. */
1909 if (fixP->fx_addsy == NULL)
1911 gas_assert (fixP->fx_size <= sizeof (valueT));
1912 md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
1917 case BFD_RELOC_RISCV_JMP:
1920 /* Fill in a tentative value to improve objdump readability. */
1921 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
1922 bfd_vma delta = target - md_pcrel_from (fixP);
1923 bfd_putl32 (bfd_getl32 (buf) | ENCODE_UJTYPE_IMM (delta), buf);
1927 case BFD_RELOC_12_PCREL:
1930 /* Fill in a tentative value to improve objdump readability. */
1931 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
1932 bfd_vma delta = target - md_pcrel_from (fixP);
1933 bfd_putl32 (bfd_getl32 (buf) | ENCODE_SBTYPE_IMM (delta), buf);
1937 case BFD_RELOC_RISCV_RVC_BRANCH:
1940 /* Fill in a tentative value to improve objdump readability. */
1941 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
1942 bfd_vma delta = target - md_pcrel_from (fixP);
1943 bfd_putl16 (bfd_getl16 (buf) | ENCODE_RVC_B_IMM (delta), buf);
1947 case BFD_RELOC_RISCV_RVC_JUMP:
1950 /* Fill in a tentative value to improve objdump readability. */
1951 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
1952 bfd_vma delta = target - md_pcrel_from (fixP);
1953 bfd_putl16 (bfd_getl16 (buf) | ENCODE_RVC_J_IMM (delta), buf);
1957 case BFD_RELOC_RISCV_PCREL_LO12_S:
1958 case BFD_RELOC_RISCV_PCREL_LO12_I:
1959 case BFD_RELOC_RISCV_CALL:
1960 case BFD_RELOC_RISCV_CALL_PLT:
1961 case BFD_RELOC_RISCV_ALIGN:
1965 /* We ignore generic BFD relocations we don't know about. */
1966 if (bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type) != NULL)
1967 as_fatal (_("internal error: bad relocation #%d"), fixP->fx_r_type);
1971 /* This structure is used to hold a stack of .option values. */
1973 struct riscv_option_stack
1975 struct riscv_option_stack *next;
1976 struct riscv_set_options options;
1979 static struct riscv_option_stack *riscv_opts_stack;
1981 /* Handle the .option pseudo-op. */
1984 s_riscv_option (int x ATTRIBUTE_UNUSED)
1986 char *name = input_line_pointer, ch;
1988 while (!is_end_of_line[(unsigned char) *input_line_pointer])
1989 ++input_line_pointer;
1990 ch = *input_line_pointer;
1991 *input_line_pointer = '\0';
1993 if (strcmp (name, "rvc") == 0)
1994 riscv_set_rvc (TRUE);
1995 else if (strcmp (name, "norvc") == 0)
1996 riscv_set_rvc (FALSE);
1997 else if (strcmp (name, "pic") == 0)
1998 riscv_opts.pic = TRUE;
1999 else if (strcmp (name, "nopic") == 0)
2000 riscv_opts.pic = FALSE;
2001 else if (strcmp (name, "soft-float") == 0)
2002 float_mode = FLOAT_MODE_SOFT;
2003 else if (strcmp (name, "hard-float") == 0)
2004 float_mode = FLOAT_MODE_HARD;
2005 else if (strcmp (name, "push") == 0)
2007 struct riscv_option_stack *s;
2009 s = (struct riscv_option_stack *) xmalloc (sizeof *s);
2010 s->next = riscv_opts_stack;
2011 s->options = riscv_opts;
2012 riscv_opts_stack = s;
2014 else if (strcmp (name, "pop") == 0)
2016 struct riscv_option_stack *s;
2018 s = riscv_opts_stack;
2020 as_bad (_(".option pop with no .option push"));
2023 riscv_opts = s->options;
2024 riscv_opts_stack = s->next;
2030 as_warn (_("Unrecognized .option directive: %s\n"), name);
2032 *input_line_pointer = ch;
2033 demand_empty_rest_of_line ();
2036 /* Handle the .dtprelword and .dtpreldword pseudo-ops. They generate
2037 a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
2038 use in DWARF debug information. */
2041 s_dtprel (int bytes)
2048 if (ex.X_op != O_symbol)
2050 as_bad (_("Unsupported use of %s"), (bytes == 8
2053 ignore_rest_of_line ();
2056 p = frag_more (bytes);
2057 md_number_to_chars (p, 0, bytes);
2058 fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE,
2060 ? BFD_RELOC_RISCV_TLS_DTPREL64
2061 : BFD_RELOC_RISCV_TLS_DTPREL32));
2063 demand_empty_rest_of_line ();
2066 /* Handle the .bss pseudo-op. */
2069 s_bss (int ignore ATTRIBUTE_UNUSED)
2071 subseg_set (bss_section, 0);
2072 demand_empty_rest_of_line ();
2075 /* Align to a given power of two. */
2078 s_align (int bytes_p)
2080 int fill_value = 0, fill_value_specified = 0;
2081 int min_text_alignment = riscv_opts.rvc ? 2 : 4;
2082 int alignment = get_absolute_expression(), bytes;
2087 if (bytes < 1 || (bytes & (bytes-1)) != 0)
2088 as_bad (_("alignment not a power of 2: %d"), bytes);
2089 for (alignment = 0; bytes > 1; bytes >>= 1)
2093 bytes = 1 << alignment;
2095 if (alignment < 0 || alignment > 31)
2096 as_bad (_("unsatisfiable alignment: %d"), alignment);
2098 if (*input_line_pointer == ',')
2100 ++input_line_pointer;
2101 fill_value = get_absolute_expression ();
2102 fill_value_specified = 1;
2105 if (!fill_value_specified
2106 && subseg_text_p (now_seg)
2107 && bytes > min_text_alignment)
2109 /* Emit the worst-case NOP string. The linker will delete any
2110 unnecessary NOPs. This allows us to support code alignment
2111 in spite of linker relaxations. */
2112 bfd_vma i, worst_case_bytes = bytes - min_text_alignment;
2113 char *nops = frag_more (worst_case_bytes);
2114 for (i = 0; i < worst_case_bytes - 2; i += 4)
2115 md_number_to_chars (nops + i, RISCV_NOP, 4);
2116 if (i < worst_case_bytes)
2117 md_number_to_chars (nops + i, RVC_NOP, 2);
2120 ex.X_op = O_constant;
2121 ex.X_add_number = worst_case_bytes;
2123 fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
2124 &ex, FALSE, BFD_RELOC_RISCV_ALIGN);
2127 frag_align (alignment, fill_value, 0);
2129 record_alignment (now_seg, alignment);
2131 demand_empty_rest_of_line ();
2135 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
2137 return (fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE));
2140 /* Translate internal representation of relocation info to BFD target
2144 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
2146 arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
2148 reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
2149 *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
2150 reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
2151 reloc->addend = fixp->fx_addnumber;
2153 reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
2154 if (reloc->howto == NULL)
2156 if ((fixp->fx_r_type == BFD_RELOC_16 || fixp->fx_r_type == BFD_RELOC_8)
2157 && fixp->fx_addsy != NULL && fixp->fx_subsy != NULL)
2159 /* We don't have R_RISCV_8/16, but for this special case,
2160 we can use R_RISCV_ADD8/16 with R_RISCV_SUB8/16. */
2164 as_bad_where (fixp->fx_file, fixp->fx_line,
2165 _("cannot represent %s relocation in object file"),
2166 bfd_get_reloc_code_name (fixp->fx_r_type));
2174 riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
2176 if (RELAX_BRANCH_P (fragp->fr_subtype))
2178 offsetT old_var = fragp->fr_var;
2179 fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
2180 return fragp->fr_var - old_var;
2186 /* Expand far branches to multi-instruction sequences. */
2189 md_convert_frag_branch (fragS *fragp)
2197 buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
2199 exp.X_op = O_symbol;
2200 exp.X_add_symbol = fragp->fr_symbol;
2201 exp.X_add_number = fragp->fr_offset;
2203 gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
2205 if (RELAX_BRANCH_RVC (fragp->fr_subtype))
2207 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
2211 /* Expand the RVC branch into a RISC-V one. */
2212 insn = bfd_getl16 (buf);
2213 rs1 = 8 + ((insn >> OP_SH_CRS1S) & OP_MASK_CRS1S);
2214 if ((insn & MASK_C_J) == MATCH_C_J)
2216 else if ((insn & MASK_C_JAL) == MATCH_C_JAL)
2217 insn = MATCH_JAL | (X_RA << OP_SH_RD);
2218 else if ((insn & MASK_C_BEQZ) == MATCH_C_BEQZ)
2219 insn = MATCH_BEQ | (rs1 << OP_SH_RS1);
2220 else if ((insn & MASK_C_BNEZ) == MATCH_C_BNEZ)
2221 insn = MATCH_BNE | (rs1 << OP_SH_RS1);
2224 bfd_putl32 (insn, buf);
2228 /* Invert the branch condition. Branch over the jump. */
2229 insn = bfd_getl16 (buf);
2230 insn ^= MATCH_C_BEQZ ^ MATCH_C_BNEZ;
2231 insn |= ENCODE_RVC_B_IMM (6);
2232 bfd_putl16 (insn, buf);
2237 /* Just keep the RVC branch. */
2238 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
2239 ? BFD_RELOC_RISCV_RVC_JUMP : BFD_RELOC_RISCV_RVC_BRANCH;
2240 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2241 2, &exp, FALSE, reloc);
2250 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
2253 gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
2255 /* Invert the branch condition. Branch over the jump. */
2256 insn = bfd_getl32 (buf);
2257 insn ^= MATCH_BEQ ^ MATCH_BNE;
2258 insn |= ENCODE_SBTYPE_IMM (8);
2259 md_number_to_chars ((char *) buf, insn, 4);
2263 /* Jump to the target. */
2264 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2265 4, &exp, FALSE, BFD_RELOC_RISCV_JMP);
2266 md_number_to_chars ((char *) buf, MATCH_JAL, 4);
2271 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
2272 ? BFD_RELOC_RISCV_JMP : BFD_RELOC_12_PCREL;
2273 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2274 4, &exp, FALSE, reloc);
2283 fixp->fx_file = fragp->fr_file;
2284 fixp->fx_line = fragp->fr_line;
2286 gas_assert (buf == (bfd_byte *)fragp->fr_literal
2287 + fragp->fr_fix + fragp->fr_var);
2289 fragp->fr_fix += fragp->fr_var;
2292 /* Relax a machine dependent frag. This returns the amount by which
2293 the current size of the frag should change. */
2296 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
2299 gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
2300 md_convert_frag_branch (fragp);
2304 md_show_usage (FILE *stream)
2306 fprintf (stream, _("\
2308 -m32 assemble RV32 code\n\
2309 -m64 assemble RV64 code (default)\n\
2310 -fpic generate position-independent code\n\
2311 -fno-pic don't generate position-independent code (default)\n\
2312 -msoft-float don't use F registers for floating-point values\n\
2313 -mhard-float use F registers for floating-point values (default)\n\
2314 -mno-rvc disable the C extension for compressed instructions (default)\n\
2315 -mrvc enable the C extension for compressed instructions\n\
2316 -march=ISA set the RISC-V architecture, RV64IMAFD by default\n\
2320 /* Standard calling conventions leave the CFA at SP on entry. */
2322 riscv_cfi_frame_initial_instructions (void)
2324 cfi_add_CFA_def_cfa_register (X_SP);
2328 tc_riscv_regname_to_dw2regnum (char *regname)
2332 if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
2335 if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
2338 as_bad (_("unknown register `%s'"), regname);
2343 riscv_elf_final_processing (void)
2345 enum float_mode elf_float_mode = float_mode;
2347 elf_elfheader (stdoutput)->e_flags |= elf_flags;
2349 if (elf_float_mode == FLOAT_MODE_DEFAULT)
2351 struct riscv_subset *subset;
2353 /* Assume soft-float unless D extension is present. */
2354 elf_float_mode = FLOAT_MODE_SOFT;
2356 for (subset = riscv_subsets; subset != NULL; subset = subset->next)
2357 if (strcasecmp (subset->name, "D") == 0)
2358 elf_float_mode = FLOAT_MODE_HARD;
2361 if (elf_float_mode == FLOAT_MODE_SOFT)
2362 elf_elfheader (stdoutput)->e_flags |= EF_RISCV_SOFT_FLOAT;
2365 /* Parse the .sleb128 and .uleb128 pseudos. Only allow constant expressions,
2366 since these directives break relaxation when used with symbol deltas. */
2369 s_riscv_leb128 (int sign)
2372 char *save_in = input_line_pointer;
2375 if (exp.X_op != O_constant)
2376 as_bad (_("non-constant .%cleb128 is not supported"), sign ? 's' : 'u');
2377 demand_empty_rest_of_line ();
2379 input_line_pointer = save_in;
2380 return s_leb128 (sign);
2383 /* Pseudo-op table. */
2385 static const pseudo_typeS riscv_pseudo_table[] =
2387 /* RISC-V-specific pseudo-ops. */
2388 {"option", s_riscv_option, 0},
2392 {"dtprelword", s_dtprel, 4},
2393 {"dtpreldword", s_dtprel, 8},
2395 {"align", s_align, 0},
2396 {"p2align", s_align, 0},
2397 {"balign", s_align, 1},
2398 {"uleb128", s_riscv_leb128, 0},
2399 {"sleb128", s_riscv_leb128, 1},
2405 riscv_pop_insert (void)
2407 extern void pop_insert (const pseudo_typeS *);
2409 pop_insert (riscv_pseudo_table);