]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gas/config/tc-riscv.c
Formatting changes for RISC-V
[thirdparty/binutils-gdb.git] / gas / config / tc-riscv.c
1 /* tc-riscv.c -- RISC-V assembler
2 Copyright 2011-2016 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 #include "struc-symbol.h"
32
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 static const char default_arch[] = DEFAULT_ARCH;
63
64 unsigned xlen = 0; /* width of an x-register */
65
66 #define LOAD_ADDRESS_INSN (xlen == 64 ? "ld" : "lw")
67 #define ADD32_INSN (xlen == 64 ? "addiw" : "addi")
68
69 static unsigned elf_flags = 0;
70
71 /* This is the set of options which the .option pseudo-op may modify. */
72
73 struct riscv_set_options
74 {
75 int pic; /* Generate position-independent code. */
76 int rvc; /* Generate RVC code. */
77 };
78
79 static struct riscv_set_options riscv_opts =
80 {
81 0, /* pic */
82 0, /* rvc */
83 };
84
85 static void
86 riscv_set_rvc (bfd_boolean rvc_value)
87 {
88 if (rvc_value)
89 elf_flags |= EF_RISCV_RVC;
90
91 riscv_opts.rvc = rvc_value;
92 }
93
94 struct riscv_subset
95 {
96 const char *name;
97
98 struct riscv_subset *next;
99 };
100
101 static struct riscv_subset *riscv_subsets;
102
103 static bfd_boolean
104 riscv_subset_supports (const char *feature)
105 {
106 struct riscv_subset *s;
107 char *p;
108 unsigned xlen_required = strtoul (feature, &p, 10);
109
110 if (xlen_required && xlen != xlen_required)
111 return FALSE;
112
113 for (s = riscv_subsets; s != NULL; s = s->next)
114 if (strcasecmp (s->name, p) == 0)
115 return TRUE;
116
117 return FALSE;
118 }
119
120 static void
121 riscv_add_subset (const char *subset)
122 {
123 struct riscv_subset *s = xmalloc (sizeof *s);
124
125 s->name = xstrdup (subset);
126 s->next = riscv_subsets;
127 riscv_subsets = s;
128 }
129
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.
132
133 FIXME: Version numbers are not supported yet. */
134 static void
135 riscv_set_arch (const char *p)
136 {
137 const char *all_subsets = "IMAFDC";
138 const char *extension = NULL;
139 int rvc = 0;
140 int i;
141
142 if (strncasecmp (p, "RV32", 4) == 0)
143 {
144 xlen = 32;
145 p += 4;
146 }
147 else if (strncasecmp (p, "RV64", 4) == 0)
148 {
149 xlen = 64;
150 p += 4;
151 }
152 else if (strncasecmp (p, "RV", 2) == 0)
153 p += 2;
154
155 switch (TOUPPER(*p))
156 {
157 case 'I':
158 break;
159
160 case 'G':
161 p++;
162 /* Fall through. */
163
164 case '\0':
165 for (i = 0; all_subsets[i] != '\0'; i++)
166 {
167 const char subset[] = {all_subsets[i], '\0'};
168 riscv_add_subset (subset);
169 }
170 break;
171
172 default:
173 as_fatal ("`I' must be the first ISA subset name specified (got %c)",
174 *p);
175 }
176
177 while (*p)
178 {
179 if (TOUPPER(*p) == 'X')
180 {
181 char *subset = xstrdup (p), *q = subset;
182
183 while (*++q != '\0' && *q != '_')
184 ;
185 *q = '\0';
186
187 if (extension)
188 as_fatal ("only one eXtension is supported (found %s and %s)",
189 extension, subset);
190 extension = subset;
191 riscv_add_subset (subset);
192 p += strlen (subset);
193 free (subset);
194 }
195 else if (*p == '_')
196 p++;
197 else if ((all_subsets = strchr (all_subsets, *p)) != NULL)
198 {
199 const char subset[] = {*p, 0};
200 riscv_add_subset (subset);
201 if (TOUPPER(*p) == 'C')
202 rvc = 1;
203 all_subsets++;
204 p++;
205 }
206 else
207 as_fatal ("unsupported ISA subset %c", *p);
208 }
209
210 if (rvc)
211 {
212 /* Override -m[no-]rvc setting if C was explicitly listed. */
213 riscv_set_rvc (TRUE);
214 }
215 else
216 {
217 /* Add RVC anyway. -m[no-]rvc toggles its availability. */
218 riscv_add_subset ("C");
219 }
220 }
221
222 /* Handle of the OPCODE hash table. */
223 static struct hash_control *op_hash = NULL;
224
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[] = "#";
228
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[] = "#";
237
238 /* This array holds machine specific line separator characters. */
239 const char line_separator_chars[] = ";";
240
241 /* Chars that can be used to separate mant from exp in floating point nums */
242 const char EXP_CHARS[] = "eE";
243
244 /* Chars that mean this number is a floating point constant */
245 /* As in 0f12.456 */
246 /* or 0d1.2345e12 */
247 const char FLT_CHARS[] = "rRsSfFdDxXpP";
248
249 /* Macros for encoding relaxation state for RVC branches and far jumps. */
250 #define RELAX_BRANCH_ENCODE(uncond, rvc, length) \
251 ((relax_substateT) \
252 (0xc0000000 \
253 | ((uncond) ? 1 : 0) \
254 | ((rvc) ? 2 : 0) \
255 | ((length) << 2)))
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)
260
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))
265
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))
270
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)
275
276 /* Determine if an instruction matches an opcode. */
277 #define OPCODE_MATCHES(OPCODE, OP) \
278 (((OPCODE) & MASK_##OP) == MATCH_##OP)
279
280 static char *expr_end;
281
282 /* The default target format to use. */
283
284 const char *
285 riscv_target_format (void)
286 {
287 return xlen == 64 ? "elf64-littleriscv" : "elf32-littleriscv";
288 }
289
290 /* Return the length of instruction INSN. */
291
292 static inline unsigned int
293 insn_length (const struct riscv_cl_insn *insn)
294 {
295 return riscv_insn_length (insn->insn_opcode);
296 }
297
298 /* Initialise INSN from opcode entry MO. Leave its position unspecified. */
299
300 static void
301 create_insn (struct riscv_cl_insn *insn, const struct riscv_opcode *mo)
302 {
303 insn->insn_mo = mo;
304 insn->insn_opcode = mo->match;
305 insn->frag = NULL;
306 insn->where = 0;
307 insn->fixp = NULL;
308 }
309
310 /* Install INSN at the location specified by its "frag" and "where" fields. */
311
312 static void
313 install_insn (const struct riscv_cl_insn *insn)
314 {
315 char *f = insn->frag->fr_literal + insn->where;
316 md_number_to_chars (f, insn->insn_opcode, insn_length (insn));
317 }
318
319 /* Move INSN to offset WHERE in FRAG. Adjust the fixups accordingly
320 and install the opcode in the new location. */
321
322 static void
323 move_insn (struct riscv_cl_insn *insn, fragS *frag, long where)
324 {
325 insn->frag = frag;
326 insn->where = where;
327 if (insn->fixp != NULL)
328 {
329 insn->fixp->fx_frag = frag;
330 insn->fixp->fx_where = where;
331 }
332 install_insn (insn);
333 }
334
335 /* Add INSN to the end of the output. */
336
337 static void
338 add_fixed_insn (struct riscv_cl_insn *insn)
339 {
340 char *f = frag_more (insn_length (insn));
341 move_insn (insn, frag_now, f - frag_now->fr_literal);
342 }
343
344 static void
345 add_relaxed_insn (struct riscv_cl_insn *insn, int max_chars, int var,
346 relax_substateT subtype, symbolS *symbol, offsetT offset)
347 {
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);
352 }
353
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. */
356
357 static unsigned
358 relaxed_branch_length (fragS *fragp, asection *sec, int update)
359 {
360 int jump, rvc, length = 8;
361
362 if (!fragp)
363 return length;
364
365 jump = RELAX_BRANCH_UNCOND (fragp->fr_subtype);
366 rvc = RELAX_BRANCH_RVC (fragp->fr_subtype);
367 length = RELAX_BRANCH_LENGTH (fragp->fr_subtype);
368
369 /* Assume jumps are in range; the linker will catch any that aren't. */
370 length = jump ? 4 : 8;
371
372 if (fragp->fr_symbol != NULL
373 && S_IS_DEFINED (fragp->fr_symbol)
374 && sec == S_GET_SEGMENT (fragp->fr_symbol))
375 {
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;
379
380 if (rvc && (bfd_vma)(val + rvc_range/2) < rvc_range)
381 length = 2;
382 else if ((bfd_vma)(val + RISCV_BRANCH_REACH/2) < RISCV_BRANCH_REACH)
383 length = 4;
384 else if (!jump && rvc)
385 length = 6;
386 }
387
388 if (update)
389 fragp->fr_subtype = RELAX_BRANCH_ENCODE (jump, rvc, length);
390
391 return length;
392 }
393
394 struct regname
395 {
396 const char *name;
397 unsigned int num;
398 };
399
400 enum reg_class
401 {
402 RCLASS_GPR,
403 RCLASS_FPR,
404 RCLASS_CSR,
405 RCLASS_MAX
406 };
407
408 static struct hash_control *reg_names_hash = NULL;
409
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)
414
415 static void
416 hash_reg_name (enum reg_class class, const char *name, unsigned n)
417 {
418 void *hash = ENCODE_REG_HASH (class, n);
419 const char *retval = hash_insert (reg_names_hash, name, hash);
420
421 if (retval != NULL)
422 as_fatal (_("internal error: can't hash `%s': %s"), name, retval);
423 }
424
425 static void
426 hash_reg_names (enum reg_class class, const char * const names[], unsigned n)
427 {
428 unsigned i;
429
430 for (i = 0; i < n; i++)
431 hash_reg_name (class, names[i], i);
432 }
433
434 static unsigned int
435 reg_lookup_internal (const char *s, enum reg_class class)
436 {
437 struct regname *r = (struct regname *) hash_find (reg_names_hash, s);
438
439 if (r == NULL || DECODE_REG_CLASS (r) != class)
440 return -1;
441 return DECODE_REG_NUM (r);
442 }
443
444 static bfd_boolean
445 reg_lookup (char **s, enum reg_class class, unsigned int *regnop)
446 {
447 char *e;
448 char save_c;
449 int reg = -1;
450
451 /* Find end of name. */
452 e = *s;
453 if (is_name_beginner (*e))
454 ++e;
455 while (is_part_of_name (*e))
456 ++e;
457
458 /* Terminate name. */
459 save_c = *e;
460 *e = '\0';
461
462 /* Look for the register. Advance to next token if one was recognized. */
463 if ((reg = reg_lookup_internal (*s, class)) >= 0)
464 *s = e;
465
466 *e = save_c;
467 if (regnop)
468 *regnop = reg;
469 return reg >= 0;
470 }
471
472 static bfd_boolean
473 arg_lookup (char **s, const char *const *array, size_t size, unsigned *regnop)
474 {
475 const char *p = strchr (*s, ',');
476 size_t i, len = p ? (size_t)(p - *s) : strlen (*s);
477
478 for (i = 0; i < size; i++)
479 if (array[i] != NULL && strncmp (array[i], *s, len) == 0)
480 {
481 *regnop = i;
482 *s += len;
483 return TRUE;
484 }
485
486 return FALSE;
487 }
488
489 /* For consistency checking, verify that all bits are specified either
490 by the match/mask part of the instruction definition, or by the
491 operand list. */
492 static bfd_boolean
493 validate_riscv_insn (const struct riscv_opcode *opc)
494 {
495 const char *p = opc->args;
496 char c;
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);
500
501 if ((used_bits & opc->match) != (opc->match & required_bits))
502 {
503 as_bad (_("internal: bad RISC-V opcode (mask error): %s %s"),
504 opc->name, opc->args);
505 return FALSE;
506 }
507
508 #define USE_BITS(mask,shift) (used_bits |= ((insn_t)(mask) << (shift)))
509 while (*p)
510 switch (c = *p++)
511 {
512 case 'C': /* RVC */
513 switch (c = *p++)
514 {
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;
540 default:
541 as_bad (_("internal: bad RISC-V opcode (unknown operand type `C%c'): %s %s"),
542 c, opc->name, opc->args);
543 return FALSE;
544 }
545 break;
546 case ',': break;
547 case '(': break;
548 case ')': break;
549 case '<': USE_BITS (OP_MASK_SHAMTW, OP_SH_SHAMTW); break;
550 case '>': USE_BITS (OP_MASK_SHAMT, OP_SH_SHAMT); break;
551 case 'A': 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;
555 case 'I': 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;
566 case 'o':
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;
572 case '[': break;
573 case ']': break;
574 case '0': break;
575 default:
576 as_bad (_("internal: bad RISC-V opcode "
577 "(unknown operand type `%c'): %s %s"),
578 c, opc->name, opc->args);
579 return FALSE;
580 }
581 #undef USE_BITS
582 if (used_bits != required_bits)
583 {
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);
587 return FALSE;
588 }
589 return TRUE;
590 }
591
592 struct percent_op_match
593 {
594 const char *str;
595 bfd_reloc_code_real_type reloc;
596 };
597
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. */
600
601 void
602 md_begin (void)
603 {
604 int i = 0;
605
606 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, 0))
607 as_warn (_("Could not set architecture and machine"));
608
609 op_hash = hash_new ();
610
611 while (riscv_opcodes[i].name)
612 {
613 const char *name = riscv_opcodes[i].name;
614 const char *hash_error =
615 hash_insert (op_hash, name, (void *) &riscv_opcodes[i]);
616
617 if (hash_error)
618 {
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."));
623 }
624
625 do
626 {
627 if (riscv_opcodes[i].pinfo != INSN_MACRO)
628 {
629 if (!validate_riscv_insn (&riscv_opcodes[i]))
630 as_fatal (_("Broken assembler. No assembly attempted."));
631 }
632 ++i;
633 }
634 while (riscv_opcodes[i].name && !strcmp (riscv_opcodes[i].name, name));
635 }
636
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);
642
643 #define DECLARE_CSR(name, num) hash_reg_name (RCLASS_CSR, #name, num);
644 #include "opcode/riscv-opc.h"
645 #undef DECLARE_CSR
646
647 /* Set the default alignment for the text section. */
648 record_alignment (text_section, riscv_opts.rvc ? 1 : 2);
649 }
650
651 /* Output an instruction. IP is the instruction information.
652 ADDRESS_EXPR is an operand of the instruction to be used with
653 RELOC_TYPE. */
654
655 static void
656 append_insn (struct riscv_cl_insn *ip, expressionS *address_expr,
657 bfd_reloc_code_real_type reloc_type)
658 {
659 dwarf2_emit_insn (0);
660
661 if (reloc_type != BFD_RELOC_UNUSED)
662 {
663 reloc_howto_type *howto;
664
665 gas_assert (address_expr);
666 if (reloc_type == BFD_RELOC_12_PCREL
667 || reloc_type == BFD_RELOC_RISCV_JMP)
668 {
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);
676 return;
677 }
678 else if (address_expr->X_op == O_constant)
679 {
680 switch (reloc_type)
681 {
682 case BFD_RELOC_32:
683 ip->insn_opcode |= address_expr->X_add_number;
684 goto append;
685
686 case BFD_RELOC_RISCV_HI20:
687 {
688 insn_t imm = RISCV_CONST_HIGH_PART (address_expr->X_add_number);
689 ip->insn_opcode |= ENCODE_UTYPE_IMM (imm);
690 goto append;
691 }
692
693 case BFD_RELOC_RISCV_LO12_S:
694 ip->insn_opcode |= ENCODE_STYPE_IMM (address_expr->X_add_number);
695 goto append;
696
697 case BFD_RELOC_RISCV_LO12_I:
698 ip->insn_opcode |= ENCODE_ITYPE_IMM (address_expr->X_add_number);
699 goto append;
700
701 default:
702 break;
703 }
704 }
705
706 howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
707 if (howto == NULL)
708 as_bad (_("Unsupported RISC-V relocation number %d"), reloc_type);
709
710 ip->fixp = fix_new_exp (ip->frag, ip->where,
711 bfd_get_reloc_size (howto),
712 address_expr, FALSE, reloc_type);
713 }
714
715 append:
716 add_fixed_insn (ip);
717 install_insn (ip);
718 }
719
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. */
724
725 static void
726 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
727 {
728 const struct riscv_opcode *mo;
729 struct riscv_cl_insn insn;
730 bfd_reloc_code_real_type r;
731 va_list args;
732
733 va_start (args, fmt);
734
735 r = BFD_RELOC_UNUSED;
736 mo = (struct riscv_opcode *) hash_find (op_hash, name);
737 gas_assert (mo);
738
739 /* Find a non-RVC variant of the instruction. append_insn will compress
740 it if possible. */
741 while (riscv_insn_length (mo->match) < 4)
742 mo++;
743 gas_assert (strcmp (name, mo->name) == 0);
744
745 create_insn (&insn, mo);
746 for (;;)
747 {
748 switch (*fmt++)
749 {
750 case 'd':
751 INSERT_OPERAND (RD, insn, va_arg (args, int));
752 continue;
753
754 case 's':
755 INSERT_OPERAND (RS1, insn, va_arg (args, int));
756 continue;
757
758 case 't':
759 INSERT_OPERAND (RS2, insn, va_arg (args, int));
760 continue;
761
762 case '>':
763 INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
764 continue;
765
766 case 'j':
767 case 'u':
768 case 'q':
769 gas_assert (ep != NULL);
770 r = va_arg (args, int);
771 continue;
772
773 case '\0':
774 break;
775 case ',':
776 continue;
777 default:
778 as_fatal (_("internal error: invalid macro"));
779 }
780 break;
781 }
782 va_end (args);
783 gas_assert (r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
784
785 append_insn (&insn, ep, r);
786 }
787
788 /* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
789 unset. */
790 static void
791 normalize_constant_expr (expressionS *ex)
792 {
793 if (xlen > 32)
794 return;
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)
798 - 0x80000000);
799 }
800
801 /* Fail if an expression is not a constant. */
802
803 static void
804 check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex)
805 {
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"),
810 ip->insn_mo->name);
811 normalize_constant_expr (ex);
812 }
813
814 static symbolS *
815 make_internal_label (void)
816 {
817 return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg,
818 (valueT) frag_now_fix (), frag_now);
819 }
820
821 /* Load an entry from the GOT. */
822 static void
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)
827 {
828 expressionS ep2;
829 ep2.X_op = O_symbol;
830 ep2.X_add_symbol = make_internal_label ();
831 ep2.X_add_number = 0;
832
833 macro_build (ep, "auipc", "d,u", tempreg, hi_reloc);
834 macro_build (&ep2, lo_insn, lo_pattern, destreg, tempreg, lo_reloc);
835 }
836
837 static void
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)
841 {
842 pcrel_access (destreg, tempreg, ep, lo_insn, "d,s,j", hi_reloc, lo_reloc);
843 }
844
845 static void
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)
849 {
850 pcrel_access (srcreg, tempreg, ep, lo_insn, "t,s,q", hi_reloc, lo_reloc);
851 }
852
853 /* PC-relative function call using AUIPC/JALR, relaxed to JAL. */
854 static void
855 riscv_call (int destreg, int tempreg, expressionS *ep,
856 bfd_reloc_code_real_type reloc)
857 {
858 macro_build (ep, "auipc", "d,u", tempreg, reloc);
859 macro_build (NULL, "jalr", "d,s", destreg, tempreg);
860 }
861
862 /* Load an integer constant into a register. */
863
864 static void
865 load_const (int reg, expressionS *ep)
866 {
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;
871
872 if (ep->X_op != O_constant)
873 {
874 as_bad (_("unsupported large constant"));
875 return;
876 }
877
878 if (xlen > 32 && !IS_SEXT_32BIT_NUM (ep->X_add_number))
879 {
880 /* Reduce to a signed 32-bit constant using SLLI and ADDI. */
881 while (((upper.X_add_number >> shift) & 1) == 0)
882 shift++;
883
884 upper.X_add_number = (int64_t) upper.X_add_number >> shift;
885 load_const (reg, &upper);
886
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);
890 }
891 else
892 {
893 /* Simply emit LUI and/or ADDI to build a 32-bit signed constant. */
894 int hi_reg = 0;
895
896 if (upper.X_add_number != 0)
897 {
898 macro_build (ep, "lui", "d,u", reg, BFD_RELOC_RISCV_HI20);
899 hi_reg = reg;
900 }
901
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);
905 }
906 }
907
908 /* Expand RISC-V assembly macros into one or more instructions. */
909 static void
910 macro (struct riscv_cl_insn *ip, expressionS *imm_expr,
911 bfd_reloc_code_real_type *imm_reloc)
912 {
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;
917
918 switch (mask)
919 {
920 case M_LI:
921 load_const (rd, imm_expr);
922 break;
923
924 case M_LA:
925 case M_LLA:
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"));
929
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);
938 break;
939
940 case M_LA_TLS_GD:
941 pcrel_load (rd, rd, imm_expr, "addi",
942 BFD_RELOC_RISCV_TLS_GD_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
943 break;
944
945 case M_LA_TLS_IE:
946 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
947 BFD_RELOC_RISCV_TLS_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
948 break;
949
950 case M_LB:
951 pcrel_load (rd, rd, imm_expr, "lb",
952 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
953 break;
954
955 case M_LBU:
956 pcrel_load (rd, rd, imm_expr, "lbu",
957 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
958 break;
959
960 case M_LH:
961 pcrel_load (rd, rd, imm_expr, "lh",
962 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
963 break;
964
965 case M_LHU:
966 pcrel_load (rd, rd, imm_expr, "lhu",
967 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
968 break;
969
970 case M_LW:
971 pcrel_load (rd, rd, imm_expr, "lw",
972 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
973 break;
974
975 case M_LWU:
976 pcrel_load (rd, rd, imm_expr, "lwu",
977 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
978 break;
979
980 case M_LD:
981 pcrel_load (rd, rd, imm_expr, "ld",
982 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
983 break;
984
985 case M_FLW:
986 pcrel_load (rd, rs1, imm_expr, "flw",
987 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
988 break;
989
990 case M_FLD:
991 pcrel_load (rd, rs1, imm_expr, "fld",
992 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
993 break;
994
995 case M_SB:
996 pcrel_store (rs2, rs1, imm_expr, "sb",
997 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
998 break;
999
1000 case M_SH:
1001 pcrel_store (rs2, rs1, imm_expr, "sh",
1002 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1003 break;
1004
1005 case M_SW:
1006 pcrel_store (rs2, rs1, imm_expr, "sw",
1007 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1008 break;
1009
1010 case M_SD:
1011 pcrel_store (rs2, rs1, imm_expr, "sd",
1012 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1013 break;
1014
1015 case M_FSW:
1016 pcrel_store (rs2, rs1, imm_expr, "fsw",
1017 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1018 break;
1019
1020 case M_FSD:
1021 pcrel_store (rs2, rs1, imm_expr, "fsd",
1022 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1023 break;
1024
1025 case M_CALL:
1026 riscv_call (rd, rs1, imm_expr, *imm_reloc);
1027 break;
1028
1029 default:
1030 as_bad (_("Macro %s not implemented"), ip->insn_mo->name);
1031 break;
1032 }
1033 }
1034
1035 static const struct percent_op_match percent_op_utype[] =
1036 {
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},
1042 {0, 0}
1043 };
1044
1045 static const struct percent_op_match percent_op_itype[] =
1046 {
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},
1050 {0, 0}
1051 };
1052
1053 static const struct percent_op_match percent_op_stype[] =
1054 {
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},
1058 {0, 0}
1059 };
1060
1061 static const struct percent_op_match percent_op_rtype[] =
1062 {
1063 {"%tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
1064 {0, 0}
1065 };
1066
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. */
1070
1071 static bfd_boolean
1072 parse_relocation (char **str, bfd_reloc_code_real_type *reloc,
1073 const struct percent_op_match *percent_op)
1074 {
1075 for ( ; percent_op->str; percent_op++)
1076 if (strncasecmp (*str, percent_op->str, strlen (percent_op->str)) == 0)
1077 {
1078 int len = strlen (percent_op->str);
1079
1080 if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
1081 continue;
1082
1083 *str += strlen (percent_op->str);
1084 *reloc = percent_op->reloc;
1085
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))
1089 {
1090 as_bad ("relocation %s isn't supported by the current ABI",
1091 percent_op->str);
1092 *reloc = BFD_RELOC_UNUSED;
1093 }
1094 return TRUE;
1095 }
1096 return FALSE;
1097 }
1098
1099 static void
1100 my_getExpression (expressionS *ep, char *str)
1101 {
1102 char *save_in;
1103
1104 save_in = input_line_pointer;
1105 input_line_pointer = str;
1106 expression (ep);
1107 expr_end = input_line_pointer;
1108 input_line_pointer = save_in;
1109 }
1110
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).
1114
1115 On exit, EXPR_END points to the first character after the expression. */
1116
1117 static size_t
1118 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1119 char *str, const struct percent_op_match *percent_op)
1120 {
1121 size_t reloc_index;
1122 unsigned crux_depth, str_depth, regno;
1123 char *crux;
1124
1125 /* First, check for integer registers. */
1126 if (reg_lookup (&str, RCLASS_GPR, &regno))
1127 {
1128 ep->X_op = O_register;
1129 ep->X_add_number = regno;
1130 return 0;
1131 }
1132
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. */
1137 reloc_index = -1;
1138 str_depth = 0;
1139 do
1140 {
1141 reloc_index++;
1142 crux = str;
1143 crux_depth = str_depth;
1144
1145 /* Skip over whitespace and brackets, keeping count of the number
1146 of brackets. */
1147 while (*str == ' ' || *str == '\t' || *str == '(')
1148 if (*str++ == '(')
1149 str_depth++;
1150 }
1151 while (*str == '%'
1152 && reloc_index < 1
1153 && parse_relocation (&str, reloc, percent_op));
1154
1155 my_getExpression (ep, crux);
1156 str = expr_end;
1157
1158 /* Match every open bracket. */
1159 while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
1160 if (*str++ == ')')
1161 crux_depth--;
1162
1163 if (crux_depth > 0)
1164 as_bad ("unclosed '('");
1165
1166 expr_end = str;
1167
1168 return reloc_index;
1169 }
1170
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. */
1174
1175 static const char *
1176 riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
1177 bfd_reloc_code_real_type *imm_reloc)
1178 {
1179 char *s;
1180 const char *args;
1181 char c = 0;
1182 struct riscv_opcode *insn;
1183 char *argsStart;
1184 unsigned int regno;
1185 char save_c = 0;
1186 int argnum;
1187 const struct percent_op_match *p;
1188 const char *error = "unrecognized opcode";
1189
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)
1193 if (ISSPACE (*s))
1194 {
1195 save_c = *s;
1196 *s++ = '\0';
1197 break;
1198 }
1199
1200 insn = (struct riscv_opcode *) hash_find (op_hash, str);
1201
1202 argsStart = s;
1203 for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
1204 {
1205 if (!riscv_subset_supports (insn->subset))
1206 continue;
1207
1208 create_insn (ip, insn);
1209 argnum = 1;
1210
1211 imm_expr->X_op = O_absent;
1212 *imm_reloc = BFD_RELOC_UNUSED;
1213 p = percent_op_itype;
1214
1215 for (args = insn->args;; ++args)
1216 {
1217 s += strspn (s, " \t");
1218 switch (*args)
1219 {
1220 case '\0': /* End of args. */
1221 if (insn->pinfo != INSN_MACRO)
1222 {
1223 if (!insn->match_func (insn, ip->insn_opcode))
1224 break;
1225 if (riscv_insn_length (insn->match) == 2 && !riscv_opts.rvc)
1226 break;
1227 }
1228 if (*s != '\0')
1229 break;
1230 /* Successful assembly. */
1231 error = NULL;
1232 goto out;
1233
1234 case 'C': /* RVC */
1235 switch (*++args)
1236 {
1237 case 's': /* RS1 x8-x15 */
1238 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1239 || !(regno >= 8 && regno <= 15))
1240 break;
1241 INSERT_OPERAND (CRS1S, *ip, regno % 8);
1242 continue;
1243 case 'w': /* RS1 x8-x15, constrained to equal RD x8-x15. */
1244 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1245 || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
1246 break;
1247 continue;
1248 case 't': /* RS2 x8-x15 */
1249 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1250 || !(regno >= 8 && regno <= 15))
1251 break;
1252 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1253 continue;
1254 case 'x': /* RS2 x8-x15, constrained to equal RD x8-x15. */
1255 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1256 || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
1257 break;
1258 continue;
1259 case 'U': /* RS1, constrained to equal RD. */
1260 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1261 || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
1262 break;
1263 continue;
1264 case 'V': /* RS2 */
1265 if (!reg_lookup (&s, RCLASS_GPR, &regno))
1266 break;
1267 INSERT_OPERAND (CRS2, *ip, regno);
1268 continue;
1269 case 'c': /* RS1, constrained to equal sp. */
1270 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1271 || regno != X_SP)
1272 break;
1273 continue;
1274 case '>':
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)
1279 break;
1280 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1281 rvc_imm_done:
1282 s = expr_end;
1283 imm_expr->X_op = O_absent;
1284 continue;
1285 case '<':
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)
1291 break;
1292 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1293 goto rvc_imm_done;
1294 case 'i':
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))
1299 break;
1300 ip->insn_opcode |= ENCODE_RVC_SIMM3 (imm_expr->X_add_number);
1301 goto rvc_imm_done;
1302 case 'j':
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))
1307 break;
1308 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1309 goto rvc_imm_done;
1310 case 'k':
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))
1314 break;
1315 ip->insn_opcode |= ENCODE_RVC_LW_IMM (imm_expr->X_add_number);
1316 goto rvc_imm_done;
1317 case 'l':
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))
1321 break;
1322 ip->insn_opcode |= ENCODE_RVC_LD_IMM (imm_expr->X_add_number);
1323 goto rvc_imm_done;
1324 case 'm':
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))
1328 break;
1329 ip->insn_opcode |=
1330 ENCODE_RVC_LWSP_IMM (imm_expr->X_add_number);
1331 goto rvc_imm_done;
1332 case 'n':
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))
1336 break;
1337 ip->insn_opcode |=
1338 ENCODE_RVC_LDSP_IMM (imm_expr->X_add_number);
1339 goto rvc_imm_done;
1340 case 'K':
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)
1345 break;
1346 ip->insn_opcode |=
1347 ENCODE_RVC_ADDI4SPN_IMM (imm_expr->X_add_number);
1348 goto rvc_imm_done;
1349 case 'L':
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)
1354 break;
1355 ip->insn_opcode |=
1356 ENCODE_RVC_ADDI16SP_IMM (imm_expr->X_add_number);
1357 goto rvc_imm_done;
1358 case 'M':
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))
1362 break;
1363 ip->insn_opcode |=
1364 ENCODE_RVC_SWSP_IMM (imm_expr->X_add_number);
1365 goto rvc_imm_done;
1366 case 'N':
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))
1370 break;
1371 ip->insn_opcode |=
1372 ENCODE_RVC_SDSP_IMM (imm_expr->X_add_number);
1373 goto rvc_imm_done;
1374 case 'u':
1375 p = percent_op_utype;
1376 if (my_getSmallExpression (imm_expr, imm_reloc, s, p))
1377 break;
1378 rvc_lui:
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)))
1385 break;
1386 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1387 goto rvc_imm_done;
1388 case 'v':
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))
1393 break;
1394 imm_expr->X_add_number =
1395 ((uint32_t) imm_expr->X_add_number) >> RISCV_IMM_BITS;
1396 goto rvc_lui;
1397 case 'p':
1398 goto branch;
1399 case 'a':
1400 goto jump;
1401 case 'D': /* Floating-point RS2 x8-x15. */
1402 if (!reg_lookup (&s, RCLASS_FPR, &regno)
1403 || !(regno >= 8 && regno <= 15))
1404 break;
1405 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1406 continue;
1407 case 'T': /* Floating-point RS2. */
1408 if (!reg_lookup (&s, RCLASS_FPR, &regno))
1409 break;
1410 INSERT_OPERAND (CRS2, *ip, regno);
1411 continue;
1412 default:
1413 as_bad (_("bad RVC field specifier 'C%c'\n"), *args);
1414 }
1415 break;
1416
1417 case ',':
1418 ++argnum;
1419 if (*s++ == *args)
1420 continue;
1421 s--;
1422 break;
1423
1424 case '(':
1425 case ')':
1426 case '[':
1427 case ']':
1428 if (*s++ == *args)
1429 continue;
1430 break;
1431
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;
1440 s = expr_end;
1441 continue;
1442
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;
1451 s = expr_end;
1452 continue;
1453
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;
1462 s = expr_end;
1463 continue;
1464
1465 case 'E': /* Control register. */
1466 if (reg_lookup (&s, RCLASS_CSR, &regno))
1467 INSERT_OPERAND (CSR, *ip, regno);
1468 else
1469 {
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;
1477 s = expr_end;
1478 }
1479 continue;
1480
1481 case 'm': /* Rounding mode. */
1482 if (arg_lookup (&s, riscv_rm, ARRAY_SIZE (riscv_rm), &regno))
1483 {
1484 INSERT_OPERAND (RM, *ip, regno);
1485 continue;
1486 }
1487 break;
1488
1489 case 'P':
1490 case 'Q': /* Fence predecessor/successor. */
1491 if (arg_lookup (&s, riscv_pred_succ, ARRAY_SIZE (riscv_pred_succ),
1492 &regno))
1493 {
1494 if (*args == 'P')
1495 INSERT_OPERAND (PRED, *ip, regno);
1496 else
1497 INSERT_OPERAND (SUCC, *ip, regno);
1498 continue;
1499 }
1500 break;
1501
1502 case 'd': /* Destination register. */
1503 case 's': /* Source register. */
1504 case 't': /* Target register. */
1505 if (reg_lookup (&s, RCLASS_GPR, &regno))
1506 {
1507 c = *args;
1508 if (*s == ' ')
1509 ++s;
1510
1511 /* Now that we have assembled one operand, we use the args
1512 string to figure out where it goes in the instruction. */
1513 switch (c)
1514 {
1515 case 's':
1516 INSERT_OPERAND (RS1, *ip, regno);
1517 break;
1518 case 'd':
1519 INSERT_OPERAND (RD, *ip, regno);
1520 break;
1521 case 't':
1522 INSERT_OPERAND (RS2, *ip, regno);
1523 break;
1524 }
1525 continue;
1526 }
1527 break;
1528
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, &regno))
1535 {
1536 c = *args;
1537 if (*s == ' ')
1538 ++s;
1539 switch (c)
1540 {
1541 case 'D':
1542 INSERT_OPERAND (RD, *ip, regno);
1543 break;
1544 case 'S':
1545 INSERT_OPERAND (RS1, *ip, regno);
1546 break;
1547 case 'U':
1548 INSERT_OPERAND (RS1, *ip, regno);
1549 /* fallthru */
1550 case 'T':
1551 INSERT_OPERAND (RS2, *ip, regno);
1552 break;
1553 case 'R':
1554 INSERT_OPERAND (RS3, *ip, regno);
1555 break;
1556 }
1557 continue;
1558 }
1559
1560 break;
1561
1562 case 'I':
1563 my_getExpression (imm_expr, s);
1564 if (imm_expr->X_op != O_big
1565 && imm_expr->X_op != O_constant)
1566 break;
1567 normalize_constant_expr (imm_expr);
1568 s = expr_end;
1569 continue;
1570
1571 case 'A':
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)
1576 break;
1577 *imm_reloc = BFD_RELOC_32;
1578 s = expr_end;
1579 continue;
1580
1581 case 'j': /* Sign-extended immediate. */
1582 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
1583 p = percent_op_itype;
1584 goto alu_op;
1585 case 'q': /* Store displacement. */
1586 p = percent_op_stype;
1587 *imm_reloc = BFD_RELOC_RISCV_LO12_S;
1588 goto load_store;
1589 case 'o': /* Load displacement. */
1590 p = percent_op_itype;
1591 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
1592 goto load_store;
1593 case '0': /* AMO "displacement," which must be zero. */
1594 p = percent_op_rtype;
1595 *imm_reloc = BFD_RELOC_UNUSED;
1596 load_store:
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)
1603 continue;
1604 alu_op:
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
1607 code pattern. */
1608 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p))
1609 {
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)
1615 break;
1616 }
1617
1618 s = expr_end;
1619 continue;
1620
1621 case 'p': /* PC-relative offset. */
1622 branch:
1623 *imm_reloc = BFD_RELOC_12_PCREL;
1624 my_getExpression (imm_expr, s);
1625 s = expr_end;
1626 continue;
1627
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)
1632 {
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"));
1636
1637 *imm_reloc = BFD_RELOC_RISCV_HI20;
1638 imm_expr->X_add_number <<= RISCV_IMM_BITS;
1639 }
1640 s = expr_end;
1641 continue;
1642
1643 case 'a': /* 20-bit PC-relative offset. */
1644 jump:
1645 my_getExpression (imm_expr, s);
1646 s = expr_end;
1647 *imm_reloc = BFD_RELOC_RISCV_JMP;
1648 continue;
1649
1650 case 'c':
1651 my_getExpression (imm_expr, s);
1652 s = expr_end;
1653 if (strcmp (s, "@plt") == 0)
1654 {
1655 *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
1656 s += 4;
1657 }
1658 else
1659 *imm_reloc = BFD_RELOC_RISCV_CALL;
1660 continue;
1661
1662 default:
1663 as_fatal (_("internal error: bad argument type %c"), *args);
1664 }
1665 break;
1666 }
1667 s = argsStart;
1668 error = _("illegal operands");
1669 }
1670
1671 out:
1672 /* Restore the character we might have clobbered above. */
1673 if (save_c)
1674 *(argsStart - 1) = save_c;
1675
1676 return error;
1677 }
1678
1679 void
1680 md_assemble (char *str)
1681 {
1682 struct riscv_cl_insn insn;
1683 expressionS imm_expr;
1684 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
1685
1686 const char *error = riscv_ip (str, &insn, &imm_expr, &imm_reloc);
1687
1688 if (error)
1689 {
1690 as_bad ("%s `%s'", error, str);
1691 return;
1692 }
1693
1694 if (insn.insn_mo->pinfo == INSN_MACRO)
1695 macro (&insn, &imm_expr, &imm_reloc);
1696 else
1697 append_insn (&insn, &imm_expr, imm_reloc);
1698 }
1699
1700 const char *
1701 md_atof (int type, char *litP, int *sizeP)
1702 {
1703 return ieee_md_atof (type, litP, sizeP, TARGET_BYTES_BIG_ENDIAN);
1704 }
1705
1706 void
1707 md_number_to_chars (char *buf, valueT val, int n)
1708 {
1709 number_to_chars_littleendian (buf, val, n);
1710 }
1711
1712 const char *md_shortopts = "O::g::G:";
1713
1714 enum options
1715 {
1716 OPTION_M32 = OPTION_MD_BASE,
1717 OPTION_M64,
1718 OPTION_MARCH,
1719 OPTION_PIC,
1720 OPTION_NO_PIC,
1721 OPTION_MSOFT_FLOAT,
1722 OPTION_MHARD_FLOAT,
1723 OPTION_MRVC,
1724 OPTION_MNO_RVC,
1725 OPTION_END_OF_ENUM
1726 };
1727
1728 struct option md_longopts[] =
1729 {
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},
1740
1741 {NULL, no_argument, NULL, 0}
1742 };
1743 size_t md_longopts_size = sizeof (md_longopts);
1744
1745 enum float_mode
1746 {
1747 FLOAT_MODE_DEFAULT,
1748 FLOAT_MODE_SOFT,
1749 FLOAT_MODE_HARD
1750 };
1751 static enum float_mode float_mode = FLOAT_MODE_DEFAULT;
1752
1753 int
1754 md_parse_option (int c, const char *arg)
1755 {
1756 switch (c)
1757 {
1758 case OPTION_MRVC:
1759 riscv_set_rvc (TRUE);
1760 break;
1761
1762 case OPTION_MNO_RVC:
1763 riscv_set_rvc (FALSE);
1764 break;
1765
1766 case OPTION_MSOFT_FLOAT:
1767 float_mode = FLOAT_MODE_SOFT;
1768 break;
1769
1770 case OPTION_MHARD_FLOAT:
1771 float_mode = FLOAT_MODE_HARD;
1772 break;
1773
1774 case OPTION_M32:
1775 xlen = 32;
1776 break;
1777
1778 case OPTION_M64:
1779 xlen = 64;
1780 break;
1781
1782 case OPTION_MARCH:
1783 riscv_set_arch (arg);
1784 break;
1785
1786 case OPTION_NO_PIC:
1787 riscv_opts.pic = FALSE;
1788 break;
1789
1790 case OPTION_PIC:
1791 riscv_opts.pic = TRUE;
1792 break;
1793
1794 default:
1795 return 0;
1796 }
1797
1798 return 1;
1799 }
1800
1801 void
1802 riscv_after_parse_args (void)
1803 {
1804 if (riscv_subsets == NULL)
1805 riscv_set_arch ("RVIMAFD");
1806
1807 if (xlen == 0)
1808 {
1809 if (strcmp (default_arch, "riscv32") == 0)
1810 xlen = 32;
1811 else if (strcmp (default_arch, "riscv64") == 0)
1812 xlen = 64;
1813 else
1814 as_bad ("unknown default architecture `%s'", default_arch);
1815 }
1816 }
1817
1818 long
1819 md_pcrel_from (fixS *fixP)
1820 {
1821 return fixP->fx_where + fixP->fx_frag->fr_address;
1822 }
1823
1824 /* Apply a fixup to the object file. */
1825
1826 void
1827 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
1828 {
1829 bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
1830
1831 /* Remember value for tc_gen_reloc. */
1832 fixP->fx_addnumber = *valP;
1833
1834 switch (fixP->fx_r_type)
1835 {
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);
1845 /* Fall through. */
1846
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. */
1862 break;
1863
1864 case BFD_RELOC_64:
1865 case BFD_RELOC_32:
1866 case BFD_RELOC_16:
1867 case BFD_RELOC_8:
1868 if (fixP->fx_addsy && fixP->fx_subsy)
1869 {
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;
1875
1876 switch (fixP->fx_r_type)
1877 {
1878 case BFD_RELOC_64:
1879 fixP->fx_r_type = BFD_RELOC_RISCV_ADD64;
1880 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB64;
1881 break;
1882
1883 case BFD_RELOC_32:
1884 fixP->fx_r_type = BFD_RELOC_RISCV_ADD32;
1885 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
1886 break;
1887
1888 case BFD_RELOC_16:
1889 fixP->fx_r_type = BFD_RELOC_RISCV_ADD16;
1890 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
1891 break;
1892
1893 case BFD_RELOC_8:
1894 fixP->fx_r_type = BFD_RELOC_RISCV_ADD8;
1895 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
1896 break;
1897
1898 default:
1899 /* This case is unreachable. */
1900 abort ();
1901 }
1902 }
1903 /* Fall through. */
1904
1905 case BFD_RELOC_RVA:
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)
1910 {
1911 gas_assert (fixP->fx_size <= sizeof (valueT));
1912 md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
1913 fixP->fx_done = 1;
1914 }
1915 break;
1916
1917 case BFD_RELOC_RISCV_JMP:
1918 if (fixP->fx_addsy)
1919 {
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);
1924 }
1925 break;
1926
1927 case BFD_RELOC_12_PCREL:
1928 if (fixP->fx_addsy)
1929 {
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);
1934 }
1935 break;
1936
1937 case BFD_RELOC_RISCV_RVC_BRANCH:
1938 if (fixP->fx_addsy)
1939 {
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);
1944 }
1945 break;
1946
1947 case BFD_RELOC_RISCV_RVC_JUMP:
1948 if (fixP->fx_addsy)
1949 {
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);
1954 }
1955 break;
1956
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:
1962 break;
1963
1964 default:
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);
1968 }
1969 }
1970
1971 /* This structure is used to hold a stack of .option values. */
1972
1973 struct riscv_option_stack
1974 {
1975 struct riscv_option_stack *next;
1976 struct riscv_set_options options;
1977 };
1978
1979 static struct riscv_option_stack *riscv_opts_stack;
1980
1981 /* Handle the .option pseudo-op. */
1982
1983 static void
1984 s_riscv_option (int x ATTRIBUTE_UNUSED)
1985 {
1986 char *name = input_line_pointer, ch;
1987
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';
1992
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)
2006 {
2007 struct riscv_option_stack *s;
2008
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;
2013 }
2014 else if (strcmp (name, "pop") == 0)
2015 {
2016 struct riscv_option_stack *s;
2017
2018 s = riscv_opts_stack;
2019 if (s == NULL)
2020 as_bad (_(".option pop with no .option push"));
2021 else
2022 {
2023 riscv_opts = s->options;
2024 riscv_opts_stack = s->next;
2025 free (s);
2026 }
2027 }
2028 else
2029 {
2030 as_warn (_("Unrecognized .option directive: %s\n"), name);
2031 }
2032 *input_line_pointer = ch;
2033 demand_empty_rest_of_line ();
2034 }
2035
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. */
2039
2040 static void
2041 s_dtprel (int bytes)
2042 {
2043 expressionS ex;
2044 char *p;
2045
2046 expression (&ex);
2047
2048 if (ex.X_op != O_symbol)
2049 {
2050 as_bad (_("Unsupported use of %s"), (bytes == 8
2051 ? ".dtpreldword"
2052 : ".dtprelword"));
2053 ignore_rest_of_line ();
2054 }
2055
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,
2059 (bytes == 8
2060 ? BFD_RELOC_RISCV_TLS_DTPREL64
2061 : BFD_RELOC_RISCV_TLS_DTPREL32));
2062
2063 demand_empty_rest_of_line ();
2064 }
2065
2066 /* Handle the .bss pseudo-op. */
2067
2068 static void
2069 s_bss (int ignore ATTRIBUTE_UNUSED)
2070 {
2071 subseg_set (bss_section, 0);
2072 demand_empty_rest_of_line ();
2073 }
2074
2075 /* Align to a given power of two. */
2076
2077 static void
2078 s_align (int bytes_p)
2079 {
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;
2083
2084 if (bytes_p)
2085 {
2086 bytes = alignment;
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)
2090 alignment++;
2091 }
2092
2093 bytes = 1 << alignment;
2094
2095 if (alignment < 0 || alignment > 31)
2096 as_bad (_("unsatisfiable alignment: %d"), alignment);
2097
2098 if (*input_line_pointer == ',')
2099 {
2100 ++input_line_pointer;
2101 fill_value = get_absolute_expression ();
2102 fill_value_specified = 1;
2103 }
2104
2105 if (!fill_value_specified
2106 && subseg_text_p (now_seg)
2107 && bytes > min_text_alignment)
2108 {
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);
2118
2119 expressionS ex;
2120 ex.X_op = O_constant;
2121 ex.X_add_number = worst_case_bytes;
2122
2123 fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
2124 &ex, FALSE, BFD_RELOC_RISCV_ALIGN);
2125 }
2126 else if (alignment)
2127 frag_align (alignment, fill_value, 0);
2128
2129 record_alignment (now_seg, alignment);
2130
2131 demand_empty_rest_of_line ();
2132 }
2133
2134 int
2135 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
2136 {
2137 return (fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE));
2138 }
2139
2140 /* Translate internal representation of relocation info to BFD target
2141 format. */
2142
2143 arelent *
2144 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
2145 {
2146 arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
2147
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;
2152
2153 reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
2154 if (reloc->howto == NULL)
2155 {
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)
2158 {
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. */
2161 return reloc;
2162 }
2163
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));
2167 return NULL;
2168 }
2169
2170 return reloc;
2171 }
2172
2173 int
2174 riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
2175 {
2176 if (RELAX_BRANCH_P (fragp->fr_subtype))
2177 {
2178 offsetT old_var = fragp->fr_var;
2179 fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
2180 return fragp->fr_var - old_var;
2181 }
2182
2183 return 0;
2184 }
2185
2186 /* Expand far branches to multi-instruction sequences. */
2187
2188 static void
2189 md_convert_frag_branch (fragS *fragp)
2190 {
2191 bfd_byte *buf;
2192 expressionS exp;
2193 fixS *fixp;
2194 insn_t insn;
2195 int rs1, reloc;
2196
2197 buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
2198
2199 exp.X_op = O_symbol;
2200 exp.X_add_symbol = fragp->fr_symbol;
2201 exp.X_add_number = fragp->fr_offset;
2202
2203 gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
2204
2205 if (RELAX_BRANCH_RVC (fragp->fr_subtype))
2206 {
2207 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
2208 {
2209 case 8:
2210 case 4:
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)
2215 insn = MATCH_JAL;
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);
2222 else
2223 abort ();
2224 bfd_putl32 (insn, buf);
2225 break;
2226
2227 case 6:
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);
2233 buf += 2;
2234 goto jump;
2235
2236 case 2:
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);
2242 buf += 2;
2243 goto done;
2244
2245 default:
2246 abort ();
2247 }
2248 }
2249
2250 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
2251 {
2252 case 8:
2253 gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
2254
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);
2260 buf += 4;
2261
2262 jump:
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);
2267 buf += 4;
2268 break;
2269
2270 case 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);
2275 buf += 4;
2276 break;
2277
2278 default:
2279 abort ();
2280 }
2281
2282 done:
2283 fixp->fx_file = fragp->fr_file;
2284 fixp->fx_line = fragp->fr_line;
2285
2286 gas_assert (buf == (bfd_byte *)fragp->fr_literal
2287 + fragp->fr_fix + fragp->fr_var);
2288
2289 fragp->fr_fix += fragp->fr_var;
2290 }
2291
2292 /* Relax a machine dependent frag. This returns the amount by which
2293 the current size of the frag should change. */
2294
2295 void
2296 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
2297 fragS *fragp)
2298 {
2299 gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
2300 md_convert_frag_branch (fragp);
2301 }
2302
2303 void
2304 md_show_usage (FILE *stream)
2305 {
2306 fprintf (stream, _("\
2307 RISC-V options:\n\
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\
2317 "));
2318 }
2319
2320 /* Standard calling conventions leave the CFA at SP on entry. */
2321 void
2322 riscv_cfi_frame_initial_instructions (void)
2323 {
2324 cfi_add_CFA_def_cfa_register (X_SP);
2325 }
2326
2327 int
2328 tc_riscv_regname_to_dw2regnum (char *regname)
2329 {
2330 int reg;
2331
2332 if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
2333 return reg;
2334
2335 if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
2336 return reg + 32;
2337
2338 as_bad (_("unknown register `%s'"), regname);
2339 return -1;
2340 }
2341
2342 void
2343 riscv_elf_final_processing (void)
2344 {
2345 enum float_mode elf_float_mode = float_mode;
2346
2347 elf_elfheader (stdoutput)->e_flags |= elf_flags;
2348
2349 if (elf_float_mode == FLOAT_MODE_DEFAULT)
2350 {
2351 struct riscv_subset *subset;
2352
2353 /* Assume soft-float unless D extension is present. */
2354 elf_float_mode = FLOAT_MODE_SOFT;
2355
2356 for (subset = riscv_subsets; subset != NULL; subset = subset->next)
2357 if (strcasecmp (subset->name, "D") == 0)
2358 elf_float_mode = FLOAT_MODE_HARD;
2359 }
2360
2361 if (elf_float_mode == FLOAT_MODE_SOFT)
2362 elf_elfheader (stdoutput)->e_flags |= EF_RISCV_SOFT_FLOAT;
2363 }
2364
2365 /* Parse the .sleb128 and .uleb128 pseudos. Only allow constant expressions,
2366 since these directives break relaxation when used with symbol deltas. */
2367
2368 static void
2369 s_riscv_leb128 (int sign)
2370 {
2371 expressionS exp;
2372 char *save_in = input_line_pointer;
2373
2374 expression (&exp);
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 ();
2378
2379 input_line_pointer = save_in;
2380 return s_leb128 (sign);
2381 }
2382
2383 /* Pseudo-op table. */
2384
2385 static const pseudo_typeS riscv_pseudo_table[] =
2386 {
2387 /* RISC-V-specific pseudo-ops. */
2388 {"option", s_riscv_option, 0},
2389 {"half", cons, 2},
2390 {"word", cons, 4},
2391 {"dword", cons, 8},
2392 {"dtprelword", s_dtprel, 4},
2393 {"dtpreldword", s_dtprel, 8},
2394 {"bss", s_bss, 0},
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},
2400
2401 { NULL, NULL, 0 },
2402 };
2403
2404 void
2405 riscv_pop_insert (void)
2406 {
2407 extern void pop_insert (const pseudo_typeS *);
2408
2409 pop_insert (riscv_pseudo_table);
2410 }