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