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