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