Add support for the Q extension to the RISCV ISA.
[deliverable/binutils-gdb.git] / gas / config / tc-riscv.c
1 /* tc-riscv.c -- RISC-V assembler
2 Copyright (C) 2011-2017 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 static unsigned xlen = 0; /* width of an x-register */
65 static unsigned abi_xlen = 0; /* width of a pointer in the ABI */
66
67 #define LOAD_ADDRESS_INSN (abi_xlen == 64 ? "ld" : "lw")
68 #define ADD32_INSN (xlen == 64 ? "addiw" : "addi")
69
70 static unsigned elf_flags = 0;
71
72 /* This is the set of options which the .option pseudo-op may modify. */
73
74 struct riscv_set_options
75 {
76 int pic; /* Generate position-independent code. */
77 int rvc; /* Generate RVC code. */
78 int relax; /* Emit relocs the linker is allowed to relax. */
79 };
80
81 static struct riscv_set_options riscv_opts =
82 {
83 0, /* pic */
84 0, /* rvc */
85 1, /* relax */
86 };
87
88 static void
89 riscv_set_rvc (bfd_boolean rvc_value)
90 {
91 if (rvc_value)
92 elf_flags |= EF_RISCV_RVC;
93
94 riscv_opts.rvc = rvc_value;
95 }
96
97 struct riscv_subset
98 {
99 const char *name;
100
101 struct riscv_subset *next;
102 };
103
104 static struct riscv_subset *riscv_subsets;
105
106 static bfd_boolean
107 riscv_subset_supports (const char *feature)
108 {
109 struct riscv_subset *s;
110 char *p;
111 unsigned xlen_required = strtoul (feature, &p, 10);
112
113 if (xlen_required && xlen != xlen_required)
114 return FALSE;
115
116 for (s = riscv_subsets; s != NULL; s = s->next)
117 if (strcasecmp (s->name, p) == 0)
118 return TRUE;
119
120 return FALSE;
121 }
122
123 static void
124 riscv_add_subset (const char *subset)
125 {
126 struct riscv_subset *s = xmalloc (sizeof *s);
127
128 s->name = xstrdup (subset);
129 s->next = riscv_subsets;
130 riscv_subsets = s;
131 }
132
133 /* Set which ISA and extensions are available. */
134
135 static void
136 riscv_set_arch (const char *s)
137 {
138 const char *all_subsets = "imafdc";
139 const char *extension = NULL;
140 const char *p = s;
141
142 if (strncmp (p, "rv32", 4) == 0)
143 {
144 xlen = 32;
145 p += 4;
146 }
147 else if (strncmp (p, "rv64", 4) == 0)
148 {
149 xlen = 64;
150 p += 4;
151 }
152 else
153 as_fatal ("-march=%s: ISA string must begin with rv32 or rv64", s);
154
155 switch (*p)
156 {
157 case 'i':
158 break;
159
160 case 'g':
161 p++;
162 for ( ; *all_subsets != 'c'; all_subsets++)
163 {
164 const char subset[] = {*all_subsets, '\0'};
165 riscv_add_subset (subset);
166 }
167 break;
168
169 default:
170 as_fatal ("-march=%s: first ISA subset must be `i' or `g'", s);
171 }
172
173 while (*p)
174 {
175 if (*p == 'x')
176 {
177 char *subset = xstrdup (p), *q = subset;
178
179 while (*++q != '\0' && *q != '_')
180 ;
181 *q = '\0';
182
183 if (extension)
184 as_fatal ("-march=%s: only one non-standard extension is supported"
185 " (found `%s' and `%s')", s, extension, subset);
186 extension = subset;
187 riscv_add_subset (subset);
188 p += strlen (subset);
189 free (subset);
190 }
191 else if (*p == '_')
192 p++;
193 else if ((all_subsets = strchr (all_subsets, *p)) != NULL)
194 {
195 const char subset[] = {*p, 0};
196 riscv_add_subset (subset);
197 all_subsets++;
198 p++;
199 }
200 else if (*p == 'q')
201 {
202 const char subset[] = {*p, 0};
203 riscv_add_subset (subset);
204 p++;
205 }
206 else
207 as_fatal ("-march=%s: unsupported ISA subset `%c'", s, *p);
208 }
209 }
210
211 /* Handle of the OPCODE hash table. */
212 static struct hash_control *op_hash = NULL;
213
214 /* This array holds the chars that always start a comment. If the
215 pre-processor is disabled, these aren't very useful */
216 const char comment_chars[] = "#";
217
218 /* This array holds the chars that only start a comment at the beginning of
219 a line. If the line seems to have the form '# 123 filename'
220 .line and .file directives will appear in the pre-processed output */
221 /* Note that input_file.c hand checks for '#' at the beginning of the
222 first line of the input file. This is because the compiler outputs
223 #NO_APP at the beginning of its output. */
224 /* Also note that C style comments are always supported. */
225 const char line_comment_chars[] = "#";
226
227 /* This array holds machine specific line separator characters. */
228 const char line_separator_chars[] = ";";
229
230 /* Chars that can be used to separate mant from exp in floating point nums */
231 const char EXP_CHARS[] = "eE";
232
233 /* Chars that mean this number is a floating point constant */
234 /* As in 0f12.456 */
235 /* or 0d1.2345e12 */
236 const char FLT_CHARS[] = "rRsSfFdDxXpP";
237
238 /* Macros for encoding relaxation state for RVC branches and far jumps. */
239 #define RELAX_BRANCH_ENCODE(uncond, rvc, length) \
240 ((relax_substateT) \
241 (0xc0000000 \
242 | ((uncond) ? 1 : 0) \
243 | ((rvc) ? 2 : 0) \
244 | ((length) << 2)))
245 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
246 #define RELAX_BRANCH_LENGTH(i) (((i) >> 2) & 0xF)
247 #define RELAX_BRANCH_RVC(i) (((i) & 2) != 0)
248 #define RELAX_BRANCH_UNCOND(i) (((i) & 1) != 0)
249
250 /* Is the given value a sign-extended 32-bit value? */
251 #define IS_SEXT_32BIT_NUM(x) \
252 (((x) &~ (offsetT) 0x7fffffff) == 0 \
253 || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
254
255 /* Is the given value a zero-extended 32-bit value? Or a negated one? */
256 #define IS_ZEXT_32BIT_NUM(x) \
257 (((x) &~ (offsetT) 0xffffffff) == 0 \
258 || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
259
260 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
261 INSN is a riscv_cl_insn structure and VALUE is evaluated exactly once. */
262 #define INSERT_OPERAND(FIELD, INSN, VALUE) \
263 INSERT_BITS ((INSN).insn_opcode, VALUE, OP_MASK_##FIELD, OP_SH_##FIELD)
264
265 /* Determine if an instruction matches an opcode. */
266 #define OPCODE_MATCHES(OPCODE, OP) \
267 (((OPCODE) & MASK_##OP) == MATCH_##OP)
268
269 static char *expr_end;
270
271 /* The default target format to use. */
272
273 const char *
274 riscv_target_format (void)
275 {
276 return xlen == 64 ? "elf64-littleriscv" : "elf32-littleriscv";
277 }
278
279 /* Return the length of instruction INSN. */
280
281 static inline unsigned int
282 insn_length (const struct riscv_cl_insn *insn)
283 {
284 return riscv_insn_length (insn->insn_opcode);
285 }
286
287 /* Initialise INSN from opcode entry MO. Leave its position unspecified. */
288
289 static void
290 create_insn (struct riscv_cl_insn *insn, const struct riscv_opcode *mo)
291 {
292 insn->insn_mo = mo;
293 insn->insn_opcode = mo->match;
294 insn->frag = NULL;
295 insn->where = 0;
296 insn->fixp = NULL;
297 }
298
299 /* Install INSN at the location specified by its "frag" and "where" fields. */
300
301 static void
302 install_insn (const struct riscv_cl_insn *insn)
303 {
304 char *f = insn->frag->fr_literal + insn->where;
305 md_number_to_chars (f, insn->insn_opcode, insn_length (insn));
306 }
307
308 /* Move INSN to offset WHERE in FRAG. Adjust the fixups accordingly
309 and install the opcode in the new location. */
310
311 static void
312 move_insn (struct riscv_cl_insn *insn, fragS *frag, long where)
313 {
314 insn->frag = frag;
315 insn->where = where;
316 if (insn->fixp != NULL)
317 {
318 insn->fixp->fx_frag = frag;
319 insn->fixp->fx_where = where;
320 }
321 install_insn (insn);
322 }
323
324 /* Add INSN to the end of the output. */
325
326 static void
327 add_fixed_insn (struct riscv_cl_insn *insn)
328 {
329 char *f = frag_more (insn_length (insn));
330 move_insn (insn, frag_now, f - frag_now->fr_literal);
331 }
332
333 static void
334 add_relaxed_insn (struct riscv_cl_insn *insn, int max_chars, int var,
335 relax_substateT subtype, symbolS *symbol, offsetT offset)
336 {
337 frag_grow (max_chars);
338 move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
339 frag_var (rs_machine_dependent, max_chars, var,
340 subtype, symbol, offset, NULL);
341 }
342
343 /* Compute the length of a branch sequence, and adjust the stored length
344 accordingly. If FRAGP is NULL, the worst-case length is returned. */
345
346 static unsigned
347 relaxed_branch_length (fragS *fragp, asection *sec, int update)
348 {
349 int jump, rvc, length = 8;
350
351 if (!fragp)
352 return length;
353
354 jump = RELAX_BRANCH_UNCOND (fragp->fr_subtype);
355 rvc = RELAX_BRANCH_RVC (fragp->fr_subtype);
356 length = RELAX_BRANCH_LENGTH (fragp->fr_subtype);
357
358 /* Assume jumps are in range; the linker will catch any that aren't. */
359 length = jump ? 4 : 8;
360
361 if (fragp->fr_symbol != NULL
362 && S_IS_DEFINED (fragp->fr_symbol)
363 && sec == S_GET_SEGMENT (fragp->fr_symbol))
364 {
365 offsetT val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
366 bfd_vma rvc_range = jump ? RVC_JUMP_REACH : RVC_BRANCH_REACH;
367 val -= fragp->fr_address + fragp->fr_fix;
368
369 if (rvc && (bfd_vma)(val + rvc_range/2) < rvc_range)
370 length = 2;
371 else if ((bfd_vma)(val + RISCV_BRANCH_REACH/2) < RISCV_BRANCH_REACH)
372 length = 4;
373 else if (!jump && rvc)
374 length = 6;
375 }
376
377 if (update)
378 fragp->fr_subtype = RELAX_BRANCH_ENCODE (jump, rvc, length);
379
380 return length;
381 }
382
383 struct regname
384 {
385 const char *name;
386 unsigned int num;
387 };
388
389 enum reg_class
390 {
391 RCLASS_GPR,
392 RCLASS_FPR,
393 RCLASS_CSR,
394 RCLASS_MAX
395 };
396
397 static struct hash_control *reg_names_hash = NULL;
398
399 #define ENCODE_REG_HASH(cls, n) \
400 ((void *)(uintptr_t)((n) * RCLASS_MAX + (cls) + 1))
401 #define DECODE_REG_CLASS(hash) (((uintptr_t)(hash) - 1) % RCLASS_MAX)
402 #define DECODE_REG_NUM(hash) (((uintptr_t)(hash) - 1) / RCLASS_MAX)
403
404 static void
405 hash_reg_name (enum reg_class class, const char *name, unsigned n)
406 {
407 void *hash = ENCODE_REG_HASH (class, n);
408 const char *retval = hash_insert (reg_names_hash, name, hash);
409
410 if (retval != NULL)
411 as_fatal (_("internal error: can't hash `%s': %s"), name, retval);
412 }
413
414 static void
415 hash_reg_names (enum reg_class class, const char * const names[], unsigned n)
416 {
417 unsigned i;
418
419 for (i = 0; i < n; i++)
420 hash_reg_name (class, names[i], i);
421 }
422
423 static unsigned int
424 reg_lookup_internal (const char *s, enum reg_class class)
425 {
426 struct regname *r = (struct regname *) hash_find (reg_names_hash, s);
427
428 if (r == NULL || DECODE_REG_CLASS (r) != class)
429 return -1;
430 return DECODE_REG_NUM (r);
431 }
432
433 static bfd_boolean
434 reg_lookup (char **s, enum reg_class class, unsigned int *regnop)
435 {
436 char *e;
437 char save_c;
438 int reg = -1;
439
440 /* Find end of name. */
441 e = *s;
442 if (is_name_beginner (*e))
443 ++e;
444 while (is_part_of_name (*e))
445 ++e;
446
447 /* Terminate name. */
448 save_c = *e;
449 *e = '\0';
450
451 /* Look for the register. Advance to next token if one was recognized. */
452 if ((reg = reg_lookup_internal (*s, class)) >= 0)
453 *s = e;
454
455 *e = save_c;
456 if (regnop)
457 *regnop = reg;
458 return reg >= 0;
459 }
460
461 static bfd_boolean
462 arg_lookup (char **s, const char *const *array, size_t size, unsigned *regnop)
463 {
464 const char *p = strchr (*s, ',');
465 size_t i, len = p ? (size_t)(p - *s) : strlen (*s);
466
467 for (i = 0; i < size; i++)
468 if (array[i] != NULL && strncmp (array[i], *s, len) == 0)
469 {
470 *regnop = i;
471 *s += len;
472 return TRUE;
473 }
474
475 return FALSE;
476 }
477
478 /* For consistency checking, verify that all bits are specified either
479 by the match/mask part of the instruction definition, or by the
480 operand list. */
481 static bfd_boolean
482 validate_riscv_insn (const struct riscv_opcode *opc)
483 {
484 const char *p = opc->args;
485 char c;
486 insn_t used_bits = opc->mask;
487 int insn_width = 8 * riscv_insn_length (opc->match);
488 insn_t required_bits = ~0ULL >> (64 - insn_width);
489
490 if ((used_bits & opc->match) != (opc->match & required_bits))
491 {
492 as_bad (_("internal: bad RISC-V opcode (mask error): %s %s"),
493 opc->name, opc->args);
494 return FALSE;
495 }
496
497 #define USE_BITS(mask,shift) (used_bits |= ((insn_t)(mask) << (shift)))
498 while (*p)
499 switch (c = *p++)
500 {
501 case 'C': /* RVC */
502 switch (c = *p++)
503 {
504 case 'a': used_bits |= ENCODE_RVC_J_IMM (-1U); break;
505 case 'c': break; /* RS1, constrained to equal sp */
506 case 'i': used_bits |= ENCODE_RVC_SIMM3(-1U); break;
507 case 'j': used_bits |= ENCODE_RVC_IMM (-1U); break;
508 case 'k': used_bits |= ENCODE_RVC_LW_IMM (-1U); break;
509 case 'l': used_bits |= ENCODE_RVC_LD_IMM (-1U); break;
510 case 'm': used_bits |= ENCODE_RVC_LWSP_IMM (-1U); break;
511 case 'n': used_bits |= ENCODE_RVC_LDSP_IMM (-1U); break;
512 case 'p': used_bits |= ENCODE_RVC_B_IMM (-1U); break;
513 case 's': USE_BITS (OP_MASK_CRS1S, OP_SH_CRS1S); break;
514 case 't': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
515 case 'u': used_bits |= ENCODE_RVC_IMM (-1U); break;
516 case 'v': used_bits |= ENCODE_RVC_IMM (-1U); break;
517 case 'w': break; /* RS1S, constrained to equal RD */
518 case 'x': break; /* RS2S, constrained to equal RD */
519 case 'K': used_bits |= ENCODE_RVC_ADDI4SPN_IMM (-1U); break;
520 case 'L': used_bits |= ENCODE_RVC_ADDI16SP_IMM (-1U); break;
521 case 'M': used_bits |= ENCODE_RVC_SWSP_IMM (-1U); break;
522 case 'N': used_bits |= ENCODE_RVC_SDSP_IMM (-1U); break;
523 case 'U': break; /* RS1, constrained to equal RD */
524 case 'V': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
525 case '<': used_bits |= ENCODE_RVC_IMM (-1U); break;
526 case '>': used_bits |= ENCODE_RVC_IMM (-1U); break;
527 case 'T': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
528 case 'D': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
529 default:
530 as_bad (_("internal: bad RISC-V opcode (unknown operand type `C%c'): %s %s"),
531 c, opc->name, opc->args);
532 return FALSE;
533 }
534 break;
535 case ',': break;
536 case '(': break;
537 case ')': break;
538 case '<': USE_BITS (OP_MASK_SHAMTW, OP_SH_SHAMTW); break;
539 case '>': USE_BITS (OP_MASK_SHAMT, OP_SH_SHAMT); break;
540 case 'A': break;
541 case 'D': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
542 case 'Z': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
543 case 'E': USE_BITS (OP_MASK_CSR, OP_SH_CSR); break;
544 case 'I': break;
545 case 'R': USE_BITS (OP_MASK_RS3, OP_SH_RS3); break;
546 case 'S': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
547 case 'U': USE_BITS (OP_MASK_RS1, OP_SH_RS1); /* fallthru */
548 case 'T': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
549 case 'd': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
550 case 'm': USE_BITS (OP_MASK_RM, OP_SH_RM); break;
551 case 's': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
552 case 't': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
553 case 'P': USE_BITS (OP_MASK_PRED, OP_SH_PRED); break;
554 case 'Q': USE_BITS (OP_MASK_SUCC, OP_SH_SUCC); break;
555 case 'o':
556 case 'j': used_bits |= ENCODE_ITYPE_IMM (-1U); break;
557 case 'a': used_bits |= ENCODE_UJTYPE_IMM (-1U); break;
558 case 'p': used_bits |= ENCODE_SBTYPE_IMM (-1U); break;
559 case 'q': used_bits |= ENCODE_STYPE_IMM (-1U); break;
560 case 'u': used_bits |= ENCODE_UTYPE_IMM (-1U); break;
561 case '[': break;
562 case ']': break;
563 case '0': break;
564 default:
565 as_bad (_("internal: bad RISC-V opcode "
566 "(unknown operand type `%c'): %s %s"),
567 c, opc->name, opc->args);
568 return FALSE;
569 }
570 #undef USE_BITS
571 if (used_bits != required_bits)
572 {
573 as_bad (_("internal: bad RISC-V opcode (bits 0x%lx undefined): %s %s"),
574 ~(unsigned long)(used_bits & required_bits),
575 opc->name, opc->args);
576 return FALSE;
577 }
578 return TRUE;
579 }
580
581 struct percent_op_match
582 {
583 const char *str;
584 bfd_reloc_code_real_type reloc;
585 };
586
587 /* This function is called once, at assembler startup time. It should set up
588 all the tables, etc. that the MD part of the assembler will need. */
589
590 void
591 md_begin (void)
592 {
593 int i = 0;
594 unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
595
596 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
597 as_warn (_("Could not set architecture and machine"));
598
599 op_hash = hash_new ();
600
601 while (riscv_opcodes[i].name)
602 {
603 const char *name = riscv_opcodes[i].name;
604 const char *hash_error =
605 hash_insert (op_hash, name, (void *) &riscv_opcodes[i]);
606
607 if (hash_error)
608 {
609 fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
610 riscv_opcodes[i].name, hash_error);
611 /* Probably a memory allocation problem? Give up now. */
612 as_fatal (_("Broken assembler. No assembly attempted."));
613 }
614
615 do
616 {
617 if (riscv_opcodes[i].pinfo != INSN_MACRO)
618 {
619 if (!validate_riscv_insn (&riscv_opcodes[i]))
620 as_fatal (_("Broken assembler. No assembly attempted."));
621 }
622 ++i;
623 }
624 while (riscv_opcodes[i].name && !strcmp (riscv_opcodes[i].name, name));
625 }
626
627 reg_names_hash = hash_new ();
628 hash_reg_names (RCLASS_GPR, riscv_gpr_names_numeric, NGPR);
629 hash_reg_names (RCLASS_GPR, riscv_gpr_names_abi, NGPR);
630 hash_reg_names (RCLASS_FPR, riscv_fpr_names_numeric, NFPR);
631 hash_reg_names (RCLASS_FPR, riscv_fpr_names_abi, NFPR);
632
633 #define DECLARE_CSR(name, num) hash_reg_name (RCLASS_CSR, #name, num);
634 #include "opcode/riscv-opc.h"
635 #undef DECLARE_CSR
636
637 /* Set the default alignment for the text section. */
638 record_alignment (text_section, riscv_opts.rvc ? 1 : 2);
639 }
640
641 static insn_t
642 riscv_apply_const_reloc (bfd_reloc_code_real_type reloc_type, bfd_vma value)
643 {
644 switch (reloc_type)
645 {
646 case BFD_RELOC_32:
647 return value;
648
649 case BFD_RELOC_RISCV_HI20:
650 return ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value));
651
652 case BFD_RELOC_RISCV_LO12_S:
653 return ENCODE_STYPE_IMM (value);
654
655 case BFD_RELOC_RISCV_LO12_I:
656 return ENCODE_ITYPE_IMM (value);
657
658 default:
659 abort ();
660 }
661 }
662
663 /* Output an instruction. IP is the instruction information.
664 ADDRESS_EXPR is an operand of the instruction to be used with
665 RELOC_TYPE. */
666
667 static void
668 append_insn (struct riscv_cl_insn *ip, expressionS *address_expr,
669 bfd_reloc_code_real_type reloc_type)
670 {
671 dwarf2_emit_insn (0);
672
673 if (reloc_type != BFD_RELOC_UNUSED)
674 {
675 reloc_howto_type *howto;
676
677 gas_assert (address_expr);
678 if (reloc_type == BFD_RELOC_12_PCREL
679 || reloc_type == BFD_RELOC_RISCV_JMP)
680 {
681 int j = reloc_type == BFD_RELOC_RISCV_JMP;
682 int best_case = riscv_insn_length (ip->insn_opcode);
683 unsigned worst_case = relaxed_branch_length (NULL, NULL, 0);
684 add_relaxed_insn (ip, worst_case, best_case,
685 RELAX_BRANCH_ENCODE (j, best_case == 2, worst_case),
686 address_expr->X_add_symbol,
687 address_expr->X_add_number);
688 return;
689 }
690 else if (address_expr->X_op == O_constant)
691 ip->insn_opcode |= riscv_apply_const_reloc (reloc_type,
692 address_expr->X_add_number);
693 else
694 {
695 howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
696 if (howto == NULL)
697 as_bad (_("Unsupported RISC-V relocation number %d"), reloc_type);
698
699 ip->fixp = fix_new_exp (ip->frag, ip->where,
700 bfd_get_reloc_size (howto),
701 address_expr, FALSE, reloc_type);
702
703 ip->fixp->fx_tcbit = riscv_opts.relax;
704 }
705 }
706
707 add_fixed_insn (ip);
708 install_insn (ip);
709 }
710
711 /* Build an instruction created by a macro expansion. This is passed
712 a pointer to the count of instructions created so far, an
713 expression, the name of the instruction to build, an operand format
714 string, and corresponding arguments. */
715
716 static void
717 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
718 {
719 const struct riscv_opcode *mo;
720 struct riscv_cl_insn insn;
721 bfd_reloc_code_real_type r;
722 va_list args;
723
724 va_start (args, fmt);
725
726 r = BFD_RELOC_UNUSED;
727 mo = (struct riscv_opcode *) hash_find (op_hash, name);
728 gas_assert (mo);
729
730 /* Find a non-RVC variant of the instruction. append_insn will compress
731 it if possible. */
732 while (riscv_insn_length (mo->match) < 4)
733 mo++;
734 gas_assert (strcmp (name, mo->name) == 0);
735
736 create_insn (&insn, mo);
737 for (;;)
738 {
739 switch (*fmt++)
740 {
741 case 'd':
742 INSERT_OPERAND (RD, insn, va_arg (args, int));
743 continue;
744
745 case 's':
746 INSERT_OPERAND (RS1, insn, va_arg (args, int));
747 continue;
748
749 case 't':
750 INSERT_OPERAND (RS2, insn, va_arg (args, int));
751 continue;
752
753 case '>':
754 INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
755 continue;
756
757 case 'j':
758 case 'u':
759 case 'q':
760 gas_assert (ep != NULL);
761 r = va_arg (args, int);
762 continue;
763
764 case '\0':
765 break;
766 case ',':
767 continue;
768 default:
769 as_fatal (_("internal error: invalid macro"));
770 }
771 break;
772 }
773 va_end (args);
774 gas_assert (r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
775
776 append_insn (&insn, ep, r);
777 }
778
779 /* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
780 unset. */
781 static void
782 normalize_constant_expr (expressionS *ex)
783 {
784 if (xlen > 32)
785 return;
786 if ((ex->X_op == O_constant || ex->X_op == O_symbol)
787 && IS_ZEXT_32BIT_NUM (ex->X_add_number))
788 ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
789 - 0x80000000);
790 }
791
792 /* Fail if an expression is not a constant. */
793
794 static void
795 check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex)
796 {
797 if (ex->X_op == O_big)
798 as_bad (_("unsupported large constant"));
799 else if (ex->X_op != O_constant)
800 as_bad (_("Instruction %s requires absolute expression"),
801 ip->insn_mo->name);
802 normalize_constant_expr (ex);
803 }
804
805 static symbolS *
806 make_internal_label (void)
807 {
808 return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg,
809 (valueT) frag_now_fix (), frag_now);
810 }
811
812 /* Load an entry from the GOT. */
813 static void
814 pcrel_access (int destreg, int tempreg, expressionS *ep,
815 const char *lo_insn, const char *lo_pattern,
816 bfd_reloc_code_real_type hi_reloc,
817 bfd_reloc_code_real_type lo_reloc)
818 {
819 expressionS ep2;
820 ep2.X_op = O_symbol;
821 ep2.X_add_symbol = make_internal_label ();
822 ep2.X_add_number = 0;
823
824 macro_build (ep, "auipc", "d,u", tempreg, hi_reloc);
825 macro_build (&ep2, lo_insn, lo_pattern, destreg, tempreg, lo_reloc);
826 }
827
828 static void
829 pcrel_load (int destreg, int tempreg, expressionS *ep, const char *lo_insn,
830 bfd_reloc_code_real_type hi_reloc,
831 bfd_reloc_code_real_type lo_reloc)
832 {
833 pcrel_access (destreg, tempreg, ep, lo_insn, "d,s,j", hi_reloc, lo_reloc);
834 }
835
836 static void
837 pcrel_store (int srcreg, int tempreg, expressionS *ep, const char *lo_insn,
838 bfd_reloc_code_real_type hi_reloc,
839 bfd_reloc_code_real_type lo_reloc)
840 {
841 pcrel_access (srcreg, tempreg, ep, lo_insn, "t,s,q", hi_reloc, lo_reloc);
842 }
843
844 /* PC-relative function call using AUIPC/JALR, relaxed to JAL. */
845 static void
846 riscv_call (int destreg, int tempreg, expressionS *ep,
847 bfd_reloc_code_real_type reloc)
848 {
849 macro_build (ep, "auipc", "d,u", tempreg, reloc);
850 macro_build (NULL, "jalr", "d,s", destreg, tempreg);
851 }
852
853 /* Load an integer constant into a register. */
854
855 static void
856 load_const (int reg, expressionS *ep)
857 {
858 int shift = RISCV_IMM_BITS;
859 expressionS upper = *ep, lower = *ep;
860 lower.X_add_number = (int32_t) ep->X_add_number << (32-shift) >> (32-shift);
861 upper.X_add_number -= lower.X_add_number;
862
863 if (ep->X_op != O_constant)
864 {
865 as_bad (_("unsupported large constant"));
866 return;
867 }
868
869 if (xlen > 32 && !IS_SEXT_32BIT_NUM (ep->X_add_number))
870 {
871 /* Reduce to a signed 32-bit constant using SLLI and ADDI. */
872 while (((upper.X_add_number >> shift) & 1) == 0)
873 shift++;
874
875 upper.X_add_number = (int64_t) upper.X_add_number >> shift;
876 load_const (reg, &upper);
877
878 macro_build (NULL, "slli", "d,s,>", reg, reg, shift);
879 if (lower.X_add_number != 0)
880 macro_build (&lower, "addi", "d,s,j", reg, reg, BFD_RELOC_RISCV_LO12_I);
881 }
882 else
883 {
884 /* Simply emit LUI and/or ADDI to build a 32-bit signed constant. */
885 int hi_reg = 0;
886
887 if (upper.X_add_number != 0)
888 {
889 macro_build (ep, "lui", "d,u", reg, BFD_RELOC_RISCV_HI20);
890 hi_reg = reg;
891 }
892
893 if (lower.X_add_number != 0 || hi_reg == 0)
894 macro_build (ep, ADD32_INSN, "d,s,j", reg, hi_reg,
895 BFD_RELOC_RISCV_LO12_I);
896 }
897 }
898
899 /* Expand RISC-V assembly macros into one or more instructions. */
900 static void
901 macro (struct riscv_cl_insn *ip, expressionS *imm_expr,
902 bfd_reloc_code_real_type *imm_reloc)
903 {
904 int rd = (ip->insn_opcode >> OP_SH_RD) & OP_MASK_RD;
905 int rs1 = (ip->insn_opcode >> OP_SH_RS1) & OP_MASK_RS1;
906 int rs2 = (ip->insn_opcode >> OP_SH_RS2) & OP_MASK_RS2;
907 int mask = ip->insn_mo->mask;
908
909 switch (mask)
910 {
911 case M_LI:
912 load_const (rd, imm_expr);
913 break;
914
915 case M_LA:
916 case M_LLA:
917 /* Load the address of a symbol into a register. */
918 if (!IS_SEXT_32BIT_NUM (imm_expr->X_add_number))
919 as_bad (_("offset too large"));
920
921 if (imm_expr->X_op == O_constant)
922 load_const (rd, imm_expr);
923 else if (riscv_opts.pic && mask == M_LA) /* Global PIC symbol */
924 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
925 BFD_RELOC_RISCV_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
926 else /* Local PIC symbol, or any non-PIC symbol */
927 pcrel_load (rd, rd, imm_expr, "addi",
928 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
929 break;
930
931 case M_LA_TLS_GD:
932 pcrel_load (rd, rd, imm_expr, "addi",
933 BFD_RELOC_RISCV_TLS_GD_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
934 break;
935
936 case M_LA_TLS_IE:
937 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
938 BFD_RELOC_RISCV_TLS_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
939 break;
940
941 case M_LB:
942 pcrel_load (rd, rd, imm_expr, "lb",
943 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
944 break;
945
946 case M_LBU:
947 pcrel_load (rd, rd, imm_expr, "lbu",
948 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
949 break;
950
951 case M_LH:
952 pcrel_load (rd, rd, imm_expr, "lh",
953 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
954 break;
955
956 case M_LHU:
957 pcrel_load (rd, rd, imm_expr, "lhu",
958 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
959 break;
960
961 case M_LW:
962 pcrel_load (rd, rd, imm_expr, "lw",
963 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
964 break;
965
966 case M_LWU:
967 pcrel_load (rd, rd, imm_expr, "lwu",
968 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
969 break;
970
971 case M_LD:
972 pcrel_load (rd, rd, imm_expr, "ld",
973 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
974 break;
975
976 case M_FLW:
977 pcrel_load (rd, rs1, imm_expr, "flw",
978 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
979 break;
980
981 case M_FLD:
982 pcrel_load (rd, rs1, imm_expr, "fld",
983 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
984 break;
985
986 case M_SB:
987 pcrel_store (rs2, rs1, imm_expr, "sb",
988 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
989 break;
990
991 case M_SH:
992 pcrel_store (rs2, rs1, imm_expr, "sh",
993 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
994 break;
995
996 case M_SW:
997 pcrel_store (rs2, rs1, imm_expr, "sw",
998 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
999 break;
1000
1001 case M_SD:
1002 pcrel_store (rs2, rs1, imm_expr, "sd",
1003 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1004 break;
1005
1006 case M_FSW:
1007 pcrel_store (rs2, rs1, imm_expr, "fsw",
1008 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1009 break;
1010
1011 case M_FSD:
1012 pcrel_store (rs2, rs1, imm_expr, "fsd",
1013 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1014 break;
1015
1016 case M_CALL:
1017 riscv_call (rd, rs1, imm_expr, *imm_reloc);
1018 break;
1019
1020 default:
1021 as_bad (_("Macro %s not implemented"), ip->insn_mo->name);
1022 break;
1023 }
1024 }
1025
1026 static const struct percent_op_match percent_op_utype[] =
1027 {
1028 {"%tprel_hi", BFD_RELOC_RISCV_TPREL_HI20},
1029 {"%pcrel_hi", BFD_RELOC_RISCV_PCREL_HI20},
1030 {"%tls_ie_pcrel_hi", BFD_RELOC_RISCV_TLS_GOT_HI20},
1031 {"%tls_gd_pcrel_hi", BFD_RELOC_RISCV_TLS_GD_HI20},
1032 {"%hi", BFD_RELOC_RISCV_HI20},
1033 {0, 0}
1034 };
1035
1036 static const struct percent_op_match percent_op_itype[] =
1037 {
1038 {"%lo", BFD_RELOC_RISCV_LO12_I},
1039 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_I},
1040 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_I},
1041 {0, 0}
1042 };
1043
1044 static const struct percent_op_match percent_op_stype[] =
1045 {
1046 {"%lo", BFD_RELOC_RISCV_LO12_S},
1047 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_S},
1048 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_S},
1049 {0, 0}
1050 };
1051
1052 static const struct percent_op_match percent_op_rtype[] =
1053 {
1054 {"%tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
1055 {0, 0}
1056 };
1057
1058 /* Return true if *STR points to a relocation operator. When returning true,
1059 move *STR over the operator and store its relocation code in *RELOC.
1060 Leave both *STR and *RELOC alone when returning false. */
1061
1062 static bfd_boolean
1063 parse_relocation (char **str, bfd_reloc_code_real_type *reloc,
1064 const struct percent_op_match *percent_op)
1065 {
1066 for ( ; percent_op->str; percent_op++)
1067 if (strncasecmp (*str, percent_op->str, strlen (percent_op->str)) == 0)
1068 {
1069 int len = strlen (percent_op->str);
1070
1071 if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
1072 continue;
1073
1074 *str += strlen (percent_op->str);
1075 *reloc = percent_op->reloc;
1076
1077 /* Check whether the output BFD supports this relocation.
1078 If not, issue an error and fall back on something safe. */
1079 if (*reloc != BFD_RELOC_UNUSED
1080 && !bfd_reloc_type_lookup (stdoutput, *reloc))
1081 {
1082 as_bad ("relocation %s isn't supported by the current ABI",
1083 percent_op->str);
1084 *reloc = BFD_RELOC_UNUSED;
1085 }
1086 return TRUE;
1087 }
1088 return FALSE;
1089 }
1090
1091 static void
1092 my_getExpression (expressionS *ep, char *str)
1093 {
1094 char *save_in;
1095
1096 save_in = input_line_pointer;
1097 input_line_pointer = str;
1098 expression (ep);
1099 expr_end = input_line_pointer;
1100 input_line_pointer = save_in;
1101 }
1102
1103 /* Parse string STR as a 16-bit relocatable operand. Store the
1104 expression in *EP and the relocation, if any, in RELOC.
1105 Return the number of relocation operators used (0 or 1).
1106
1107 On exit, EXPR_END points to the first character after the expression. */
1108
1109 static size_t
1110 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1111 char *str, const struct percent_op_match *percent_op)
1112 {
1113 size_t reloc_index;
1114 unsigned crux_depth, str_depth, regno;
1115 char *crux;
1116
1117 /* First, check for integer registers. */
1118 if (reg_lookup (&str, RCLASS_GPR, &regno))
1119 {
1120 ep->X_op = O_register;
1121 ep->X_add_number = regno;
1122 return 0;
1123 }
1124
1125 /* Search for the start of the main expression.
1126 End the loop with CRUX pointing to the start
1127 of the main expression and with CRUX_DEPTH containing the number
1128 of open brackets at that point. */
1129 reloc_index = -1;
1130 str_depth = 0;
1131 do
1132 {
1133 reloc_index++;
1134 crux = str;
1135 crux_depth = str_depth;
1136
1137 /* Skip over whitespace and brackets, keeping count of the number
1138 of brackets. */
1139 while (*str == ' ' || *str == '\t' || *str == '(')
1140 if (*str++ == '(')
1141 str_depth++;
1142 }
1143 while (*str == '%'
1144 && reloc_index < 1
1145 && parse_relocation (&str, reloc, percent_op));
1146
1147 my_getExpression (ep, crux);
1148 str = expr_end;
1149
1150 /* Match every open bracket. */
1151 while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
1152 if (*str++ == ')')
1153 crux_depth--;
1154
1155 if (crux_depth > 0)
1156 as_bad ("unclosed '('");
1157
1158 expr_end = str;
1159
1160 return reloc_index;
1161 }
1162
1163 /* This routine assembles an instruction into its binary format. As a
1164 side effect, it sets the global variable imm_reloc to the type of
1165 relocation to do if one of the operands is an address expression. */
1166
1167 static const char *
1168 riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
1169 bfd_reloc_code_real_type *imm_reloc)
1170 {
1171 char *s;
1172 const char *args;
1173 char c = 0;
1174 struct riscv_opcode *insn;
1175 char *argsStart;
1176 unsigned int regno;
1177 char save_c = 0;
1178 int argnum;
1179 const struct percent_op_match *p;
1180 const char *error = "unrecognized opcode";
1181
1182 /* Parse the name of the instruction. Terminate the string if whitespace
1183 is found so that hash_find only sees the name part of the string. */
1184 for (s = str; *s != '\0'; ++s)
1185 if (ISSPACE (*s))
1186 {
1187 save_c = *s;
1188 *s++ = '\0';
1189 break;
1190 }
1191
1192 insn = (struct riscv_opcode *) hash_find (op_hash, str);
1193
1194 argsStart = s;
1195 for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
1196 {
1197 if (!riscv_subset_supports (insn->subset))
1198 continue;
1199
1200 create_insn (ip, insn);
1201 argnum = 1;
1202
1203 imm_expr->X_op = O_absent;
1204 *imm_reloc = BFD_RELOC_UNUSED;
1205 p = percent_op_itype;
1206
1207 for (args = insn->args;; ++args)
1208 {
1209 s += strspn (s, " \t");
1210 switch (*args)
1211 {
1212 case '\0': /* End of args. */
1213 if (insn->pinfo != INSN_MACRO)
1214 {
1215 if (!insn->match_func (insn, ip->insn_opcode))
1216 break;
1217 if (riscv_insn_length (insn->match) == 2 && !riscv_opts.rvc)
1218 break;
1219 }
1220 if (*s != '\0')
1221 break;
1222 /* Successful assembly. */
1223 error = NULL;
1224 goto out;
1225
1226 case 'C': /* RVC */
1227 switch (*++args)
1228 {
1229 case 's': /* RS1 x8-x15 */
1230 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1231 || !(regno >= 8 && regno <= 15))
1232 break;
1233 INSERT_OPERAND (CRS1S, *ip, regno % 8);
1234 continue;
1235 case 'w': /* RS1 x8-x15, constrained to equal RD x8-x15. */
1236 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1237 || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
1238 break;
1239 continue;
1240 case 't': /* RS2 x8-x15 */
1241 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1242 || !(regno >= 8 && regno <= 15))
1243 break;
1244 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1245 continue;
1246 case 'x': /* RS2 x8-x15, constrained to equal RD x8-x15. */
1247 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1248 || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
1249 break;
1250 continue;
1251 case 'U': /* RS1, constrained to equal RD. */
1252 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1253 || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
1254 break;
1255 continue;
1256 case 'V': /* RS2 */
1257 if (!reg_lookup (&s, RCLASS_GPR, &regno))
1258 break;
1259 INSERT_OPERAND (CRS2, *ip, regno);
1260 continue;
1261 case 'c': /* RS1, constrained to equal sp. */
1262 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1263 || regno != X_SP)
1264 break;
1265 continue;
1266 case '>':
1267 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1268 || imm_expr->X_op != O_constant
1269 || imm_expr->X_add_number <= 0
1270 || imm_expr->X_add_number >= 64)
1271 break;
1272 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1273 rvc_imm_done:
1274 s = expr_end;
1275 imm_expr->X_op = O_absent;
1276 continue;
1277 case '<':
1278 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1279 || imm_expr->X_op != O_constant
1280 || !VALID_RVC_IMM (imm_expr->X_add_number)
1281 || imm_expr->X_add_number <= 0
1282 || imm_expr->X_add_number >= 32)
1283 break;
1284 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1285 goto rvc_imm_done;
1286 case 'i':
1287 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1288 || imm_expr->X_op != O_constant
1289 || imm_expr->X_add_number == 0
1290 || !VALID_RVC_SIMM3 (imm_expr->X_add_number))
1291 break;
1292 ip->insn_opcode |= ENCODE_RVC_SIMM3 (imm_expr->X_add_number);
1293 goto rvc_imm_done;
1294 case 'j':
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_IMM (imm_expr->X_add_number))
1299 break;
1300 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1301 goto rvc_imm_done;
1302 case 'k':
1303 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1304 || imm_expr->X_op != O_constant
1305 || !VALID_RVC_LW_IMM (imm_expr->X_add_number))
1306 break;
1307 ip->insn_opcode |= ENCODE_RVC_LW_IMM (imm_expr->X_add_number);
1308 goto rvc_imm_done;
1309 case 'l':
1310 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1311 || imm_expr->X_op != O_constant
1312 || !VALID_RVC_LD_IMM (imm_expr->X_add_number))
1313 break;
1314 ip->insn_opcode |= ENCODE_RVC_LD_IMM (imm_expr->X_add_number);
1315 goto rvc_imm_done;
1316 case 'm':
1317 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1318 || imm_expr->X_op != O_constant
1319 || !VALID_RVC_LWSP_IMM (imm_expr->X_add_number))
1320 break;
1321 ip->insn_opcode |=
1322 ENCODE_RVC_LWSP_IMM (imm_expr->X_add_number);
1323 goto rvc_imm_done;
1324 case 'n':
1325 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1326 || imm_expr->X_op != O_constant
1327 || !VALID_RVC_LDSP_IMM (imm_expr->X_add_number))
1328 break;
1329 ip->insn_opcode |=
1330 ENCODE_RVC_LDSP_IMM (imm_expr->X_add_number);
1331 goto rvc_imm_done;
1332 case 'K':
1333 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1334 || imm_expr->X_op != O_constant
1335 || !VALID_RVC_ADDI4SPN_IMM (imm_expr->X_add_number)
1336 || imm_expr->X_add_number == 0)
1337 break;
1338 ip->insn_opcode |=
1339 ENCODE_RVC_ADDI4SPN_IMM (imm_expr->X_add_number);
1340 goto rvc_imm_done;
1341 case 'L':
1342 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1343 || imm_expr->X_op != O_constant
1344 || !VALID_RVC_ADDI16SP_IMM (imm_expr->X_add_number)
1345 || imm_expr->X_add_number == 0)
1346 break;
1347 ip->insn_opcode |=
1348 ENCODE_RVC_ADDI16SP_IMM (imm_expr->X_add_number);
1349 goto rvc_imm_done;
1350 case 'M':
1351 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1352 || imm_expr->X_op != O_constant
1353 || !VALID_RVC_SWSP_IMM (imm_expr->X_add_number))
1354 break;
1355 ip->insn_opcode |=
1356 ENCODE_RVC_SWSP_IMM (imm_expr->X_add_number);
1357 goto rvc_imm_done;
1358 case 'N':
1359 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1360 || imm_expr->X_op != O_constant
1361 || !VALID_RVC_SDSP_IMM (imm_expr->X_add_number))
1362 break;
1363 ip->insn_opcode |=
1364 ENCODE_RVC_SDSP_IMM (imm_expr->X_add_number);
1365 goto rvc_imm_done;
1366 case 'u':
1367 p = percent_op_utype;
1368 if (my_getSmallExpression (imm_expr, imm_reloc, s, p))
1369 break;
1370 rvc_lui:
1371 if (imm_expr->X_op != O_constant
1372 || imm_expr->X_add_number <= 0
1373 || imm_expr->X_add_number >= RISCV_BIGIMM_REACH
1374 || (imm_expr->X_add_number >= RISCV_RVC_IMM_REACH / 2
1375 && (imm_expr->X_add_number <
1376 RISCV_BIGIMM_REACH - RISCV_RVC_IMM_REACH / 2)))
1377 break;
1378 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1379 goto rvc_imm_done;
1380 case 'v':
1381 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1382 || (imm_expr->X_add_number & (RISCV_IMM_REACH - 1))
1383 || ((int32_t)imm_expr->X_add_number
1384 != imm_expr->X_add_number))
1385 break;
1386 imm_expr->X_add_number =
1387 ((uint32_t) imm_expr->X_add_number) >> RISCV_IMM_BITS;
1388 goto rvc_lui;
1389 case 'p':
1390 goto branch;
1391 case 'a':
1392 goto jump;
1393 case 'D': /* Floating-point RS2 x8-x15. */
1394 if (!reg_lookup (&s, RCLASS_FPR, &regno)
1395 || !(regno >= 8 && regno <= 15))
1396 break;
1397 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1398 continue;
1399 case 'T': /* Floating-point RS2. */
1400 if (!reg_lookup (&s, RCLASS_FPR, &regno))
1401 break;
1402 INSERT_OPERAND (CRS2, *ip, regno);
1403 continue;
1404 default:
1405 as_bad (_("bad RVC field specifier 'C%c'\n"), *args);
1406 }
1407 break;
1408
1409 case ',':
1410 ++argnum;
1411 if (*s++ == *args)
1412 continue;
1413 s--;
1414 break;
1415
1416 case '(':
1417 case ')':
1418 case '[':
1419 case ']':
1420 if (*s++ == *args)
1421 continue;
1422 break;
1423
1424 case '<': /* Shift amount, 0 - 31. */
1425 my_getExpression (imm_expr, s);
1426 check_absolute_expr (ip, imm_expr);
1427 if ((unsigned long) imm_expr->X_add_number > 31)
1428 as_warn (_("Improper shift amount (%lu)"),
1429 (unsigned long) imm_expr->X_add_number);
1430 INSERT_OPERAND (SHAMTW, *ip, imm_expr->X_add_number);
1431 imm_expr->X_op = O_absent;
1432 s = expr_end;
1433 continue;
1434
1435 case '>': /* Shift amount, 0 - (XLEN-1). */
1436 my_getExpression (imm_expr, s);
1437 check_absolute_expr (ip, imm_expr);
1438 if ((unsigned long) imm_expr->X_add_number >= xlen)
1439 as_warn (_("Improper shift amount (%lu)"),
1440 (unsigned long) imm_expr->X_add_number);
1441 INSERT_OPERAND (SHAMT, *ip, imm_expr->X_add_number);
1442 imm_expr->X_op = O_absent;
1443 s = expr_end;
1444 continue;
1445
1446 case 'Z': /* CSRRxI immediate. */
1447 my_getExpression (imm_expr, s);
1448 check_absolute_expr (ip, imm_expr);
1449 if ((unsigned long) imm_expr->X_add_number > 31)
1450 as_warn (_("Improper CSRxI immediate (%lu)"),
1451 (unsigned long) imm_expr->X_add_number);
1452 INSERT_OPERAND (RS1, *ip, imm_expr->X_add_number);
1453 imm_expr->X_op = O_absent;
1454 s = expr_end;
1455 continue;
1456
1457 case 'E': /* Control register. */
1458 if (reg_lookup (&s, RCLASS_CSR, &regno))
1459 INSERT_OPERAND (CSR, *ip, regno);
1460 else
1461 {
1462 my_getExpression (imm_expr, s);
1463 check_absolute_expr (ip, imm_expr);
1464 if ((unsigned long) imm_expr->X_add_number > 0xfff)
1465 as_warn (_("Improper CSR address (%lu)"),
1466 (unsigned long) imm_expr->X_add_number);
1467 INSERT_OPERAND (CSR, *ip, imm_expr->X_add_number);
1468 imm_expr->X_op = O_absent;
1469 s = expr_end;
1470 }
1471 continue;
1472
1473 case 'm': /* Rounding mode. */
1474 if (arg_lookup (&s, riscv_rm, ARRAY_SIZE (riscv_rm), &regno))
1475 {
1476 INSERT_OPERAND (RM, *ip, regno);
1477 continue;
1478 }
1479 break;
1480
1481 case 'P':
1482 case 'Q': /* Fence predecessor/successor. */
1483 if (arg_lookup (&s, riscv_pred_succ, ARRAY_SIZE (riscv_pred_succ),
1484 &regno))
1485 {
1486 if (*args == 'P')
1487 INSERT_OPERAND (PRED, *ip, regno);
1488 else
1489 INSERT_OPERAND (SUCC, *ip, regno);
1490 continue;
1491 }
1492 break;
1493
1494 case 'd': /* Destination register. */
1495 case 's': /* Source register. */
1496 case 't': /* Target register. */
1497 if (reg_lookup (&s, RCLASS_GPR, &regno))
1498 {
1499 c = *args;
1500 if (*s == ' ')
1501 ++s;
1502
1503 /* Now that we have assembled one operand, we use the args
1504 string to figure out where it goes in the instruction. */
1505 switch (c)
1506 {
1507 case 's':
1508 INSERT_OPERAND (RS1, *ip, regno);
1509 break;
1510 case 'd':
1511 INSERT_OPERAND (RD, *ip, regno);
1512 break;
1513 case 't':
1514 INSERT_OPERAND (RS2, *ip, regno);
1515 break;
1516 }
1517 continue;
1518 }
1519 break;
1520
1521 case 'D': /* Floating point rd. */
1522 case 'S': /* Floating point rs1. */
1523 case 'T': /* Floating point rs2. */
1524 case 'U': /* Floating point rs1 and rs2. */
1525 case 'R': /* Floating point rs3. */
1526 if (reg_lookup (&s, RCLASS_FPR, &regno))
1527 {
1528 c = *args;
1529 if (*s == ' ')
1530 ++s;
1531 switch (c)
1532 {
1533 case 'D':
1534 INSERT_OPERAND (RD, *ip, regno);
1535 break;
1536 case 'S':
1537 INSERT_OPERAND (RS1, *ip, regno);
1538 break;
1539 case 'U':
1540 INSERT_OPERAND (RS1, *ip, regno);
1541 /* fallthru */
1542 case 'T':
1543 INSERT_OPERAND (RS2, *ip, regno);
1544 break;
1545 case 'R':
1546 INSERT_OPERAND (RS3, *ip, regno);
1547 break;
1548 }
1549 continue;
1550 }
1551
1552 break;
1553
1554 case 'I':
1555 my_getExpression (imm_expr, s);
1556 if (imm_expr->X_op != O_big
1557 && imm_expr->X_op != O_constant)
1558 break;
1559 normalize_constant_expr (imm_expr);
1560 s = expr_end;
1561 continue;
1562
1563 case 'A':
1564 my_getExpression (imm_expr, s);
1565 normalize_constant_expr (imm_expr);
1566 /* The 'A' format specifier must be a symbol. */
1567 if (imm_expr->X_op != O_symbol)
1568 break;
1569 *imm_reloc = BFD_RELOC_32;
1570 s = expr_end;
1571 continue;
1572
1573 case 'j': /* Sign-extended immediate. */
1574 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
1575 p = percent_op_itype;
1576 goto alu_op;
1577 case 'q': /* Store displacement. */
1578 p = percent_op_stype;
1579 *imm_reloc = BFD_RELOC_RISCV_LO12_S;
1580 goto load_store;
1581 case 'o': /* Load displacement. */
1582 p = percent_op_itype;
1583 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
1584 goto load_store;
1585 case '0': /* AMO "displacement," which must be zero. */
1586 p = percent_op_rtype;
1587 *imm_reloc = BFD_RELOC_UNUSED;
1588 load_store:
1589 /* Check whether there is only a single bracketed expression
1590 left. If so, it must be the base register and the
1591 constant must be zero. */
1592 imm_expr->X_op = O_constant;
1593 imm_expr->X_add_number = 0;
1594 if (*s == '(' && strchr (s + 1, '(') == 0)
1595 continue;
1596 alu_op:
1597 /* If this value won't fit into a 16 bit offset, then go
1598 find a macro that will generate the 32 bit offset
1599 code pattern. */
1600 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p))
1601 {
1602 normalize_constant_expr (imm_expr);
1603 if (imm_expr->X_op != O_constant
1604 || (*args == '0' && imm_expr->X_add_number != 0)
1605 || imm_expr->X_add_number >= (signed)RISCV_IMM_REACH/2
1606 || imm_expr->X_add_number < -(signed)RISCV_IMM_REACH/2)
1607 break;
1608 }
1609
1610 s = expr_end;
1611 continue;
1612
1613 case 'p': /* PC-relative offset. */
1614 branch:
1615 *imm_reloc = BFD_RELOC_12_PCREL;
1616 my_getExpression (imm_expr, s);
1617 s = expr_end;
1618 continue;
1619
1620 case 'u': /* Upper 20 bits. */
1621 p = percent_op_utype;
1622 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p)
1623 && imm_expr->X_op == O_constant)
1624 {
1625 if (imm_expr->X_add_number < 0
1626 || imm_expr->X_add_number >= (signed)RISCV_BIGIMM_REACH)
1627 as_bad (_("lui expression not in range 0..1048575"));
1628
1629 *imm_reloc = BFD_RELOC_RISCV_HI20;
1630 imm_expr->X_add_number <<= RISCV_IMM_BITS;
1631 }
1632 s = expr_end;
1633 continue;
1634
1635 case 'a': /* 20-bit PC-relative offset. */
1636 jump:
1637 my_getExpression (imm_expr, s);
1638 s = expr_end;
1639 *imm_reloc = BFD_RELOC_RISCV_JMP;
1640 continue;
1641
1642 case 'c':
1643 my_getExpression (imm_expr, s);
1644 s = expr_end;
1645 if (strcmp (s, "@plt") == 0)
1646 {
1647 *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
1648 s += 4;
1649 }
1650 else
1651 *imm_reloc = BFD_RELOC_RISCV_CALL;
1652 continue;
1653
1654 default:
1655 as_fatal (_("internal error: bad argument type %c"), *args);
1656 }
1657 break;
1658 }
1659 s = argsStart;
1660 error = _("illegal operands");
1661 }
1662
1663 out:
1664 /* Restore the character we might have clobbered above. */
1665 if (save_c)
1666 *(argsStart - 1) = save_c;
1667
1668 return error;
1669 }
1670
1671 void
1672 md_assemble (char *str)
1673 {
1674 struct riscv_cl_insn insn;
1675 expressionS imm_expr;
1676 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
1677
1678 const char *error = riscv_ip (str, &insn, &imm_expr, &imm_reloc);
1679
1680 if (error)
1681 {
1682 as_bad ("%s `%s'", error, str);
1683 return;
1684 }
1685
1686 if (insn.insn_mo->pinfo == INSN_MACRO)
1687 macro (&insn, &imm_expr, &imm_reloc);
1688 else
1689 append_insn (&insn, &imm_expr, imm_reloc);
1690 }
1691
1692 const char *
1693 md_atof (int type, char *litP, int *sizeP)
1694 {
1695 return ieee_md_atof (type, litP, sizeP, TARGET_BYTES_BIG_ENDIAN);
1696 }
1697
1698 void
1699 md_number_to_chars (char *buf, valueT val, int n)
1700 {
1701 number_to_chars_littleendian (buf, val, n);
1702 }
1703
1704 const char *md_shortopts = "O::g::G:";
1705
1706 enum options
1707 {
1708 OPTION_MARCH = OPTION_MD_BASE,
1709 OPTION_PIC,
1710 OPTION_NO_PIC,
1711 OPTION_MABI,
1712 OPTION_END_OF_ENUM
1713 };
1714
1715 struct option md_longopts[] =
1716 {
1717 {"march", required_argument, NULL, OPTION_MARCH},
1718 {"fPIC", no_argument, NULL, OPTION_PIC},
1719 {"fpic", no_argument, NULL, OPTION_PIC},
1720 {"fno-pic", no_argument, NULL, OPTION_NO_PIC},
1721 {"mabi", required_argument, NULL, OPTION_MABI},
1722
1723 {NULL, no_argument, NULL, 0}
1724 };
1725 size_t md_longopts_size = sizeof (md_longopts);
1726
1727 enum float_abi {
1728 FLOAT_ABI_DEFAULT = -1,
1729 FLOAT_ABI_SOFT,
1730 FLOAT_ABI_SINGLE,
1731 FLOAT_ABI_DOUBLE,
1732 FLOAT_ABI_QUAD
1733 };
1734 static enum float_abi float_abi = FLOAT_ABI_DEFAULT;
1735
1736 static void
1737 riscv_set_abi (unsigned new_xlen, enum float_abi new_float_abi)
1738 {
1739 abi_xlen = new_xlen;
1740 float_abi = new_float_abi;
1741 }
1742
1743 int
1744 md_parse_option (int c, const char *arg)
1745 {
1746 switch (c)
1747 {
1748 case OPTION_MARCH:
1749 riscv_set_arch (arg);
1750 break;
1751
1752 case OPTION_NO_PIC:
1753 riscv_opts.pic = FALSE;
1754 break;
1755
1756 case OPTION_PIC:
1757 riscv_opts.pic = TRUE;
1758 break;
1759
1760 case OPTION_MABI:
1761 if (strcmp (arg, "ilp32") == 0)
1762 riscv_set_abi (32, FLOAT_ABI_SOFT);
1763 else if (strcmp (arg, "ilp32f") == 0)
1764 riscv_set_abi (32, FLOAT_ABI_SINGLE);
1765 else if (strcmp (arg, "ilp32d") == 0)
1766 riscv_set_abi (32, FLOAT_ABI_DOUBLE);
1767 else if (strcmp (arg, "ilp32q") == 0)
1768 riscv_set_abi (32, FLOAT_ABI_QUAD);
1769 else if (strcmp (arg, "lp64") == 0)
1770 riscv_set_abi (64, FLOAT_ABI_SOFT);
1771 else if (strcmp (arg, "lp64f") == 0)
1772 riscv_set_abi (64, FLOAT_ABI_SINGLE);
1773 else if (strcmp (arg, "lp64d") == 0)
1774 riscv_set_abi (64, FLOAT_ABI_DOUBLE);
1775 else if (strcmp (arg, "lp64q") == 0)
1776 riscv_set_abi (64, FLOAT_ABI_QUAD);
1777 else
1778 return 0;
1779 break;
1780
1781 default:
1782 return 0;
1783 }
1784
1785 return 1;
1786 }
1787
1788 void
1789 riscv_after_parse_args (void)
1790 {
1791 if (xlen == 0)
1792 {
1793 if (strcmp (default_arch, "riscv32") == 0)
1794 xlen = 32;
1795 else if (strcmp (default_arch, "riscv64") == 0)
1796 xlen = 64;
1797 else
1798 as_bad ("unknown default architecture `%s'", default_arch);
1799 }
1800
1801 if (riscv_subsets == NULL)
1802 riscv_set_arch (xlen == 64 ? "rv64g" : "rv32g");
1803
1804 /* Add the RVC extension, regardless of -march, to support .option rvc. */
1805 if (riscv_subset_supports ("c"))
1806 riscv_set_rvc (TRUE);
1807 else
1808 riscv_add_subset ("c");
1809
1810 /* Infer ABI from ISA if not specified on command line. */
1811 if (abi_xlen == 0)
1812 abi_xlen = xlen;
1813 else if (abi_xlen > xlen)
1814 as_bad ("can't have %d-bit ABI on %d-bit ISA", abi_xlen, xlen);
1815 else if (abi_xlen < xlen)
1816 as_bad ("%d-bit ABI not yet supported on %d-bit ISA", abi_xlen, xlen);
1817
1818 if (float_abi == FLOAT_ABI_DEFAULT)
1819 {
1820 struct riscv_subset *subset;
1821
1822 /* Assume soft-float unless D extension is present. */
1823 float_abi = FLOAT_ABI_SOFT;
1824
1825 for (subset = riscv_subsets; subset != NULL; subset = subset->next)
1826 {
1827 if (strcasecmp (subset->name, "D") == 0)
1828 float_abi = FLOAT_ABI_DOUBLE;
1829 if (strcasecmp (subset->name, "Q") == 0)
1830 float_abi = FLOAT_ABI_QUAD;
1831 }
1832 }
1833
1834 /* Insert float_abi into the EF_RISCV_FLOAT_ABI field of elf_flags. */
1835 elf_flags |= float_abi * (EF_RISCV_FLOAT_ABI & ~(EF_RISCV_FLOAT_ABI << 1));
1836 }
1837
1838 long
1839 md_pcrel_from (fixS *fixP)
1840 {
1841 return fixP->fx_where + fixP->fx_frag->fr_address;
1842 }
1843
1844 /* Apply a fixup to the object file. */
1845
1846 void
1847 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
1848 {
1849 unsigned int subtype;
1850 bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
1851 bfd_boolean relaxable = FALSE;
1852
1853 /* Remember value for tc_gen_reloc. */
1854 fixP->fx_addnumber = *valP;
1855
1856 switch (fixP->fx_r_type)
1857 {
1858 case BFD_RELOC_RISCV_HI20:
1859 case BFD_RELOC_RISCV_LO12_I:
1860 case BFD_RELOC_RISCV_LO12_S:
1861 bfd_putl32 (riscv_apply_const_reloc (fixP->fx_r_type, *valP)
1862 | bfd_getl32 (buf), buf);
1863 relaxable = TRUE;
1864 break;
1865
1866 case BFD_RELOC_RISCV_GOT_HI20:
1867 case BFD_RELOC_RISCV_PCREL_HI20:
1868 case BFD_RELOC_RISCV_ADD8:
1869 case BFD_RELOC_RISCV_ADD16:
1870 case BFD_RELOC_RISCV_ADD32:
1871 case BFD_RELOC_RISCV_ADD64:
1872 case BFD_RELOC_RISCV_SUB6:
1873 case BFD_RELOC_RISCV_SUB8:
1874 case BFD_RELOC_RISCV_SUB16:
1875 case BFD_RELOC_RISCV_SUB32:
1876 case BFD_RELOC_RISCV_SUB64:
1877 case BFD_RELOC_RISCV_RELAX:
1878 break;
1879
1880 case BFD_RELOC_RISCV_TPREL_HI20:
1881 case BFD_RELOC_RISCV_TPREL_LO12_I:
1882 case BFD_RELOC_RISCV_TPREL_LO12_S:
1883 case BFD_RELOC_RISCV_TPREL_ADD:
1884 relaxable = TRUE;
1885 /* Fall through. */
1886
1887 case BFD_RELOC_RISCV_TLS_GOT_HI20:
1888 case BFD_RELOC_RISCV_TLS_GD_HI20:
1889 case BFD_RELOC_RISCV_TLS_DTPREL32:
1890 case BFD_RELOC_RISCV_TLS_DTPREL64:
1891 S_SET_THREAD_LOCAL (fixP->fx_addsy);
1892 break;
1893
1894 case BFD_RELOC_64:
1895 case BFD_RELOC_32:
1896 case BFD_RELOC_16:
1897 case BFD_RELOC_8:
1898 case BFD_RELOC_RISCV_CFA:
1899 if (fixP->fx_addsy && fixP->fx_subsy)
1900 {
1901 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
1902 fixP->fx_next->fx_addsy = fixP->fx_subsy;
1903 fixP->fx_next->fx_subsy = NULL;
1904 fixP->fx_next->fx_offset = 0;
1905 fixP->fx_subsy = NULL;
1906
1907 switch (fixP->fx_r_type)
1908 {
1909 case BFD_RELOC_64:
1910 fixP->fx_r_type = BFD_RELOC_RISCV_ADD64;
1911 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB64;
1912 break;
1913
1914 case BFD_RELOC_32:
1915 fixP->fx_r_type = BFD_RELOC_RISCV_ADD32;
1916 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
1917 break;
1918
1919 case BFD_RELOC_16:
1920 fixP->fx_r_type = BFD_RELOC_RISCV_ADD16;
1921 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
1922 break;
1923
1924 case BFD_RELOC_8:
1925 fixP->fx_r_type = BFD_RELOC_RISCV_ADD8;
1926 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
1927 break;
1928
1929 case BFD_RELOC_RISCV_CFA:
1930 /* Load the byte to get the subtype. */
1931 subtype = bfd_get_8 (NULL, &fixP->fx_frag->fr_literal[fixP->fx_where]);
1932 switch (subtype)
1933 {
1934 case DW_CFA_advance_loc1:
1935 fixP->fx_where++;
1936 fixP->fx_next->fx_where++;
1937 fixP->fx_r_type = BFD_RELOC_RISCV_SET8;
1938 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
1939 break;
1940
1941 case DW_CFA_advance_loc2:
1942 fixP->fx_size = 2;
1943 fixP->fx_where++;
1944 fixP->fx_next->fx_size = 2;
1945 fixP->fx_next->fx_where++;
1946 fixP->fx_r_type = BFD_RELOC_RISCV_SET16;
1947 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
1948 break;
1949
1950 case DW_CFA_advance_loc4:
1951 fixP->fx_size = 4;
1952 fixP->fx_where++;
1953 fixP->fx_next->fx_size = 4;
1954 fixP->fx_next->fx_where++;
1955 fixP->fx_r_type = BFD_RELOC_RISCV_SET32;
1956 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
1957 break;
1958
1959 default:
1960 if (subtype < 0x80 && (subtype & 0x40))
1961 {
1962 /* DW_CFA_advance_loc */
1963 fixP->fx_r_type = BFD_RELOC_RISCV_SET6;
1964 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB6;
1965 }
1966 else
1967 as_fatal (_("internal error: bad CFA value #%d"), subtype);
1968 break;
1969 }
1970 break;
1971
1972 default:
1973 /* This case is unreachable. */
1974 abort ();
1975 }
1976 }
1977 /* Fall through. */
1978
1979 case BFD_RELOC_RVA:
1980 /* If we are deleting this reloc entry, we must fill in the
1981 value now. This can happen if we have a .word which is not
1982 resolved when it appears but is later defined. */
1983 if (fixP->fx_addsy == NULL)
1984 {
1985 gas_assert (fixP->fx_size <= sizeof (valueT));
1986 md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
1987 fixP->fx_done = 1;
1988 }
1989 break;
1990
1991 case BFD_RELOC_RISCV_JMP:
1992 if (fixP->fx_addsy)
1993 {
1994 /* Fill in a tentative value to improve objdump readability. */
1995 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
1996 bfd_vma delta = target - md_pcrel_from (fixP);
1997 bfd_putl32 (bfd_getl32 (buf) | ENCODE_UJTYPE_IMM (delta), buf);
1998 }
1999 break;
2000
2001 case BFD_RELOC_12_PCREL:
2002 if (fixP->fx_addsy)
2003 {
2004 /* Fill in a tentative value to improve objdump readability. */
2005 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
2006 bfd_vma delta = target - md_pcrel_from (fixP);
2007 bfd_putl32 (bfd_getl32 (buf) | ENCODE_SBTYPE_IMM (delta), buf);
2008 }
2009 break;
2010
2011 case BFD_RELOC_RISCV_RVC_BRANCH:
2012 if (fixP->fx_addsy)
2013 {
2014 /* Fill in a tentative value to improve objdump readability. */
2015 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
2016 bfd_vma delta = target - md_pcrel_from (fixP);
2017 bfd_putl16 (bfd_getl16 (buf) | ENCODE_RVC_B_IMM (delta), buf);
2018 }
2019 break;
2020
2021 case BFD_RELOC_RISCV_RVC_JUMP:
2022 if (fixP->fx_addsy)
2023 {
2024 /* Fill in a tentative value to improve objdump readability. */
2025 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
2026 bfd_vma delta = target - md_pcrel_from (fixP);
2027 bfd_putl16 (bfd_getl16 (buf) | ENCODE_RVC_J_IMM (delta), buf);
2028 }
2029 break;
2030
2031 case BFD_RELOC_RISCV_CALL:
2032 case BFD_RELOC_RISCV_CALL_PLT:
2033 relaxable = TRUE;
2034 break;
2035
2036 case BFD_RELOC_RISCV_PCREL_LO12_S:
2037 case BFD_RELOC_RISCV_PCREL_LO12_I:
2038 case BFD_RELOC_RISCV_ALIGN:
2039 break;
2040
2041 default:
2042 /* We ignore generic BFD relocations we don't know about. */
2043 if (bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type) != NULL)
2044 as_fatal (_("internal error: bad relocation #%d"), fixP->fx_r_type);
2045 }
2046
2047 /* Add an R_RISCV_RELAX reloc if the reloc is relaxable. */
2048 if (relaxable && fixP->fx_tcbit && fixP->fx_addsy != NULL)
2049 {
2050 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
2051 fixP->fx_next->fx_addsy = fixP->fx_next->fx_subsy = NULL;
2052 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_RELAX;
2053 }
2054 }
2055
2056 /* Because the value of .cfi_remember_state may changed after relaxation,
2057 we insert a fix to relocate it again in link-time. */
2058
2059 void
2060 riscv_pre_output_hook (void)
2061 {
2062 const frchainS *frch;
2063 const asection *s;
2064
2065 for (s = stdoutput->sections; s; s = s->next)
2066 for (frch = seg_info (s)->frchainP; frch; frch = frch->frch_next)
2067 {
2068 const fragS *frag;
2069
2070 for (frag = frch->frch_root; frag; frag = frag->fr_next)
2071 {
2072 if (frag->fr_type == rs_cfa)
2073 {
2074 fragS *loc4_frag;
2075 expressionS exp;
2076
2077 symbolS *add_symbol = frag->fr_symbol->sy_value.X_add_symbol;
2078 symbolS *op_symbol = frag->fr_symbol->sy_value.X_op_symbol;
2079
2080 exp.X_op = O_subtract;
2081 exp.X_add_symbol = add_symbol;
2082 exp.X_add_number = 0;
2083 exp.X_op_symbol = op_symbol;
2084
2085 loc4_frag = (fragS *) frag->fr_opcode;
2086 fix_new_exp (loc4_frag, (int) frag->fr_offset, 1, &exp, 0,
2087 BFD_RELOC_RISCV_CFA);
2088 }
2089 }
2090 }
2091 }
2092
2093
2094 /* This structure is used to hold a stack of .option values. */
2095
2096 struct riscv_option_stack
2097 {
2098 struct riscv_option_stack *next;
2099 struct riscv_set_options options;
2100 };
2101
2102 static struct riscv_option_stack *riscv_opts_stack;
2103
2104 /* Handle the .option pseudo-op. */
2105
2106 static void
2107 s_riscv_option (int x ATTRIBUTE_UNUSED)
2108 {
2109 char *name = input_line_pointer, ch;
2110
2111 while (!is_end_of_line[(unsigned char) *input_line_pointer])
2112 ++input_line_pointer;
2113 ch = *input_line_pointer;
2114 *input_line_pointer = '\0';
2115
2116 if (strcmp (name, "rvc") == 0)
2117 riscv_set_rvc (TRUE);
2118 else if (strcmp (name, "norvc") == 0)
2119 riscv_set_rvc (FALSE);
2120 else if (strcmp (name, "pic") == 0)
2121 riscv_opts.pic = TRUE;
2122 else if (strcmp (name, "nopic") == 0)
2123 riscv_opts.pic = FALSE;
2124 else if (strcmp (name, "relax") == 0)
2125 riscv_opts.relax = TRUE;
2126 else if (strcmp (name, "norelax") == 0)
2127 riscv_opts.relax = FALSE;
2128 else if (strcmp (name, "push") == 0)
2129 {
2130 struct riscv_option_stack *s;
2131
2132 s = (struct riscv_option_stack *) xmalloc (sizeof *s);
2133 s->next = riscv_opts_stack;
2134 s->options = riscv_opts;
2135 riscv_opts_stack = s;
2136 }
2137 else if (strcmp (name, "pop") == 0)
2138 {
2139 struct riscv_option_stack *s;
2140
2141 s = riscv_opts_stack;
2142 if (s == NULL)
2143 as_bad (_(".option pop with no .option push"));
2144 else
2145 {
2146 riscv_opts = s->options;
2147 riscv_opts_stack = s->next;
2148 free (s);
2149 }
2150 }
2151 else
2152 {
2153 as_warn (_("Unrecognized .option directive: %s\n"), name);
2154 }
2155 *input_line_pointer = ch;
2156 demand_empty_rest_of_line ();
2157 }
2158
2159 /* Handle the .dtprelword and .dtpreldword pseudo-ops. They generate
2160 a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
2161 use in DWARF debug information. */
2162
2163 static void
2164 s_dtprel (int bytes)
2165 {
2166 expressionS ex;
2167 char *p;
2168
2169 expression (&ex);
2170
2171 if (ex.X_op != O_symbol)
2172 {
2173 as_bad (_("Unsupported use of %s"), (bytes == 8
2174 ? ".dtpreldword"
2175 : ".dtprelword"));
2176 ignore_rest_of_line ();
2177 }
2178
2179 p = frag_more (bytes);
2180 md_number_to_chars (p, 0, bytes);
2181 fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE,
2182 (bytes == 8
2183 ? BFD_RELOC_RISCV_TLS_DTPREL64
2184 : BFD_RELOC_RISCV_TLS_DTPREL32));
2185
2186 demand_empty_rest_of_line ();
2187 }
2188
2189 /* Handle the .bss pseudo-op. */
2190
2191 static void
2192 s_bss (int ignore ATTRIBUTE_UNUSED)
2193 {
2194 subseg_set (bss_section, 0);
2195 demand_empty_rest_of_line ();
2196 }
2197
2198 static void
2199 riscv_make_nops (char *buf, bfd_vma bytes)
2200 {
2201 bfd_vma i = 0;
2202
2203 /* RISC-V instructions cannot begin or end on odd addresses, so this case
2204 means we are not within a valid instruction sequence. It is thus safe
2205 to use a zero byte, even though that is not a valid instruction. */
2206 if (bytes % 2 == 1)
2207 buf[i++] = 0;
2208
2209 /* Use at most one 2-byte NOP. */
2210 if ((bytes - i) % 4 == 2)
2211 {
2212 md_number_to_chars (buf + i, RVC_NOP, 2);
2213 i += 2;
2214 }
2215
2216 /* Fill the remainder with 4-byte NOPs. */
2217 for ( ; i < bytes; i += 4)
2218 md_number_to_chars (buf + i, RISCV_NOP, 4);
2219 }
2220
2221 /* Called from md_do_align. Used to create an alignment frag in a
2222 code section by emitting a worst-case NOP sequence that the linker
2223 will later relax to the correct number of NOPs. We can't compute
2224 the correct alignment now because of other linker relaxations. */
2225
2226 bfd_boolean
2227 riscv_frag_align_code (int n)
2228 {
2229 bfd_vma bytes = (bfd_vma) 1 << n;
2230 bfd_vma min_text_alignment_order = riscv_opts.rvc ? 1 : 2;
2231 bfd_vma min_text_alignment = (bfd_vma) 1 << min_text_alignment_order;
2232
2233 /* First, get back to minimal alignment. */
2234 frag_align_code (min_text_alignment_order, 0);
2235
2236 /* When not relaxing, riscv_handle_align handles code alignment. */
2237 if (!riscv_opts.relax)
2238 return FALSE;
2239
2240 if (bytes > min_text_alignment)
2241 {
2242 bfd_vma worst_case_bytes = bytes - min_text_alignment;
2243 char *nops = frag_more (worst_case_bytes);
2244 expressionS ex;
2245
2246 ex.X_op = O_constant;
2247 ex.X_add_number = worst_case_bytes;
2248
2249 riscv_make_nops (nops, worst_case_bytes);
2250
2251 fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
2252 &ex, FALSE, BFD_RELOC_RISCV_ALIGN);
2253 }
2254
2255 return TRUE;
2256 }
2257
2258 /* Implement HANDLE_ALIGN. */
2259
2260 void
2261 riscv_handle_align (fragS *fragP)
2262 {
2263 switch (fragP->fr_type)
2264 {
2265 case rs_align_code:
2266 /* When relaxing, riscv_frag_align_code handles code alignment. */
2267 if (!riscv_opts.relax)
2268 {
2269 bfd_signed_vma count = fragP->fr_next->fr_address
2270 - fragP->fr_address - fragP->fr_fix;
2271
2272 if (count <= 0)
2273 break;
2274
2275 count &= MAX_MEM_FOR_RS_ALIGN_CODE;
2276 riscv_make_nops (fragP->fr_literal + fragP->fr_fix, count);
2277 fragP->fr_var = count;
2278 }
2279 break;
2280
2281 default:
2282 break;
2283 }
2284 }
2285
2286 int
2287 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
2288 {
2289 return (fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE));
2290 }
2291
2292 /* Translate internal representation of relocation info to BFD target
2293 format. */
2294
2295 arelent *
2296 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
2297 {
2298 arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
2299
2300 reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
2301 *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
2302 reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
2303 reloc->addend = fixp->fx_addnumber;
2304
2305 reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
2306 if (reloc->howto == NULL)
2307 {
2308 if ((fixp->fx_r_type == BFD_RELOC_16 || fixp->fx_r_type == BFD_RELOC_8)
2309 && fixp->fx_addsy != NULL && fixp->fx_subsy != NULL)
2310 {
2311 /* We don't have R_RISCV_8/16, but for this special case,
2312 we can use R_RISCV_ADD8/16 with R_RISCV_SUB8/16. */
2313 return reloc;
2314 }
2315
2316 as_bad_where (fixp->fx_file, fixp->fx_line,
2317 _("cannot represent %s relocation in object file"),
2318 bfd_get_reloc_code_name (fixp->fx_r_type));
2319 return NULL;
2320 }
2321
2322 return reloc;
2323 }
2324
2325 int
2326 riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
2327 {
2328 if (RELAX_BRANCH_P (fragp->fr_subtype))
2329 {
2330 offsetT old_var = fragp->fr_var;
2331 fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
2332 return fragp->fr_var - old_var;
2333 }
2334
2335 return 0;
2336 }
2337
2338 /* Expand far branches to multi-instruction sequences. */
2339
2340 static void
2341 md_convert_frag_branch (fragS *fragp)
2342 {
2343 bfd_byte *buf;
2344 expressionS exp;
2345 fixS *fixp;
2346 insn_t insn;
2347 int rs1, reloc;
2348
2349 buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
2350
2351 exp.X_op = O_symbol;
2352 exp.X_add_symbol = fragp->fr_symbol;
2353 exp.X_add_number = fragp->fr_offset;
2354
2355 gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
2356
2357 if (RELAX_BRANCH_RVC (fragp->fr_subtype))
2358 {
2359 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
2360 {
2361 case 8:
2362 case 4:
2363 /* Expand the RVC branch into a RISC-V one. */
2364 insn = bfd_getl16 (buf);
2365 rs1 = 8 + ((insn >> OP_SH_CRS1S) & OP_MASK_CRS1S);
2366 if ((insn & MASK_C_J) == MATCH_C_J)
2367 insn = MATCH_JAL;
2368 else if ((insn & MASK_C_JAL) == MATCH_C_JAL)
2369 insn = MATCH_JAL | (X_RA << OP_SH_RD);
2370 else if ((insn & MASK_C_BEQZ) == MATCH_C_BEQZ)
2371 insn = MATCH_BEQ | (rs1 << OP_SH_RS1);
2372 else if ((insn & MASK_C_BNEZ) == MATCH_C_BNEZ)
2373 insn = MATCH_BNE | (rs1 << OP_SH_RS1);
2374 else
2375 abort ();
2376 bfd_putl32 (insn, buf);
2377 break;
2378
2379 case 6:
2380 /* Invert the branch condition. Branch over the jump. */
2381 insn = bfd_getl16 (buf);
2382 insn ^= MATCH_C_BEQZ ^ MATCH_C_BNEZ;
2383 insn |= ENCODE_RVC_B_IMM (6);
2384 bfd_putl16 (insn, buf);
2385 buf += 2;
2386 goto jump;
2387
2388 case 2:
2389 /* Just keep the RVC branch. */
2390 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
2391 ? BFD_RELOC_RISCV_RVC_JUMP : BFD_RELOC_RISCV_RVC_BRANCH;
2392 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2393 2, &exp, FALSE, reloc);
2394 buf += 2;
2395 goto done;
2396
2397 default:
2398 abort ();
2399 }
2400 }
2401
2402 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
2403 {
2404 case 8:
2405 gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
2406
2407 /* Invert the branch condition. Branch over the jump. */
2408 insn = bfd_getl32 (buf);
2409 insn ^= MATCH_BEQ ^ MATCH_BNE;
2410 insn |= ENCODE_SBTYPE_IMM (8);
2411 md_number_to_chars ((char *) buf, insn, 4);
2412 buf += 4;
2413
2414 jump:
2415 /* Jump to the target. */
2416 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2417 4, &exp, FALSE, BFD_RELOC_RISCV_JMP);
2418 md_number_to_chars ((char *) buf, MATCH_JAL, 4);
2419 buf += 4;
2420 break;
2421
2422 case 4:
2423 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
2424 ? BFD_RELOC_RISCV_JMP : BFD_RELOC_12_PCREL;
2425 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2426 4, &exp, FALSE, reloc);
2427 buf += 4;
2428 break;
2429
2430 default:
2431 abort ();
2432 }
2433
2434 done:
2435 fixp->fx_file = fragp->fr_file;
2436 fixp->fx_line = fragp->fr_line;
2437
2438 gas_assert (buf == (bfd_byte *)fragp->fr_literal
2439 + fragp->fr_fix + fragp->fr_var);
2440
2441 fragp->fr_fix += fragp->fr_var;
2442 }
2443
2444 /* Relax a machine dependent frag. This returns the amount by which
2445 the current size of the frag should change. */
2446
2447 void
2448 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
2449 fragS *fragp)
2450 {
2451 gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
2452 md_convert_frag_branch (fragp);
2453 }
2454
2455 void
2456 md_show_usage (FILE *stream)
2457 {
2458 fprintf (stream, _("\
2459 RISC-V options:\n\
2460 -m32 assemble RV32 code\n\
2461 -m64 assemble RV64 code (default)\n\
2462 -fpic generate position-independent code\n\
2463 -fno-pic don't generate position-independent code (default)\n\
2464 -msoft-float don't use F registers for floating-point values\n\
2465 -mhard-float use F registers for floating-point values (default)\n\
2466 -mno-rvc disable the C extension for compressed instructions (default)\n\
2467 -mrvc enable the C extension for compressed instructions\n\
2468 -march=ISA set the RISC-V architecture, RV64IMAFD by default\n\
2469 "));
2470 }
2471
2472 /* Standard calling conventions leave the CFA at SP on entry. */
2473 void
2474 riscv_cfi_frame_initial_instructions (void)
2475 {
2476 cfi_add_CFA_def_cfa_register (X_SP);
2477 }
2478
2479 int
2480 tc_riscv_regname_to_dw2regnum (char *regname)
2481 {
2482 int reg;
2483
2484 if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
2485 return reg;
2486
2487 if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
2488 return reg + 32;
2489
2490 as_bad (_("unknown register `%s'"), regname);
2491 return -1;
2492 }
2493
2494 void
2495 riscv_elf_final_processing (void)
2496 {
2497 elf_elfheader (stdoutput)->e_flags |= elf_flags;
2498 }
2499
2500 /* Parse the .sleb128 and .uleb128 pseudos. Only allow constant expressions,
2501 since these directives break relaxation when used with symbol deltas. */
2502
2503 static void
2504 s_riscv_leb128 (int sign)
2505 {
2506 expressionS exp;
2507 char *save_in = input_line_pointer;
2508
2509 expression (&exp);
2510 if (exp.X_op != O_constant)
2511 as_bad (_("non-constant .%cleb128 is not supported"), sign ? 's' : 'u');
2512 demand_empty_rest_of_line ();
2513
2514 input_line_pointer = save_in;
2515 return s_leb128 (sign);
2516 }
2517
2518 /* Pseudo-op table. */
2519
2520 static const pseudo_typeS riscv_pseudo_table[] =
2521 {
2522 /* RISC-V-specific pseudo-ops. */
2523 {"option", s_riscv_option, 0},
2524 {"half", cons, 2},
2525 {"word", cons, 4},
2526 {"dword", cons, 8},
2527 {"dtprelword", s_dtprel, 4},
2528 {"dtpreldword", s_dtprel, 8},
2529 {"bss", s_bss, 0},
2530 {"uleb128", s_riscv_leb128, 0},
2531 {"sleb128", s_riscv_leb128, 1},
2532
2533 { NULL, NULL, 0 },
2534 };
2535
2536 void
2537 riscv_pop_insert (void)
2538 {
2539 extern void pop_insert (const pseudo_typeS *);
2540
2541 pop_insert (riscv_pseudo_table);
2542 }
This page took 0.079003 seconds and 5 git commands to generate.