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