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