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