gdb/riscv: Give user-friendly names for CSRs
[external/binutils.git] / gdb / riscv-tdep.c
1 /* Target-dependent code for the RISC-V architecture, for GDB.
2
3    Copyright (C) 2018 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "frame.h"
22 #include "inferior.h"
23 #include "symtab.h"
24 #include "value.h"
25 #include "gdbcmd.h"
26 #include "language.h"
27 #include "gdbcore.h"
28 #include "symfile.h"
29 #include "objfiles.h"
30 #include "gdbtypes.h"
31 #include "target.h"
32 #include "arch-utils.h"
33 #include "regcache.h"
34 #include "osabi.h"
35 #include "riscv-tdep.h"
36 #include "block.h"
37 #include "reggroups.h"
38 #include "opcode/riscv.h"
39 #include "elf/riscv.h"
40 #include "elf-bfd.h"
41 #include "symcat.h"
42 #include "dis-asm.h"
43 #include "frame-unwind.h"
44 #include "frame-base.h"
45 #include "trad-frame.h"
46 #include "infcall.h"
47 #include "floatformat.h"
48 #include "remote.h"
49 #include "target-descriptions.h"
50 #include "dwarf2-frame.h"
51 #include "user-regs.h"
52 #include "valprint.h"
53 #include "common-defs.h"
54 #include "opcode/riscv-opc.h"
55 #include "cli/cli-decode.h"
56 #include "observable.h"
57 #include "prologue-value.h"
58
59 /* The stack must be 16-byte aligned.  */
60 #define SP_ALIGNMENT 16
61
62 /* Forward declarations.  */
63 static bool riscv_has_feature (struct gdbarch *gdbarch, char feature);
64
65 /* Define a series of is_XXX_insn functions to check if the value INSN
66    is an instance of instruction XXX.  */
67 #define DECLARE_INSN(INSN_NAME, INSN_MATCH, INSN_MASK) \
68 static inline bool is_ ## INSN_NAME ## _insn (long insn) \
69 { \
70   return (insn & INSN_MASK) == INSN_MATCH; \
71 }
72 #include "opcode/riscv-opc.h"
73 #undef DECLARE_INSN
74
75 /* Cached information about a frame.  */
76
77 struct riscv_unwind_cache
78 {
79   /* The register from which we can calculate the frame base.  This is
80      usually $sp or $fp.  */
81   int frame_base_reg;
82
83   /* The offset from the current value in register FRAME_BASE_REG to the
84      actual frame base address.  */
85   int frame_base_offset;
86
87   /* Information about previous register values.  */
88   struct trad_frame_saved_reg *regs;
89
90   /* The id for this frame.  */
91   struct frame_id this_id;
92
93   /* The base (stack) address for this frame.  This is the stack pointer
94      value on entry to this frame before any adjustments are made.  */
95   CORE_ADDR frame_base;
96 };
97
98 /* The preferred register names for all the general purpose and floating
99    point registers.  These are what GDB will use when referencing a
100    register.  */
101
102 static const char * const riscv_gdb_reg_names[RISCV_LAST_FP_REGNUM + 1] =
103 {
104  "zero", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "fp", "s1",
105  "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "s2", "s3", "s4",
106  "s5", "s6", "s7", "s8", "s9", "s10", "s11", "t3", "t4", "t5", "t6",
107  "pc",
108  "ft0", "ft1", "ft2", "ft3", "ft4", "ft5", "ft6", "ft7", "fs0", "fs1",
109  "fa0", "fa1", "fa2", "fa3", "fa4", "fa5", "fa6", "fa7", "fs2", "fs3",
110  "fs4", "fs5", "fs6", "fs7", "fs8", "fs9", "fs10", "fs11", "ft8", "ft9",
111  "ft10", "ft11",
112 };
113
114 /* Map alternative register names onto their GDB register number.  */
115
116 struct riscv_register_alias
117 {
118   /* The register alias.  Usually more descriptive than the
119      architectural name of the register.  */
120   const char *name;
121
122   /* The GDB register number.  */
123   int regnum;
124 };
125
126 /* Table of register aliases.  */
127
128 static const struct riscv_register_alias riscv_register_aliases[] =
129 {
130  /* Aliases for general purpose registers.  These are the architectural
131     names, as GDB uses the more user friendly names by default.  */
132  { "x0", (RISCV_ZERO_REGNUM + 0) },
133  { "x1", (RISCV_ZERO_REGNUM + 1) },
134  { "x2", (RISCV_ZERO_REGNUM + 2) },
135  { "x3", (RISCV_ZERO_REGNUM + 3) },
136  { "x4", (RISCV_ZERO_REGNUM + 4) },
137  { "x5", (RISCV_ZERO_REGNUM + 5) },
138  { "x6", (RISCV_ZERO_REGNUM + 6) },
139  { "x7", (RISCV_ZERO_REGNUM + 7) },
140  { "x8", (RISCV_ZERO_REGNUM + 8) },
141  { "s0", (RISCV_ZERO_REGNUM + 8) },     /* fp, s0, and x8 are all aliases.  */
142  { "x9", (RISCV_ZERO_REGNUM + 9) },
143  { "x10", (RISCV_ZERO_REGNUM + 10) },
144  { "x11", (RISCV_ZERO_REGNUM + 11) },
145  { "x12", (RISCV_ZERO_REGNUM + 12) },
146  { "x13", (RISCV_ZERO_REGNUM + 13) },
147  { "x14", (RISCV_ZERO_REGNUM + 14) },
148  { "x15", (RISCV_ZERO_REGNUM + 15) },
149  { "x16", (RISCV_ZERO_REGNUM + 16) },
150  { "x17", (RISCV_ZERO_REGNUM + 17) },
151  { "x18", (RISCV_ZERO_REGNUM + 18) },
152  { "x19", (RISCV_ZERO_REGNUM + 19) },
153  { "x20", (RISCV_ZERO_REGNUM + 20) },
154  { "x21", (RISCV_ZERO_REGNUM + 21) },
155  { "x22", (RISCV_ZERO_REGNUM + 22) },
156  { "x23", (RISCV_ZERO_REGNUM + 23) },
157  { "x24", (RISCV_ZERO_REGNUM + 24) },
158  { "x25", (RISCV_ZERO_REGNUM + 25) },
159  { "x26", (RISCV_ZERO_REGNUM + 26) },
160  { "x27", (RISCV_ZERO_REGNUM + 27) },
161  { "x28", (RISCV_ZERO_REGNUM + 28) },
162  { "x29", (RISCV_ZERO_REGNUM + 29) },
163  { "x30", (RISCV_ZERO_REGNUM + 30) },
164  { "x31", (RISCV_ZERO_REGNUM + 31) },
165
166  /* Aliases for the floating-point registers.  These are the architectural
167     names as GDB uses the more user friendly names by default.  */
168  { "f0", (RISCV_FIRST_FP_REGNUM + 0) },
169  { "f1", (RISCV_FIRST_FP_REGNUM + 1) },
170  { "f2", (RISCV_FIRST_FP_REGNUM + 2) },
171  { "f3", (RISCV_FIRST_FP_REGNUM + 3) },
172  { "f4", (RISCV_FIRST_FP_REGNUM + 4) },
173  { "f5", (RISCV_FIRST_FP_REGNUM + 5) },
174  { "f6", (RISCV_FIRST_FP_REGNUM + 6) },
175  { "f7", (RISCV_FIRST_FP_REGNUM + 7) },
176  { "f8", (RISCV_FIRST_FP_REGNUM + 8) },
177  { "f9", (RISCV_FIRST_FP_REGNUM + 9) },
178  { "f10", (RISCV_FIRST_FP_REGNUM + 10) },
179  { "f11", (RISCV_FIRST_FP_REGNUM + 11) },
180  { "f12", (RISCV_FIRST_FP_REGNUM + 12) },
181  { "f13", (RISCV_FIRST_FP_REGNUM + 13) },
182  { "f14", (RISCV_FIRST_FP_REGNUM + 14) },
183  { "f15", (RISCV_FIRST_FP_REGNUM + 15) },
184  { "f16", (RISCV_FIRST_FP_REGNUM + 16) },
185  { "f17", (RISCV_FIRST_FP_REGNUM + 17) },
186  { "f18", (RISCV_FIRST_FP_REGNUM + 18) },
187  { "f19", (RISCV_FIRST_FP_REGNUM + 19) },
188  { "f20", (RISCV_FIRST_FP_REGNUM + 20) },
189  { "f21", (RISCV_FIRST_FP_REGNUM + 21) },
190  { "f22", (RISCV_FIRST_FP_REGNUM + 22) },
191  { "f23", (RISCV_FIRST_FP_REGNUM + 23) },
192  { "f24", (RISCV_FIRST_FP_REGNUM + 24) },
193  { "f25", (RISCV_FIRST_FP_REGNUM + 25) },
194  { "f26", (RISCV_FIRST_FP_REGNUM + 26) },
195  { "f27", (RISCV_FIRST_FP_REGNUM + 27) },
196  { "f28", (RISCV_FIRST_FP_REGNUM + 28) },
197  { "f29", (RISCV_FIRST_FP_REGNUM + 29) },
198  { "f30", (RISCV_FIRST_FP_REGNUM + 30) },
199  { "f31", (RISCV_FIRST_FP_REGNUM + 31) },
200 };
201
202 /* Controls whether we place compressed breakpoints or not.  When in auto
203    mode GDB tries to determine if the target supports compressed
204    breakpoints, and uses them if it does.  */
205
206 static enum auto_boolean use_compressed_breakpoints;
207
208 /* The show callback for 'show riscv use-compressed-breakpoints'.  */
209
210 static void
211 show_use_compressed_breakpoints (struct ui_file *file, int from_tty,
212                                  struct cmd_list_element *c,
213                                  const char *value)
214 {
215   fprintf_filtered (file,
216                     _("Debugger's use of compressed breakpoints is set "
217                       "to %s.\n"), value);
218 }
219
220 /* The set and show lists for 'set riscv' and 'show riscv' prefixes.  */
221
222 static struct cmd_list_element *setriscvcmdlist = NULL;
223 static struct cmd_list_element *showriscvcmdlist = NULL;
224
225 /* The show callback for the 'show riscv' prefix command.  */
226
227 static void
228 show_riscv_command (const char *args, int from_tty)
229 {
230   help_list (showriscvcmdlist, "show riscv ", all_commands, gdb_stdout);
231 }
232
233 /* The set callback for the 'set riscv' prefix command.  */
234
235 static void
236 set_riscv_command (const char *args, int from_tty)
237 {
238   printf_unfiltered
239     (_("\"set riscv\" must be followed by an appropriate subcommand.\n"));
240   help_list (setriscvcmdlist, "set riscv ", all_commands, gdb_stdout);
241 }
242
243 /* The set and show lists for 'set riscv' and 'show riscv' prefixes.  */
244
245 static struct cmd_list_element *setdebugriscvcmdlist = NULL;
246 static struct cmd_list_element *showdebugriscvcmdlist = NULL;
247
248 /* The show callback for the 'show debug riscv' prefix command.  */
249
250 static void
251 show_debug_riscv_command (const char *args, int from_tty)
252 {
253   help_list (showdebugriscvcmdlist, "show debug riscv ", all_commands, gdb_stdout);
254 }
255
256 /* The set callback for the 'set debug riscv' prefix command.  */
257
258 static void
259 set_debug_riscv_command (const char *args, int from_tty)
260 {
261   printf_unfiltered
262     (_("\"set debug riscv\" must be followed by an appropriate subcommand.\n"));
263   help_list (setdebugriscvcmdlist, "set debug riscv ", all_commands, gdb_stdout);
264 }
265
266 /* The show callback for all 'show debug riscv VARNAME' variables.  */
267
268 static void
269 show_riscv_debug_variable (struct ui_file *file, int from_tty,
270                            struct cmd_list_element *c,
271                            const char *value)
272 {
273   fprintf_filtered (file,
274                     _("RiscV debug variable `%s' is set to: %s\n"),
275                     c->name, value);
276 }
277
278 /* When this is set to non-zero debugging information about breakpoint
279    kinds will be printed.  */
280
281 static unsigned int riscv_debug_breakpoints = 0;
282
283 /* When this is set to non-zero debugging information about inferior calls
284    will be printed.  */
285
286 static unsigned int riscv_debug_infcall = 0;
287
288 /* When this is set to non-zero debugging information about stack unwinding
289    will be printed.  */
290
291 static unsigned int riscv_debug_unwinder = 0;
292
293 /* Read the MISA register from the target.  The register will only be read
294    once, and the value read will be cached.  If the register can't be read
295    from the target then a default value (0) will be returned.  If the
296    pointer READ_P is not null, then the bool pointed to is updated  to
297    indicate if the value returned was read from the target (true) or is the
298    default (false).  */
299
300 static uint32_t
301 riscv_read_misa_reg (bool *read_p)
302 {
303   uint32_t value = 0;
304
305   if (target_has_registers)
306     {
307       struct frame_info *frame = get_current_frame ();
308
309       TRY
310         {
311           value = get_frame_register_unsigned (frame,
312                                                RISCV_CSR_MISA_REGNUM);
313         }
314       CATCH (ex, RETURN_MASK_ERROR)
315         {
316           /* Old cores might have MISA located at a different offset.  */
317           value = get_frame_register_unsigned (frame,
318                                                RISCV_CSR_LEGACY_MISA_REGNUM);
319         }
320       END_CATCH
321     }
322
323   return value;
324 }
325
326 /* Return true if FEATURE is available for the architecture GDBARCH.  The
327    FEATURE should be one of the single character feature codes described in
328    the RiscV ISA manual, these are between 'A' and 'Z'.  */
329
330 static bool
331 riscv_has_feature (struct gdbarch *gdbarch, char feature)
332 {
333   bool have_read_misa = false;
334   uint32_t misa;
335
336   gdb_assert (feature >= 'A' && feature <= 'Z');
337
338   misa = riscv_read_misa_reg (&have_read_misa);
339   if (!have_read_misa || misa == 0)
340     misa = gdbarch_tdep (gdbarch)->core_features;
341
342   return (misa & (1 << (feature - 'A'))) != 0;
343 }
344
345 /* Return the width in bytes  of the general purpose registers for GDBARCH.
346    Possible return values are 4, 8, or 16 for RiscV variants RV32, RV64, or
347    RV128.  */
348
349 int
350 riscv_isa_xlen (struct gdbarch *gdbarch)
351 {
352   switch (gdbarch_tdep (gdbarch)->abi.fields.base_len)
353     {
354     default:
355       warning (_("unknown xlen size, assuming 4 bytes"));
356       /* Fall through.  */
357     case 1:
358       return 4;
359     case 2:
360       return 8;
361     case 3:
362       return 16;
363     }
364 }
365
366 /* Return the width in bytes of the floating point registers for GDBARCH.
367    If this architecture has no floating point registers, then return 0.
368    Possible values are 4, 8, or 16 for depending on which of single, double
369    or quad floating point support is available.  */
370
371 static int
372 riscv_isa_flen (struct gdbarch *gdbarch)
373 {
374   if (riscv_has_feature (gdbarch, 'Q'))
375     return 16;
376   else if (riscv_has_feature (gdbarch, 'D'))
377     return 8;
378   else if (riscv_has_feature (gdbarch, 'F'))
379     return 4;
380
381   return 0;
382 }
383
384 /* Return true if the target for GDBARCH has floating point hardware.  */
385
386 static bool
387 riscv_has_fp_regs (struct gdbarch *gdbarch)
388 {
389   return (riscv_isa_flen (gdbarch) > 0);
390 }
391
392 /* Return true if GDBARCH is using any of the floating point hardware ABIs.  */
393
394 static bool
395 riscv_has_fp_abi (struct gdbarch *gdbarch)
396 {
397   return (gdbarch_tdep (gdbarch)->abi.fields.float_abi != 0);
398 }
399
400 /* Return true if REGNO is a floating pointer register.  */
401
402 static bool
403 riscv_is_fp_regno_p (int regno)
404 {
405   return (regno >= RISCV_FIRST_FP_REGNUM
406           && regno <= RISCV_LAST_FP_REGNUM);
407 }
408
409 /* Implement the breakpoint_kind_from_pc gdbarch method.  */
410
411 static int
412 riscv_breakpoint_kind_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr)
413 {
414   if (use_compressed_breakpoints == AUTO_BOOLEAN_AUTO)
415     {
416       gdb_byte buf[1];
417
418       /* Read the opcode byte to determine the instruction length.  */
419       read_code (*pcptr, buf, 1);
420
421       if (riscv_debug_breakpoints)
422         fprintf_unfiltered
423           (gdb_stdlog,
424            "Using %s for breakpoint at %s (instruction length %d)\n",
425            riscv_insn_length (buf[0]) == 2 ? "C.EBREAK" : "EBREAK",
426            paddress (gdbarch, *pcptr), riscv_insn_length (buf[0]));
427       if (riscv_insn_length (buf[0]) == 2)
428         return 2;
429       else
430         return 4;
431     }
432   else if (use_compressed_breakpoints == AUTO_BOOLEAN_TRUE)
433     return 2;
434   else
435     return 4;
436 }
437
438 /* Implement the sw_breakpoint_from_kind gdbarch method.  */
439
440 static const gdb_byte *
441 riscv_sw_breakpoint_from_kind (struct gdbarch *gdbarch, int kind, int *size)
442 {
443   static const gdb_byte ebreak[] = { 0x73, 0x00, 0x10, 0x00, };
444   static const gdb_byte c_ebreak[] = { 0x02, 0x90 };
445
446   *size = kind;
447   switch (kind)
448     {
449     case 2:
450       return c_ebreak;
451     case 4:
452       return ebreak;
453     default:
454       gdb_assert_not_reached (_("unhandled breakpoint kind"));
455     }
456 }
457
458 /* Callback function for user_reg_add.  */
459
460 static struct value *
461 value_of_riscv_user_reg (struct frame_info *frame, const void *baton)
462 {
463   const int *reg_p = (const int *) baton;
464   return value_of_register (*reg_p, frame);
465 }
466
467 /* Implement the register_name gdbarch method.  */
468
469 static const char *
470 riscv_register_name (struct gdbarch *gdbarch, int regnum)
471 {
472   /* Prefer to use the alias. */
473   if (regnum >= RISCV_ZERO_REGNUM && regnum <= RISCV_LAST_FP_REGNUM)
474     {
475       gdb_assert (regnum < ARRAY_SIZE (riscv_gdb_reg_names));
476       return riscv_gdb_reg_names[regnum];
477     }
478
479   /* Check that there's no gap between the set of registers handled above,
480      and the set of registers handled next.  */
481   gdb_assert ((RISCV_LAST_FP_REGNUM + 1) == RISCV_FIRST_CSR_REGNUM);
482
483   if (regnum >= RISCV_FIRST_CSR_REGNUM && regnum <= RISCV_LAST_CSR_REGNUM)
484     {
485 #define DECLARE_CSR(NAME,VALUE) \
486       case RISCV_ ## VALUE ## _REGNUM: return # NAME;
487
488       switch (regnum)
489         {
490           #include "opcode/riscv-opc.h"
491         default:
492           {
493             static char buf[20];
494
495             xsnprintf (buf, sizeof (buf), "csr%d",
496                        regnum - RISCV_FIRST_CSR_REGNUM);
497             return buf;
498           }
499         }
500 #undef DECLARE_CSR
501     }
502
503   if (regnum == RISCV_PRIV_REGNUM)
504     return "priv";
505
506   return NULL;
507 }
508
509 /* Construct a type for 64-bit FP registers.  */
510
511 static struct type *
512 riscv_fpreg_d_type (struct gdbarch *gdbarch)
513 {
514   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
515
516   if (tdep->riscv_fpreg_d_type == nullptr)
517     {
518       const struct builtin_type *bt = builtin_type (gdbarch);
519
520       /* The type we're building is this: */
521 #if 0
522       union __gdb_builtin_type_fpreg_d
523       {
524         float f;
525         double d;
526       };
527 #endif
528
529       struct type *t;
530
531       t = arch_composite_type (gdbarch,
532                                "__gdb_builtin_type_fpreg_d", TYPE_CODE_UNION);
533       append_composite_type_field (t, "float", bt->builtin_float);
534       append_composite_type_field (t, "double", bt->builtin_double);
535       TYPE_VECTOR (t) = 1;
536       TYPE_NAME (t) = "builtin_type_fpreg_d";
537       tdep->riscv_fpreg_d_type = t;
538     }
539
540   return tdep->riscv_fpreg_d_type;
541 }
542
543 /* Construct a type for 128-bit FP registers.  */
544
545 static struct type *
546 riscv_fpreg_q_type (struct gdbarch *gdbarch)
547 {
548   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
549
550   if (tdep->riscv_fpreg_q_type == nullptr)
551     {
552       const struct builtin_type *bt = builtin_type (gdbarch);
553
554       /* The type we're building is this: */
555 #if 0
556       union __gdb_builtin_type_fpreg_d
557       {
558         float f;
559         double d;
560         long double ld;
561       };
562 #endif
563
564       struct type *t;
565
566       t = arch_composite_type (gdbarch,
567                                "__gdb_builtin_type_fpreg_q", TYPE_CODE_UNION);
568       append_composite_type_field (t, "float", bt->builtin_float);
569       append_composite_type_field (t, "double", bt->builtin_double);
570       append_composite_type_field (t, "long double", bt->builtin_long_double);
571       TYPE_VECTOR (t) = 1;
572       TYPE_NAME (t) = "builtin_type_fpreg_q";
573       tdep->riscv_fpreg_q_type = t;
574     }
575
576   return tdep->riscv_fpreg_q_type;
577 }
578
579 /* Implement the register_type gdbarch method.  */
580
581 static struct type *
582 riscv_register_type (struct gdbarch *gdbarch, int regnum)
583 {
584   int regsize;
585
586   if (regnum < RISCV_FIRST_FP_REGNUM)
587     {
588       if (regnum == gdbarch_pc_regnum (gdbarch)
589           || regnum == RISCV_RA_REGNUM)
590         return builtin_type (gdbarch)->builtin_func_ptr;
591
592       if (regnum == RISCV_FP_REGNUM
593           || regnum == RISCV_SP_REGNUM
594           || regnum == RISCV_GP_REGNUM
595           || regnum == RISCV_TP_REGNUM)
596         return builtin_type (gdbarch)->builtin_data_ptr;
597
598       /* Remaining GPRs vary in size based on the current ISA.  */
599       regsize = riscv_isa_xlen (gdbarch);
600       switch (regsize)
601         {
602         case 4:
603           return builtin_type (gdbarch)->builtin_uint32;
604         case 8:
605           return builtin_type (gdbarch)->builtin_uint64;
606         case 16:
607           return builtin_type (gdbarch)->builtin_uint128;
608         default:
609           internal_error (__FILE__, __LINE__,
610                           _("unknown isa regsize %i"), regsize);
611         }
612     }
613   else if (regnum <= RISCV_LAST_FP_REGNUM)
614     {
615       regsize = riscv_isa_xlen (gdbarch);
616       switch (regsize)
617         {
618         case 4:
619           return builtin_type (gdbarch)->builtin_float;
620         case 8:
621           return riscv_fpreg_d_type (gdbarch);
622         case 16:
623           return riscv_fpreg_q_type (gdbarch);
624         default:
625           internal_error (__FILE__, __LINE__,
626                           _("unknown isa regsize %i"), regsize);
627         }
628     }
629   else if (regnum == RISCV_PRIV_REGNUM)
630     return builtin_type (gdbarch)->builtin_int8;
631   else
632     {
633       if (regnum == RISCV_CSR_FFLAGS_REGNUM
634           || regnum == RISCV_CSR_FRM_REGNUM
635           || regnum == RISCV_CSR_FCSR_REGNUM)
636         return builtin_type (gdbarch)->builtin_int32;
637
638       regsize = riscv_isa_xlen (gdbarch);
639       switch (regsize)
640         {
641         case 4:
642           return builtin_type (gdbarch)->builtin_int32;
643         case 8:
644           return builtin_type (gdbarch)->builtin_int64;
645         case 16:
646           return builtin_type (gdbarch)->builtin_int128;
647         default:
648           internal_error (__FILE__, __LINE__,
649                           _("unknown isa regsize %i"), regsize);
650         }
651     }
652 }
653
654 /* Helper for riscv_print_registers_info, prints info for a single register
655    REGNUM.  */
656
657 static void
658 riscv_print_one_register_info (struct gdbarch *gdbarch,
659                                struct ui_file *file,
660                                struct frame_info *frame,
661                                int regnum)
662 {
663   const char *name = gdbarch_register_name (gdbarch, regnum);
664   struct value *val = value_of_register (regnum, frame);
665   struct type *regtype = value_type (val);
666   int print_raw_format;
667   enum tab_stops { value_column_1 = 15 };
668
669   fputs_filtered (name, file);
670   print_spaces_filtered (value_column_1 - strlen (name), file);
671
672   print_raw_format = (value_entirely_available (val)
673                       && !value_optimized_out (val));
674
675   if (TYPE_CODE (regtype) == TYPE_CODE_FLT
676       || (TYPE_CODE (regtype) == TYPE_CODE_UNION
677           && TYPE_NFIELDS (regtype) == 2
678           && TYPE_CODE (TYPE_FIELD_TYPE (regtype, 0)) == TYPE_CODE_FLT
679           && TYPE_CODE (TYPE_FIELD_TYPE (regtype, 1)) == TYPE_CODE_FLT)
680       || (TYPE_CODE (regtype) == TYPE_CODE_UNION
681           && TYPE_NFIELDS (regtype) == 3
682           && TYPE_CODE (TYPE_FIELD_TYPE (regtype, 0)) == TYPE_CODE_FLT
683           && TYPE_CODE (TYPE_FIELD_TYPE (regtype, 1)) == TYPE_CODE_FLT
684           && TYPE_CODE (TYPE_FIELD_TYPE (regtype, 2)) == TYPE_CODE_FLT))
685     {
686       struct value_print_options opts;
687       const gdb_byte *valaddr = value_contents_for_printing (val);
688       enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (regtype));
689
690       get_user_print_options (&opts);
691       opts.deref_ref = 1;
692
693       val_print (regtype,
694                  value_embedded_offset (val), 0,
695                  file, 0, val, &opts, current_language);
696
697       if (print_raw_format)
698         {
699           fprintf_filtered (file, "\t(raw ");
700           print_hex_chars (file, valaddr, TYPE_LENGTH (regtype), byte_order,
701                            true);
702           fprintf_filtered (file, ")");
703         }
704     }
705   else
706     {
707       struct value_print_options opts;
708
709       /* Print the register in hex.  */
710       get_formatted_print_options (&opts, 'x');
711       opts.deref_ref = 1;
712       val_print (regtype,
713                  value_embedded_offset (val), 0,
714                  file, 0, val, &opts, current_language);
715
716       if (print_raw_format)
717         {
718           if (regnum == RISCV_CSR_MSTATUS_REGNUM)
719             {
720               LONGEST d;
721               int size = register_size (gdbarch, regnum);
722               unsigned xlen;
723
724               d = value_as_long (val);
725               xlen = size * 4;
726               fprintf_filtered (file,
727                                 "\tSD:%X VM:%02X MXR:%X PUM:%X MPRV:%X XS:%X "
728                                 "FS:%X MPP:%x HPP:%X SPP:%X MPIE:%X HPIE:%X "
729                                 "SPIE:%X UPIE:%X MIE:%X HIE:%X SIE:%X UIE:%X",
730                                 (int) ((d >> (xlen - 1)) & 0x1),
731                                 (int) ((d >> 24) & 0x1f),
732                                 (int) ((d >> 19) & 0x1),
733                                 (int) ((d >> 18) & 0x1),
734                                 (int) ((d >> 17) & 0x1),
735                                 (int) ((d >> 15) & 0x3),
736                                 (int) ((d >> 13) & 0x3),
737                                 (int) ((d >> 11) & 0x3),
738                                 (int) ((d >> 9) & 0x3),
739                                 (int) ((d >> 8) & 0x1),
740                                 (int) ((d >> 7) & 0x1),
741                                 (int) ((d >> 6) & 0x1),
742                                 (int) ((d >> 5) & 0x1),
743                                 (int) ((d >> 4) & 0x1),
744                                 (int) ((d >> 3) & 0x1),
745                                 (int) ((d >> 2) & 0x1),
746                                 (int) ((d >> 1) & 0x1),
747                                 (int) ((d >> 0) & 0x1));
748             }
749           else if (regnum == RISCV_CSR_MISA_REGNUM)
750             {
751               int base;
752               unsigned xlen, i;
753               LONGEST d;
754
755               d = value_as_long (val);
756               base = d >> 30;
757               xlen = 16;
758
759               for (; base > 0; base--)
760                 xlen *= 2;
761               fprintf_filtered (file, "\tRV%d", xlen);
762
763               for (i = 0; i < 26; i++)
764                 {
765                   if (d & (1 << i))
766                     fprintf_filtered (file, "%c", 'A' + i);
767                 }
768             }
769           else if (regnum == RISCV_CSR_FCSR_REGNUM
770                    || regnum == RISCV_CSR_FFLAGS_REGNUM
771                    || regnum == RISCV_CSR_FRM_REGNUM)
772             {
773               LONGEST d;
774
775               d = value_as_long (val);
776
777               fprintf_filtered (file, "\t");
778               if (regnum != RISCV_CSR_FRM_REGNUM)
779                 fprintf_filtered (file,
780                                   "RD:%01X NV:%d DZ:%d OF:%d UF:%d NX:%d",
781                                   (int) ((d >> 5) & 0x7),
782                                   (int) ((d >> 4) & 0x1),
783                                   (int) ((d >> 3) & 0x1),
784                                   (int) ((d >> 2) & 0x1),
785                                   (int) ((d >> 1) & 0x1),
786                                   (int) ((d >> 0) & 0x1));
787
788               if (regnum != RISCV_CSR_FFLAGS_REGNUM)
789                 {
790                   static const char * const sfrm[] =
791                     {
792                       "RNE (round to nearest; ties to even)",
793                       "RTZ (Round towards zero)",
794                       "RDN (Round down towards -INF)",
795                       "RUP (Round up towards +INF)",
796                       "RMM (Round to nearest; ties to max magnitude)",
797                       "INVALID[5]",
798                       "INVALID[6]",
799                       "dynamic rounding mode",
800                     };
801                   int frm = ((regnum == RISCV_CSR_FCSR_REGNUM)
802                              ? (d >> 5) : d) & 0x3;
803
804                   fprintf_filtered (file, "%sFRM:%i [%s]",
805                                     (regnum == RISCV_CSR_FCSR_REGNUM
806                                      ? " " : ""),
807                                     frm, sfrm[frm]);
808                 }
809             }
810           else if (regnum == RISCV_PRIV_REGNUM)
811             {
812               LONGEST d;
813               uint8_t priv;
814
815               d = value_as_long (val);
816               priv = d & 0xff;
817
818               if (priv < 4)
819                 {
820                   static const char * const sprv[] =
821                     {
822                       "User/Application",
823                       "Supervisor",
824                       "Hypervisor",
825                       "Machine"
826                     };
827                   fprintf_filtered (file, "\tprv:%d [%s]",
828                                     priv, sprv[priv]);
829                 }
830               else
831                 fprintf_filtered (file, "\tprv:%d [INVALID]", priv);
832             }
833           else
834             {
835               /* If not a vector register, print it also according to its
836                  natural format.  */
837               if (TYPE_VECTOR (regtype) == 0)
838                 {
839                   get_user_print_options (&opts);
840                   opts.deref_ref = 1;
841                   fprintf_filtered (file, "\t");
842                   val_print (regtype,
843                              value_embedded_offset (val), 0,
844                              file, 0, val, &opts, current_language);
845                 }
846             }
847         }
848     }
849   fprintf_filtered (file, "\n");
850 }
851
852 /* Return true if REGNUM is a valid CSR register.  The CSR register space
853    is sparsely populated, so not every number is a named CSR.  */
854
855 static bool
856 riscv_is_regnum_a_named_csr (int regnum)
857 {
858   gdb_assert (regnum >= RISCV_FIRST_CSR_REGNUM
859               && regnum <= RISCV_LAST_CSR_REGNUM);
860
861   switch (regnum)
862     {
863 #define DECLARE_CSR(name, num) case RISCV_ ## num ## _REGNUM:
864 #include "opcode/riscv-opc.h"
865 #undef DECLARE_CSR
866       return true;
867
868     default:
869       return false;
870     }
871 }
872
873 /* Implement the register_reggroup_p gdbarch method.  Is REGNUM a member
874    of REGGROUP?  */
875
876 static int
877 riscv_register_reggroup_p (struct gdbarch  *gdbarch, int regnum,
878                            struct reggroup *reggroup)
879 {
880   /* Used by 'info registers' and 'info registers <groupname>'.  */
881
882   if (gdbarch_register_name (gdbarch, regnum) == NULL
883       || gdbarch_register_name (gdbarch, regnum)[0] == '\0')
884     return 0;
885
886   if (reggroup == all_reggroup)
887     {
888       if (regnum < RISCV_FIRST_CSR_REGNUM || regnum == RISCV_PRIV_REGNUM)
889         return 1;
890       if (riscv_is_regnum_a_named_csr (regnum))
891         return 1;
892       return 0;
893     }
894   else if (reggroup == float_reggroup)
895     return (riscv_is_fp_regno_p (regnum)
896             || regnum == RISCV_CSR_FCSR_REGNUM
897             || regnum == RISCV_CSR_FFLAGS_REGNUM
898             || regnum == RISCV_CSR_FRM_REGNUM);
899   else if (reggroup == general_reggroup)
900     return regnum < RISCV_FIRST_FP_REGNUM;
901   else if (reggroup == restore_reggroup || reggroup == save_reggroup)
902     {
903       if (riscv_has_fp_regs (gdbarch))
904         return regnum <= RISCV_LAST_FP_REGNUM;
905       else
906         return regnum < RISCV_FIRST_FP_REGNUM;
907     }
908   else if (reggroup == system_reggroup)
909     {
910       if (regnum == RISCV_PRIV_REGNUM)
911         return 1;
912       if (regnum < RISCV_FIRST_CSR_REGNUM || regnum > RISCV_LAST_CSR_REGNUM)
913         return 0;
914       if (riscv_is_regnum_a_named_csr (regnum))
915         return 1;
916       return 0;
917     }
918   else if (reggroup == vector_reggroup)
919     return 0;
920   else
921     return 0;
922 }
923
924 /* Implement the print_registers_info gdbarch method.  This is used by
925    'info registers' and 'info all-registers'.  */
926
927 static void
928 riscv_print_registers_info (struct gdbarch *gdbarch,
929                             struct ui_file *file,
930                             struct frame_info *frame,
931                             int regnum, int print_all)
932 {
933   if (regnum != -1)
934     {
935       /* Print one specified register.  */
936       gdb_assert (regnum <= RISCV_LAST_REGNUM);
937       if (gdbarch_register_name (gdbarch, regnum) == NULL
938           || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
939         error (_("Not a valid register for the current processor type"));
940       riscv_print_one_register_info (gdbarch, file, frame, regnum);
941     }
942   else
943     {
944       struct reggroup *reggroup;
945
946       if (print_all)
947         reggroup = all_reggroup;
948       else
949         reggroup = general_reggroup;
950
951       for (regnum = 0; regnum <= RISCV_LAST_REGNUM; ++regnum)
952         {
953           /* Zero never changes, so might as well hide by default.  */
954           if (regnum == RISCV_ZERO_REGNUM && !print_all)
955             continue;
956
957           /* Registers with no name are not valid on this ISA.  */
958           if (gdbarch_register_name (gdbarch, regnum) == NULL
959               || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
960             continue;
961
962           /* Is the register in the group we're interested in?  */
963           if (!riscv_register_reggroup_p (gdbarch, regnum, reggroup))
964             continue;
965
966           riscv_print_one_register_info (gdbarch, file, frame, regnum);
967         }
968     }
969 }
970
971 /* Class that handles one decoded RiscV instruction.  */
972
973 class riscv_insn
974 {
975 public:
976
977   /* Enum of all the opcodes that GDB cares about during the prologue scan.  */
978   enum opcode
979     {
980       /* Unknown value is used at initialisation time.  */
981       UNKNOWN = 0,
982
983       /* These instructions are all the ones we are interested in during the
984          prologue scan.  */
985       ADD,
986       ADDI,
987       ADDIW,
988       ADDW,
989       AUIPC,
990       LUI,
991       SD,
992       SW,
993       /* These are needed for software breakopint support.  */
994       JAL,
995       JALR,
996       BEQ,
997       BNE,
998       BLT,
999       BGE,
1000       BLTU,
1001       BGEU,
1002       /* These are needed for stepping over atomic sequences.  */
1003       LR,
1004       SC,
1005
1006       /* Other instructions are not interesting during the prologue scan, and
1007          are ignored.  */
1008       OTHER
1009     };
1010
1011   riscv_insn ()
1012     : m_length (0),
1013       m_opcode (OTHER),
1014       m_rd (0),
1015       m_rs1 (0),
1016       m_rs2 (0)
1017   {
1018     /* Nothing.  */
1019   }
1020
1021   void decode (struct gdbarch *gdbarch, CORE_ADDR pc);
1022
1023   /* Get the length of the instruction in bytes.  */
1024   int length () const
1025   { return m_length; }
1026
1027   /* Get the opcode for this instruction.  */
1028   enum opcode opcode () const
1029   { return m_opcode; }
1030
1031   /* Get destination register field for this instruction.  This is only
1032      valid if the OPCODE implies there is such a field for this
1033      instruction.  */
1034   int rd () const
1035   { return m_rd; }
1036
1037   /* Get the RS1 register field for this instruction.  This is only valid
1038      if the OPCODE implies there is such a field for this instruction.  */
1039   int rs1 () const
1040   { return m_rs1; }
1041
1042   /* Get the RS2 register field for this instruction.  This is only valid
1043      if the OPCODE implies there is such a field for this instruction.  */
1044   int rs2 () const
1045   { return m_rs2; }
1046
1047   /* Get the immediate for this instruction in signed form.  This is only
1048      valid if the OPCODE implies there is such a field for this
1049      instruction.  */
1050   int imm_signed () const
1051   { return m_imm.s; }
1052
1053 private:
1054
1055   /* Extract 5 bit register field at OFFSET from instruction OPCODE.  */
1056   int decode_register_index (unsigned long opcode, int offset)
1057   {
1058     return (opcode >> offset) & 0x1F;
1059   }
1060
1061   /* Extract 5 bit register field at OFFSET from instruction OPCODE.  */
1062   int decode_register_index_short (unsigned long opcode, int offset)
1063   {
1064     return ((opcode >> offset) & 0x7) + 8;
1065   }
1066
1067   /* Helper for DECODE, decode 32-bit R-type instruction.  */
1068   void decode_r_type_insn (enum opcode opcode, ULONGEST ival)
1069   {
1070     m_opcode = opcode;
1071     m_rd = decode_register_index (ival, OP_SH_RD);
1072     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1073     m_rs2 = decode_register_index (ival, OP_SH_RS2);
1074   }
1075
1076   /* Helper for DECODE, decode 16-bit compressed R-type instruction.  */
1077   void decode_cr_type_insn (enum opcode opcode, ULONGEST ival)
1078   {
1079     m_opcode = opcode;
1080     m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
1081     m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1082   }
1083
1084   /* Helper for DECODE, decode 32-bit I-type instruction.  */
1085   void decode_i_type_insn (enum opcode opcode, ULONGEST ival)
1086   {
1087     m_opcode = opcode;
1088     m_rd = decode_register_index (ival, OP_SH_RD);
1089     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1090     m_imm.s = EXTRACT_ITYPE_IMM (ival);
1091   }
1092
1093   /* Helper for DECODE, decode 16-bit compressed I-type instruction.  */
1094   void decode_ci_type_insn (enum opcode opcode, ULONGEST ival)
1095   {
1096     m_opcode = opcode;
1097     m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
1098     m_imm.s = EXTRACT_RVC_IMM (ival);
1099   }
1100
1101   /* Helper for DECODE, decode 32-bit S-type instruction.  */
1102   void decode_s_type_insn (enum opcode opcode, ULONGEST ival)
1103   {
1104     m_opcode = opcode;
1105     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1106     m_rs2 = decode_register_index (ival, OP_SH_RS2);
1107     m_imm.s = EXTRACT_STYPE_IMM (ival);
1108   }
1109
1110   /* Helper for DECODE, decode 16-bit CS-type instruction.  The immediate
1111      encoding is different for each CS format instruction, so extracting
1112      the immediate is left up to the caller, who should pass the extracted
1113      immediate value through in IMM.  */
1114   void decode_cs_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1115   {
1116     m_opcode = opcode;
1117     m_imm.s = imm;
1118     m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1119     m_rs2 = decode_register_index_short (ival, OP_SH_CRS2S);
1120   }
1121
1122   /* Helper for DECODE, decode 16-bit CSS-type instruction.  The immediate
1123      encoding is different for each CSS format instruction, so extracting
1124      the immediate is left up to the caller, who should pass the extracted
1125      immediate value through in IMM.  */
1126   void decode_css_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1127   {
1128     m_opcode = opcode;
1129     m_imm.s = imm;
1130     m_rs1 = RISCV_SP_REGNUM;
1131     /* Not a compressed register number in this case.  */
1132     m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1133   }
1134
1135   /* Helper for DECODE, decode 32-bit U-type instruction.  */
1136   void decode_u_type_insn (enum opcode opcode, ULONGEST ival)
1137   {
1138     m_opcode = opcode;
1139     m_rd = decode_register_index (ival, OP_SH_RD);
1140     m_imm.s = EXTRACT_UTYPE_IMM (ival);
1141   }
1142
1143   /* Helper for DECODE, decode 32-bit J-type instruction.  */
1144   void decode_j_type_insn (enum opcode opcode, ULONGEST ival)
1145   {
1146     m_opcode = opcode;
1147     m_rd = decode_register_index (ival, OP_SH_RD);
1148     m_imm.s = EXTRACT_UJTYPE_IMM (ival);
1149   }
1150
1151   /* Helper for DECODE, decode 32-bit J-type instruction.  */
1152   void decode_cj_type_insn (enum opcode opcode, ULONGEST ival)
1153   {
1154     m_opcode = opcode;
1155     m_imm.s = EXTRACT_RVC_J_IMM (ival);
1156   }
1157
1158   void decode_b_type_insn (enum opcode opcode, ULONGEST ival)
1159   {
1160     m_opcode = opcode;
1161     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1162     m_rs2 = decode_register_index (ival, OP_SH_RS2);
1163     m_imm.s = EXTRACT_SBTYPE_IMM (ival);
1164   }
1165
1166   void decode_cb_type_insn (enum opcode opcode, ULONGEST ival)
1167   {
1168     m_opcode = opcode;
1169     m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1170     m_imm.s = EXTRACT_RVC_B_IMM (ival);
1171   }
1172
1173   /* Fetch instruction from target memory at ADDR, return the content of
1174      the instruction, and update LEN with the instruction length.  */
1175   static ULONGEST fetch_instruction (struct gdbarch *gdbarch,
1176                                      CORE_ADDR addr, int *len);
1177
1178   /* The length of the instruction in bytes.  Should be 2 or 4.  */
1179   int m_length;
1180
1181   /* The instruction opcode.  */
1182   enum opcode m_opcode;
1183
1184   /* The three possible registers an instruction might reference.  Not
1185      every instruction fills in all of these registers.  Which fields are
1186      valid depends on the opcode.  The naming of these fields matches the
1187      naming in the riscv isa manual.  */
1188   int m_rd;
1189   int m_rs1;
1190   int m_rs2;
1191
1192   /* Possible instruction immediate.  This is only valid if the instruction
1193      format contains an immediate, not all instruction, whether this is
1194      valid depends on the opcode.  Despite only having one format for now
1195      the immediate is packed into a union, later instructions might require
1196      an unsigned formatted immediate, having the union in place now will
1197      reduce the need for code churn later.  */
1198   union riscv_insn_immediate
1199   {
1200     riscv_insn_immediate ()
1201       : s (0)
1202     {
1203       /* Nothing.  */
1204     }
1205
1206     int s;
1207   } m_imm;
1208 };
1209
1210 /* Fetch instruction from target memory at ADDR, return the content of the
1211    instruction, and update LEN with the instruction length.  */
1212
1213 ULONGEST
1214 riscv_insn::fetch_instruction (struct gdbarch *gdbarch,
1215                                CORE_ADDR addr, int *len)
1216 {
1217   enum bfd_endian byte_order = gdbarch_byte_order_for_code (gdbarch);
1218   gdb_byte buf[8];
1219   int instlen, status;
1220
1221   /* All insns are at least 16 bits.  */
1222   status = target_read_memory (addr, buf, 2);
1223   if (status)
1224     memory_error (TARGET_XFER_E_IO, addr);
1225
1226   /* If we need more, grab it now.  */
1227   instlen = riscv_insn_length (buf[0]);
1228   gdb_assert (instlen <= sizeof (buf));
1229   *len = instlen;
1230
1231   if (instlen > 2)
1232     {
1233       status = target_read_memory (addr + 2, buf + 2, instlen - 2);
1234       if (status)
1235         memory_error (TARGET_XFER_E_IO, addr + 2);
1236     }
1237
1238   return extract_unsigned_integer (buf, instlen, byte_order);
1239 }
1240
1241 /* Fetch from target memory an instruction at PC and decode it.  */
1242
1243 void
1244 riscv_insn::decode (struct gdbarch *gdbarch, CORE_ADDR pc)
1245 {
1246   ULONGEST ival;
1247
1248   /* Fetch the instruction, and the instructions length.  */
1249   ival = fetch_instruction (gdbarch, pc, &m_length);
1250
1251   if (m_length == 4)
1252     {
1253       if (is_add_insn (ival))
1254         decode_r_type_insn (ADD, ival);
1255       else if (is_addw_insn (ival))
1256         decode_r_type_insn (ADDW, ival);
1257       else if (is_addi_insn (ival))
1258         decode_i_type_insn (ADDI, ival);
1259       else if (is_addiw_insn (ival))
1260         decode_i_type_insn (ADDIW, ival);
1261       else if (is_auipc_insn (ival))
1262         decode_u_type_insn (AUIPC, ival);
1263       else if (is_lui_insn (ival))
1264         decode_u_type_insn (LUI, ival);
1265       else if (is_sd_insn (ival))
1266         decode_s_type_insn (SD, ival);
1267       else if (is_sw_insn (ival))
1268         decode_s_type_insn (SW, ival);
1269       else if (is_jal_insn (ival))
1270         decode_j_type_insn (JAL, ival);
1271       else if (is_jalr_insn (ival))
1272         decode_i_type_insn (JALR, ival);
1273       else if (is_beq_insn (ival))
1274         decode_b_type_insn (BEQ, ival);
1275       else if (is_bne_insn (ival))
1276         decode_b_type_insn (BNE, ival);
1277       else if (is_blt_insn (ival))
1278         decode_b_type_insn (BLT, ival);
1279       else if (is_bge_insn (ival))
1280         decode_b_type_insn (BGE, ival);
1281       else if (is_bltu_insn (ival))
1282         decode_b_type_insn (BLTU, ival);
1283       else if (is_bgeu_insn (ival))
1284         decode_b_type_insn (BGEU, ival);
1285       else if (is_lr_w_insn (ival))
1286         decode_r_type_insn (LR, ival);
1287       else if (is_lr_d_insn (ival))
1288         decode_r_type_insn (LR, ival);
1289       else if (is_sc_w_insn (ival))
1290         decode_r_type_insn (SC, ival);
1291       else if (is_sc_d_insn (ival))
1292         decode_r_type_insn (SC, ival);
1293       else
1294         /* None of the other fields are valid in this case.  */
1295         m_opcode = OTHER;
1296     }
1297   else if (m_length == 2)
1298     {
1299       int xlen = riscv_isa_xlen (gdbarch);
1300
1301       /* C_ADD and C_JALR have the same opcode.  If RS2 is 0, then this is a
1302          C_JALR.  So must try to match C_JALR first as it has more bits in
1303          mask.  */
1304       if (is_c_jalr_insn (ival))
1305         decode_cr_type_insn (JALR, ival);
1306       else if (is_c_add_insn (ival))
1307         decode_cr_type_insn (ADD, ival);
1308       /* C_ADDW is RV64 and RV128 only.  */
1309       else if (xlen != 4 && is_c_addw_insn (ival))
1310         decode_cr_type_insn (ADDW, ival);
1311       else if (is_c_addi_insn (ival))
1312         decode_ci_type_insn (ADDI, ival);
1313       /* C_ADDIW and C_JAL have the same opcode.  C_ADDIW is RV64 and RV128
1314          only and C_JAL is RV32 only.  */
1315       else if (xlen != 4 && is_c_addiw_insn (ival))
1316         decode_ci_type_insn (ADDIW, ival);
1317       else if (xlen == 4 && is_c_jal_insn (ival))
1318         decode_cj_type_insn (JAL, ival);
1319       /* C_ADDI16SP and C_LUI have the same opcode.  If RD is 2, then this is a
1320          C_ADDI16SP.  So must try to match C_ADDI16SP first as it has more bits
1321          in mask.  */
1322       else if (is_c_addi16sp_insn (ival))
1323         {
1324           m_opcode = ADDI;
1325           m_rd = m_rs1 = decode_register_index (ival, OP_SH_RD);
1326           m_imm.s = EXTRACT_RVC_ADDI16SP_IMM (ival);
1327         }
1328       else if (is_c_addi4spn_insn (ival))
1329         {
1330           m_opcode = ADDI;
1331           m_rd = decode_register_index_short (ival, OP_SH_CRS2S);
1332           m_rs1 = RISCV_SP_REGNUM;
1333           m_imm.s = EXTRACT_RVC_ADDI4SPN_IMM (ival);
1334         }
1335       else if (is_c_lui_insn (ival))
1336         {
1337           m_opcode = LUI;
1338           m_rd = decode_register_index (ival, OP_SH_CRS1S);
1339           m_imm.s = EXTRACT_RVC_LUI_IMM (ival);
1340         }
1341       /* C_SD and C_FSW have the same opcode.  C_SD is RV64 and RV128 only,
1342          and C_FSW is RV32 only.  */
1343       else if (xlen != 4 && is_c_sd_insn (ival))
1344         decode_cs_type_insn (SD, ival, EXTRACT_RVC_LD_IMM (ival));
1345       else if (is_c_sw_insn (ival))
1346         decode_cs_type_insn (SW, ival, EXTRACT_RVC_LW_IMM (ival));
1347       else if (is_c_swsp_insn (ival))
1348         decode_css_type_insn (SW, ival, EXTRACT_RVC_SWSP_IMM (ival));
1349       else if (xlen != 4 && is_c_sdsp_insn (ival))
1350         decode_css_type_insn (SW, ival, EXTRACT_RVC_SDSP_IMM (ival));
1351       /* C_JR and C_MV have the same opcode.  If RS2 is 0, then this is a C_JR.
1352          So must try to match C_JR first as it ahs more bits in mask.  */
1353       else if (is_c_jr_insn (ival))
1354         decode_cr_type_insn (JALR, ival);
1355       else if (is_c_j_insn (ival))
1356         decode_cj_type_insn (JAL, ival);
1357       else if (is_c_beqz_insn (ival))
1358         decode_cb_type_insn (BEQ, ival);
1359       else if (is_c_bnez_insn (ival))
1360         decode_cb_type_insn (BNE, ival);
1361       else
1362         /* None of the other fields of INSN are valid in this case.  */
1363         m_opcode = OTHER;
1364     }
1365   else
1366     internal_error (__FILE__, __LINE__,
1367                     _("unable to decode %d byte instructions in "
1368                       "prologue at %s"), m_length,
1369                     core_addr_to_string (pc));
1370 }
1371
1372 /* The prologue scanner.  This is currently only used for skipping the
1373    prologue of a function when the DWARF information is not sufficient.
1374    However, it is written with filling of the frame cache in mind, which
1375    is why different groups of stack setup instructions are split apart
1376    during the core of the inner loop.  In the future, the intention is to
1377    extend this function to fully support building up a frame cache that
1378    can unwind register values when there is no DWARF information.  */
1379
1380 static CORE_ADDR
1381 riscv_scan_prologue (struct gdbarch *gdbarch,
1382                      CORE_ADDR start_pc, CORE_ADDR end_pc,
1383                      struct riscv_unwind_cache *cache)
1384 {
1385   CORE_ADDR cur_pc, next_pc, after_prologue_pc;
1386   CORE_ADDR end_prologue_addr = 0;
1387
1388   /* Find an upper limit on the function prologue using the debug
1389      information.  If the debug information could not be used to provide
1390      that bound, then use an arbitrary large number as the upper bound.  */
1391   after_prologue_pc = skip_prologue_using_sal (gdbarch, start_pc);
1392   if (after_prologue_pc == 0)
1393     after_prologue_pc = start_pc + 100;   /* Arbitrary large number.  */
1394   if (after_prologue_pc < end_pc)
1395     end_pc = after_prologue_pc;
1396
1397   pv_t regs[RISCV_NUM_INTEGER_REGS]; /* Number of GPR.  */
1398   for (int regno = 0; regno < RISCV_NUM_INTEGER_REGS; regno++)
1399     regs[regno] = pv_register (regno, 0);
1400   pv_area stack (RISCV_SP_REGNUM, gdbarch_addr_bit (gdbarch));
1401
1402   if (riscv_debug_unwinder)
1403     fprintf_unfiltered
1404       (gdb_stdlog,
1405        "Prologue scan for function starting at %s (limit %s)\n",
1406        core_addr_to_string (start_pc),
1407        core_addr_to_string (end_pc));
1408
1409   for (next_pc = cur_pc = start_pc; cur_pc < end_pc; cur_pc = next_pc)
1410     {
1411       struct riscv_insn insn;
1412
1413       /* Decode the current instruction, and decide where the next
1414          instruction lives based on the size of this instruction.  */
1415       insn.decode (gdbarch, cur_pc);
1416       gdb_assert (insn.length () > 0);
1417       next_pc = cur_pc + insn.length ();
1418
1419       /* Look for common stack adjustment insns.  */
1420       if ((insn.opcode () == riscv_insn::ADDI
1421            || insn.opcode () == riscv_insn::ADDIW)
1422           && insn.rd () == RISCV_SP_REGNUM
1423           && insn.rs1 () == RISCV_SP_REGNUM)
1424         {
1425           /* Handle: addi sp, sp, -i
1426              or:     addiw sp, sp, -i  */
1427           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1428           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1429           regs[insn.rd ()]
1430             = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
1431         }
1432       else if ((insn.opcode () == riscv_insn::SW
1433                 || insn.opcode () == riscv_insn::SD)
1434                && (insn.rs1 () == RISCV_SP_REGNUM
1435                    || insn.rs1 () == RISCV_FP_REGNUM))
1436         {
1437           /* Handle: sw reg, offset(sp)
1438              or:     sd reg, offset(sp)
1439              or:     sw reg, offset(s0)
1440              or:     sd reg, offset(s0)  */
1441           /* Instruction storing a register onto the stack.  */
1442           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1443           gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
1444           stack.store (pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ()),
1445                         (insn.opcode () == riscv_insn::SW ? 4 : 8),
1446                         regs[insn.rs2 ()]);
1447         }
1448       else if (insn.opcode () == riscv_insn::ADDI
1449                && insn.rd () == RISCV_FP_REGNUM
1450                && insn.rs1 () == RISCV_SP_REGNUM)
1451         {
1452           /* Handle: addi s0, sp, size  */
1453           /* Instructions setting up the frame pointer.  */
1454           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1455           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1456           regs[insn.rd ()]
1457             = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
1458         }
1459       else if ((insn.opcode () == riscv_insn::ADD
1460                 || insn.opcode () == riscv_insn::ADDW)
1461                && insn.rd () == RISCV_FP_REGNUM
1462                && insn.rs1 () == RISCV_SP_REGNUM
1463                && insn.rs2 () == RISCV_ZERO_REGNUM)
1464         {
1465           /* Handle: add s0, sp, 0
1466              or:     addw s0, sp, 0  */
1467           /* Instructions setting up the frame pointer.  */
1468           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1469           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1470           regs[insn.rd ()] = pv_add_constant (regs[insn.rs1 ()], 0);
1471         }
1472       else if ((insn.opcode () == riscv_insn::ADDI
1473                 && insn.rd () == RISCV_ZERO_REGNUM
1474                 && insn.rs1 () == RISCV_ZERO_REGNUM
1475                 && insn.imm_signed () == 0))
1476         {
1477           /* Handle: add x0, x0, 0   (NOP)  */
1478         }
1479       else if (insn.opcode () == riscv_insn::AUIPC)
1480         {
1481           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1482           regs[insn.rd ()] = pv_constant (cur_pc + insn.imm_signed ());
1483         }
1484       else if (insn.opcode () == riscv_insn::LUI)
1485         {
1486           /* Handle: lui REG, n
1487              Where REG is not gp register.  */
1488           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1489           regs[insn.rd ()] = pv_constant (insn.imm_signed ());
1490         }
1491       else if (insn.opcode () == riscv_insn::ADDI)
1492         {
1493           /* Handle: addi REG1, REG2, IMM  */
1494           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1495           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1496           regs[insn.rd ()]
1497             = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
1498         }
1499       else if (insn.opcode () == riscv_insn::ADD)
1500         {
1501           /* Handle: addi REG1, REG2, IMM  */
1502           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1503           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1504           gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
1505           regs[insn.rd ()] = pv_add (regs[insn.rs1 ()], regs[insn.rs2 ()]);
1506         }
1507       else
1508         {
1509           end_prologue_addr = cur_pc;
1510           break;
1511         }
1512     }
1513
1514   if (end_prologue_addr == 0)
1515     end_prologue_addr = cur_pc;
1516
1517   if (riscv_debug_unwinder)
1518     fprintf_unfiltered (gdb_stdlog, "End of prologue at %s\n",
1519                         core_addr_to_string (end_prologue_addr));
1520
1521   if (cache != NULL)
1522     {
1523       /* Figure out if it is a frame pointer or just a stack pointer.  Also
1524          the offset held in the pv_t is from the original register value to
1525          the current value, which for a grows down stack means a negative
1526          value.  The FRAME_BASE_OFFSET is the negation of this, how to get
1527          from the current value to the original value.  */
1528       if (pv_is_register (regs[RISCV_FP_REGNUM], RISCV_SP_REGNUM))
1529         {
1530           cache->frame_base_reg = RISCV_FP_REGNUM;
1531           cache->frame_base_offset = -regs[RISCV_FP_REGNUM].k;
1532         }
1533       else
1534         {
1535           cache->frame_base_reg = RISCV_SP_REGNUM;
1536           cache->frame_base_offset = -regs[RISCV_SP_REGNUM].k;
1537         }
1538
1539       /* Assign offset from old SP to all saved registers.  As we don't
1540          have the previous value for the frame base register at this
1541          point, we store the offset as the address in the trad_frame, and
1542          then convert this to an actual address later.  */
1543       for (int i = 0; i <= RISCV_NUM_INTEGER_REGS; i++)
1544         {
1545           CORE_ADDR offset;
1546           if (stack.find_reg (gdbarch, i, &offset))
1547             {
1548               if (riscv_debug_unwinder)
1549                 fprintf_unfiltered (gdb_stdlog,
1550                                     "Register $%s at stack offset %ld\n",
1551                                     gdbarch_register_name (gdbarch, i),
1552                                     offset);
1553               trad_frame_set_addr (cache->regs, i, offset);
1554             }
1555         }
1556     }
1557
1558   return end_prologue_addr;
1559 }
1560
1561 /* Implement the riscv_skip_prologue gdbarch method.  */
1562
1563 static CORE_ADDR
1564 riscv_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
1565 {
1566   CORE_ADDR func_addr;
1567
1568   /* See if we can determine the end of the prologue via the symbol
1569      table.  If so, then return either PC, or the PC after the
1570      prologue, whichever is greater.  */
1571   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
1572     {
1573       CORE_ADDR post_prologue_pc
1574         = skip_prologue_using_sal (gdbarch, func_addr);
1575
1576       if (post_prologue_pc != 0)
1577         return std::max (pc, post_prologue_pc);
1578     }
1579
1580   /* Can't determine prologue from the symbol table, need to examine
1581      instructions.  Pass -1 for the end address to indicate the prologue
1582      scanner can scan as far as it needs to find the end of the prologue.  */
1583   return riscv_scan_prologue (gdbarch, pc, ((CORE_ADDR) -1), NULL);
1584 }
1585
1586 /* Implement the gdbarch push dummy code callback.  */
1587
1588 static CORE_ADDR
1589 riscv_push_dummy_code (struct gdbarch *gdbarch, CORE_ADDR sp,
1590                        CORE_ADDR funaddr, struct value **args, int nargs,
1591                        struct type *value_type, CORE_ADDR *real_pc,
1592                        CORE_ADDR *bp_addr, struct regcache *regcache)
1593 {
1594   /* Allocate space for a breakpoint, and keep the stack correctly
1595      aligned.  */
1596   sp -= 16;
1597   *bp_addr = sp;
1598   *real_pc = funaddr;
1599   return sp;
1600 }
1601
1602 /* Compute the alignment of the type T.  Used while setting up the
1603    arguments for a dummy call.  */
1604
1605 static int
1606 riscv_type_alignment (struct type *t)
1607 {
1608   t = check_typedef (t);
1609   switch (TYPE_CODE (t))
1610     {
1611     default:
1612       error (_("Could not compute alignment of type"));
1613
1614     case TYPE_CODE_RVALUE_REF:
1615     case TYPE_CODE_PTR:
1616     case TYPE_CODE_ENUM:
1617     case TYPE_CODE_INT:
1618     case TYPE_CODE_FLT:
1619     case TYPE_CODE_REF:
1620     case TYPE_CODE_CHAR:
1621     case TYPE_CODE_BOOL:
1622       return TYPE_LENGTH (t);
1623
1624     case TYPE_CODE_ARRAY:
1625     case TYPE_CODE_COMPLEX:
1626       return riscv_type_alignment (TYPE_TARGET_TYPE (t));
1627
1628     case TYPE_CODE_STRUCT:
1629     case TYPE_CODE_UNION:
1630       {
1631         int i;
1632         int align = 1;
1633
1634         for (i = 0; i < TYPE_NFIELDS (t); ++i)
1635           {
1636             if (TYPE_FIELD_LOC_KIND (t, i) == FIELD_LOC_KIND_BITPOS)
1637               {
1638                 int a = riscv_type_alignment (TYPE_FIELD_TYPE (t, i));
1639                 if (a > align)
1640                   align = a;
1641               }
1642           }
1643         return align;
1644       }
1645     }
1646 }
1647
1648 /* Holds information about a single argument either being passed to an
1649    inferior function, or returned from an inferior function.  This includes
1650    information about the size, type, etc of the argument, and also
1651    information about how the argument will be passed (or returned).  */
1652
1653 struct riscv_arg_info
1654 {
1655   /* Contents of the argument.  */
1656   const gdb_byte *contents;
1657
1658   /* Length of argument.  */
1659   int length;
1660
1661   /* Alignment required for an argument of this type.  */
1662   int align;
1663
1664   /* The type for this argument.  */
1665   struct type *type;
1666
1667   /* Each argument can have either 1 or 2 locations assigned to it.  Each
1668      location describes where part of the argument will be placed.  The
1669      second location is valid based on the LOC_TYPE and C_LENGTH fields
1670      of the first location (which is always valid).  */
1671   struct location
1672   {
1673     /* What type of location this is.  */
1674     enum location_type
1675       {
1676        /* Argument passed in a register.  */
1677        in_reg,
1678
1679        /* Argument passed as an on stack argument.  */
1680        on_stack,
1681
1682        /* Argument passed by reference.  The second location is always
1683           valid for a BY_REF argument, and describes where the address
1684           of the BY_REF argument should be placed.  */
1685        by_ref
1686       } loc_type;
1687
1688     /* Information that depends on the location type.  */
1689     union
1690     {
1691       /* Which register number to use.  */
1692       int regno;
1693
1694       /* The offset into the stack region.  */
1695       int offset;
1696     } loc_data;
1697
1698     /* The length of contents covered by this location.  If this is less
1699        than the total length of the argument, then the second location
1700        will be valid, and will describe where the rest of the argument
1701        will go.  */
1702     int c_length;
1703
1704     /* The offset within CONTENTS for this part of the argument.  Will
1705        always be 0 for the first part.  For the second part of the
1706        argument, this might be the C_LENGTH value of the first part,
1707        however, if we are passing a structure in two registers, and there's
1708        is padding between the first and second field, then this offset
1709        might be greater than the length of the first argument part.  When
1710        the second argument location is not holding part of the argument
1711        value, but is instead holding the address of a reference argument,
1712        then this offset will be set to 0.  */
1713     int c_offset;
1714   } argloc[2];
1715 };
1716
1717 /* Information about a set of registers being used for passing arguments as
1718    part of a function call.  The register set must be numerically
1719    sequential from NEXT_REGNUM to LAST_REGNUM.  The register set can be
1720    disabled from use by setting NEXT_REGNUM greater than LAST_REGNUM.  */
1721
1722 struct riscv_arg_reg
1723 {
1724   riscv_arg_reg (int first, int last)
1725     : next_regnum (first),
1726       last_regnum (last)
1727   {
1728     /* Nothing.  */
1729   }
1730
1731   /* The GDB register number to use in this set.  */
1732   int next_regnum;
1733
1734   /* The last GDB register number to use in this set.  */
1735   int last_regnum;
1736 };
1737
1738 /* Arguments can be passed as on stack arguments, or by reference.  The
1739    on stack arguments must be in a continuous region starting from $sp,
1740    while the by reference arguments can be anywhere, but we'll put them
1741    on the stack after (at higher address) the on stack arguments.
1742
1743    This might not be the right approach to take.  The ABI is clear that
1744    an argument passed by reference can be modified by the callee, which
1745    us placing the argument (temporarily) onto the stack will not achieve
1746    (changes will be lost).  There's also the possibility that very large
1747    arguments could overflow the stack.
1748
1749    This struct is used to track offset into these two areas for where
1750    arguments are to be placed.  */
1751 struct riscv_memory_offsets
1752 {
1753   riscv_memory_offsets ()
1754     : arg_offset (0),
1755       ref_offset (0)
1756   {
1757     /* Nothing.  */
1758   }
1759
1760   /* Offset into on stack argument area.  */
1761   int arg_offset;
1762
1763   /* Offset into the pass by reference area.  */
1764   int ref_offset;
1765 };
1766
1767 /* Holds information about where arguments to a call will be placed.  This
1768    is updated as arguments are added onto the call, and can be used to
1769    figure out where the next argument should be placed.  */
1770
1771 struct riscv_call_info
1772 {
1773   riscv_call_info (struct gdbarch *gdbarch)
1774     : int_regs (RISCV_A0_REGNUM, RISCV_A0_REGNUM + 7),
1775       float_regs (RISCV_FA0_REGNUM, RISCV_FA0_REGNUM + 7)
1776   {
1777     xlen = riscv_isa_xlen (gdbarch);
1778     flen = riscv_isa_flen (gdbarch);
1779
1780     /* Disable use of floating point registers if needed.  */
1781     if (!riscv_has_fp_abi (gdbarch))
1782       float_regs.next_regnum = float_regs.last_regnum + 1;
1783   }
1784
1785   /* Track the memory areas used for holding in-memory arguments to a
1786      call.  */
1787   struct riscv_memory_offsets memory;
1788
1789   /* Holds information about the next integer register to use for passing
1790      an argument.  */
1791   struct riscv_arg_reg int_regs;
1792
1793   /* Holds information about the next floating point register to use for
1794      passing an argument.  */
1795   struct riscv_arg_reg float_regs;
1796
1797   /* The XLEN and FLEN are copied in to this structure for convenience, and
1798      are just the results of calling RISCV_ISA_XLEN and RISCV_ISA_FLEN.  */
1799   int xlen;
1800   int flen;
1801 };
1802
1803 /* Return the number of registers available for use as parameters in the
1804    register set REG.  Returned value can be 0 or more.  */
1805
1806 static int
1807 riscv_arg_regs_available (struct riscv_arg_reg *reg)
1808 {
1809   if (reg->next_regnum > reg->last_regnum)
1810     return 0;
1811
1812   return (reg->last_regnum - reg->next_regnum + 1);
1813 }
1814
1815 /* If there is at least one register available in the register set REG then
1816    the next register from REG is assigned to LOC and the length field of
1817    LOC is updated to LENGTH.  The register set REG is updated to indicate
1818    that the assigned register is no longer available and the function
1819    returns true.
1820
1821    If there are no registers available in REG then the function returns
1822    false, and LOC and REG are unchanged.  */
1823
1824 static bool
1825 riscv_assign_reg_location (struct riscv_arg_info::location *loc,
1826                            struct riscv_arg_reg *reg,
1827                            int length, int offset)
1828 {
1829   if (reg->next_regnum <= reg->last_regnum)
1830     {
1831       loc->loc_type = riscv_arg_info::location::in_reg;
1832       loc->loc_data.regno = reg->next_regnum;
1833       reg->next_regnum++;
1834       loc->c_length = length;
1835       loc->c_offset = offset;
1836       return true;
1837     }
1838
1839   return false;
1840 }
1841
1842 /* Assign LOC a location as the next stack parameter, and update MEMORY to
1843    record that an area of stack has been used to hold the parameter
1844    described by LOC.
1845
1846    The length field of LOC is updated to LENGTH, the length of the
1847    parameter being stored, and ALIGN is the alignment required by the
1848    parameter, which will affect how memory is allocated out of MEMORY.  */
1849
1850 static void
1851 riscv_assign_stack_location (struct riscv_arg_info::location *loc,
1852                              struct riscv_memory_offsets *memory,
1853                              int length, int align)
1854 {
1855   loc->loc_type = riscv_arg_info::location::on_stack;
1856   memory->arg_offset
1857     = align_up (memory->arg_offset, align);
1858   loc->loc_data.offset = memory->arg_offset;
1859   memory->arg_offset += length;
1860   loc->c_length = length;
1861
1862   /* Offset is always 0, either we're the first location part, in which
1863      case we're reading content from the start of the argument, or we're
1864      passing the address of a reference argument, so 0.  */
1865   loc->c_offset = 0;
1866 }
1867
1868 /* Update AINFO, which describes an argument that should be passed or
1869    returned using the integer ABI.  The argloc fields within AINFO are
1870    updated to describe the location in which the argument will be passed to
1871    a function, or returned from a function.
1872
1873    The CINFO structure contains the ongoing call information, the holds
1874    information such as which argument registers are remaining to be
1875    assigned to parameter, and how much memory has been used by parameters
1876    so far.
1877
1878    By examining the state of CINFO a suitable location can be selected,
1879    and assigned to AINFO.  */
1880
1881 static void
1882 riscv_call_arg_scalar_int (struct riscv_arg_info *ainfo,
1883                            struct riscv_call_info *cinfo)
1884 {
1885   if (ainfo->length > (2 * cinfo->xlen))
1886     {
1887       /* Argument is going to be passed by reference.  */
1888       ainfo->argloc[0].loc_type
1889         = riscv_arg_info::location::by_ref;
1890       cinfo->memory.ref_offset
1891         = align_up (cinfo->memory.ref_offset, ainfo->align);
1892       ainfo->argloc[0].loc_data.offset = cinfo->memory.ref_offset;
1893       cinfo->memory.ref_offset += ainfo->length;
1894       ainfo->argloc[0].c_length = ainfo->length;
1895
1896       /* The second location for this argument is given over to holding the
1897          address of the by-reference data.  Pass 0 for the offset as this
1898          is not part of the actual argument value.  */
1899       if (!riscv_assign_reg_location (&ainfo->argloc[1],
1900                                       &cinfo->int_regs,
1901                                       cinfo->xlen, 0))
1902         riscv_assign_stack_location (&ainfo->argloc[1],
1903                                      &cinfo->memory, cinfo->xlen,
1904                                      cinfo->xlen);
1905     }
1906   else
1907     {
1908       int len = (ainfo->length > cinfo->xlen) ? cinfo->xlen : ainfo->length;
1909
1910       if (!riscv_assign_reg_location (&ainfo->argloc[0],
1911                                       &cinfo->int_regs, len, 0))
1912         riscv_assign_stack_location (&ainfo->argloc[0],
1913                                      &cinfo->memory, len, ainfo->align);
1914
1915       if (len < ainfo->length)
1916         {
1917           len = ainfo->length - len;
1918           if (!riscv_assign_reg_location (&ainfo->argloc[1],
1919                                           &cinfo->int_regs, len,
1920                                           cinfo->xlen))
1921             riscv_assign_stack_location (&ainfo->argloc[1],
1922                                          &cinfo->memory, len, cinfo->xlen);
1923         }
1924     }
1925 }
1926
1927 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
1928    is being passed with the floating point ABI.  */
1929
1930 static void
1931 riscv_call_arg_scalar_float (struct riscv_arg_info *ainfo,
1932                              struct riscv_call_info *cinfo)
1933 {
1934   if (ainfo->length > cinfo->flen)
1935     return riscv_call_arg_scalar_int (ainfo, cinfo);
1936   else
1937     {
1938       if (!riscv_assign_reg_location (&ainfo->argloc[0],
1939                                       &cinfo->float_regs,
1940                                       ainfo->length, 0))
1941         return riscv_call_arg_scalar_int (ainfo, cinfo);
1942     }
1943 }
1944
1945 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
1946    is a complex floating point argument, and is therefore handled
1947    differently to other argument types.  */
1948
1949 static void
1950 riscv_call_arg_complex_float (struct riscv_arg_info *ainfo,
1951                               struct riscv_call_info *cinfo)
1952 {
1953   if (ainfo->length <= (2 * cinfo->flen)
1954       && riscv_arg_regs_available (&cinfo->float_regs) >= 2)
1955     {
1956       bool result;
1957       int len = ainfo->length / 2;
1958
1959       result = riscv_assign_reg_location (&ainfo->argloc[0],
1960                                           &cinfo->float_regs, len, len);
1961       gdb_assert (result);
1962
1963       result = riscv_assign_reg_location (&ainfo->argloc[1],
1964                                           &cinfo->float_regs, len, len);
1965       gdb_assert (result);
1966     }
1967   else
1968     return riscv_call_arg_scalar_int (ainfo, cinfo);
1969 }
1970
1971 /* A structure used for holding information about a structure type within
1972    the inferior program.  The RiscV ABI has special rules for handling some
1973    structures with a single field or with two fields.  The counting of
1974    fields here is done after flattening out all nested structures.  */
1975
1976 class riscv_struct_info
1977 {
1978 public:
1979   riscv_struct_info ()
1980     : m_number_of_fields (0),
1981       m_types { nullptr, nullptr }
1982   {
1983     /* Nothing.  */
1984   }
1985
1986   /* Analyse TYPE descending into nested structures, count the number of
1987      scalar fields and record the types of the first two fields found.  */
1988   void analyse (struct type *type);
1989
1990   /* The number of scalar fields found in the analysed type.  This is
1991      currently only accurate if the value returned is 0, 1, or 2 as the
1992      analysis stops counting when the number of fields is 3.  This is
1993      because the RiscV ABI only has special cases for 1 or 2 fields,
1994      anything else we just don't care about.  */
1995   int number_of_fields () const
1996   { return m_number_of_fields; }
1997
1998   /* Return the type for scalar field INDEX within the analysed type.  Will
1999      return nullptr if there is no field at that index.  Only INDEX values
2000      0 and 1 can be requested as the RiscV ABI only has special cases for
2001      structures with 1 or 2 fields.  */
2002   struct type *field_type (int index) const
2003   {
2004     gdb_assert (index < (sizeof (m_types) / sizeof (m_types[0])));
2005     return m_types[index];
2006   }
2007
2008 private:
2009   /* The number of scalar fields found within the structure after recursing
2010      into nested structures.  */
2011   int m_number_of_fields;
2012
2013   /* The types of the first two scalar fields found within the structure
2014      after recursing into nested structures.  */
2015   struct type *m_types[2];
2016 };
2017
2018 /* Analyse TYPE descending into nested structures, count the number of
2019    scalar fields and record the types of the first two fields found.  */
2020
2021 void
2022 riscv_struct_info::analyse (struct type *type)
2023 {
2024   unsigned int count = TYPE_NFIELDS (type);
2025   unsigned int i;
2026
2027   for (i = 0; i < count; ++i)
2028     {
2029       if (TYPE_FIELD_LOC_KIND (type, i) != FIELD_LOC_KIND_BITPOS)
2030         continue;
2031
2032       struct type *field_type = TYPE_FIELD_TYPE (type, i);
2033       field_type = check_typedef (field_type);
2034
2035       switch (TYPE_CODE (field_type))
2036         {
2037         case TYPE_CODE_STRUCT:
2038           analyse (field_type);
2039           break;
2040
2041         default:
2042           /* RiscV only flattens out structures.  Anything else does not
2043              need to be flattened, we just record the type, and when we
2044              look at the analysis results we'll realise this is not a
2045              structure we can special case, and pass the structure in
2046              memory.  */
2047           if (m_number_of_fields < 2)
2048             m_types[m_number_of_fields] = field_type;
2049           m_number_of_fields++;
2050           break;
2051         }
2052
2053       /* RiscV only has special handling for structures with 1 or 2 scalar
2054          fields, any more than that and the structure is just passed in
2055          memory.  We can safely drop out early when we find 3 or more
2056          fields then.  */
2057
2058       if (m_number_of_fields > 2)
2059         return;
2060     }
2061 }
2062
2063 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2064    is a structure.  Small structures on RiscV have some special case
2065    handling in order that the structure might be passed in register.
2066    Larger structures are passed in memory.  After assigning location
2067    information to AINFO, CINFO will have been updated.  */
2068
2069 static void
2070 riscv_call_arg_struct (struct riscv_arg_info *ainfo,
2071                        struct riscv_call_info *cinfo)
2072 {
2073   if (riscv_arg_regs_available (&cinfo->float_regs) >= 1)
2074     {
2075       struct riscv_struct_info sinfo;
2076
2077       sinfo.analyse (ainfo->type);
2078       if (sinfo.number_of_fields () == 1
2079           && TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_COMPLEX)
2080         {
2081           gdb_assert (TYPE_LENGTH (ainfo->type)
2082                       == TYPE_LENGTH (sinfo.field_type (0)));
2083           return riscv_call_arg_complex_float (ainfo, cinfo);
2084         }
2085
2086       if (sinfo.number_of_fields () == 1
2087           && TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_FLT)
2088         {
2089           gdb_assert (TYPE_LENGTH (ainfo->type)
2090                       == TYPE_LENGTH (sinfo.field_type (0)));
2091           return riscv_call_arg_scalar_float (ainfo, cinfo);
2092         }
2093
2094       if (sinfo.number_of_fields () == 2
2095           && TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_FLT
2096           && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->flen
2097           && TYPE_CODE (sinfo.field_type (1)) == TYPE_CODE_FLT
2098           && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->flen
2099           && riscv_arg_regs_available (&cinfo->float_regs) >= 2)
2100         {
2101           int len0, len1, offset;
2102
2103           gdb_assert (TYPE_LENGTH (ainfo->type) <= (2 * cinfo->flen));
2104
2105           len0 = TYPE_LENGTH (sinfo.field_type (0));
2106           if (!riscv_assign_reg_location (&ainfo->argloc[0],
2107                                           &cinfo->float_regs, len0, 0))
2108             error (_("failed during argument setup"));
2109
2110           len1 = TYPE_LENGTH (sinfo.field_type (1));
2111           offset = align_up (len0, riscv_type_alignment (sinfo.field_type (1)));
2112           gdb_assert (len1 <= (TYPE_LENGTH (ainfo->type)
2113                                - TYPE_LENGTH (sinfo.field_type (0))));
2114
2115           if (!riscv_assign_reg_location (&ainfo->argloc[1],
2116                                           &cinfo->float_regs,
2117                                           len1, offset))
2118             error (_("failed during argument setup"));
2119           return;
2120         }
2121
2122       if (sinfo.number_of_fields () == 2
2123           && riscv_arg_regs_available (&cinfo->int_regs) >= 1
2124           && (TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_FLT
2125               && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->flen
2126               && is_integral_type (sinfo.field_type (1))
2127               && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->xlen))
2128         {
2129           int len0, len1, offset;
2130
2131           gdb_assert (TYPE_LENGTH (ainfo->type)
2132                       <= (cinfo->flen + cinfo->xlen));
2133
2134           len0 = TYPE_LENGTH (sinfo.field_type (0));
2135           if (!riscv_assign_reg_location (&ainfo->argloc[0],
2136                                           &cinfo->float_regs, len0, 0))
2137             error (_("failed during argument setup"));
2138
2139           len1 = TYPE_LENGTH (sinfo.field_type (1));
2140           offset = align_up (len0, riscv_type_alignment (sinfo.field_type (1)));
2141           gdb_assert (len1 <= cinfo->xlen);
2142           if (!riscv_assign_reg_location (&ainfo->argloc[1],
2143                                           &cinfo->int_regs, len1, offset))
2144             error (_("failed during argument setup"));
2145           return;
2146         }
2147
2148       if (sinfo.number_of_fields () == 2
2149           && riscv_arg_regs_available (&cinfo->int_regs) >= 1
2150           && (is_integral_type (sinfo.field_type (0))
2151               && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->xlen
2152               && TYPE_CODE (sinfo.field_type (1)) == TYPE_CODE_FLT
2153               && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->flen))
2154         {
2155           int len0, len1, offset;
2156
2157           gdb_assert (TYPE_LENGTH (ainfo->type)
2158                       <= (cinfo->flen + cinfo->xlen));
2159
2160           len0 = TYPE_LENGTH (sinfo.field_type (0));
2161           len1 = TYPE_LENGTH (sinfo.field_type (1));
2162           offset = align_up (len0, riscv_type_alignment (sinfo.field_type (1)));
2163
2164           gdb_assert (len0 <= cinfo->xlen);
2165           gdb_assert (len1 <= cinfo->flen);
2166
2167           if (!riscv_assign_reg_location (&ainfo->argloc[0],
2168                                           &cinfo->int_regs, len0, 0))
2169             error (_("failed during argument setup"));
2170
2171           if (!riscv_assign_reg_location (&ainfo->argloc[1],
2172                                           &cinfo->float_regs,
2173                                           len1, offset))
2174             error (_("failed during argument setup"));
2175
2176           return;
2177         }
2178     }
2179
2180   /* Non of the structure flattening cases apply, so we just pass using
2181      the integer ABI.  */
2182   ainfo->length = align_up (ainfo->length, cinfo->xlen);
2183   riscv_call_arg_scalar_int (ainfo, cinfo);
2184 }
2185
2186 /* Assign a location to call (or return) argument AINFO, the location is
2187    selected from CINFO which holds information about what call argument
2188    locations are available for use next.  The TYPE is the type of the
2189    argument being passed, this information is recorded into AINFO (along
2190    with some additional information derived from the type).
2191
2192    After assigning a location to AINFO, CINFO will have been updated.  */
2193
2194 static void
2195 riscv_arg_location (struct gdbarch *gdbarch,
2196                     struct riscv_arg_info *ainfo,
2197                     struct riscv_call_info *cinfo,
2198                     struct type *type)
2199 {
2200   ainfo->type = type;
2201   ainfo->length = TYPE_LENGTH (ainfo->type);
2202   ainfo->align = riscv_type_alignment (ainfo->type);
2203   ainfo->contents = nullptr;
2204
2205   switch (TYPE_CODE (ainfo->type))
2206     {
2207     case TYPE_CODE_INT:
2208     case TYPE_CODE_BOOL:
2209     case TYPE_CODE_CHAR:
2210     case TYPE_CODE_RANGE:
2211     case TYPE_CODE_ENUM:
2212     case TYPE_CODE_PTR:
2213       if (ainfo->length <= cinfo->xlen)
2214         {
2215           ainfo->type = builtin_type (gdbarch)->builtin_long;
2216           ainfo->length = cinfo->xlen;
2217         }
2218       else if (ainfo->length <= (2 * cinfo->xlen))
2219         {
2220           ainfo->type = builtin_type (gdbarch)->builtin_long_long;
2221           ainfo->length = 2 * cinfo->xlen;
2222         }
2223
2224       /* Recalculate the alignment requirement.  */
2225       ainfo->align = riscv_type_alignment (ainfo->type);
2226       riscv_call_arg_scalar_int (ainfo, cinfo);
2227       break;
2228
2229     case TYPE_CODE_FLT:
2230       riscv_call_arg_scalar_float (ainfo, cinfo);
2231       break;
2232
2233     case TYPE_CODE_COMPLEX:
2234       riscv_call_arg_complex_float (ainfo, cinfo);
2235       break;
2236
2237     case TYPE_CODE_STRUCT:
2238       riscv_call_arg_struct (ainfo, cinfo);
2239       break;
2240
2241     default:
2242       riscv_call_arg_scalar_int (ainfo, cinfo);
2243       break;
2244     }
2245 }
2246
2247 /* Used for printing debug information about the call argument location in
2248    INFO to STREAM.  The addresses in SP_REFS and SP_ARGS are the base
2249    addresses for the location of pass-by-reference and
2250    arguments-on-the-stack memory areas.  */
2251
2252 static void
2253 riscv_print_arg_location (ui_file *stream, struct gdbarch *gdbarch,
2254                           struct riscv_arg_info *info,
2255                           CORE_ADDR sp_refs, CORE_ADDR sp_args)
2256 {
2257   fprintf_unfiltered (stream, "type: '%s', length: 0x%x, alignment: 0x%x",
2258                       TYPE_SAFE_NAME (info->type), info->length, info->align);
2259   switch (info->argloc[0].loc_type)
2260     {
2261     case riscv_arg_info::location::in_reg:
2262       fprintf_unfiltered
2263         (stream, ", register %s",
2264          gdbarch_register_name (gdbarch, info->argloc[0].loc_data.regno));
2265       if (info->argloc[0].c_length < info->length)
2266         {
2267           switch (info->argloc[1].loc_type)
2268             {
2269             case riscv_arg_info::location::in_reg:
2270               fprintf_unfiltered
2271                 (stream, ", register %s",
2272                  gdbarch_register_name (gdbarch,
2273                                         info->argloc[1].loc_data.regno));
2274               break;
2275
2276             case riscv_arg_info::location::on_stack:
2277               fprintf_unfiltered (stream, ", on stack at offset 0x%x",
2278                                   info->argloc[1].loc_data.offset);
2279               break;
2280
2281             case riscv_arg_info::location::by_ref:
2282             default:
2283               /* The second location should never be a reference, any
2284                  argument being passed by reference just places its address
2285                  in the first location and is done.  */
2286               error (_("invalid argument location"));
2287               break;
2288             }
2289
2290           if (info->argloc[1].c_offset > info->argloc[0].c_length)
2291             fprintf_unfiltered (stream, " (offset 0x%x)",
2292                                 info->argloc[1].c_offset);
2293         }
2294       break;
2295
2296     case riscv_arg_info::location::on_stack:
2297       fprintf_unfiltered (stream, ", on stack at offset 0x%x",
2298                           info->argloc[0].loc_data.offset);
2299       break;
2300
2301     case riscv_arg_info::location::by_ref:
2302       fprintf_unfiltered
2303         (stream, ", by reference, data at offset 0x%x (%s)",
2304          info->argloc[0].loc_data.offset,
2305          core_addr_to_string (sp_refs + info->argloc[0].loc_data.offset));
2306       if (info->argloc[1].loc_type
2307           == riscv_arg_info::location::in_reg)
2308         fprintf_unfiltered
2309           (stream, ", address in register %s",
2310            gdbarch_register_name (gdbarch, info->argloc[1].loc_data.regno));
2311       else
2312         {
2313           gdb_assert (info->argloc[1].loc_type
2314                       == riscv_arg_info::location::on_stack);
2315           fprintf_unfiltered
2316             (stream, ", address on stack at offset 0x%x (%s)",
2317              info->argloc[1].loc_data.offset,
2318              core_addr_to_string (sp_args + info->argloc[1].loc_data.offset));
2319         }
2320       break;
2321
2322     default:
2323       gdb_assert_not_reached (_("unknown argument location type"));
2324     }
2325 }
2326
2327 /* Implement the push dummy call gdbarch callback.  */
2328
2329 static CORE_ADDR
2330 riscv_push_dummy_call (struct gdbarch *gdbarch,
2331                        struct value *function,
2332                        struct regcache *regcache,
2333                        CORE_ADDR bp_addr,
2334                        int nargs,
2335                        struct value **args,
2336                        CORE_ADDR sp,
2337                        int struct_return,
2338                        CORE_ADDR struct_addr)
2339 {
2340   int i;
2341   CORE_ADDR sp_args, sp_refs;
2342   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2343
2344   struct riscv_arg_info *arg_info =
2345     (struct riscv_arg_info *) alloca (nargs * sizeof (struct riscv_arg_info));
2346
2347   struct riscv_call_info call_info (gdbarch);
2348
2349   CORE_ADDR osp = sp;
2350
2351   /* We'll use register $a0 if we're returning a struct.  */
2352   if (struct_return)
2353     ++call_info.int_regs.next_regnum;
2354
2355   for (i = 0; i < nargs; ++i)
2356     {
2357       struct value *arg_value;
2358       struct type *arg_type;
2359       struct riscv_arg_info *info = &arg_info[i];
2360
2361       arg_value = args[i];
2362       arg_type = check_typedef (value_type (arg_value));
2363
2364       riscv_arg_location (gdbarch, info, &call_info, arg_type);
2365
2366       if (info->type != arg_type)
2367         arg_value = value_cast (info->type, arg_value);
2368       info->contents = value_contents (arg_value);
2369     }
2370
2371   /* Adjust the stack pointer and align it.  */
2372   sp = sp_refs = align_down (sp - call_info.memory.ref_offset, SP_ALIGNMENT);
2373   sp = sp_args = align_down (sp - call_info.memory.arg_offset, SP_ALIGNMENT);
2374
2375   if (riscv_debug_infcall > 0)
2376     {
2377       fprintf_unfiltered (gdb_stdlog, "dummy call args:\n");
2378       fprintf_unfiltered (gdb_stdlog, ": floating point ABI %s in use\n",
2379                (riscv_has_fp_abi (gdbarch) ? "is" : "is not"));
2380       fprintf_unfiltered (gdb_stdlog, ": xlen: %d\n: flen: %d\n",
2381                call_info.xlen, call_info.flen);
2382       if (struct_return)
2383         fprintf_unfiltered (gdb_stdlog,
2384                             "[*] struct return pointer in register $A0\n");
2385       for (i = 0; i < nargs; ++i)
2386         {
2387           struct riscv_arg_info *info = &arg_info [i];
2388
2389           fprintf_unfiltered (gdb_stdlog, "[%2d] ", i);
2390           riscv_print_arg_location (gdb_stdlog, gdbarch, info, sp_refs, sp_args);
2391           fprintf_unfiltered (gdb_stdlog, "\n");
2392         }
2393       if (call_info.memory.arg_offset > 0
2394           || call_info.memory.ref_offset > 0)
2395         {
2396           fprintf_unfiltered (gdb_stdlog, "              Original sp: %s\n",
2397                               core_addr_to_string (osp));
2398           fprintf_unfiltered (gdb_stdlog, "Stack required (for args): 0x%x\n",
2399                               call_info.memory.arg_offset);
2400           fprintf_unfiltered (gdb_stdlog, "Stack required (for refs): 0x%x\n",
2401                               call_info.memory.ref_offset);
2402           fprintf_unfiltered (gdb_stdlog, "          Stack allocated: %s\n",
2403                               core_addr_to_string_nz (osp - sp));
2404         }
2405     }
2406
2407   /* Now load the argument into registers, or onto the stack.  */
2408
2409   if (struct_return)
2410     {
2411       gdb_byte buf[sizeof (LONGEST)];
2412
2413       store_unsigned_integer (buf, call_info.xlen, byte_order, struct_addr);
2414       regcache->cooked_write (RISCV_A0_REGNUM, buf);
2415     }
2416
2417   for (i = 0; i < nargs; ++i)
2418     {
2419       CORE_ADDR dst;
2420       int second_arg_length = 0;
2421       const gdb_byte *second_arg_data;
2422       struct riscv_arg_info *info = &arg_info [i];
2423
2424       gdb_assert (info->length > 0);
2425
2426       switch (info->argloc[0].loc_type)
2427         {
2428         case riscv_arg_info::location::in_reg:
2429           {
2430             gdb_byte tmp [sizeof (ULONGEST)];
2431
2432             gdb_assert (info->argloc[0].c_length <= info->length);
2433             /* FP values in FP registers must be NaN-boxed.  */
2434             if (riscv_is_fp_regno_p (info->argloc[0].loc_data.regno)
2435                 && info->argloc[0].c_length < call_info.flen)
2436               memset (tmp, -1, sizeof (tmp));
2437             else
2438               memset (tmp, 0, sizeof (tmp));
2439             memcpy (tmp, info->contents, info->argloc[0].c_length);
2440             regcache->cooked_write (info->argloc[0].loc_data.regno, tmp);
2441             second_arg_length =
2442               ((info->argloc[0].c_length < info->length)
2443                ? info->argloc[1].c_length : 0);
2444             second_arg_data = info->contents + info->argloc[1].c_offset;
2445           }
2446           break;
2447
2448         case riscv_arg_info::location::on_stack:
2449           dst = sp_args + info->argloc[0].loc_data.offset;
2450           write_memory (dst, info->contents, info->length);
2451           second_arg_length = 0;
2452           break;
2453
2454         case riscv_arg_info::location::by_ref:
2455           dst = sp_refs + info->argloc[0].loc_data.offset;
2456           write_memory (dst, info->contents, info->length);
2457
2458           second_arg_length = call_info.xlen;
2459           second_arg_data = (gdb_byte *) &dst;
2460           break;
2461
2462         default:
2463           gdb_assert_not_reached (_("unknown argument location type"));
2464         }
2465
2466       if (second_arg_length > 0)
2467         {
2468           switch (info->argloc[1].loc_type)
2469             {
2470             case riscv_arg_info::location::in_reg:
2471               {
2472                 gdb_byte tmp [sizeof (ULONGEST)];
2473
2474                 gdb_assert ((riscv_is_fp_regno_p (info->argloc[1].loc_data.regno)
2475                              && second_arg_length <= call_info.flen)
2476                             || second_arg_length <= call_info.xlen);
2477                 /* FP values in FP registers must be NaN-boxed.  */
2478                 if (riscv_is_fp_regno_p (info->argloc[1].loc_data.regno)
2479                     && second_arg_length < call_info.flen)
2480                   memset (tmp, -1, sizeof (tmp));
2481                 else
2482                   memset (tmp, 0, sizeof (tmp));
2483                 memcpy (tmp, second_arg_data, second_arg_length);
2484                 regcache->cooked_write (info->argloc[1].loc_data.regno, tmp);
2485               }
2486               break;
2487
2488             case riscv_arg_info::location::on_stack:
2489               {
2490                 CORE_ADDR arg_addr;
2491
2492                 arg_addr = sp_args + info->argloc[1].loc_data.offset;
2493                 write_memory (arg_addr, second_arg_data, second_arg_length);
2494                 break;
2495               }
2496
2497             case riscv_arg_info::location::by_ref:
2498             default:
2499               /* The second location should never be a reference, any
2500                  argument being passed by reference just places its address
2501                  in the first location and is done.  */
2502               error (_("invalid argument location"));
2503               break;
2504             }
2505         }
2506     }
2507
2508   /* Set the dummy return value to bp_addr.
2509      A dummy breakpoint will be setup to execute the call.  */
2510
2511   if (riscv_debug_infcall > 0)
2512     fprintf_unfiltered (gdb_stdlog, ": writing $ra = %s\n",
2513                         core_addr_to_string (bp_addr));
2514   regcache_cooked_write_unsigned (regcache, RISCV_RA_REGNUM, bp_addr);
2515
2516   /* Finally, update the stack pointer.  */
2517
2518   if (riscv_debug_infcall > 0)
2519     fprintf_unfiltered (gdb_stdlog, ": writing $sp = %s\n",
2520                         core_addr_to_string (sp));
2521   regcache_cooked_write_unsigned (regcache, RISCV_SP_REGNUM, sp);
2522
2523   return sp;
2524 }
2525
2526 /* Implement the return_value gdbarch method.  */
2527
2528 static enum return_value_convention
2529 riscv_return_value (struct gdbarch  *gdbarch,
2530                     struct value *function,
2531                     struct type *type,
2532                     struct regcache *regcache,
2533                     gdb_byte *readbuf,
2534                     const gdb_byte *writebuf)
2535 {
2536   struct riscv_call_info call_info (gdbarch);
2537   struct riscv_arg_info info;
2538   struct type *arg_type;
2539
2540   arg_type = check_typedef (type);
2541   riscv_arg_location (gdbarch, &info, &call_info, arg_type);
2542
2543   if (riscv_debug_infcall > 0)
2544     {
2545       fprintf_unfiltered (gdb_stdlog, "riscv return value:\n");
2546       fprintf_unfiltered (gdb_stdlog, "[R] ");
2547       riscv_print_arg_location (gdb_stdlog, gdbarch, &info, 0, 0);
2548       fprintf_unfiltered (gdb_stdlog, "\n");
2549     }
2550
2551   if (readbuf != nullptr || writebuf != nullptr)
2552     {
2553         int regnum;
2554
2555         switch (info.argloc[0].loc_type)
2556           {
2557             /* Return value in register(s).  */
2558           case riscv_arg_info::location::in_reg:
2559             {
2560               regnum = info.argloc[0].loc_data.regno;
2561
2562               if (readbuf)
2563                 regcache->cooked_read (regnum, readbuf);
2564
2565               if (writebuf)
2566                 regcache->cooked_write (regnum, writebuf);
2567
2568               /* A return value in register can have a second part in a
2569                  second register.  */
2570               if (info.argloc[0].c_length < info.length)
2571                 {
2572                   switch (info.argloc[1].loc_type)
2573                     {
2574                     case riscv_arg_info::location::in_reg:
2575                       regnum = info.argloc[1].loc_data.regno;
2576
2577                       if (readbuf)
2578                         {
2579                           readbuf += info.argloc[1].c_offset;
2580                           regcache->cooked_read (regnum, readbuf);
2581                         }
2582
2583                       if (writebuf)
2584                         {
2585                           writebuf += info.argloc[1].c_offset;
2586                           regcache->cooked_write (regnum, writebuf);
2587                         }
2588                       break;
2589
2590                     case riscv_arg_info::location::by_ref:
2591                     case riscv_arg_info::location::on_stack:
2592                     default:
2593                       error (_("invalid argument location"));
2594                       break;
2595                     }
2596                 }
2597             }
2598             break;
2599
2600             /* Return value by reference will have its address in A0.  */
2601           case riscv_arg_info::location::by_ref:
2602             {
2603               ULONGEST addr;
2604
2605               regcache_cooked_read_unsigned (regcache, RISCV_A0_REGNUM,
2606                                              &addr);
2607               if (readbuf != nullptr)
2608                 read_memory (addr, readbuf, info.length);
2609               if (writebuf != nullptr)
2610                 write_memory (addr, writebuf, info.length);
2611             }
2612             break;
2613
2614           case riscv_arg_info::location::on_stack:
2615           default:
2616             error (_("invalid argument location"));
2617             break;
2618           }
2619     }
2620
2621   switch (info.argloc[0].loc_type)
2622     {
2623     case riscv_arg_info::location::in_reg:
2624       return RETURN_VALUE_REGISTER_CONVENTION;
2625     case riscv_arg_info::location::by_ref:
2626       return RETURN_VALUE_ABI_RETURNS_ADDRESS;
2627     case riscv_arg_info::location::on_stack:
2628     default:
2629       error (_("invalid argument location"));
2630     }
2631 }
2632
2633 /* Implement the frame_align gdbarch method.  */
2634
2635 static CORE_ADDR
2636 riscv_frame_align (struct gdbarch *gdbarch, CORE_ADDR addr)
2637 {
2638   return align_down (addr, 16);
2639 }
2640
2641 /* Implement the unwind_pc gdbarch method.  */
2642
2643 static CORE_ADDR
2644 riscv_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
2645 {
2646   return frame_unwind_register_unsigned (next_frame, RISCV_PC_REGNUM);
2647 }
2648
2649 /* Implement the unwind_sp gdbarch method.  */
2650
2651 static CORE_ADDR
2652 riscv_unwind_sp (struct gdbarch *gdbarch, struct frame_info *next_frame)
2653 {
2654   return frame_unwind_register_unsigned (next_frame, RISCV_SP_REGNUM);
2655 }
2656
2657 /* Implement the dummy_id gdbarch method.  */
2658
2659 static struct frame_id
2660 riscv_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
2661 {
2662   return frame_id_build (get_frame_register_signed (this_frame, RISCV_SP_REGNUM),
2663                          get_frame_pc (this_frame));
2664 }
2665
2666 /* Generate, or return the cached frame cache for the RiscV frame
2667    unwinder.  */
2668
2669 static struct riscv_unwind_cache *
2670 riscv_frame_cache (struct frame_info *this_frame, void **this_cache)
2671 {
2672   CORE_ADDR pc, start_addr;
2673   struct riscv_unwind_cache *cache;
2674   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2675   int numregs, regno;
2676
2677   if ((*this_cache) != NULL)
2678     return (struct riscv_unwind_cache *) *this_cache;
2679
2680   cache = FRAME_OBSTACK_ZALLOC (struct riscv_unwind_cache);
2681   cache->regs = trad_frame_alloc_saved_regs (this_frame);
2682   (*this_cache) = cache;
2683
2684   /* Scan the prologue, filling in the cache.  */
2685   start_addr = get_frame_func (this_frame);
2686   pc = get_frame_pc (this_frame);
2687   riscv_scan_prologue (gdbarch, start_addr, pc, cache);
2688
2689   /* We can now calculate the frame base address.  */
2690   cache->frame_base
2691     = (get_frame_register_signed (this_frame, cache->frame_base_reg)
2692        + cache->frame_base_offset);
2693   if (riscv_debug_unwinder)
2694     fprintf_unfiltered (gdb_stdlog, "Frame base is %s ($%s + 0x%x)\n",
2695                         core_addr_to_string (cache->frame_base),
2696                         gdbarch_register_name (gdbarch,
2697                                                cache->frame_base_reg),
2698                         cache->frame_base_offset);
2699
2700   /* The prologue scanner sets the address of registers stored to the stack
2701      as the offset of that register from the frame base.  The prologue
2702      scanner doesn't know the actual frame base value, and so is unable to
2703      compute the exact address.  We do now know the frame base value, so
2704      update the address of registers stored to the stack.  */
2705   numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
2706   for (regno = 0; regno < numregs; ++regno)
2707     {
2708       if (trad_frame_addr_p (cache->regs, regno))
2709         cache->regs[regno].addr += cache->frame_base;
2710     }
2711
2712   /* The previous $pc can be found wherever the $ra value can be found.
2713      The previous $ra value is gone, this would have been stored be the
2714      previous frame if required.  */
2715   cache->regs[gdbarch_pc_regnum (gdbarch)] = cache->regs[RISCV_RA_REGNUM];
2716   trad_frame_set_unknown (cache->regs, RISCV_RA_REGNUM);
2717
2718   /* Build the frame id.  */
2719   cache->this_id = frame_id_build (cache->frame_base, start_addr);
2720
2721   /* The previous $sp value is the frame base value.  */
2722   trad_frame_set_value (cache->regs, gdbarch_sp_regnum (gdbarch),
2723                         cache->frame_base);
2724
2725   return cache;
2726 }
2727
2728 /* Implement the this_id callback for RiscV frame unwinder.  */
2729
2730 static void
2731 riscv_frame_this_id (struct frame_info *this_frame,
2732                      void **prologue_cache,
2733                      struct frame_id *this_id)
2734 {
2735   struct riscv_unwind_cache *cache;
2736
2737   cache = riscv_frame_cache (this_frame, prologue_cache);
2738   *this_id = cache->this_id;
2739 }
2740
2741 /* Implement the prev_register callback for RiscV frame unwinder.  */
2742
2743 static struct value *
2744 riscv_frame_prev_register (struct frame_info *this_frame,
2745                            void **prologue_cache,
2746                            int regnum)
2747 {
2748   struct riscv_unwind_cache *cache;
2749
2750   cache = riscv_frame_cache (this_frame, prologue_cache);
2751   return trad_frame_get_prev_register (this_frame, cache->regs, regnum);
2752 }
2753
2754 /* Structure defining the RiscV normal frame unwind functions.  Since we
2755    are the fallback unwinder (DWARF unwinder is used first), we use the
2756    default frame sniffer, which always accepts the frame.  */
2757
2758 static const struct frame_unwind riscv_frame_unwind =
2759 {
2760   /*.type          =*/ NORMAL_FRAME,
2761   /*.stop_reason   =*/ default_frame_unwind_stop_reason,
2762   /*.this_id       =*/ riscv_frame_this_id,
2763   /*.prev_register =*/ riscv_frame_prev_register,
2764   /*.unwind_data   =*/ NULL,
2765   /*.sniffer       =*/ default_frame_sniffer,
2766   /*.dealloc_cache =*/ NULL,
2767   /*.prev_arch     =*/ NULL,
2768 };
2769
2770 /* Initialize the current architecture based on INFO.  If possible,
2771    re-use an architecture from ARCHES, which is a list of
2772    architectures already created during this debugging session.
2773
2774    Called e.g. at program startup, when reading a core file, and when
2775    reading a binary file.  */
2776
2777 static struct gdbarch *
2778 riscv_gdbarch_init (struct gdbarch_info info,
2779                     struct gdbarch_list *arches)
2780 {
2781   struct gdbarch *gdbarch;
2782   struct gdbarch_tdep *tdep;
2783   struct gdbarch_tdep tmp_tdep;
2784   int i;
2785
2786   /* Ideally, we'd like to get as much information from the target for
2787      things like register size, and whether the target has floating point
2788      hardware.  However, there are some things that the target can't tell
2789      us, like, what ABI is being used.
2790
2791      So, for now, we take as much information as possible from the ELF,
2792      including things like register size, and FP hardware support, along
2793      with information about the ABI.
2794
2795      Information about this target is built up in TMP_TDEP, and then we
2796      look for an existing gdbarch in ARCHES that matches TMP_TDEP.  If no
2797      match is found we'll create a new gdbarch and copy TMP_TDEP over.  */
2798   memset (&tmp_tdep, 0, sizeof (tmp_tdep));
2799
2800   if (info.abfd != NULL
2801       && bfd_get_flavour (info.abfd) == bfd_target_elf_flavour)
2802     {
2803       unsigned char eclass = elf_elfheader (info.abfd)->e_ident[EI_CLASS];
2804       int e_flags = elf_elfheader (info.abfd)->e_flags;
2805
2806       if (eclass == ELFCLASS32)
2807         tmp_tdep.abi.fields.base_len = 1;
2808       else if (eclass == ELFCLASS64)
2809         tmp_tdep.abi.fields.base_len = 2;
2810       else
2811         internal_error (__FILE__, __LINE__,
2812                         _("unknown ELF header class %d"), eclass);
2813
2814       if (e_flags & EF_RISCV_RVC)
2815         tmp_tdep.core_features |= (1 << ('C' - 'A'));
2816
2817       if (e_flags & EF_RISCV_FLOAT_ABI_DOUBLE)
2818         {
2819           tmp_tdep.abi.fields.float_abi = 2;
2820           tmp_tdep.core_features |= (1 << ('D' - 'A'));
2821           tmp_tdep.core_features |= (1 << ('F' - 'A'));
2822         }
2823       else if (e_flags & EF_RISCV_FLOAT_ABI_SINGLE)
2824         {
2825           tmp_tdep.abi.fields.float_abi = 1;
2826           tmp_tdep.core_features |= (1 << ('F' - 'A'));
2827         }
2828     }
2829   else
2830     {
2831       const struct bfd_arch_info *binfo = info.bfd_arch_info;
2832
2833       if (binfo->bits_per_word == 32)
2834         tmp_tdep.abi.fields.base_len = 1;
2835       else if (binfo->bits_per_word == 64)
2836         tmp_tdep.abi.fields.base_len = 2;
2837       else
2838         internal_error (__FILE__, __LINE__, _("unknown bits_per_word %d"),
2839                         binfo->bits_per_word);
2840     }
2841
2842   /* Find a candidate among the list of pre-declared architectures.  */
2843   for (arches = gdbarch_list_lookup_by_info (arches, &info);
2844        arches != NULL;
2845        arches = gdbarch_list_lookup_by_info (arches->next, &info))
2846     if (gdbarch_tdep (arches->gdbarch)->abi.value == tmp_tdep.abi.value)
2847       return arches->gdbarch;
2848
2849   /* None found, so create a new architecture from the information provided.  */
2850   tdep = (struct gdbarch_tdep *) xmalloc (sizeof *tdep);
2851   gdbarch = gdbarch_alloc (&info, tdep);
2852   memcpy (tdep, &tmp_tdep, sizeof (tmp_tdep));
2853
2854   /* Target data types.  */
2855   set_gdbarch_short_bit (gdbarch, 16);
2856   set_gdbarch_int_bit (gdbarch, 32);
2857   set_gdbarch_long_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
2858   set_gdbarch_long_long_bit (gdbarch, 64);
2859   set_gdbarch_float_bit (gdbarch, 32);
2860   set_gdbarch_double_bit (gdbarch, 64);
2861   set_gdbarch_long_double_bit (gdbarch, 128);
2862   set_gdbarch_long_double_format (gdbarch, floatformats_ia64_quad);
2863   set_gdbarch_ptr_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
2864   set_gdbarch_char_signed (gdbarch, 0);
2865
2866   /* Information about the target architecture.  */
2867   set_gdbarch_return_value (gdbarch, riscv_return_value);
2868   set_gdbarch_breakpoint_kind_from_pc (gdbarch, riscv_breakpoint_kind_from_pc);
2869   set_gdbarch_sw_breakpoint_from_kind (gdbarch, riscv_sw_breakpoint_from_kind);
2870   set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
2871
2872   /* Register architecture.  */
2873   set_gdbarch_num_regs (gdbarch, RISCV_LAST_REGNUM + 1);
2874   set_gdbarch_sp_regnum (gdbarch, RISCV_SP_REGNUM);
2875   set_gdbarch_pc_regnum (gdbarch, RISCV_PC_REGNUM);
2876   set_gdbarch_ps_regnum (gdbarch, RISCV_FP_REGNUM);
2877   set_gdbarch_deprecated_fp_regnum (gdbarch, RISCV_FP_REGNUM);
2878
2879   /* Functions to supply register information.  */
2880   set_gdbarch_register_name (gdbarch, riscv_register_name);
2881   set_gdbarch_register_type (gdbarch, riscv_register_type);
2882   set_gdbarch_print_registers_info (gdbarch, riscv_print_registers_info);
2883   set_gdbarch_register_reggroup_p (gdbarch, riscv_register_reggroup_p);
2884
2885   /* Functions to analyze frames.  */
2886   set_gdbarch_skip_prologue (gdbarch, riscv_skip_prologue);
2887   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
2888   set_gdbarch_frame_align (gdbarch, riscv_frame_align);
2889
2890   /* Functions to access frame data.  */
2891   set_gdbarch_unwind_pc (gdbarch, riscv_unwind_pc);
2892   set_gdbarch_unwind_sp (gdbarch, riscv_unwind_sp);
2893
2894   /* Functions handling dummy frames.  */
2895   set_gdbarch_call_dummy_location (gdbarch, ON_STACK);
2896   set_gdbarch_push_dummy_code (gdbarch, riscv_push_dummy_code);
2897   set_gdbarch_push_dummy_call (gdbarch, riscv_push_dummy_call);
2898   set_gdbarch_dummy_id (gdbarch, riscv_dummy_id);
2899
2900   /* Frame unwinders.  Use DWARF debug info if available, otherwise use our own
2901      unwinder.  */
2902   dwarf2_append_unwinders (gdbarch);
2903   frame_unwind_append_unwinder (gdbarch, &riscv_frame_unwind);
2904
2905   for (i = 0; i < ARRAY_SIZE (riscv_register_aliases); ++i)
2906     user_reg_add (gdbarch, riscv_register_aliases[i].name,
2907                   value_of_riscv_user_reg, &riscv_register_aliases[i].regnum);
2908
2909   /* Hook in OS ABI-specific overrides, if they have been registered.  */
2910   gdbarch_init_osabi (info, gdbarch);
2911
2912   return gdbarch;
2913 }
2914
2915 /* This decodes the current instruction and determines the address of the
2916    next instruction.  */
2917
2918 static CORE_ADDR
2919 riscv_next_pc (struct regcache *regcache, CORE_ADDR pc)
2920 {
2921   struct gdbarch *gdbarch = regcache->arch ();
2922   struct riscv_insn insn;
2923   CORE_ADDR next_pc;
2924
2925   insn.decode (gdbarch, pc);
2926   next_pc = pc + insn.length ();
2927
2928   if (insn.opcode () == riscv_insn::JAL)
2929     next_pc = pc + insn.imm_signed ();
2930   else if (insn.opcode () == riscv_insn::JALR)
2931     {
2932       LONGEST source;
2933       regcache->cooked_read (insn.rs1 (), &source);
2934       next_pc = (source + insn.imm_signed ()) & ~(CORE_ADDR) 0x1;
2935     }
2936   else if (insn.opcode () == riscv_insn::BEQ)
2937     {
2938       LONGEST src1, src2;
2939       regcache->cooked_read (insn.rs1 (), &src1);
2940       regcache->cooked_read (insn.rs2 (), &src2);
2941       if (src1 == src2)
2942         next_pc = pc + insn.imm_signed ();
2943     }
2944   else if (insn.opcode () == riscv_insn::BNE)
2945     {
2946       LONGEST src1, src2;
2947       regcache->cooked_read (insn.rs1 (), &src1);
2948       regcache->cooked_read (insn.rs2 (), &src2);
2949       if (src1 != src2)
2950         next_pc = pc + insn.imm_signed ();
2951     }
2952   else if (insn.opcode () == riscv_insn::BLT)
2953     {
2954       LONGEST src1, src2;
2955       regcache->cooked_read (insn.rs1 (), &src1);
2956       regcache->cooked_read (insn.rs2 (), &src2);
2957       if (src1 < src2)
2958         next_pc = pc + insn.imm_signed ();
2959     }
2960   else if (insn.opcode () == riscv_insn::BGE)
2961     {
2962       LONGEST src1, src2;
2963       regcache->cooked_read (insn.rs1 (), &src1);
2964       regcache->cooked_read (insn.rs2 (), &src2);
2965       if (src1 >= src2)
2966         next_pc = pc + insn.imm_signed ();
2967     }
2968   else if (insn.opcode () == riscv_insn::BLTU)
2969     {
2970       ULONGEST src1, src2;
2971       regcache->cooked_read (insn.rs1 (), &src1);
2972       regcache->cooked_read (insn.rs2 (), &src2);
2973       if (src1 < src2)
2974         next_pc = pc + insn.imm_signed ();
2975     }
2976   else if (insn.opcode () == riscv_insn::BGEU)
2977     {
2978       ULONGEST src1, src2;
2979       regcache->cooked_read (insn.rs1 (), &src1);
2980       regcache->cooked_read (insn.rs2 (), &src2);
2981       if (src1 >= src2)
2982         next_pc = pc + insn.imm_signed ();
2983     }
2984
2985   return next_pc;
2986 }
2987
2988 /* We can't put a breakpoint in the middle of a lr/sc atomic sequence, so look
2989    for the end of the sequence and put the breakpoint there.  */
2990
2991 static bool
2992 riscv_next_pc_atomic_sequence (struct regcache *regcache, CORE_ADDR pc,
2993                                CORE_ADDR *next_pc)
2994 {
2995   struct gdbarch *gdbarch = regcache->arch ();
2996   struct riscv_insn insn;
2997   CORE_ADDR cur_step_pc = pc;
2998   CORE_ADDR last_addr = 0;
2999
3000   /* First instruction has to be a load reserved.  */
3001   insn.decode (gdbarch, cur_step_pc);
3002   if (insn.opcode () != riscv_insn::LR)
3003     return false;
3004   cur_step_pc = cur_step_pc + insn.length ();
3005
3006   /* Next instruction should be branch to exit.  */
3007   insn.decode (gdbarch, cur_step_pc);
3008   if (insn.opcode () != riscv_insn::BNE)
3009     return false;
3010   last_addr = cur_step_pc + insn.imm_signed ();
3011   cur_step_pc = cur_step_pc + insn.length ();
3012
3013   /* Next instruction should be store conditional.  */
3014   insn.decode (gdbarch, cur_step_pc);
3015   if (insn.opcode () != riscv_insn::SC)
3016     return false;
3017   cur_step_pc = cur_step_pc + insn.length ();
3018
3019   /* Next instruction should be branch to start.  */
3020   insn.decode (gdbarch, cur_step_pc);
3021   if (insn.opcode () != riscv_insn::BNE)
3022     return false;
3023   if (pc != (cur_step_pc + insn.imm_signed ()))
3024     return false;
3025   cur_step_pc = cur_step_pc + insn.length ();
3026
3027   /* We should now be at the end of the sequence.  */
3028   if (cur_step_pc != last_addr)
3029     return false;
3030
3031   *next_pc = cur_step_pc;
3032   return true;
3033 }
3034
3035 /* This is called just before we want to resume the inferior, if we want to
3036    single-step it but there is no hardware or kernel single-step support.  We
3037    find the target of the coming instruction and breakpoint it.  */
3038
3039 std::vector<CORE_ADDR>
3040 riscv_software_single_step (struct regcache *regcache)
3041 {
3042   CORE_ADDR pc, next_pc;
3043
3044   pc = regcache_read_pc (regcache);
3045
3046   if (riscv_next_pc_atomic_sequence (regcache, pc, &next_pc))
3047     return {next_pc};
3048
3049   next_pc = riscv_next_pc (regcache, pc);
3050
3051   return {next_pc};
3052 }
3053
3054 void
3055 _initialize_riscv_tdep (void)
3056 {
3057   gdbarch_register (bfd_arch_riscv, riscv_gdbarch_init, NULL);
3058
3059   /* Add root prefix command for all "set debug riscv" and "show debug
3060      riscv" commands.  */
3061   add_prefix_cmd ("riscv", no_class, set_debug_riscv_command,
3062                   _("RISC-V specific debug commands."),
3063                   &setdebugriscvcmdlist, "set debug riscv ", 0,
3064                   &setdebuglist);
3065
3066   add_prefix_cmd ("riscv", no_class, show_debug_riscv_command,
3067                   _("RISC-V specific debug commands."),
3068                   &showdebugriscvcmdlist, "show debug riscv ", 0,
3069                   &showdebuglist);
3070
3071   add_setshow_zuinteger_cmd ("breakpoints", class_maintenance,
3072                              &riscv_debug_breakpoints,  _("\
3073 Set riscv breakpoint debugging."), _("\
3074 Show riscv breakpoint debugging."), _("\
3075 When non-zero, print debugging information for the riscv specific parts\n\
3076 of the breakpoint mechanism."),
3077                              NULL,
3078                              show_riscv_debug_variable,
3079                              &setdebugriscvcmdlist, &showdebugriscvcmdlist);
3080
3081   add_setshow_zuinteger_cmd ("infcall", class_maintenance,
3082                              &riscv_debug_infcall,  _("\
3083 Set riscv inferior call debugging."), _("\
3084 Show riscv inferior call debugging."), _("\
3085 When non-zero, print debugging information for the riscv specific parts\n\
3086 of the inferior call mechanism."),
3087                              NULL,
3088                              show_riscv_debug_variable,
3089                              &setdebugriscvcmdlist, &showdebugriscvcmdlist);
3090
3091   add_setshow_zuinteger_cmd ("unwinder", class_maintenance,
3092                              &riscv_debug_unwinder,  _("\
3093 Set riscv stack unwinding debugging."), _("\
3094 Show riscv stack unwinding debugging."), _("\
3095 When non-zero, print debugging information for the riscv specific parts\n\
3096 of the stack unwinding mechanism."),
3097                              NULL,
3098                              show_riscv_debug_variable,
3099                              &setdebugriscvcmdlist, &showdebugriscvcmdlist);
3100
3101   /* Add root prefix command for all "set riscv" and "show riscv" commands.  */
3102   add_prefix_cmd ("riscv", no_class, set_riscv_command,
3103                   _("RISC-V specific commands."),
3104                   &setriscvcmdlist, "set riscv ", 0, &setlist);
3105
3106   add_prefix_cmd ("riscv", no_class, show_riscv_command,
3107                   _("RISC-V specific commands."),
3108                   &showriscvcmdlist, "show riscv ", 0, &showlist);
3109
3110
3111   use_compressed_breakpoints = AUTO_BOOLEAN_AUTO;
3112   add_setshow_auto_boolean_cmd ("use-compressed-breakpoints", no_class,
3113                                 &use_compressed_breakpoints,
3114                                 _("\
3115 Set debugger's use of compressed breakpoints."), _("    \
3116 Show debugger's use of compressed breakpoints."), _("\
3117 Debugging compressed code requires compressed breakpoints to be used. If\n\
3118 left to 'auto' then gdb will use them if the existing instruction is a\n\
3119 compressed instruction. If that doesn't give the correct behavior, then\n\
3120 this option can be used."),
3121                                 NULL,
3122                                 show_use_compressed_breakpoints,
3123                                 &setriscvcmdlist,
3124                                 &showriscvcmdlist);
3125 }