gdb/MAINTAINERS: add Luis Machado as global maintainer
[binutils-gdb.git] / gdb / riscv-tdep.c
1 /* Target-dependent code for the RISC-V architecture, for GDB.
2
3 Copyright (C) 2018-2023 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 "reggroups.h"
37 #include "opcode/riscv.h"
38 #include "elf/riscv.h"
39 #include "elf-bfd.h"
40 #include "symcat.h"
41 #include "dis-asm.h"
42 #include "frame-unwind.h"
43 #include "frame-base.h"
44 #include "trad-frame.h"
45 #include "infcall.h"
46 #include "floatformat.h"
47 #include "remote.h"
48 #include "target-descriptions.h"
49 #include "dwarf2/frame.h"
50 #include "user-regs.h"
51 #include "valprint.h"
52 #include "gdbsupport/common-defs.h"
53 #include "opcode/riscv-opc.h"
54 #include "cli/cli-decode.h"
55 #include "observable.h"
56 #include "prologue-value.h"
57 #include "arch/riscv.h"
58 #include "riscv-ravenscar-thread.h"
59 #include "gdbsupport/gdb-safe-ctype.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 /* When this is true debugging information about breakpoint kinds will be
78 printed. */
79
80 static bool riscv_debug_breakpoints = false;
81
82 /* Print a "riscv-breakpoints" debug statement. */
83
84 #define riscv_breakpoints_debug_printf(fmt, ...) \
85 debug_prefixed_printf_cond (riscv_debug_breakpoints, \
86 "riscv-breakpoints", \
87 fmt, ##__VA_ARGS__)
88
89 /* When this is true debugging information about inferior calls will be
90 printed. */
91
92 static bool riscv_debug_infcall = false;
93
94 /* Print a "riscv-infcall" debug statement. */
95
96 #define riscv_infcall_debug_printf(fmt, ...) \
97 debug_prefixed_printf_cond (riscv_debug_infcall, "riscv-infcall", \
98 fmt, ##__VA_ARGS__)
99
100 /* Print "riscv-infcall" start/end debug statements. */
101
102 #define RISCV_INFCALL_SCOPED_DEBUG_START_END(fmt, ...) \
103 scoped_debug_start_end (riscv_debug_infcall, "riscv-infcall", \
104 fmt, ##__VA_ARGS__)
105
106 /* When this is true debugging information about stack unwinding will be
107 printed. */
108
109 static bool riscv_debug_unwinder = false;
110
111 /* Print a "riscv-unwinder" debug statement. */
112
113 #define riscv_unwinder_debug_printf(fmt, ...) \
114 debug_prefixed_printf_cond (riscv_debug_unwinder, "riscv-unwinder", \
115 fmt, ##__VA_ARGS__)
116
117 /* When this is true debugging information about gdbarch initialisation
118 will be printed. */
119
120 static bool riscv_debug_gdbarch = false;
121
122 /* Print a "riscv-gdbarch" debug statement. */
123
124 #define riscv_gdbarch_debug_printf(fmt, ...) \
125 debug_prefixed_printf_cond (riscv_debug_gdbarch, "riscv-gdbarch", \
126 fmt, ##__VA_ARGS__)
127
128 /* The names of the RISC-V target description features. */
129 const char *riscv_feature_name_csr = "org.gnu.gdb.riscv.csr";
130 static const char *riscv_feature_name_cpu = "org.gnu.gdb.riscv.cpu";
131 static const char *riscv_feature_name_fpu = "org.gnu.gdb.riscv.fpu";
132 static const char *riscv_feature_name_virtual = "org.gnu.gdb.riscv.virtual";
133 static const char *riscv_feature_name_vector = "org.gnu.gdb.riscv.vector";
134
135 /* The current set of options to be passed to the disassembler. */
136 static char *riscv_disassembler_options;
137
138 /* Cached information about a frame. */
139
140 struct riscv_unwind_cache
141 {
142 /* The register from which we can calculate the frame base. This is
143 usually $sp or $fp. */
144 int frame_base_reg;
145
146 /* The offset from the current value in register FRAME_BASE_REG to the
147 actual frame base address. */
148 int frame_base_offset;
149
150 /* Information about previous register values. */
151 trad_frame_saved_reg *regs;
152
153 /* The id for this frame. */
154 struct frame_id this_id;
155
156 /* The base (stack) address for this frame. This is the stack pointer
157 value on entry to this frame before any adjustments are made. */
158 CORE_ADDR frame_base;
159 };
160
161 /* RISC-V specific register group for CSRs. */
162
163 static const reggroup *csr_reggroup = nullptr;
164
165 /* Callback function for user_reg_add. */
166
167 static struct value *
168 value_of_riscv_user_reg (frame_info_ptr frame, const void *baton)
169 {
170 const int *reg_p = (const int *) baton;
171 return value_of_register (*reg_p, frame);
172 }
173
174 /* Information about a register alias that needs to be set up for this
175 target. These are collected when the target's XML description is
176 analysed, and then processed later, once the gdbarch has been created. */
177
178 class riscv_pending_register_alias
179 {
180 public:
181 /* Constructor. */
182
183 riscv_pending_register_alias (const char *name, const void *baton)
184 : m_name (name),
185 m_baton (baton)
186 { /* Nothing. */ }
187
188 /* Convert this into a user register for GDBARCH. */
189
190 void create (struct gdbarch *gdbarch) const
191 {
192 user_reg_add (gdbarch, m_name, value_of_riscv_user_reg, m_baton);
193 }
194
195 private:
196 /* The name for this alias. */
197 const char *m_name;
198
199 /* The baton value for passing to user_reg_add. This must point to some
200 data that will live for at least as long as the gdbarch object to
201 which the user register is attached. */
202 const void *m_baton;
203 };
204
205 /* A set of registers that we expect to find in a tdesc_feature. These
206 are use in RISCV_GDBARCH_INIT when processing the target description. */
207
208 struct riscv_register_feature
209 {
210 explicit riscv_register_feature (const char *feature_name)
211 : m_feature_name (feature_name)
212 { /* Delete. */ }
213
214 riscv_register_feature () = delete;
215 DISABLE_COPY_AND_ASSIGN (riscv_register_feature);
216
217 /* Information for a single register. */
218 struct register_info
219 {
220 /* The GDB register number for this register. */
221 int regnum;
222
223 /* List of names for this register. The first name in this list is the
224 preferred name, the name GDB should use when describing this
225 register. */
226 std::vector<const char *> names;
227
228 /* Look in FEATURE for a register with a name from this classes names
229 list. If the register is found then register its number with
230 TDESC_DATA and add all its aliases to the ALIASES list.
231 PREFER_FIRST_NAME_P is used when deciding which aliases to create. */
232 bool check (struct tdesc_arch_data *tdesc_data,
233 const struct tdesc_feature *feature,
234 bool prefer_first_name_p,
235 std::vector<riscv_pending_register_alias> *aliases) const;
236 };
237
238 /* Return the name of this feature. */
239 const char *name () const
240 { return m_feature_name; }
241
242 protected:
243
244 /* Return a target description feature extracted from TDESC for this
245 register feature. Will return nullptr if there is no feature in TDESC
246 with the name M_FEATURE_NAME. */
247 const struct tdesc_feature *tdesc_feature (const struct target_desc *tdesc) const
248 {
249 return tdesc_find_feature (tdesc, name ());
250 }
251
252 /* List of all the registers that we expect that we might find in this
253 register set. */
254 std::vector<struct register_info> m_registers;
255
256 private:
257
258 /* The name for this feature. This is the name used to find this feature
259 within the target description. */
260 const char *m_feature_name;
261 };
262
263 /* See description in the class declaration above. */
264
265 bool
266 riscv_register_feature::register_info::check
267 (struct tdesc_arch_data *tdesc_data,
268 const struct tdesc_feature *feature,
269 bool prefer_first_name_p,
270 std::vector<riscv_pending_register_alias> *aliases) const
271 {
272 for (const char *name : this->names)
273 {
274 bool found = tdesc_numbered_register (feature, tdesc_data,
275 this->regnum, name);
276 if (found)
277 {
278 /* We know that the target description mentions this
279 register. In RISCV_REGISTER_NAME we ensure that GDB
280 always uses the first name for each register, so here we
281 add aliases for all of the remaining names. */
282 int start_index = prefer_first_name_p ? 1 : 0;
283 for (int i = start_index; i < this->names.size (); ++i)
284 {
285 const char *alias = this->names[i];
286 if (alias == name && !prefer_first_name_p)
287 continue;
288 aliases->emplace_back (alias, (void *) &this->regnum);
289 }
290 return true;
291 }
292 }
293 return false;
294 }
295
296 /* Class representing the x-registers feature set. */
297
298 struct riscv_xreg_feature : public riscv_register_feature
299 {
300 riscv_xreg_feature ()
301 : riscv_register_feature (riscv_feature_name_cpu)
302 {
303 m_registers = {
304 { RISCV_ZERO_REGNUM + 0, { "zero", "x0" } },
305 { RISCV_ZERO_REGNUM + 1, { "ra", "x1" } },
306 { RISCV_ZERO_REGNUM + 2, { "sp", "x2" } },
307 { RISCV_ZERO_REGNUM + 3, { "gp", "x3" } },
308 { RISCV_ZERO_REGNUM + 4, { "tp", "x4" } },
309 { RISCV_ZERO_REGNUM + 5, { "t0", "x5" } },
310 { RISCV_ZERO_REGNUM + 6, { "t1", "x6" } },
311 { RISCV_ZERO_REGNUM + 7, { "t2", "x7" } },
312 { RISCV_ZERO_REGNUM + 8, { "fp", "x8", "s0" } },
313 { RISCV_ZERO_REGNUM + 9, { "s1", "x9" } },
314 { RISCV_ZERO_REGNUM + 10, { "a0", "x10" } },
315 { RISCV_ZERO_REGNUM + 11, { "a1", "x11" } },
316 { RISCV_ZERO_REGNUM + 12, { "a2", "x12" } },
317 { RISCV_ZERO_REGNUM + 13, { "a3", "x13" } },
318 { RISCV_ZERO_REGNUM + 14, { "a4", "x14" } },
319 { RISCV_ZERO_REGNUM + 15, { "a5", "x15" } },
320 { RISCV_ZERO_REGNUM + 16, { "a6", "x16" } },
321 { RISCV_ZERO_REGNUM + 17, { "a7", "x17" } },
322 { RISCV_ZERO_REGNUM + 18, { "s2", "x18" } },
323 { RISCV_ZERO_REGNUM + 19, { "s3", "x19" } },
324 { RISCV_ZERO_REGNUM + 20, { "s4", "x20" } },
325 { RISCV_ZERO_REGNUM + 21, { "s5", "x21" } },
326 { RISCV_ZERO_REGNUM + 22, { "s6", "x22" } },
327 { RISCV_ZERO_REGNUM + 23, { "s7", "x23" } },
328 { RISCV_ZERO_REGNUM + 24, { "s8", "x24" } },
329 { RISCV_ZERO_REGNUM + 25, { "s9", "x25" } },
330 { RISCV_ZERO_REGNUM + 26, { "s10", "x26" } },
331 { RISCV_ZERO_REGNUM + 27, { "s11", "x27" } },
332 { RISCV_ZERO_REGNUM + 28, { "t3", "x28" } },
333 { RISCV_ZERO_REGNUM + 29, { "t4", "x29" } },
334 { RISCV_ZERO_REGNUM + 30, { "t5", "x30" } },
335 { RISCV_ZERO_REGNUM + 31, { "t6", "x31" } },
336 { RISCV_ZERO_REGNUM + 32, { "pc" } }
337 };
338 }
339
340 /* Return the preferred name for the register with gdb register number
341 REGNUM, which must be in the inclusive range RISCV_ZERO_REGNUM to
342 RISCV_PC_REGNUM. */
343 const char *register_name (int regnum) const
344 {
345 gdb_assert (regnum >= RISCV_ZERO_REGNUM && regnum <= m_registers.size ());
346 return m_registers[regnum].names[0];
347 }
348
349 /* Check this feature within TDESC, record the registers from this
350 feature into TDESC_DATA and update ALIASES and FEATURES. */
351 bool check (const struct target_desc *tdesc,
352 struct tdesc_arch_data *tdesc_data,
353 std::vector<riscv_pending_register_alias> *aliases,
354 struct riscv_gdbarch_features *features) const
355 {
356 const struct tdesc_feature *feature_cpu = tdesc_feature (tdesc);
357
358 if (feature_cpu == nullptr)
359 return false;
360
361 bool seen_an_optional_reg_p = false;
362 for (const auto &reg : m_registers)
363 {
364 bool found = reg.check (tdesc_data, feature_cpu, true, aliases);
365
366 bool is_optional_reg_p = (reg.regnum >= RISCV_ZERO_REGNUM + 16
367 && reg.regnum < RISCV_ZERO_REGNUM + 32);
368
369 if (!found && (!is_optional_reg_p || seen_an_optional_reg_p))
370 return false;
371 else if (found && is_optional_reg_p)
372 seen_an_optional_reg_p = true;
373 }
374
375 /* Check that all of the core cpu registers have the same bitsize. */
376 int xlen_bitsize = tdesc_register_bitsize (feature_cpu, "pc");
377
378 bool valid_p = true;
379 for (auto &tdesc_reg : feature_cpu->registers)
380 valid_p &= (tdesc_reg->bitsize == xlen_bitsize);
381
382 features->xlen = (xlen_bitsize / 8);
383 features->embedded = !seen_an_optional_reg_p;
384
385 return valid_p;
386 }
387 };
388
389 /* An instance of the x-register feature set. */
390
391 static const struct riscv_xreg_feature riscv_xreg_feature;
392
393 /* Class representing the f-registers feature set. */
394
395 struct riscv_freg_feature : public riscv_register_feature
396 {
397 riscv_freg_feature ()
398 : riscv_register_feature (riscv_feature_name_fpu)
399 {
400 m_registers = {
401 { RISCV_FIRST_FP_REGNUM + 0, { "ft0", "f0" } },
402 { RISCV_FIRST_FP_REGNUM + 1, { "ft1", "f1" } },
403 { RISCV_FIRST_FP_REGNUM + 2, { "ft2", "f2" } },
404 { RISCV_FIRST_FP_REGNUM + 3, { "ft3", "f3" } },
405 { RISCV_FIRST_FP_REGNUM + 4, { "ft4", "f4" } },
406 { RISCV_FIRST_FP_REGNUM + 5, { "ft5", "f5" } },
407 { RISCV_FIRST_FP_REGNUM + 6, { "ft6", "f6" } },
408 { RISCV_FIRST_FP_REGNUM + 7, { "ft7", "f7" } },
409 { RISCV_FIRST_FP_REGNUM + 8, { "fs0", "f8" } },
410 { RISCV_FIRST_FP_REGNUM + 9, { "fs1", "f9" } },
411 { RISCV_FIRST_FP_REGNUM + 10, { "fa0", "f10" } },
412 { RISCV_FIRST_FP_REGNUM + 11, { "fa1", "f11" } },
413 { RISCV_FIRST_FP_REGNUM + 12, { "fa2", "f12" } },
414 { RISCV_FIRST_FP_REGNUM + 13, { "fa3", "f13" } },
415 { RISCV_FIRST_FP_REGNUM + 14, { "fa4", "f14" } },
416 { RISCV_FIRST_FP_REGNUM + 15, { "fa5", "f15" } },
417 { RISCV_FIRST_FP_REGNUM + 16, { "fa6", "f16" } },
418 { RISCV_FIRST_FP_REGNUM + 17, { "fa7", "f17" } },
419 { RISCV_FIRST_FP_REGNUM + 18, { "fs2", "f18" } },
420 { RISCV_FIRST_FP_REGNUM + 19, { "fs3", "f19" } },
421 { RISCV_FIRST_FP_REGNUM + 20, { "fs4", "f20" } },
422 { RISCV_FIRST_FP_REGNUM + 21, { "fs5", "f21" } },
423 { RISCV_FIRST_FP_REGNUM + 22, { "fs6", "f22" } },
424 { RISCV_FIRST_FP_REGNUM + 23, { "fs7", "f23" } },
425 { RISCV_FIRST_FP_REGNUM + 24, { "fs8", "f24" } },
426 { RISCV_FIRST_FP_REGNUM + 25, { "fs9", "f25" } },
427 { RISCV_FIRST_FP_REGNUM + 26, { "fs10", "f26" } },
428 { RISCV_FIRST_FP_REGNUM + 27, { "fs11", "f27" } },
429 { RISCV_FIRST_FP_REGNUM + 28, { "ft8", "f28" } },
430 { RISCV_FIRST_FP_REGNUM + 29, { "ft9", "f29" } },
431 { RISCV_FIRST_FP_REGNUM + 30, { "ft10", "f30" } },
432 { RISCV_FIRST_FP_REGNUM + 31, { "ft11", "f31" } },
433 { RISCV_CSR_FFLAGS_REGNUM, { "fflags", "csr1" } },
434 { RISCV_CSR_FRM_REGNUM, { "frm", "csr2" } },
435 { RISCV_CSR_FCSR_REGNUM, { "fcsr", "csr3" } },
436 };
437 }
438
439 /* Return the preferred name for the register with gdb register number
440 REGNUM, which must be in the inclusive range RISCV_FIRST_FP_REGNUM to
441 RISCV_LAST_FP_REGNUM. */
442 const char *register_name (int regnum) const
443 {
444 gdb_static_assert (RISCV_LAST_FP_REGNUM == RISCV_FIRST_FP_REGNUM + 31);
445 gdb_assert (regnum >= RISCV_FIRST_FP_REGNUM
446 && regnum <= RISCV_LAST_FP_REGNUM);
447 regnum -= RISCV_FIRST_FP_REGNUM;
448 return m_registers[regnum].names[0];
449 }
450
451 /* Check this feature within TDESC, record the registers from this
452 feature into TDESC_DATA and update ALIASES and FEATURES. */
453 bool check (const struct target_desc *tdesc,
454 struct tdesc_arch_data *tdesc_data,
455 std::vector<riscv_pending_register_alias> *aliases,
456 struct riscv_gdbarch_features *features) const
457 {
458 const struct tdesc_feature *feature_fpu = tdesc_feature (tdesc);
459
460 /* It's fine if this feature is missing. Update the architecture
461 feature set and return. */
462 if (feature_fpu == nullptr)
463 {
464 features->flen = 0;
465 return true;
466 }
467
468 /* Check all of the floating pointer registers are present. We also
469 check that the floating point CSRs are present too, though if these
470 are missing this is not fatal. */
471 for (const auto &reg : m_registers)
472 {
473 bool found = reg.check (tdesc_data, feature_fpu, true, aliases);
474
475 bool is_ctrl_reg_p = reg.regnum > RISCV_LAST_FP_REGNUM;
476
477 if (!found && !is_ctrl_reg_p)
478 return false;
479 }
480
481 /* Look through all of the floating point registers (not the FP CSRs
482 though), and check they all have the same bitsize. Use this bitsize
483 to update the feature set for this gdbarch. */
484 int fp_bitsize = -1;
485 for (const auto &reg : m_registers)
486 {
487 /* Stop once we get to the CSRs which are at the end of the
488 M_REGISTERS list. */
489 if (reg.regnum > RISCV_LAST_FP_REGNUM)
490 break;
491
492 int reg_bitsize = -1;
493 for (const char *name : reg.names)
494 {
495 if (tdesc_unnumbered_register (feature_fpu, name))
496 {
497 reg_bitsize = tdesc_register_bitsize (feature_fpu, name);
498 break;
499 }
500 }
501 gdb_assert (reg_bitsize != -1);
502 if (fp_bitsize == -1)
503 fp_bitsize = reg_bitsize;
504 else if (fp_bitsize != reg_bitsize)
505 return false;
506 }
507
508 features->flen = (fp_bitsize / 8);
509 return true;
510 }
511 };
512
513 /* An instance of the f-register feature set. */
514
515 static const struct riscv_freg_feature riscv_freg_feature;
516
517 /* Class representing the virtual registers. These are not physical
518 registers on the hardware, but might be available from the target.
519 These are not pseudo registers, reading these really does result in a
520 register read from the target, it is just that there might not be a
521 physical register backing the result. */
522
523 struct riscv_virtual_feature : public riscv_register_feature
524 {
525 riscv_virtual_feature ()
526 : riscv_register_feature (riscv_feature_name_virtual)
527 {
528 m_registers = {
529 { RISCV_PRIV_REGNUM, { "priv" } }
530 };
531 }
532
533 bool check (const struct target_desc *tdesc,
534 struct tdesc_arch_data *tdesc_data,
535 std::vector<riscv_pending_register_alias> *aliases,
536 struct riscv_gdbarch_features *features) const
537 {
538 const struct tdesc_feature *feature_virtual = tdesc_feature (tdesc);
539
540 /* It's fine if this feature is missing. */
541 if (feature_virtual == nullptr)
542 return true;
543
544 /* We don't check the return value from the call to check here, all the
545 registers in this feature are optional. */
546 for (const auto &reg : m_registers)
547 reg.check (tdesc_data, feature_virtual, true, aliases);
548
549 return true;
550 }
551 };
552
553 /* An instance of the virtual register feature. */
554
555 static const struct riscv_virtual_feature riscv_virtual_feature;
556
557 /* Class representing the CSR feature. */
558
559 struct riscv_csr_feature : public riscv_register_feature
560 {
561 riscv_csr_feature ()
562 : riscv_register_feature (riscv_feature_name_csr)
563 {
564 m_registers = {
565 #define DECLARE_CSR(NAME,VALUE,CLASS,DEFINE_VER,ABORT_VER) \
566 { RISCV_ ## VALUE ## _REGNUM, { # NAME } },
567 #include "opcode/riscv-opc.h"
568 #undef DECLARE_CSR
569 };
570 riscv_create_csr_aliases ();
571 }
572
573 bool check (const struct target_desc *tdesc,
574 struct tdesc_arch_data *tdesc_data,
575 std::vector<riscv_pending_register_alias> *aliases,
576 struct riscv_gdbarch_features *features) const
577 {
578 const struct tdesc_feature *feature_csr = tdesc_feature (tdesc);
579
580 /* It's fine if this feature is missing. */
581 if (feature_csr == nullptr)
582 return true;
583
584 /* We don't check the return value from the call to check here, all the
585 registers in this feature are optional. */
586 for (const auto &reg : m_registers)
587 reg.check (tdesc_data, feature_csr, true, aliases);
588
589 return true;
590 }
591
592 private:
593
594 /* Complete RISCV_CSR_FEATURE, building the CSR alias names and adding them
595 to the name list for each register. */
596
597 void
598 riscv_create_csr_aliases ()
599 {
600 for (auto &reg : m_registers)
601 {
602 int csr_num = reg.regnum - RISCV_FIRST_CSR_REGNUM;
603 gdb::unique_xmalloc_ptr<char> alias = xstrprintf ("csr%d", csr_num);
604 reg.names.push_back (alias.release ());
605 }
606 }
607 };
608
609 /* An instance of the csr register feature. */
610
611 static const struct riscv_csr_feature riscv_csr_feature;
612
613 /* Class representing the v-registers feature set. */
614
615 struct riscv_vector_feature : public riscv_register_feature
616 {
617 riscv_vector_feature ()
618 : riscv_register_feature (riscv_feature_name_vector)
619 {
620 m_registers = {
621 { RISCV_V0_REGNUM + 0, { "v0" } },
622 { RISCV_V0_REGNUM + 1, { "v1" } },
623 { RISCV_V0_REGNUM + 2, { "v2" } },
624 { RISCV_V0_REGNUM + 3, { "v3" } },
625 { RISCV_V0_REGNUM + 4, { "v4" } },
626 { RISCV_V0_REGNUM + 5, { "v5" } },
627 { RISCV_V0_REGNUM + 6, { "v6" } },
628 { RISCV_V0_REGNUM + 7, { "v7" } },
629 { RISCV_V0_REGNUM + 8, { "v8" } },
630 { RISCV_V0_REGNUM + 9, { "v9" } },
631 { RISCV_V0_REGNUM + 10, { "v10" } },
632 { RISCV_V0_REGNUM + 11, { "v11" } },
633 { RISCV_V0_REGNUM + 12, { "v12" } },
634 { RISCV_V0_REGNUM + 13, { "v13" } },
635 { RISCV_V0_REGNUM + 14, { "v14" } },
636 { RISCV_V0_REGNUM + 15, { "v15" } },
637 { RISCV_V0_REGNUM + 16, { "v16" } },
638 { RISCV_V0_REGNUM + 17, { "v17" } },
639 { RISCV_V0_REGNUM + 18, { "v18" } },
640 { RISCV_V0_REGNUM + 19, { "v19" } },
641 { RISCV_V0_REGNUM + 20, { "v20" } },
642 { RISCV_V0_REGNUM + 21, { "v21" } },
643 { RISCV_V0_REGNUM + 22, { "v22" } },
644 { RISCV_V0_REGNUM + 23, { "v23" } },
645 { RISCV_V0_REGNUM + 24, { "v24" } },
646 { RISCV_V0_REGNUM + 25, { "v25" } },
647 { RISCV_V0_REGNUM + 26, { "v26" } },
648 { RISCV_V0_REGNUM + 27, { "v27" } },
649 { RISCV_V0_REGNUM + 28, { "v28" } },
650 { RISCV_V0_REGNUM + 29, { "v29" } },
651 { RISCV_V0_REGNUM + 30, { "v30" } },
652 { RISCV_V0_REGNUM + 31, { "v31" } },
653 };
654 }
655
656 /* Return the preferred name for the register with gdb register number
657 REGNUM, which must be in the inclusive range RISCV_V0_REGNUM to
658 RISCV_V0_REGNUM + 31. */
659 const char *register_name (int regnum) const
660 {
661 gdb_assert (regnum >= RISCV_V0_REGNUM
662 && regnum <= RISCV_V0_REGNUM + 31);
663 regnum -= RISCV_V0_REGNUM;
664 return m_registers[regnum].names[0];
665 }
666
667 /* Check this feature within TDESC, record the registers from this
668 feature into TDESC_DATA and update ALIASES and FEATURES. */
669 bool check (const struct target_desc *tdesc,
670 struct tdesc_arch_data *tdesc_data,
671 std::vector<riscv_pending_register_alias> *aliases,
672 struct riscv_gdbarch_features *features) const
673 {
674 const struct tdesc_feature *feature_vector = tdesc_feature (tdesc);
675
676 /* It's fine if this feature is missing. Update the architecture
677 feature set and return. */
678 if (feature_vector == nullptr)
679 {
680 features->vlen = 0;
681 return true;
682 }
683
684 /* Check all of the vector registers are present. */
685 for (const auto &reg : m_registers)
686 {
687 if (!reg.check (tdesc_data, feature_vector, true, aliases))
688 return false;
689 }
690
691 /* Look through all of the vector registers and check they all have the
692 same bitsize. Use this bitsize to update the feature set for this
693 gdbarch. */
694 int vector_bitsize = -1;
695 for (const auto &reg : m_registers)
696 {
697 int reg_bitsize = -1;
698 for (const char *name : reg.names)
699 {
700 if (tdesc_unnumbered_register (feature_vector, name))
701 {
702 reg_bitsize = tdesc_register_bitsize (feature_vector, name);
703 break;
704 }
705 }
706 gdb_assert (reg_bitsize != -1);
707 if (vector_bitsize == -1)
708 vector_bitsize = reg_bitsize;
709 else if (vector_bitsize != reg_bitsize)
710 return false;
711 }
712
713 features->vlen = (vector_bitsize / 8);
714 return true;
715 }
716 };
717
718 /* An instance of the v-register feature set. */
719
720 static const struct riscv_vector_feature riscv_vector_feature;
721
722 /* Controls whether we place compressed breakpoints or not. When in auto
723 mode GDB tries to determine if the target supports compressed
724 breakpoints, and uses them if it does. */
725
726 static enum auto_boolean use_compressed_breakpoints;
727
728 /* The show callback for 'show riscv use-compressed-breakpoints'. */
729
730 static void
731 show_use_compressed_breakpoints (struct ui_file *file, int from_tty,
732 struct cmd_list_element *c,
733 const char *value)
734 {
735 gdb_printf (file,
736 _("Debugger's use of compressed breakpoints is set "
737 "to %s.\n"), value);
738 }
739
740 /* The set and show lists for 'set riscv' and 'show riscv' prefixes. */
741
742 static struct cmd_list_element *setriscvcmdlist = NULL;
743 static struct cmd_list_element *showriscvcmdlist = NULL;
744
745 /* The set and show lists for 'set riscv' and 'show riscv' prefixes. */
746
747 static struct cmd_list_element *setdebugriscvcmdlist = NULL;
748 static struct cmd_list_element *showdebugriscvcmdlist = NULL;
749
750 /* The show callback for all 'show debug riscv VARNAME' variables. */
751
752 static void
753 show_riscv_debug_variable (struct ui_file *file, int from_tty,
754 struct cmd_list_element *c,
755 const char *value)
756 {
757 gdb_printf (file,
758 _("RiscV debug variable `%s' is set to: %s\n"),
759 c->name, value);
760 }
761
762 /* See riscv-tdep.h. */
763
764 int
765 riscv_isa_xlen (struct gdbarch *gdbarch)
766 {
767 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
768 return tdep->isa_features.xlen;
769 }
770
771 /* See riscv-tdep.h. */
772
773 int
774 riscv_abi_xlen (struct gdbarch *gdbarch)
775 {
776 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
777 return tdep->abi_features.xlen;
778 }
779
780 /* See riscv-tdep.h. */
781
782 int
783 riscv_isa_flen (struct gdbarch *gdbarch)
784 {
785 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
786 return tdep->isa_features.flen;
787 }
788
789 /* See riscv-tdep.h. */
790
791 int
792 riscv_abi_flen (struct gdbarch *gdbarch)
793 {
794 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
795 return tdep->abi_features.flen;
796 }
797
798 /* See riscv-tdep.h. */
799
800 bool
801 riscv_abi_embedded (struct gdbarch *gdbarch)
802 {
803 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
804 return tdep->abi_features.embedded;
805 }
806
807 /* Return true if the target for GDBARCH has floating point hardware. */
808
809 static bool
810 riscv_has_fp_regs (struct gdbarch *gdbarch)
811 {
812 return (riscv_isa_flen (gdbarch) > 0);
813 }
814
815 /* Return true if GDBARCH is using any of the floating point hardware ABIs. */
816
817 static bool
818 riscv_has_fp_abi (struct gdbarch *gdbarch)
819 {
820 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
821 return tdep->abi_features.flen > 0;
822 }
823
824 /* Return true if REGNO is a floating pointer register. */
825
826 static bool
827 riscv_is_fp_regno_p (int regno)
828 {
829 return (regno >= RISCV_FIRST_FP_REGNUM
830 && regno <= RISCV_LAST_FP_REGNUM);
831 }
832
833 /* Implement the breakpoint_kind_from_pc gdbarch method. */
834
835 static int
836 riscv_breakpoint_kind_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr)
837 {
838 if (use_compressed_breakpoints == AUTO_BOOLEAN_AUTO)
839 {
840 bool unaligned_p = false;
841 gdb_byte buf[1];
842
843 /* Some targets don't support unaligned reads. The address can only
844 be unaligned if the C extension is supported. So it is safe to
845 use a compressed breakpoint in this case. */
846 if (*pcptr & 0x2)
847 unaligned_p = true;
848 else
849 {
850 /* Read the opcode byte to determine the instruction length. If
851 the read fails this may be because we tried to set the
852 breakpoint at an invalid address, in this case we provide a
853 fake result which will give a breakpoint length of 4.
854 Hopefully when we try to actually insert the breakpoint we
855 will see a failure then too which will be reported to the
856 user. */
857 if (target_read_code (*pcptr, buf, 1) == -1)
858 buf[0] = 0;
859 }
860
861 if (riscv_debug_breakpoints)
862 {
863 const char *bp = (unaligned_p || riscv_insn_length (buf[0]) == 2
864 ? "C.EBREAK" : "EBREAK");
865
866 std::string suffix;
867 if (unaligned_p)
868 suffix = "(unaligned address)";
869 else
870 suffix = string_printf ("(instruction length %d)",
871 riscv_insn_length (buf[0]));
872 riscv_breakpoints_debug_printf ("Using %s for breakpoint at %s %s",
873 bp, paddress (gdbarch, *pcptr),
874 suffix.c_str ());
875 }
876 if (unaligned_p || riscv_insn_length (buf[0]) == 2)
877 return 2;
878 else
879 return 4;
880 }
881 else if (use_compressed_breakpoints == AUTO_BOOLEAN_TRUE)
882 return 2;
883 else
884 return 4;
885 }
886
887 /* Implement the sw_breakpoint_from_kind gdbarch method. */
888
889 static const gdb_byte *
890 riscv_sw_breakpoint_from_kind (struct gdbarch *gdbarch, int kind, int *size)
891 {
892 static const gdb_byte ebreak[] = { 0x73, 0x00, 0x10, 0x00, };
893 static const gdb_byte c_ebreak[] = { 0x02, 0x90 };
894
895 *size = kind;
896 switch (kind)
897 {
898 case 2:
899 return c_ebreak;
900 case 4:
901 return ebreak;
902 default:
903 gdb_assert_not_reached ("unhandled breakpoint kind");
904 }
905 }
906
907 /* Implement the register_name gdbarch method. This is used instead of
908 the function supplied by calling TDESC_USE_REGISTERS so that we can
909 ensure the preferred names are offered for x-regs and f-regs. */
910
911 static const char *
912 riscv_register_name (struct gdbarch *gdbarch, int regnum)
913 {
914 /* Lookup the name through the target description. If we get back NULL
915 then this is an unknown register. If we do get a name back then we
916 look up the registers preferred name below. */
917 const char *name = tdesc_register_name (gdbarch, regnum);
918 gdb_assert (name != nullptr);
919 if (name[0] == '\0')
920 return name;
921
922 /* We want GDB to use the ABI names for registers even if the target
923 gives us a target description with the architectural name. For
924 example we want to see 'ra' instead of 'x1' whatever the target
925 description called it. */
926 if (regnum >= RISCV_ZERO_REGNUM && regnum < RISCV_FIRST_FP_REGNUM)
927 return riscv_xreg_feature.register_name (regnum);
928
929 /* Like with the x-regs we prefer the abi names for the floating point
930 registers. If the target doesn't have floating point registers then
931 the tdesc_register_name call above should have returned an empty
932 string. */
933 if (regnum >= RISCV_FIRST_FP_REGNUM && regnum <= RISCV_LAST_FP_REGNUM)
934 {
935 gdb_assert (riscv_has_fp_regs (gdbarch));
936 return riscv_freg_feature.register_name (regnum);
937 }
938
939 /* Some targets (QEMU) are reporting these three registers twice, once
940 in the FPU feature, and once in the CSR feature. Both of these read
941 the same underlying state inside the target, but naming the register
942 twice in the target description results in GDB having two registers
943 with the same name, only one of which can ever be accessed, but both
944 will show up in 'info register all'. Unless, we identify the
945 duplicate copies of these registers (in riscv_tdesc_unknown_reg) and
946 then hide the registers here by giving them no name. */
947 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
948 if (tdep->duplicate_fflags_regnum == regnum
949 || tdep->duplicate_frm_regnum == regnum
950 || tdep->duplicate_fcsr_regnum == regnum)
951 return "";
952
953 /* The remaining registers are different. For all other registers on the
954 machine we prefer to see the names that the target description
955 provides. This is particularly important for CSRs which might be
956 renamed over time. If GDB keeps track of the "latest" name, but a
957 particular target provides an older name then we don't want to force
958 users to see the newer name in register output.
959
960 The other case that reaches here are any registers that the target
961 provided that GDB is completely unaware of. For these we have no
962 choice but to accept the target description name.
963
964 Just accept whatever name TDESC_REGISTER_NAME returned. */
965 return name;
966 }
967
968 /* Implement gdbarch_pseudo_register_read. Read pseudo-register REGNUM
969 from REGCACHE and place the register value into BUF. BUF is sized
970 based on the type of register REGNUM, all of BUF should be written too,
971 the result should be sign or zero extended as appropriate. */
972
973 static enum register_status
974 riscv_pseudo_register_read (struct gdbarch *gdbarch,
975 readable_regcache *regcache,
976 int regnum, gdb_byte *buf)
977 {
978 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
979
980 if (regnum == tdep->fflags_regnum || regnum == tdep->frm_regnum)
981 {
982 /* Clear BUF. */
983 memset (buf, 0, register_size (gdbarch, regnum));
984
985 /* Read the first byte of the fcsr register, this contains both frm
986 and fflags. */
987 enum register_status status
988 = regcache->raw_read_part (RISCV_CSR_FCSR_REGNUM, 0, 1, buf);
989
990 if (status != REG_VALID)
991 return status;
992
993 /* Extract the appropriate parts. */
994 if (regnum == tdep->fflags_regnum)
995 buf[0] &= 0x1f;
996 else if (regnum == tdep->frm_regnum)
997 buf[0] = (buf[0] >> 5) & 0x7;
998
999 return REG_VALID;
1000 }
1001
1002 return REG_UNKNOWN;
1003 }
1004
1005 /* Implement gdbarch_pseudo_register_write. Write the contents of BUF into
1006 pseudo-register REGNUM in REGCACHE. BUF is sized based on the type of
1007 register REGNUM. */
1008
1009 static void
1010 riscv_pseudo_register_write (struct gdbarch *gdbarch,
1011 struct regcache *regcache, int regnum,
1012 const gdb_byte *buf)
1013 {
1014 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1015
1016 if (regnum == tdep->fflags_regnum || regnum == tdep->frm_regnum)
1017 {
1018 int fcsr_regnum = RISCV_CSR_FCSR_REGNUM;
1019 gdb_byte raw_buf[register_size (gdbarch, fcsr_regnum)];
1020
1021 regcache->raw_read (fcsr_regnum, raw_buf);
1022
1023 if (regnum == tdep->fflags_regnum)
1024 raw_buf[0] = (raw_buf[0] & ~0x1f) | (buf[0] & 0x1f);
1025 else if (regnum == tdep->frm_regnum)
1026 raw_buf[0] = (raw_buf[0] & ~(0x7 << 5)) | ((buf[0] & 0x7) << 5);
1027
1028 regcache->raw_write (fcsr_regnum, raw_buf);
1029 }
1030 else
1031 gdb_assert_not_reached ("unknown pseudo register %d", regnum);
1032 }
1033
1034 /* Implement the cannot_store_register gdbarch method. The zero register
1035 (x0) is read-only on RISC-V. */
1036
1037 static int
1038 riscv_cannot_store_register (struct gdbarch *gdbarch, int regnum)
1039 {
1040 return regnum == RISCV_ZERO_REGNUM;
1041 }
1042
1043 /* Construct a type for 64-bit FP registers. */
1044
1045 static struct type *
1046 riscv_fpreg_d_type (struct gdbarch *gdbarch)
1047 {
1048 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1049
1050 if (tdep->riscv_fpreg_d_type == nullptr)
1051 {
1052 const struct builtin_type *bt = builtin_type (gdbarch);
1053
1054 /* The type we're building is this: */
1055 #if 0
1056 union __gdb_builtin_type_fpreg_d
1057 {
1058 float f;
1059 double d;
1060 };
1061 #endif
1062
1063 struct type *t;
1064
1065 t = arch_composite_type (gdbarch,
1066 "__gdb_builtin_type_fpreg_d", TYPE_CODE_UNION);
1067 append_composite_type_field (t, "float", bt->builtin_float);
1068 append_composite_type_field (t, "double", bt->builtin_double);
1069 t->set_is_vector (true);
1070 t->set_name ("builtin_type_fpreg_d");
1071 tdep->riscv_fpreg_d_type = t;
1072 }
1073
1074 return tdep->riscv_fpreg_d_type;
1075 }
1076
1077 /* Implement the register_type gdbarch method. This is installed as an
1078 for the override setup by TDESC_USE_REGISTERS, for most registers we
1079 delegate the type choice to the target description, but for a few
1080 registers we try to improve the types if the target description has
1081 taken a simplistic approach. */
1082
1083 static struct type *
1084 riscv_register_type (struct gdbarch *gdbarch, int regnum)
1085 {
1086 struct type *type = tdesc_register_type (gdbarch, regnum);
1087 int xlen = riscv_isa_xlen (gdbarch);
1088
1089 /* We want to perform some specific type "fixes" in cases where we feel
1090 that we really can do better than the target description. For all
1091 other cases we just return what the target description says. */
1092 if (riscv_is_fp_regno_p (regnum))
1093 {
1094 /* This spots the case for RV64 where the double is defined as
1095 either 'ieee_double' or 'float' (which is the generic name that
1096 converts to 'double' on 64-bit). In these cases its better to
1097 present the registers using a union type. */
1098 int flen = riscv_isa_flen (gdbarch);
1099 if (flen == 8
1100 && type->code () == TYPE_CODE_FLT
1101 && type->length () == flen
1102 && (strcmp (type->name (), "builtin_type_ieee_double") == 0
1103 || strcmp (type->name (), "double") == 0))
1104 type = riscv_fpreg_d_type (gdbarch);
1105 }
1106
1107 if ((regnum == gdbarch_pc_regnum (gdbarch)
1108 || regnum == RISCV_RA_REGNUM
1109 || regnum == RISCV_FP_REGNUM
1110 || regnum == RISCV_SP_REGNUM
1111 || regnum == RISCV_GP_REGNUM
1112 || regnum == RISCV_TP_REGNUM)
1113 && type->code () == TYPE_CODE_INT
1114 && type->length () == xlen)
1115 {
1116 /* This spots the case where some interesting registers are defined
1117 as simple integers of the expected size, we force these registers
1118 to be pointers as we believe that is more useful. */
1119 if (regnum == gdbarch_pc_regnum (gdbarch)
1120 || regnum == RISCV_RA_REGNUM)
1121 type = builtin_type (gdbarch)->builtin_func_ptr;
1122 else if (regnum == RISCV_FP_REGNUM
1123 || regnum == RISCV_SP_REGNUM
1124 || regnum == RISCV_GP_REGNUM
1125 || regnum == RISCV_TP_REGNUM)
1126 type = builtin_type (gdbarch)->builtin_data_ptr;
1127 }
1128
1129 return type;
1130 }
1131
1132 /* Helper for riscv_print_registers_info, prints info for a single register
1133 REGNUM. */
1134
1135 static void
1136 riscv_print_one_register_info (struct gdbarch *gdbarch,
1137 struct ui_file *file,
1138 frame_info_ptr frame,
1139 int regnum)
1140 {
1141 const char *name = gdbarch_register_name (gdbarch, regnum);
1142 struct value *val;
1143 struct type *regtype;
1144 int print_raw_format;
1145 enum tab_stops { value_column_1 = 15 };
1146
1147 gdb_puts (name, file);
1148 print_spaces (std::max<int> (1, value_column_1 - strlen (name)), file);
1149
1150 try
1151 {
1152 val = value_of_register (regnum, frame);
1153 regtype = val->type ();
1154 }
1155 catch (const gdb_exception_error &ex)
1156 {
1157 /* Handle failure to read a register without interrupting the entire
1158 'info registers' flow. */
1159 gdb_printf (file, "%s\n", ex.what ());
1160 return;
1161 }
1162
1163 print_raw_format = (val->entirely_available ()
1164 && !val->optimized_out ());
1165
1166 if (regtype->code () == TYPE_CODE_FLT
1167 || (regtype->code () == TYPE_CODE_UNION
1168 && regtype->num_fields () == 2
1169 && regtype->field (0).type ()->code () == TYPE_CODE_FLT
1170 && regtype->field (1).type ()->code () == TYPE_CODE_FLT)
1171 || (regtype->code () == TYPE_CODE_UNION
1172 && regtype->num_fields () == 3
1173 && regtype->field (0).type ()->code () == TYPE_CODE_FLT
1174 && regtype->field (1).type ()->code () == TYPE_CODE_FLT
1175 && regtype->field (2).type ()->code () == TYPE_CODE_FLT))
1176 {
1177 struct value_print_options opts;
1178 const gdb_byte *valaddr = val->contents_for_printing ().data ();
1179 enum bfd_endian byte_order = type_byte_order (regtype);
1180
1181 get_user_print_options (&opts);
1182 opts.deref_ref = true;
1183
1184 common_val_print (val, file, 0, &opts, current_language);
1185
1186 if (print_raw_format)
1187 {
1188 gdb_printf (file, "\t(raw ");
1189 print_hex_chars (file, valaddr, regtype->length (), byte_order,
1190 true);
1191 gdb_printf (file, ")");
1192 }
1193 }
1194 else
1195 {
1196 struct value_print_options opts;
1197 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1198
1199 /* Print the register in hex. */
1200 get_formatted_print_options (&opts, 'x');
1201 opts.deref_ref = true;
1202 common_val_print (val, file, 0, &opts, current_language);
1203
1204 if (print_raw_format)
1205 {
1206 if (regnum == RISCV_CSR_MSTATUS_REGNUM)
1207 {
1208 LONGEST d;
1209 int size = register_size (gdbarch, regnum);
1210 unsigned xlen;
1211
1212 /* The SD field is always in the upper bit of MSTATUS, regardless
1213 of the number of bits in MSTATUS. */
1214 d = value_as_long (val);
1215 xlen = size * 8;
1216 gdb_printf (file,
1217 "\tSD:%X VM:%02X MXR:%X PUM:%X MPRV:%X XS:%X "
1218 "FS:%X MPP:%x HPP:%X SPP:%X MPIE:%X HPIE:%X "
1219 "SPIE:%X UPIE:%X MIE:%X HIE:%X SIE:%X UIE:%X",
1220 (int) ((d >> (xlen - 1)) & 0x1),
1221 (int) ((d >> 24) & 0x1f),
1222 (int) ((d >> 19) & 0x1),
1223 (int) ((d >> 18) & 0x1),
1224 (int) ((d >> 17) & 0x1),
1225 (int) ((d >> 15) & 0x3),
1226 (int) ((d >> 13) & 0x3),
1227 (int) ((d >> 11) & 0x3),
1228 (int) ((d >> 9) & 0x3),
1229 (int) ((d >> 8) & 0x1),
1230 (int) ((d >> 7) & 0x1),
1231 (int) ((d >> 6) & 0x1),
1232 (int) ((d >> 5) & 0x1),
1233 (int) ((d >> 4) & 0x1),
1234 (int) ((d >> 3) & 0x1),
1235 (int) ((d >> 2) & 0x1),
1236 (int) ((d >> 1) & 0x1),
1237 (int) ((d >> 0) & 0x1));
1238 }
1239 else if (regnum == RISCV_CSR_MISA_REGNUM)
1240 {
1241 int base;
1242 unsigned xlen, i;
1243 LONGEST d;
1244 int size = register_size (gdbarch, regnum);
1245
1246 /* The MXL field is always in the upper two bits of MISA,
1247 regardless of the number of bits in MISA. Mask out other
1248 bits to ensure we have a positive value. */
1249 d = value_as_long (val);
1250 base = (d >> ((size * 8) - 2)) & 0x3;
1251 xlen = 16;
1252
1253 for (; base > 0; base--)
1254 xlen *= 2;
1255 gdb_printf (file, "\tRV%d", xlen);
1256
1257 for (i = 0; i < 26; i++)
1258 {
1259 if (d & (1 << i))
1260 gdb_printf (file, "%c", 'A' + i);
1261 }
1262 }
1263 else if (regnum == RISCV_CSR_FCSR_REGNUM
1264 || regnum == tdep->fflags_regnum
1265 || regnum == tdep->frm_regnum)
1266 {
1267 LONGEST d = value_as_long (val);
1268
1269 gdb_printf (file, "\t");
1270 if (regnum != tdep->frm_regnum)
1271 gdb_printf (file,
1272 "NV:%d DZ:%d OF:%d UF:%d NX:%d",
1273 (int) ((d >> 4) & 0x1),
1274 (int) ((d >> 3) & 0x1),
1275 (int) ((d >> 2) & 0x1),
1276 (int) ((d >> 1) & 0x1),
1277 (int) ((d >> 0) & 0x1));
1278
1279 if (regnum != tdep->fflags_regnum)
1280 {
1281 static const char * const sfrm[] =
1282 {
1283 _("RNE (round to nearest; ties to even)"),
1284 _("RTZ (Round towards zero)"),
1285 _("RDN (Round down towards -INF)"),
1286 _("RUP (Round up towards +INF)"),
1287 _("RMM (Round to nearest; ties to max magnitude)"),
1288 _("INVALID[5]"),
1289 _("INVALID[6]"),
1290 /* A value of 0x7 indicates dynamic rounding mode when
1291 used within an instructions rounding-mode field, but
1292 is invalid within the FRM register. */
1293 _("INVALID[7] (Dynamic rounding mode)"),
1294 };
1295 int frm = ((regnum == RISCV_CSR_FCSR_REGNUM)
1296 ? (d >> 5) : d) & 0x7;
1297
1298 gdb_printf (file, "%sFRM:%i [%s]",
1299 (regnum == RISCV_CSR_FCSR_REGNUM
1300 ? " " : ""),
1301 frm, sfrm[frm]);
1302 }
1303 }
1304 else if (regnum == RISCV_PRIV_REGNUM)
1305 {
1306 LONGEST d;
1307 uint8_t priv;
1308
1309 d = value_as_long (val);
1310 priv = d & 0xff;
1311
1312 if (priv < 4)
1313 {
1314 static const char * const sprv[] =
1315 {
1316 "User/Application",
1317 "Supervisor",
1318 "Hypervisor",
1319 "Machine"
1320 };
1321 gdb_printf (file, "\tprv:%d [%s]",
1322 priv, sprv[priv]);
1323 }
1324 else
1325 gdb_printf (file, "\tprv:%d [INVALID]", priv);
1326 }
1327 else
1328 {
1329 /* If not a vector register, print it also according to its
1330 natural format. */
1331 if (regtype->is_vector () == 0)
1332 {
1333 get_user_print_options (&opts);
1334 opts.deref_ref = true;
1335 gdb_printf (file, "\t");
1336 common_val_print (val, file, 0, &opts, current_language);
1337 }
1338 }
1339 }
1340 }
1341 gdb_printf (file, "\n");
1342 }
1343
1344 /* Return true if REGNUM is a valid CSR register. The CSR register space
1345 is sparsely populated, so not every number is a named CSR. */
1346
1347 static bool
1348 riscv_is_regnum_a_named_csr (int regnum)
1349 {
1350 gdb_assert (regnum >= RISCV_FIRST_CSR_REGNUM
1351 && regnum <= RISCV_LAST_CSR_REGNUM);
1352
1353 switch (regnum)
1354 {
1355 #define DECLARE_CSR(name, num, class, define_ver, abort_ver) case RISCV_ ## num ## _REGNUM:
1356 #include "opcode/riscv-opc.h"
1357 #undef DECLARE_CSR
1358 return true;
1359
1360 default:
1361 return false;
1362 }
1363 }
1364
1365 /* Return true if REGNUM is an unknown CSR identified in
1366 riscv_tdesc_unknown_reg for GDBARCH. */
1367
1368 static bool
1369 riscv_is_unknown_csr (struct gdbarch *gdbarch, int regnum)
1370 {
1371 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1372 return (regnum >= tdep->unknown_csrs_first_regnum
1373 && regnum < (tdep->unknown_csrs_first_regnum
1374 + tdep->unknown_csrs_count));
1375 }
1376
1377 /* Implement the register_reggroup_p gdbarch method. Is REGNUM a member
1378 of REGGROUP? */
1379
1380 static int
1381 riscv_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
1382 const struct reggroup *reggroup)
1383 {
1384 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1385
1386 /* Used by 'info registers' and 'info registers <groupname>'. */
1387
1388 if (gdbarch_register_name (gdbarch, regnum)[0] == '\0')
1389 return 0;
1390
1391 if (regnum > RISCV_LAST_REGNUM && regnum < gdbarch_num_regs (gdbarch))
1392 {
1393 /* Any extra registers from the CSR tdesc_feature (identified in
1394 riscv_tdesc_unknown_reg) are removed from the save/restore groups
1395 as some targets (QEMU) report CSRs which then can't be read and
1396 having unreadable registers in the save/restore group breaks
1397 things like inferior calls.
1398
1399 The unknown CSRs are also removed from the general group, and
1400 added into both the csr and system group. This is inline with the
1401 known CSRs (see below). */
1402 if (riscv_is_unknown_csr (gdbarch, regnum))
1403 {
1404 if (reggroup == restore_reggroup || reggroup == save_reggroup
1405 || reggroup == general_reggroup)
1406 return 0;
1407 else if (reggroup == system_reggroup || reggroup == csr_reggroup)
1408 return 1;
1409 }
1410
1411 /* This is some other unknown register from the target description.
1412 In this case we trust whatever the target description says about
1413 which groups this register should be in. */
1414 int ret = tdesc_register_in_reggroup_p (gdbarch, regnum, reggroup);
1415 if (ret != -1)
1416 return ret;
1417
1418 return default_register_reggroup_p (gdbarch, regnum, reggroup);
1419 }
1420
1421 if (reggroup == all_reggroup)
1422 {
1423 if (regnum < RISCV_FIRST_CSR_REGNUM || regnum >= RISCV_PRIV_REGNUM)
1424 return 1;
1425 if (riscv_is_regnum_a_named_csr (regnum))
1426 return 1;
1427 return 0;
1428 }
1429 else if (reggroup == float_reggroup)
1430 return (riscv_is_fp_regno_p (regnum)
1431 || regnum == RISCV_CSR_FCSR_REGNUM
1432 || regnum == tdep->fflags_regnum
1433 || regnum == tdep->frm_regnum);
1434 else if (reggroup == general_reggroup)
1435 return regnum < RISCV_FIRST_FP_REGNUM;
1436 else if (reggroup == restore_reggroup || reggroup == save_reggroup)
1437 {
1438 if (riscv_has_fp_regs (gdbarch))
1439 return (regnum <= RISCV_LAST_FP_REGNUM
1440 || regnum == RISCV_CSR_FCSR_REGNUM
1441 || regnum == tdep->fflags_regnum
1442 || regnum == tdep->frm_regnum);
1443 else
1444 return regnum < RISCV_FIRST_FP_REGNUM;
1445 }
1446 else if (reggroup == system_reggroup || reggroup == csr_reggroup)
1447 {
1448 if (regnum == RISCV_PRIV_REGNUM)
1449 return 1;
1450 if (regnum < RISCV_FIRST_CSR_REGNUM || regnum > RISCV_LAST_CSR_REGNUM)
1451 return 0;
1452 if (riscv_is_regnum_a_named_csr (regnum))
1453 return 1;
1454 return 0;
1455 }
1456 else if (reggroup == vector_reggroup)
1457 return (regnum >= RISCV_V0_REGNUM && regnum <= RISCV_V31_REGNUM);
1458 else
1459 return 0;
1460 }
1461
1462 /* Return the name for pseudo-register REGNUM for GDBARCH. */
1463
1464 static const char *
1465 riscv_pseudo_register_name (struct gdbarch *gdbarch, int regnum)
1466 {
1467 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1468
1469 if (regnum == tdep->fflags_regnum)
1470 return "fflags";
1471 else if (regnum == tdep->frm_regnum)
1472 return "frm";
1473 else
1474 gdb_assert_not_reached ("unknown pseudo register number %d", regnum);
1475 }
1476
1477 /* Return the type for pseudo-register REGNUM for GDBARCH. */
1478
1479 static struct type *
1480 riscv_pseudo_register_type (struct gdbarch *gdbarch, int regnum)
1481 {
1482 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1483
1484 if (regnum == tdep->fflags_regnum || regnum == tdep->frm_regnum)
1485 return builtin_type (gdbarch)->builtin_int32;
1486 else
1487 gdb_assert_not_reached ("unknown pseudo register number %d", regnum);
1488 }
1489
1490 /* Return true (non-zero) if pseudo-register REGNUM from GDBARCH is a
1491 member of REGGROUP, otherwise return false (zero). */
1492
1493 static int
1494 riscv_pseudo_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
1495 const struct reggroup *reggroup)
1496 {
1497 /* The standard function will also work for pseudo-registers. */
1498 return riscv_register_reggroup_p (gdbarch, regnum, reggroup);
1499 }
1500
1501 /* Implement the print_registers_info gdbarch method. This is used by
1502 'info registers' and 'info all-registers'. */
1503
1504 static void
1505 riscv_print_registers_info (struct gdbarch *gdbarch,
1506 struct ui_file *file,
1507 frame_info_ptr frame,
1508 int regnum, int print_all)
1509 {
1510 if (regnum != -1)
1511 {
1512 /* Print one specified register. */
1513 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
1514 error (_("Not a valid register for the current processor type"));
1515 riscv_print_one_register_info (gdbarch, file, frame, regnum);
1516 }
1517 else
1518 {
1519 const struct reggroup *reggroup;
1520
1521 if (print_all)
1522 reggroup = all_reggroup;
1523 else
1524 reggroup = general_reggroup;
1525
1526 for (regnum = 0; regnum < gdbarch_num_cooked_regs (gdbarch); ++regnum)
1527 {
1528 /* Zero never changes, so might as well hide by default. */
1529 if (regnum == RISCV_ZERO_REGNUM && !print_all)
1530 continue;
1531
1532 /* Registers with no name are not valid on this ISA. */
1533 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
1534 continue;
1535
1536 /* Is the register in the group we're interested in? */
1537 if (!gdbarch_register_reggroup_p (gdbarch, regnum, reggroup))
1538 continue;
1539
1540 riscv_print_one_register_info (gdbarch, file, frame, regnum);
1541 }
1542 }
1543 }
1544
1545 /* Class that handles one decoded RiscV instruction. */
1546
1547 class riscv_insn
1548 {
1549 public:
1550
1551 /* Enum of all the opcodes that GDB cares about during the prologue scan. */
1552 enum opcode
1553 {
1554 /* Unknown value is used at initialisation time. */
1555 UNKNOWN = 0,
1556
1557 /* These instructions are all the ones we are interested in during the
1558 prologue scan. */
1559 ADD,
1560 ADDI,
1561 ADDIW,
1562 ADDW,
1563 AUIPC,
1564 LUI,
1565 LI,
1566 SD,
1567 SW,
1568 LD,
1569 LW,
1570 MV,
1571 /* These are needed for software breakpoint support. */
1572 JAL,
1573 JALR,
1574 BEQ,
1575 BNE,
1576 BLT,
1577 BGE,
1578 BLTU,
1579 BGEU,
1580 /* These are needed for stepping over atomic sequences. */
1581 LR,
1582 SC,
1583 /* This instruction is used to do a syscall. */
1584 ECALL,
1585
1586 /* Other instructions are not interesting during the prologue scan, and
1587 are ignored. */
1588 OTHER
1589 };
1590
1591 riscv_insn ()
1592 : m_length (0),
1593 m_opcode (OTHER),
1594 m_rd (0),
1595 m_rs1 (0),
1596 m_rs2 (0)
1597 {
1598 /* Nothing. */
1599 }
1600
1601 void decode (struct gdbarch *gdbarch, CORE_ADDR pc);
1602
1603 /* Get the length of the instruction in bytes. */
1604 int length () const
1605 { return m_length; }
1606
1607 /* Get the opcode for this instruction. */
1608 enum opcode opcode () const
1609 { return m_opcode; }
1610
1611 /* Get destination register field for this instruction. This is only
1612 valid if the OPCODE implies there is such a field for this
1613 instruction. */
1614 int rd () const
1615 { return m_rd; }
1616
1617 /* Get the RS1 register field for this instruction. This is only valid
1618 if the OPCODE implies there is such a field for this instruction. */
1619 int rs1 () const
1620 { return m_rs1; }
1621
1622 /* Get the RS2 register field for this instruction. This is only valid
1623 if the OPCODE implies there is such a field for this instruction. */
1624 int rs2 () const
1625 { return m_rs2; }
1626
1627 /* Get the immediate for this instruction in signed form. This is only
1628 valid if the OPCODE implies there is such a field for this
1629 instruction. */
1630 int imm_signed () const
1631 { return m_imm.s; }
1632
1633 private:
1634
1635 /* Extract 5 bit register field at OFFSET from instruction OPCODE. */
1636 int decode_register_index (unsigned long opcode, int offset)
1637 {
1638 return (opcode >> offset) & 0x1F;
1639 }
1640
1641 /* Extract 5 bit register field at OFFSET from instruction OPCODE. */
1642 int decode_register_index_short (unsigned long opcode, int offset)
1643 {
1644 return ((opcode >> offset) & 0x7) + 8;
1645 }
1646
1647 /* Helper for DECODE, decode 32-bit R-type instruction. */
1648 void decode_r_type_insn (enum opcode opcode, ULONGEST ival)
1649 {
1650 m_opcode = opcode;
1651 m_rd = decode_register_index (ival, OP_SH_RD);
1652 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1653 m_rs2 = decode_register_index (ival, OP_SH_RS2);
1654 }
1655
1656 /* Helper for DECODE, decode 16-bit compressed R-type instruction. */
1657 void decode_cr_type_insn (enum opcode opcode, ULONGEST ival)
1658 {
1659 m_opcode = opcode;
1660 m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
1661 m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1662 }
1663
1664 /* Helper for DECODE, decode 32-bit I-type instruction. */
1665 void decode_i_type_insn (enum opcode opcode, ULONGEST ival)
1666 {
1667 m_opcode = opcode;
1668 m_rd = decode_register_index (ival, OP_SH_RD);
1669 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1670 m_imm.s = EXTRACT_ITYPE_IMM (ival);
1671 }
1672
1673 /* Helper for DECODE, decode 16-bit compressed I-type instruction. Some
1674 of the CI instruction have a hard-coded rs1 register, while others
1675 just use rd for both the source and destination. RS1_REGNUM, if
1676 passed, is the value to place in rs1, otherwise rd is duplicated into
1677 rs1. */
1678 void decode_ci_type_insn (enum opcode opcode, ULONGEST ival,
1679 gdb::optional<int> rs1_regnum = {})
1680 {
1681 m_opcode = opcode;
1682 m_rd = decode_register_index (ival, OP_SH_CRS1S);
1683 if (rs1_regnum.has_value ())
1684 m_rs1 = *rs1_regnum;
1685 else
1686 m_rs1 = m_rd;
1687 m_imm.s = EXTRACT_CITYPE_IMM (ival);
1688 }
1689
1690 /* Helper for DECODE, decode 16-bit compressed CL-type instruction. */
1691 void decode_cl_type_insn (enum opcode opcode, ULONGEST ival)
1692 {
1693 m_opcode = opcode;
1694 m_rd = decode_register_index_short (ival, OP_SH_CRS2S);
1695 m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1696 m_imm.s = EXTRACT_CLTYPE_IMM (ival);
1697 }
1698
1699 /* Helper for DECODE, decode 32-bit S-type instruction. */
1700 void decode_s_type_insn (enum opcode opcode, ULONGEST ival)
1701 {
1702 m_opcode = opcode;
1703 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1704 m_rs2 = decode_register_index (ival, OP_SH_RS2);
1705 m_imm.s = EXTRACT_STYPE_IMM (ival);
1706 }
1707
1708 /* Helper for DECODE, decode 16-bit CS-type instruction. The immediate
1709 encoding is different for each CS format instruction, so extracting
1710 the immediate is left up to the caller, who should pass the extracted
1711 immediate value through in IMM. */
1712 void decode_cs_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1713 {
1714 m_opcode = opcode;
1715 m_imm.s = imm;
1716 m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1717 m_rs2 = decode_register_index_short (ival, OP_SH_CRS2S);
1718 }
1719
1720 /* Helper for DECODE, decode 16-bit CSS-type instruction. The immediate
1721 encoding is different for each CSS format instruction, so extracting
1722 the immediate is left up to the caller, who should pass the extracted
1723 immediate value through in IMM. */
1724 void decode_css_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1725 {
1726 m_opcode = opcode;
1727 m_imm.s = imm;
1728 m_rs1 = RISCV_SP_REGNUM;
1729 /* Not a compressed register number in this case. */
1730 m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1731 }
1732
1733 /* Helper for DECODE, decode 32-bit U-type instruction. */
1734 void decode_u_type_insn (enum opcode opcode, ULONGEST ival)
1735 {
1736 m_opcode = opcode;
1737 m_rd = decode_register_index (ival, OP_SH_RD);
1738 m_imm.s = EXTRACT_UTYPE_IMM (ival);
1739 }
1740
1741 /* Helper for DECODE, decode 32-bit J-type instruction. */
1742 void decode_j_type_insn (enum opcode opcode, ULONGEST ival)
1743 {
1744 m_opcode = opcode;
1745 m_rd = decode_register_index (ival, OP_SH_RD);
1746 m_imm.s = EXTRACT_JTYPE_IMM (ival);
1747 }
1748
1749 /* Helper for DECODE, decode 32-bit J-type instruction. */
1750 void decode_cj_type_insn (enum opcode opcode, ULONGEST ival)
1751 {
1752 m_opcode = opcode;
1753 m_imm.s = EXTRACT_CJTYPE_IMM (ival);
1754 }
1755
1756 void decode_b_type_insn (enum opcode opcode, ULONGEST ival)
1757 {
1758 m_opcode = opcode;
1759 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1760 m_rs2 = decode_register_index (ival, OP_SH_RS2);
1761 m_imm.s = EXTRACT_BTYPE_IMM (ival);
1762 }
1763
1764 void decode_cb_type_insn (enum opcode opcode, ULONGEST ival)
1765 {
1766 m_opcode = opcode;
1767 m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1768 m_imm.s = EXTRACT_CBTYPE_IMM (ival);
1769 }
1770
1771 /* Fetch instruction from target memory at ADDR, return the content of
1772 the instruction, and update LEN with the instruction length. */
1773 static ULONGEST fetch_instruction (struct gdbarch *gdbarch,
1774 CORE_ADDR addr, int *len);
1775
1776 /* The length of the instruction in bytes. Should be 2 or 4. */
1777 int m_length;
1778
1779 /* The instruction opcode. */
1780 enum opcode m_opcode;
1781
1782 /* The three possible registers an instruction might reference. Not
1783 every instruction fills in all of these registers. Which fields are
1784 valid depends on the opcode. The naming of these fields matches the
1785 naming in the riscv isa manual. */
1786 int m_rd;
1787 int m_rs1;
1788 int m_rs2;
1789
1790 /* Possible instruction immediate. This is only valid if the instruction
1791 format contains an immediate, not all instruction, whether this is
1792 valid depends on the opcode. Despite only having one format for now
1793 the immediate is packed into a union, later instructions might require
1794 an unsigned formatted immediate, having the union in place now will
1795 reduce the need for code churn later. */
1796 union riscv_insn_immediate
1797 {
1798 riscv_insn_immediate ()
1799 : s (0)
1800 {
1801 /* Nothing. */
1802 }
1803
1804 int s;
1805 } m_imm;
1806 };
1807
1808 /* Fetch instruction from target memory at ADDR, return the content of the
1809 instruction, and update LEN with the instruction length. */
1810
1811 ULONGEST
1812 riscv_insn::fetch_instruction (struct gdbarch *gdbarch,
1813 CORE_ADDR addr, int *len)
1814 {
1815 gdb_byte buf[RISCV_MAX_INSN_LEN];
1816 int instlen, status;
1817
1818 /* All insns are at least 16 bits. */
1819 status = target_read_memory (addr, buf, 2);
1820 if (status)
1821 memory_error (TARGET_XFER_E_IO, addr);
1822
1823 /* If we need more, grab it now. */
1824 instlen = riscv_insn_length (buf[0]);
1825 gdb_assert (instlen <= sizeof (buf));
1826 *len = instlen;
1827
1828 if (instlen > 2)
1829 {
1830 status = target_read_memory (addr + 2, buf + 2, instlen - 2);
1831 if (status)
1832 memory_error (TARGET_XFER_E_IO, addr + 2);
1833 }
1834
1835 /* RISC-V Specification states instructions are always little endian */
1836 return extract_unsigned_integer (buf, instlen, BFD_ENDIAN_LITTLE);
1837 }
1838
1839 /* Fetch from target memory an instruction at PC and decode it. This can
1840 throw an error if the memory access fails, callers are responsible for
1841 handling this error if that is appropriate. */
1842
1843 void
1844 riscv_insn::decode (struct gdbarch *gdbarch, CORE_ADDR pc)
1845 {
1846 ULONGEST ival;
1847
1848 /* Fetch the instruction, and the instructions length. */
1849 ival = fetch_instruction (gdbarch, pc, &m_length);
1850
1851 if (m_length == 4)
1852 {
1853 if (is_add_insn (ival))
1854 decode_r_type_insn (ADD, ival);
1855 else if (is_addw_insn (ival))
1856 decode_r_type_insn (ADDW, ival);
1857 else if (is_addi_insn (ival))
1858 decode_i_type_insn (ADDI, ival);
1859 else if (is_addiw_insn (ival))
1860 decode_i_type_insn (ADDIW, ival);
1861 else if (is_auipc_insn (ival))
1862 decode_u_type_insn (AUIPC, ival);
1863 else if (is_lui_insn (ival))
1864 decode_u_type_insn (LUI, ival);
1865 else if (is_sd_insn (ival))
1866 decode_s_type_insn (SD, ival);
1867 else if (is_sw_insn (ival))
1868 decode_s_type_insn (SW, ival);
1869 else if (is_jal_insn (ival))
1870 decode_j_type_insn (JAL, ival);
1871 else if (is_jalr_insn (ival))
1872 decode_i_type_insn (JALR, ival);
1873 else if (is_beq_insn (ival))
1874 decode_b_type_insn (BEQ, ival);
1875 else if (is_bne_insn (ival))
1876 decode_b_type_insn (BNE, ival);
1877 else if (is_blt_insn (ival))
1878 decode_b_type_insn (BLT, ival);
1879 else if (is_bge_insn (ival))
1880 decode_b_type_insn (BGE, ival);
1881 else if (is_bltu_insn (ival))
1882 decode_b_type_insn (BLTU, ival);
1883 else if (is_bgeu_insn (ival))
1884 decode_b_type_insn (BGEU, ival);
1885 else if (is_lr_w_insn (ival))
1886 decode_r_type_insn (LR, ival);
1887 else if (is_lr_d_insn (ival))
1888 decode_r_type_insn (LR, ival);
1889 else if (is_sc_w_insn (ival))
1890 decode_r_type_insn (SC, ival);
1891 else if (is_sc_d_insn (ival))
1892 decode_r_type_insn (SC, ival);
1893 else if (is_ecall_insn (ival))
1894 decode_i_type_insn (ECALL, ival);
1895 else if (is_ld_insn (ival))
1896 decode_i_type_insn (LD, ival);
1897 else if (is_lw_insn (ival))
1898 decode_i_type_insn (LW, ival);
1899 else
1900 /* None of the other fields are valid in this case. */
1901 m_opcode = OTHER;
1902 }
1903 else if (m_length == 2)
1904 {
1905 int xlen = riscv_isa_xlen (gdbarch);
1906
1907 /* C_ADD and C_JALR have the same opcode. If RS2 is 0, then this is a
1908 C_JALR. So must try to match C_JALR first as it has more bits in
1909 mask. */
1910 if (is_c_jalr_insn (ival))
1911 decode_cr_type_insn (JALR, ival);
1912 else if (is_c_add_insn (ival))
1913 decode_cr_type_insn (ADD, ival);
1914 /* C_ADDW is RV64 and RV128 only. */
1915 else if (xlen != 4 && is_c_addw_insn (ival))
1916 decode_cr_type_insn (ADDW, ival);
1917 else if (is_c_addi_insn (ival))
1918 decode_ci_type_insn (ADDI, ival);
1919 /* C_ADDIW and C_JAL have the same opcode. C_ADDIW is RV64 and RV128
1920 only and C_JAL is RV32 only. */
1921 else if (xlen != 4 && is_c_addiw_insn (ival))
1922 decode_ci_type_insn (ADDIW, ival);
1923 else if (xlen == 4 && is_c_jal_insn (ival))
1924 decode_cj_type_insn (JAL, ival);
1925 /* C_ADDI16SP and C_LUI have the same opcode. If RD is 2, then this is a
1926 C_ADDI16SP. So must try to match C_ADDI16SP first as it has more bits
1927 in mask. */
1928 else if (is_c_addi16sp_insn (ival))
1929 {
1930 m_opcode = ADDI;
1931 m_rd = m_rs1 = decode_register_index (ival, OP_SH_RD);
1932 m_imm.s = EXTRACT_CITYPE_ADDI16SP_IMM (ival);
1933 }
1934 else if (is_c_addi4spn_insn (ival))
1935 {
1936 m_opcode = ADDI;
1937 m_rd = decode_register_index_short (ival, OP_SH_CRS2S);
1938 m_rs1 = RISCV_SP_REGNUM;
1939 m_imm.s = EXTRACT_CIWTYPE_ADDI4SPN_IMM (ival);
1940 }
1941 else if (is_c_lui_insn (ival))
1942 {
1943 m_opcode = LUI;
1944 m_rd = decode_register_index (ival, OP_SH_CRS1S);
1945 m_imm.s = EXTRACT_CITYPE_LUI_IMM (ival);
1946 }
1947 else if (is_c_li_insn (ival))
1948 decode_ci_type_insn (LI, ival);
1949 /* C_SD and C_FSW have the same opcode. C_SD is RV64 and RV128 only,
1950 and C_FSW is RV32 only. */
1951 else if (xlen != 4 && is_c_sd_insn (ival))
1952 decode_cs_type_insn (SD, ival, EXTRACT_CLTYPE_LD_IMM (ival));
1953 else if (is_c_sw_insn (ival))
1954 decode_cs_type_insn (SW, ival, EXTRACT_CLTYPE_LW_IMM (ival));
1955 else if (is_c_swsp_insn (ival))
1956 decode_css_type_insn (SW, ival, EXTRACT_CSSTYPE_SWSP_IMM (ival));
1957 else if (xlen != 4 && is_c_sdsp_insn (ival))
1958 decode_css_type_insn (SD, ival, EXTRACT_CSSTYPE_SDSP_IMM (ival));
1959 /* C_JR and C_MV have the same opcode. If RS2 is 0, then this is a C_JR.
1960 So must try to match C_JR first as it has more bits in mask. */
1961 else if (is_c_jr_insn (ival))
1962 decode_cr_type_insn (JALR, ival);
1963 else if (is_c_mv_insn (ival))
1964 decode_cr_type_insn (MV, ival);
1965 else if (is_c_j_insn (ival))
1966 decode_cj_type_insn (JAL, ival);
1967 else if (is_c_beqz_insn (ival))
1968 decode_cb_type_insn (BEQ, ival);
1969 else if (is_c_bnez_insn (ival))
1970 decode_cb_type_insn (BNE, ival);
1971 else if (is_c_ld_insn (ival))
1972 decode_cl_type_insn (LD, ival);
1973 else if (is_c_lw_insn (ival))
1974 decode_cl_type_insn (LW, ival);
1975 else if (is_c_ldsp_insn (ival))
1976 decode_ci_type_insn (LD, ival, RISCV_SP_REGNUM);
1977 else if (is_c_lwsp_insn (ival))
1978 decode_ci_type_insn (LW, ival, RISCV_SP_REGNUM);
1979 else
1980 /* None of the other fields of INSN are valid in this case. */
1981 m_opcode = OTHER;
1982 }
1983 else
1984 {
1985 /* 6 bytes or more. If the instruction is longer than 8 bytes, we don't
1986 have full instruction bits in ival. At least, such long instructions
1987 are not defined yet, so just ignore it. */
1988 gdb_assert (m_length > 0 && m_length % 2 == 0);
1989 m_opcode = OTHER;
1990 }
1991 }
1992
1993 /* Return true if INSN represents an instruction something like:
1994
1995 ld fp,IMMEDIATE(sp)
1996
1997 That is, a load from stack-pointer plus some immediate offset, with the
1998 result stored into the frame pointer. We also accept 'lw' as well as
1999 'ld'. */
2000
2001 static bool
2002 is_insn_load_of_fp_from_sp (const struct riscv_insn &insn)
2003 {
2004 return ((insn.opcode () == riscv_insn::LD
2005 || insn.opcode () == riscv_insn::LW)
2006 && insn.rd () == RISCV_FP_REGNUM
2007 && insn.rs1 () == RISCV_SP_REGNUM);
2008 }
2009
2010 /* Return true if INSN represents an instruction something like:
2011
2012 add sp,sp,IMMEDIATE
2013
2014 That is, an add of an immediate to the value in the stack pointer
2015 register, with the result stored back to the stack pointer register. */
2016
2017 static bool
2018 is_insn_addi_of_sp_to_sp (const struct riscv_insn &insn)
2019 {
2020 return ((insn.opcode () == riscv_insn::ADDI
2021 || insn.opcode () == riscv_insn::ADDIW)
2022 && insn.rd () == RISCV_SP_REGNUM
2023 && insn.rs1 () == RISCV_SP_REGNUM);
2024 }
2025
2026 /* Is the instruction in code memory prior to address PC a load from stack
2027 instruction? Return true if it is, otherwise, return false.
2028
2029 This is a best effort that is used as part of the function prologue
2030 scanning logic. With compressed instructions and arbitrary control
2031 flow in the inferior, we can never be certain what the instruction
2032 prior to PC is.
2033
2034 This function first looks for a compressed instruction, then looks for
2035 a 32-bit non-compressed instruction. */
2036
2037 static bool
2038 previous_insn_is_load_fp_from_stack (struct gdbarch *gdbarch, CORE_ADDR pc)
2039 {
2040 struct riscv_insn insn;
2041 insn.decode (gdbarch, pc - 2);
2042 gdb_assert (insn.length () > 0);
2043
2044 if (insn.length () != 2 || !is_insn_load_of_fp_from_sp (insn))
2045 {
2046 insn.decode (gdbarch, pc - 4);
2047 gdb_assert (insn.length () > 0);
2048
2049 if (insn.length () != 4 || !is_insn_load_of_fp_from_sp (insn))
2050 return false;
2051 }
2052
2053 riscv_unwinder_debug_printf
2054 ("previous instruction at %s (length %d) was 'ld'",
2055 core_addr_to_string (pc - insn.length ()), insn.length ());
2056 return true;
2057 }
2058
2059 /* Is the instruction in code memory prior to address PC an add of an
2060 immediate to the stack pointer, with the result being written back into
2061 the stack pointer? Return true and set *PREV_PC to the address of the
2062 previous instruction if we believe the previous instruction is such an
2063 add, otherwise return false and *PREV_PC is undefined.
2064
2065 This is a best effort that is used as part of the function prologue
2066 scanning logic. With compressed instructions and arbitrary control
2067 flow in the inferior, we can never be certain what the instruction
2068 prior to PC is.
2069
2070 This function first looks for a compressed instruction, then looks for
2071 a 32-bit non-compressed instruction. */
2072
2073 static bool
2074 previous_insn_is_add_imm_to_sp (struct gdbarch *gdbarch, CORE_ADDR pc,
2075 CORE_ADDR *prev_pc)
2076 {
2077 struct riscv_insn insn;
2078 insn.decode (gdbarch, pc - 2);
2079 gdb_assert (insn.length () > 0);
2080
2081 if (insn.length () != 2 || !is_insn_addi_of_sp_to_sp (insn))
2082 {
2083 insn.decode (gdbarch, pc - 4);
2084 gdb_assert (insn.length () > 0);
2085
2086 if (insn.length () != 4 || !is_insn_addi_of_sp_to_sp (insn))
2087 return false;
2088 }
2089
2090 riscv_unwinder_debug_printf
2091 ("previous instruction at %s (length %d) was 'add'",
2092 core_addr_to_string (pc - insn.length ()), insn.length ());
2093 *prev_pc = pc - insn.length ();
2094 return true;
2095 }
2096
2097 /* Try to spot when PC is located in an exit sequence for a particular
2098 function. Detecting an exit sequence involves a limited amount of
2099 scanning backwards through the disassembly, and so, when considering
2100 compressed instructions, we can never be certain that we have
2101 disassembled the preceding instructions correctly. On top of that, we
2102 can't be certain that the inferior arrived at PC by passing through the
2103 preceding instructions.
2104
2105 With all that said, we know that using prologue scanning to figure a
2106 functions unwind information starts to fail when we consider returns
2107 from an instruction -- we must pass through some instructions that
2108 restore the previous state prior to the final return instruction, and
2109 with state partially restored, our prologue derived unwind information
2110 is no longer valid.
2111
2112 This function then, aims to spot instruction sequences like this:
2113
2114 ld fp, IMM_1(sp)
2115 add sp, sp, IMM_2
2116 ret
2117
2118 The first instruction restores the previous frame-pointer value, the
2119 second restores the previous stack pointer value, and the final
2120 instruction is the actual return.
2121
2122 We need to consider that some or all of these instructions might be
2123 compressed.
2124
2125 This function makes the assumption that, when the inferior reaches the
2126 'ret' instruction the stack pointer will have been restored to its value
2127 on entry to this function. This assumption will be true in most well
2128 formed programs.
2129
2130 Return true if we detect that we are in such an instruction sequence,
2131 that is PC points at one of the three instructions given above. In this
2132 case, set *OFFSET to IMM_2 if PC points to either of the first
2133 two instructions (the 'ld' or 'add'), otherwise set *OFFSET to 0.
2134
2135 Otherwise, this function returns false, and the contents of *OFFSET are
2136 undefined. */
2137
2138 static bool
2139 riscv_detect_end_of_function (struct gdbarch *gdbarch, CORE_ADDR pc,
2140 int *offset)
2141 {
2142 *offset = 0;
2143
2144 /* We only want to scan a maximum of 3 instructions. */
2145 for (int i = 0; i < 3; ++i)
2146 {
2147 struct riscv_insn insn;
2148 insn.decode (gdbarch, pc);
2149 gdb_assert (insn.length () > 0);
2150
2151 if (is_insn_load_of_fp_from_sp (insn))
2152 {
2153 riscv_unwinder_debug_printf ("found 'ld' instruction at %s",
2154 core_addr_to_string (pc));
2155 if (i > 0)
2156 return false;
2157 pc += insn.length ();
2158 }
2159 else if (is_insn_addi_of_sp_to_sp (insn))
2160 {
2161 riscv_unwinder_debug_printf ("found 'add' instruction at %s",
2162 core_addr_to_string (pc));
2163 if (i > 1)
2164 return false;
2165 if (i == 0)
2166 {
2167 if (!previous_insn_is_load_fp_from_stack (gdbarch, pc))
2168 return false;
2169
2170 i = 1;
2171 }
2172 *offset = insn.imm_signed ();
2173 pc += insn.length ();
2174 }
2175 else if (insn.opcode () == riscv_insn::JALR
2176 && insn.rs1 () == RISCV_RA_REGNUM
2177 && insn.rs2 () == RISCV_ZERO_REGNUM)
2178 {
2179 riscv_unwinder_debug_printf ("found 'ret' instruction at %s",
2180 core_addr_to_string (pc));
2181 gdb_assert (i != 1);
2182 if (i == 0)
2183 {
2184 CORE_ADDR prev_pc;
2185 if (!previous_insn_is_add_imm_to_sp (gdbarch, pc, &prev_pc))
2186 return false;
2187 if (!previous_insn_is_load_fp_from_stack (gdbarch, prev_pc))
2188 return false;
2189 i = 2;
2190 }
2191
2192 pc += insn.length ();
2193 }
2194 else
2195 return false;
2196 }
2197
2198 return true;
2199 }
2200
2201 /* The prologue scanner. This is currently only used for skipping the
2202 prologue of a function when the DWARF information is not sufficient.
2203 However, it is written with filling of the frame cache in mind, which
2204 is why different groups of stack setup instructions are split apart
2205 during the core of the inner loop. In the future, the intention is to
2206 extend this function to fully support building up a frame cache that
2207 can unwind register values when there is no DWARF information. */
2208
2209 static CORE_ADDR
2210 riscv_scan_prologue (struct gdbarch *gdbarch,
2211 CORE_ADDR start_pc, CORE_ADDR end_pc,
2212 struct riscv_unwind_cache *cache)
2213 {
2214 CORE_ADDR cur_pc, next_pc, after_prologue_pc;
2215 CORE_ADDR original_end_pc = end_pc;
2216 CORE_ADDR end_prologue_addr = 0;
2217
2218 /* Find an upper limit on the function prologue using the debug
2219 information. If the debug information could not be used to provide
2220 that bound, then use an arbitrary large number as the upper bound. */
2221 after_prologue_pc = skip_prologue_using_sal (gdbarch, start_pc);
2222 if (after_prologue_pc == 0)
2223 after_prologue_pc = start_pc + 100; /* Arbitrary large number. */
2224 if (after_prologue_pc < end_pc)
2225 end_pc = after_prologue_pc;
2226
2227 pv_t regs[RISCV_NUM_INTEGER_REGS]; /* Number of GPR. */
2228 for (int regno = 0; regno < RISCV_NUM_INTEGER_REGS; regno++)
2229 regs[regno] = pv_register (regno, 0);
2230 pv_area stack (RISCV_SP_REGNUM, gdbarch_addr_bit (gdbarch));
2231
2232 riscv_unwinder_debug_printf ("function starting at %s (limit %s)",
2233 core_addr_to_string (start_pc),
2234 core_addr_to_string (end_pc));
2235
2236 for (next_pc = cur_pc = start_pc; cur_pc < end_pc; cur_pc = next_pc)
2237 {
2238 struct riscv_insn insn;
2239
2240 /* Decode the current instruction, and decide where the next
2241 instruction lives based on the size of this instruction. */
2242 insn.decode (gdbarch, cur_pc);
2243 gdb_assert (insn.length () > 0);
2244 next_pc = cur_pc + insn.length ();
2245
2246 /* Look for common stack adjustment insns. */
2247 if (is_insn_addi_of_sp_to_sp (insn))
2248 {
2249 /* Handle: addi sp, sp, -i
2250 or: addiw sp, sp, -i */
2251 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2252 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2253 regs[insn.rd ()]
2254 = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
2255 }
2256 else if ((insn.opcode () == riscv_insn::SW
2257 || insn.opcode () == riscv_insn::SD)
2258 && (insn.rs1 () == RISCV_SP_REGNUM
2259 || insn.rs1 () == RISCV_FP_REGNUM))
2260 {
2261 /* Handle: sw reg, offset(sp)
2262 or: sd reg, offset(sp)
2263 or: sw reg, offset(s0)
2264 or: sd reg, offset(s0) */
2265 /* Instruction storing a register onto the stack. */
2266 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2267 gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
2268 stack.store (pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ()),
2269 (insn.opcode () == riscv_insn::SW ? 4 : 8),
2270 regs[insn.rs2 ()]);
2271 }
2272 else if (insn.opcode () == riscv_insn::ADDI
2273 && insn.rd () == RISCV_FP_REGNUM
2274 && insn.rs1 () == RISCV_SP_REGNUM)
2275 {
2276 /* Handle: addi s0, sp, size */
2277 /* Instructions setting up the frame pointer. */
2278 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2279 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2280 regs[insn.rd ()]
2281 = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
2282 }
2283 else if ((insn.opcode () == riscv_insn::ADD
2284 || insn.opcode () == riscv_insn::ADDW)
2285 && insn.rd () == RISCV_FP_REGNUM
2286 && insn.rs1 () == RISCV_SP_REGNUM
2287 && insn.rs2 () == RISCV_ZERO_REGNUM)
2288 {
2289 /* Handle: add s0, sp, 0
2290 or: addw s0, sp, 0 */
2291 /* Instructions setting up the frame pointer. */
2292 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2293 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2294 regs[insn.rd ()] = pv_add_constant (regs[insn.rs1 ()], 0);
2295 }
2296 else if ((insn.opcode () == riscv_insn::ADDI
2297 && insn.rd () == RISCV_ZERO_REGNUM
2298 && insn.rs1 () == RISCV_ZERO_REGNUM
2299 && insn.imm_signed () == 0))
2300 {
2301 /* Handle: add x0, x0, 0 (NOP) */
2302 }
2303 else if (insn.opcode () == riscv_insn::AUIPC)
2304 {
2305 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2306 regs[insn.rd ()] = pv_constant (cur_pc + insn.imm_signed ());
2307 }
2308 else if (insn.opcode () == riscv_insn::LUI
2309 || insn.opcode () == riscv_insn::LI)
2310 {
2311 /* Handle: lui REG, n
2312 or: li REG, n */
2313 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2314 regs[insn.rd ()] = pv_constant (insn.imm_signed ());
2315 }
2316 else if (insn.opcode () == riscv_insn::ADDI)
2317 {
2318 /* Handle: addi REG1, REG2, IMM */
2319 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2320 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2321 regs[insn.rd ()]
2322 = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
2323 }
2324 else if (insn.opcode () == riscv_insn::ADD)
2325 {
2326 /* Handle: add REG1, REG2, REG3 */
2327 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2328 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2329 gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
2330 regs[insn.rd ()] = pv_add (regs[insn.rs1 ()], regs[insn.rs2 ()]);
2331 }
2332 else if (insn.opcode () == riscv_insn::LD
2333 || insn.opcode () == riscv_insn::LW)
2334 {
2335 /* Handle: ld reg, offset(rs1)
2336 or: c.ld reg, offset(rs1)
2337 or: lw reg, offset(rs1)
2338 or: c.lw reg, offset(rs1) */
2339 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2340 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2341 regs[insn.rd ()]
2342 = stack.fetch (pv_add_constant (regs[insn.rs1 ()],
2343 insn.imm_signed ()),
2344 (insn.opcode () == riscv_insn::LW ? 4 : 8));
2345 }
2346 else if (insn.opcode () == riscv_insn::MV)
2347 {
2348 /* Handle: c.mv RD, RS2 */
2349 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2350 gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
2351 gdb_assert (insn.rs2 () > 0);
2352 regs[insn.rd ()] = regs[insn.rs2 ()];
2353 }
2354 else
2355 {
2356 end_prologue_addr = cur_pc;
2357 break;
2358 }
2359 }
2360
2361 if (end_prologue_addr == 0)
2362 end_prologue_addr = cur_pc;
2363
2364 riscv_unwinder_debug_printf ("end of prologue at %s",
2365 core_addr_to_string (end_prologue_addr));
2366
2367 if (cache != NULL)
2368 {
2369 /* Figure out if it is a frame pointer or just a stack pointer. Also
2370 the offset held in the pv_t is from the original register value to
2371 the current value, which for a grows down stack means a negative
2372 value. The FRAME_BASE_OFFSET is the negation of this, how to get
2373 from the current value to the original value. */
2374 if (pv_is_register (regs[RISCV_FP_REGNUM], RISCV_SP_REGNUM))
2375 {
2376 cache->frame_base_reg = RISCV_FP_REGNUM;
2377 cache->frame_base_offset = -regs[RISCV_FP_REGNUM].k;
2378 }
2379 else
2380 {
2381 cache->frame_base_reg = RISCV_SP_REGNUM;
2382 cache->frame_base_offset = -regs[RISCV_SP_REGNUM].k;
2383 }
2384
2385 /* Check to see if we are located near to a return instruction in
2386 this function. If we are then the one or both of the stack
2387 pointer and frame pointer may have been restored to their previous
2388 value. If we can spot this situation then we can adjust which
2389 register and offset we use for the frame base. */
2390 if (cache->frame_base_reg != RISCV_SP_REGNUM
2391 || cache->frame_base_offset != 0)
2392 {
2393 int sp_offset;
2394
2395 if (riscv_detect_end_of_function (gdbarch, original_end_pc,
2396 &sp_offset))
2397 {
2398 riscv_unwinder_debug_printf
2399 ("in function epilogue at %s, stack offset is %d",
2400 core_addr_to_string (original_end_pc), sp_offset);
2401 cache->frame_base_reg= RISCV_SP_REGNUM;
2402 cache->frame_base_offset = sp_offset;
2403 }
2404 }
2405
2406 /* Assign offset from old SP to all saved registers. As we don't
2407 have the previous value for the frame base register at this
2408 point, we store the offset as the address in the trad_frame, and
2409 then convert this to an actual address later. */
2410 for (int i = 0; i <= RISCV_NUM_INTEGER_REGS; i++)
2411 {
2412 CORE_ADDR offset;
2413 if (stack.find_reg (gdbarch, i, &offset))
2414 {
2415 /* Display OFFSET as a signed value, the offsets are from the
2416 frame base address to the registers location on the stack,
2417 with a descending stack this means the offsets are always
2418 negative. */
2419 riscv_unwinder_debug_printf ("register $%s at stack offset %s",
2420 gdbarch_register_name (gdbarch, i),
2421 plongest ((LONGEST) offset));
2422 cache->regs[i].set_addr (offset);
2423 }
2424 }
2425 }
2426
2427 return end_prologue_addr;
2428 }
2429
2430 /* Implement the riscv_skip_prologue gdbarch method. */
2431
2432 static CORE_ADDR
2433 riscv_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
2434 {
2435 CORE_ADDR func_addr;
2436
2437 /* See if we can determine the end of the prologue via the symbol
2438 table. If so, then return either PC, or the PC after the
2439 prologue, whichever is greater. */
2440 if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
2441 {
2442 CORE_ADDR post_prologue_pc
2443 = skip_prologue_using_sal (gdbarch, func_addr);
2444
2445 if (post_prologue_pc != 0)
2446 return std::max (pc, post_prologue_pc);
2447 }
2448
2449 /* Can't determine prologue from the symbol table, need to examine
2450 instructions. Pass -1 for the end address to indicate the prologue
2451 scanner can scan as far as it needs to find the end of the prologue. */
2452 return riscv_scan_prologue (gdbarch, pc, ((CORE_ADDR) -1), NULL);
2453 }
2454
2455 /* Implement the gdbarch push dummy code callback. */
2456
2457 static CORE_ADDR
2458 riscv_push_dummy_code (struct gdbarch *gdbarch, CORE_ADDR sp,
2459 CORE_ADDR funaddr, struct value **args, int nargs,
2460 struct type *value_type, CORE_ADDR *real_pc,
2461 CORE_ADDR *bp_addr, struct regcache *regcache)
2462 {
2463 /* A nop instruction is 'add x0, x0, 0'. */
2464 static const gdb_byte nop_insn[] = { 0x13, 0x00, 0x00, 0x00 };
2465
2466 /* Allocate space for a breakpoint, and keep the stack correctly
2467 aligned. The space allocated here must be at least big enough to
2468 accommodate the NOP_INSN defined above. */
2469 sp -= 16;
2470 *bp_addr = sp;
2471 *real_pc = funaddr;
2472
2473 /* When we insert a breakpoint we select whether to use a compressed
2474 breakpoint or not based on the existing contents of the memory.
2475
2476 If the breakpoint is being placed onto the stack as part of setting up
2477 for an inferior call from GDB, then the existing stack contents may
2478 randomly appear to be a compressed instruction, causing GDB to insert
2479 a compressed breakpoint. If this happens on a target that does not
2480 support compressed instructions then this could cause problems.
2481
2482 To prevent this issue we write an uncompressed nop onto the stack at
2483 the location where the breakpoint will be inserted. In this way we
2484 ensure that we always use an uncompressed breakpoint, which should
2485 work on all targets.
2486
2487 We call TARGET_WRITE_MEMORY here so that if the write fails we don't
2488 throw an exception. Instead we ignore the error and move on. The
2489 assumption is that either GDB will error later when actually trying to
2490 insert a software breakpoint, or GDB will use hardware breakpoints and
2491 there will be no need to write to memory later. */
2492 int status = target_write_memory (*bp_addr, nop_insn, sizeof (nop_insn));
2493
2494 riscv_infcall_debug_printf ("writing %s-byte nop instruction to %s: %s",
2495 plongest (sizeof (nop_insn)),
2496 paddress (gdbarch, *bp_addr),
2497 (status == 0 ? "success" : "failed"));
2498
2499 return sp;
2500 }
2501
2502 /* Implement the gdbarch type alignment method, overrides the generic
2503 alignment algorithm for anything that is RISC-V specific. */
2504
2505 static ULONGEST
2506 riscv_type_align (gdbarch *gdbarch, type *type)
2507 {
2508 type = check_typedef (type);
2509 if (type->code () == TYPE_CODE_ARRAY && type->is_vector ())
2510 return std::min (type->length (), (ULONGEST) BIGGEST_ALIGNMENT);
2511
2512 /* Anything else will be aligned by the generic code. */
2513 return 0;
2514 }
2515
2516 /* Holds information about a single argument either being passed to an
2517 inferior function, or returned from an inferior function. This includes
2518 information about the size, type, etc of the argument, and also
2519 information about how the argument will be passed (or returned). */
2520
2521 struct riscv_arg_info
2522 {
2523 /* Contents of the argument. */
2524 const gdb_byte *contents;
2525
2526 /* Length of argument. */
2527 int length;
2528
2529 /* Alignment required for an argument of this type. */
2530 int align;
2531
2532 /* The type for this argument. */
2533 struct type *type;
2534
2535 /* Each argument can have either 1 or 2 locations assigned to it. Each
2536 location describes where part of the argument will be placed. The
2537 second location is valid based on the LOC_TYPE and C_LENGTH fields
2538 of the first location (which is always valid). */
2539 struct location
2540 {
2541 /* What type of location this is. */
2542 enum location_type
2543 {
2544 /* Argument passed in a register. */
2545 in_reg,
2546
2547 /* Argument passed as an on stack argument. */
2548 on_stack,
2549
2550 /* Argument passed by reference. The second location is always
2551 valid for a BY_REF argument, and describes where the address
2552 of the BY_REF argument should be placed. */
2553 by_ref
2554 } loc_type;
2555
2556 /* Information that depends on the location type. */
2557 union
2558 {
2559 /* Which register number to use. */
2560 int regno;
2561
2562 /* The offset into the stack region. */
2563 int offset;
2564 } loc_data;
2565
2566 /* The length of contents covered by this location. If this is less
2567 than the total length of the argument, then the second location
2568 will be valid, and will describe where the rest of the argument
2569 will go. */
2570 int c_length;
2571
2572 /* The offset within CONTENTS for this part of the argument. This can
2573 be non-zero even for the first part (the first field of a struct can
2574 have a non-zero offset due to padding). For the second part of the
2575 argument, this might be the C_LENGTH value of the first part,
2576 however, if we are passing a structure in two registers, and there's
2577 is padding between the first and second field, then this offset
2578 might be greater than the length of the first argument part. When
2579 the second argument location is not holding part of the argument
2580 value, but is instead holding the address of a reference argument,
2581 then this offset will be set to 0. */
2582 int c_offset;
2583 } argloc[2];
2584
2585 /* TRUE if this is an unnamed argument. */
2586 bool is_unnamed;
2587 };
2588
2589 /* Information about a set of registers being used for passing arguments as
2590 part of a function call. The register set must be numerically
2591 sequential from NEXT_REGNUM to LAST_REGNUM. The register set can be
2592 disabled from use by setting NEXT_REGNUM greater than LAST_REGNUM. */
2593
2594 struct riscv_arg_reg
2595 {
2596 riscv_arg_reg (int first, int last)
2597 : next_regnum (first),
2598 last_regnum (last)
2599 {
2600 /* Nothing. */
2601 }
2602
2603 /* The GDB register number to use in this set. */
2604 int next_regnum;
2605
2606 /* The last GDB register number to use in this set. */
2607 int last_regnum;
2608 };
2609
2610 /* Arguments can be passed as on stack arguments, or by reference. The
2611 on stack arguments must be in a continuous region starting from $sp,
2612 while the by reference arguments can be anywhere, but we'll put them
2613 on the stack after (at higher address) the on stack arguments.
2614
2615 This might not be the right approach to take. The ABI is clear that
2616 an argument passed by reference can be modified by the callee, which
2617 us placing the argument (temporarily) onto the stack will not achieve
2618 (changes will be lost). There's also the possibility that very large
2619 arguments could overflow the stack.
2620
2621 This struct is used to track offset into these two areas for where
2622 arguments are to be placed. */
2623 struct riscv_memory_offsets
2624 {
2625 riscv_memory_offsets ()
2626 : arg_offset (0),
2627 ref_offset (0)
2628 {
2629 /* Nothing. */
2630 }
2631
2632 /* Offset into on stack argument area. */
2633 int arg_offset;
2634
2635 /* Offset into the pass by reference area. */
2636 int ref_offset;
2637 };
2638
2639 /* Holds information about where arguments to a call will be placed. This
2640 is updated as arguments are added onto the call, and can be used to
2641 figure out where the next argument should be placed. */
2642
2643 struct riscv_call_info
2644 {
2645 riscv_call_info (struct gdbarch *gdbarch)
2646 : int_regs (RISCV_A0_REGNUM, RISCV_A0_REGNUM + 7),
2647 float_regs (RISCV_FA0_REGNUM, RISCV_FA0_REGNUM + 7)
2648 {
2649 xlen = riscv_abi_xlen (gdbarch);
2650 flen = riscv_abi_flen (gdbarch);
2651
2652 /* Reduce the number of integer argument registers when using the
2653 embedded abi (i.e. rv32e). */
2654 if (riscv_abi_embedded (gdbarch))
2655 int_regs.last_regnum = RISCV_A0_REGNUM + 5;
2656
2657 /* Disable use of floating point registers if needed. */
2658 if (!riscv_has_fp_abi (gdbarch))
2659 float_regs.next_regnum = float_regs.last_regnum + 1;
2660 }
2661
2662 /* Track the memory areas used for holding in-memory arguments to a
2663 call. */
2664 struct riscv_memory_offsets memory;
2665
2666 /* Holds information about the next integer register to use for passing
2667 an argument. */
2668 struct riscv_arg_reg int_regs;
2669
2670 /* Holds information about the next floating point register to use for
2671 passing an argument. */
2672 struct riscv_arg_reg float_regs;
2673
2674 /* The XLEN and FLEN are copied in to this structure for convenience, and
2675 are just the results of calling RISCV_ABI_XLEN and RISCV_ABI_FLEN. */
2676 int xlen;
2677 int flen;
2678 };
2679
2680 /* Return the number of registers available for use as parameters in the
2681 register set REG. Returned value can be 0 or more. */
2682
2683 static int
2684 riscv_arg_regs_available (struct riscv_arg_reg *reg)
2685 {
2686 if (reg->next_regnum > reg->last_regnum)
2687 return 0;
2688
2689 return (reg->last_regnum - reg->next_regnum + 1);
2690 }
2691
2692 /* If there is at least one register available in the register set REG then
2693 the next register from REG is assigned to LOC and the length field of
2694 LOC is updated to LENGTH. The register set REG is updated to indicate
2695 that the assigned register is no longer available and the function
2696 returns true.
2697
2698 If there are no registers available in REG then the function returns
2699 false, and LOC and REG are unchanged. */
2700
2701 static bool
2702 riscv_assign_reg_location (struct riscv_arg_info::location *loc,
2703 struct riscv_arg_reg *reg,
2704 int length, int offset)
2705 {
2706 if (reg->next_regnum <= reg->last_regnum)
2707 {
2708 loc->loc_type = riscv_arg_info::location::in_reg;
2709 loc->loc_data.regno = reg->next_regnum;
2710 reg->next_regnum++;
2711 loc->c_length = length;
2712 loc->c_offset = offset;
2713 return true;
2714 }
2715
2716 return false;
2717 }
2718
2719 /* Assign LOC a location as the next stack parameter, and update MEMORY to
2720 record that an area of stack has been used to hold the parameter
2721 described by LOC.
2722
2723 The length field of LOC is updated to LENGTH, the length of the
2724 parameter being stored, and ALIGN is the alignment required by the
2725 parameter, which will affect how memory is allocated out of MEMORY. */
2726
2727 static void
2728 riscv_assign_stack_location (struct riscv_arg_info::location *loc,
2729 struct riscv_memory_offsets *memory,
2730 int length, int align)
2731 {
2732 loc->loc_type = riscv_arg_info::location::on_stack;
2733 memory->arg_offset
2734 = align_up (memory->arg_offset, align);
2735 loc->loc_data.offset = memory->arg_offset;
2736 memory->arg_offset += length;
2737 loc->c_length = length;
2738
2739 /* Offset is always 0, either we're the first location part, in which
2740 case we're reading content from the start of the argument, or we're
2741 passing the address of a reference argument, so 0. */
2742 loc->c_offset = 0;
2743 }
2744
2745 /* Update AINFO, which describes an argument that should be passed or
2746 returned using the integer ABI. The argloc fields within AINFO are
2747 updated to describe the location in which the argument will be passed to
2748 a function, or returned from a function.
2749
2750 The CINFO structure contains the ongoing call information, the holds
2751 information such as which argument registers are remaining to be
2752 assigned to parameter, and how much memory has been used by parameters
2753 so far.
2754
2755 By examining the state of CINFO a suitable location can be selected,
2756 and assigned to AINFO. */
2757
2758 static void
2759 riscv_call_arg_scalar_int (struct riscv_arg_info *ainfo,
2760 struct riscv_call_info *cinfo)
2761 {
2762 if (TYPE_HAS_DYNAMIC_LENGTH (ainfo->type)
2763 || ainfo->length > (2 * cinfo->xlen))
2764 {
2765 /* Argument is going to be passed by reference. */
2766 ainfo->argloc[0].loc_type
2767 = riscv_arg_info::location::by_ref;
2768 cinfo->memory.ref_offset
2769 = align_up (cinfo->memory.ref_offset, ainfo->align);
2770 ainfo->argloc[0].loc_data.offset = cinfo->memory.ref_offset;
2771 cinfo->memory.ref_offset += ainfo->length;
2772 ainfo->argloc[0].c_length = ainfo->length;
2773
2774 /* The second location for this argument is given over to holding the
2775 address of the by-reference data. Pass 0 for the offset as this
2776 is not part of the actual argument value. */
2777 if (!riscv_assign_reg_location (&ainfo->argloc[1],
2778 &cinfo->int_regs,
2779 cinfo->xlen, 0))
2780 riscv_assign_stack_location (&ainfo->argloc[1],
2781 &cinfo->memory, cinfo->xlen,
2782 cinfo->xlen);
2783 }
2784 else
2785 {
2786 int len = std::min (ainfo->length, cinfo->xlen);
2787 int align = std::max (ainfo->align, cinfo->xlen);
2788
2789 /* Unnamed arguments in registers that require 2*XLEN alignment are
2790 passed in an aligned register pair. */
2791 if (ainfo->is_unnamed && (align == cinfo->xlen * 2)
2792 && cinfo->int_regs.next_regnum & 1)
2793 cinfo->int_regs.next_regnum++;
2794
2795 if (!riscv_assign_reg_location (&ainfo->argloc[0],
2796 &cinfo->int_regs, len, 0))
2797 riscv_assign_stack_location (&ainfo->argloc[0],
2798 &cinfo->memory, len, align);
2799
2800 if (len < ainfo->length)
2801 {
2802 len = ainfo->length - len;
2803 if (!riscv_assign_reg_location (&ainfo->argloc[1],
2804 &cinfo->int_regs, len,
2805 cinfo->xlen))
2806 riscv_assign_stack_location (&ainfo->argloc[1],
2807 &cinfo->memory, len, cinfo->xlen);
2808 }
2809 }
2810 }
2811
2812 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2813 is being passed with the floating point ABI. */
2814
2815 static void
2816 riscv_call_arg_scalar_float (struct riscv_arg_info *ainfo,
2817 struct riscv_call_info *cinfo)
2818 {
2819 if (ainfo->length > cinfo->flen || ainfo->is_unnamed)
2820 return riscv_call_arg_scalar_int (ainfo, cinfo);
2821 else
2822 {
2823 if (!riscv_assign_reg_location (&ainfo->argloc[0],
2824 &cinfo->float_regs,
2825 ainfo->length, 0))
2826 return riscv_call_arg_scalar_int (ainfo, cinfo);
2827 }
2828 }
2829
2830 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2831 is a complex floating point argument, and is therefore handled
2832 differently to other argument types. */
2833
2834 static void
2835 riscv_call_arg_complex_float (struct riscv_arg_info *ainfo,
2836 struct riscv_call_info *cinfo)
2837 {
2838 if (ainfo->length <= (2 * cinfo->flen)
2839 && riscv_arg_regs_available (&cinfo->float_regs) >= 2
2840 && !ainfo->is_unnamed)
2841 {
2842 bool result;
2843 int len = ainfo->length / 2;
2844
2845 result = riscv_assign_reg_location (&ainfo->argloc[0],
2846 &cinfo->float_regs, len, 0);
2847 gdb_assert (result);
2848
2849 result = riscv_assign_reg_location (&ainfo->argloc[1],
2850 &cinfo->float_regs, len, len);
2851 gdb_assert (result);
2852 }
2853 else
2854 return riscv_call_arg_scalar_int (ainfo, cinfo);
2855 }
2856
2857 /* A structure used for holding information about a structure type within
2858 the inferior program. The RiscV ABI has special rules for handling some
2859 structures with a single field or with two fields. The counting of
2860 fields here is done after flattening out all nested structures. */
2861
2862 class riscv_struct_info
2863 {
2864 public:
2865 riscv_struct_info ()
2866 : m_number_of_fields (0),
2867 m_types { nullptr, nullptr },
2868 m_offsets { 0, 0 }
2869 {
2870 /* Nothing. */
2871 }
2872
2873 /* Analyse TYPE descending into nested structures, count the number of
2874 scalar fields and record the types of the first two fields found. */
2875 void analyse (struct type *type)
2876 {
2877 analyse_inner (type, 0);
2878 }
2879
2880 /* The number of scalar fields found in the analysed type. This is
2881 currently only accurate if the value returned is 0, 1, or 2 as the
2882 analysis stops counting when the number of fields is 3. This is
2883 because the RiscV ABI only has special cases for 1 or 2 fields,
2884 anything else we just don't care about. */
2885 int number_of_fields () const
2886 { return m_number_of_fields; }
2887
2888 /* Return the type for scalar field INDEX within the analysed type. Will
2889 return nullptr if there is no field at that index. Only INDEX values
2890 0 and 1 can be requested as the RiscV ABI only has special cases for
2891 structures with 1 or 2 fields. */
2892 struct type *field_type (int index) const
2893 {
2894 gdb_assert (index < (sizeof (m_types) / sizeof (m_types[0])));
2895 return m_types[index];
2896 }
2897
2898 /* Return the offset of scalar field INDEX within the analysed type. Will
2899 return 0 if there is no field at that index. Only INDEX values 0 and
2900 1 can be requested as the RiscV ABI only has special cases for
2901 structures with 1 or 2 fields. */
2902 int field_offset (int index) const
2903 {
2904 gdb_assert (index < (sizeof (m_offsets) / sizeof (m_offsets[0])));
2905 return m_offsets[index];
2906 }
2907
2908 private:
2909 /* The number of scalar fields found within the structure after recursing
2910 into nested structures. */
2911 int m_number_of_fields;
2912
2913 /* The types of the first two scalar fields found within the structure
2914 after recursing into nested structures. */
2915 struct type *m_types[2];
2916
2917 /* The offsets of the first two scalar fields found within the structure
2918 after recursing into nested structures. */
2919 int m_offsets[2];
2920
2921 /* Recursive core for ANALYSE, the OFFSET parameter tracks the byte
2922 offset from the start of the top level structure being analysed. */
2923 void analyse_inner (struct type *type, int offset);
2924 };
2925
2926 /* See description in class declaration. */
2927
2928 void
2929 riscv_struct_info::analyse_inner (struct type *type, int offset)
2930 {
2931 unsigned int count = type->num_fields ();
2932 unsigned int i;
2933
2934 for (i = 0; i < count; ++i)
2935 {
2936 if (type->field (i).loc_kind () != FIELD_LOC_KIND_BITPOS)
2937 continue;
2938
2939 struct type *field_type = type->field (i).type ();
2940 field_type = check_typedef (field_type);
2941 int field_offset
2942 = offset + type->field (i).loc_bitpos () / TARGET_CHAR_BIT;
2943
2944 switch (field_type->code ())
2945 {
2946 case TYPE_CODE_STRUCT:
2947 analyse_inner (field_type, field_offset);
2948 break;
2949
2950 default:
2951 /* RiscV only flattens out structures. Anything else does not
2952 need to be flattened, we just record the type, and when we
2953 look at the analysis results we'll realise this is not a
2954 structure we can special case, and pass the structure in
2955 memory. */
2956 if (m_number_of_fields < 2)
2957 {
2958 m_types[m_number_of_fields] = field_type;
2959 m_offsets[m_number_of_fields] = field_offset;
2960 }
2961 m_number_of_fields++;
2962 break;
2963 }
2964
2965 /* RiscV only has special handling for structures with 1 or 2 scalar
2966 fields, any more than that and the structure is just passed in
2967 memory. We can safely drop out early when we find 3 or more
2968 fields then. */
2969
2970 if (m_number_of_fields > 2)
2971 return;
2972 }
2973 }
2974
2975 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2976 is a structure. Small structures on RiscV have some special case
2977 handling in order that the structure might be passed in register.
2978 Larger structures are passed in memory. After assigning location
2979 information to AINFO, CINFO will have been updated. */
2980
2981 static void
2982 riscv_call_arg_struct (struct riscv_arg_info *ainfo,
2983 struct riscv_call_info *cinfo)
2984 {
2985 if (riscv_arg_regs_available (&cinfo->float_regs) >= 1)
2986 {
2987 struct riscv_struct_info sinfo;
2988
2989 sinfo.analyse (ainfo->type);
2990 if (sinfo.number_of_fields () == 1
2991 && sinfo.field_type(0)->code () == TYPE_CODE_COMPLEX)
2992 {
2993 /* The following is similar to RISCV_CALL_ARG_COMPLEX_FLOAT,
2994 except we use the type of the complex field instead of the
2995 type from AINFO, and the first location might be at a non-zero
2996 offset. */
2997 if (sinfo.field_type (0)->length () <= (2 * cinfo->flen)
2998 && riscv_arg_regs_available (&cinfo->float_regs) >= 2
2999 && !ainfo->is_unnamed)
3000 {
3001 bool result;
3002 int len = sinfo.field_type (0)->length () / 2;
3003 int offset = sinfo.field_offset (0);
3004
3005 result = riscv_assign_reg_location (&ainfo->argloc[0],
3006 &cinfo->float_regs, len,
3007 offset);
3008 gdb_assert (result);
3009
3010 result = riscv_assign_reg_location (&ainfo->argloc[1],
3011 &cinfo->float_regs, len,
3012 (offset + len));
3013 gdb_assert (result);
3014 }
3015 else
3016 riscv_call_arg_scalar_int (ainfo, cinfo);
3017 return;
3018 }
3019
3020 if (sinfo.number_of_fields () == 1
3021 && sinfo.field_type(0)->code () == TYPE_CODE_FLT)
3022 {
3023 /* The following is similar to RISCV_CALL_ARG_SCALAR_FLOAT,
3024 except we use the type of the first scalar field instead of
3025 the type from AINFO. Also the location might be at a non-zero
3026 offset. */
3027 if (sinfo.field_type (0)->length () > cinfo->flen
3028 || ainfo->is_unnamed)
3029 riscv_call_arg_scalar_int (ainfo, cinfo);
3030 else
3031 {
3032 int offset = sinfo.field_offset (0);
3033 int len = sinfo.field_type (0)->length ();
3034
3035 if (!riscv_assign_reg_location (&ainfo->argloc[0],
3036 &cinfo->float_regs,
3037 len, offset))
3038 riscv_call_arg_scalar_int (ainfo, cinfo);
3039 }
3040 return;
3041 }
3042
3043 if (sinfo.number_of_fields () == 2
3044 && sinfo.field_type(0)->code () == TYPE_CODE_FLT
3045 && sinfo.field_type (0)->length () <= cinfo->flen
3046 && sinfo.field_type(1)->code () == TYPE_CODE_FLT
3047 && sinfo.field_type (1)->length () <= cinfo->flen
3048 && riscv_arg_regs_available (&cinfo->float_regs) >= 2)
3049 {
3050 int len0 = sinfo.field_type (0)->length ();
3051 int offset = sinfo.field_offset (0);
3052 if (!riscv_assign_reg_location (&ainfo->argloc[0],
3053 &cinfo->float_regs, len0, offset))
3054 error (_("failed during argument setup"));
3055
3056 int len1 = sinfo.field_type (1)->length ();
3057 offset = sinfo.field_offset (1);
3058 gdb_assert (len1 <= (ainfo->type->length ()
3059 - sinfo.field_type (0)->length ()));
3060
3061 if (!riscv_assign_reg_location (&ainfo->argloc[1],
3062 &cinfo->float_regs,
3063 len1, offset))
3064 error (_("failed during argument setup"));
3065 return;
3066 }
3067
3068 if (sinfo.number_of_fields () == 2
3069 && riscv_arg_regs_available (&cinfo->int_regs) >= 1
3070 && (sinfo.field_type(0)->code () == TYPE_CODE_FLT
3071 && sinfo.field_type (0)->length () <= cinfo->flen
3072 && is_integral_type (sinfo.field_type (1))
3073 && sinfo.field_type (1)->length () <= cinfo->xlen))
3074 {
3075 int len0 = sinfo.field_type (0)->length ();
3076 int offset = sinfo.field_offset (0);
3077 if (!riscv_assign_reg_location (&ainfo->argloc[0],
3078 &cinfo->float_regs, len0, offset))
3079 error (_("failed during argument setup"));
3080
3081 int len1 = sinfo.field_type (1)->length ();
3082 offset = sinfo.field_offset (1);
3083 gdb_assert (len1 <= cinfo->xlen);
3084 if (!riscv_assign_reg_location (&ainfo->argloc[1],
3085 &cinfo->int_regs, len1, offset))
3086 error (_("failed during argument setup"));
3087 return;
3088 }
3089
3090 if (sinfo.number_of_fields () == 2
3091 && riscv_arg_regs_available (&cinfo->int_regs) >= 1
3092 && (is_integral_type (sinfo.field_type (0))
3093 && sinfo.field_type (0)->length () <= cinfo->xlen
3094 && sinfo.field_type(1)->code () == TYPE_CODE_FLT
3095 && sinfo.field_type (1)->length () <= cinfo->flen))
3096 {
3097 int len0 = sinfo.field_type (0)->length ();
3098 int len1 = sinfo.field_type (1)->length ();
3099
3100 gdb_assert (len0 <= cinfo->xlen);
3101 gdb_assert (len1 <= cinfo->flen);
3102
3103 int offset = sinfo.field_offset (0);
3104 if (!riscv_assign_reg_location (&ainfo->argloc[0],
3105 &cinfo->int_regs, len0, offset))
3106 error (_("failed during argument setup"));
3107
3108 offset = sinfo.field_offset (1);
3109 if (!riscv_assign_reg_location (&ainfo->argloc[1],
3110 &cinfo->float_regs,
3111 len1, offset))
3112 error (_("failed during argument setup"));
3113
3114 return;
3115 }
3116 }
3117
3118 /* Non of the structure flattening cases apply, so we just pass using
3119 the integer ABI. */
3120 riscv_call_arg_scalar_int (ainfo, cinfo);
3121 }
3122
3123 /* Assign a location to call (or return) argument AINFO, the location is
3124 selected from CINFO which holds information about what call argument
3125 locations are available for use next. The TYPE is the type of the
3126 argument being passed, this information is recorded into AINFO (along
3127 with some additional information derived from the type). IS_UNNAMED
3128 is true if this is an unnamed (stdarg) argument, this info is also
3129 recorded into AINFO.
3130
3131 After assigning a location to AINFO, CINFO will have been updated. */
3132
3133 static void
3134 riscv_arg_location (struct gdbarch *gdbarch,
3135 struct riscv_arg_info *ainfo,
3136 struct riscv_call_info *cinfo,
3137 struct type *type, bool is_unnamed)
3138 {
3139 ainfo->type = type;
3140 ainfo->length = ainfo->type->length ();
3141 ainfo->align = type_align (ainfo->type);
3142 ainfo->is_unnamed = is_unnamed;
3143 ainfo->contents = nullptr;
3144 ainfo->argloc[0].c_length = 0;
3145 ainfo->argloc[1].c_length = 0;
3146
3147 switch (ainfo->type->code ())
3148 {
3149 case TYPE_CODE_INT:
3150 case TYPE_CODE_BOOL:
3151 case TYPE_CODE_CHAR:
3152 case TYPE_CODE_RANGE:
3153 case TYPE_CODE_ENUM:
3154 case TYPE_CODE_PTR:
3155 case TYPE_CODE_FIXED_POINT:
3156 if (ainfo->length <= cinfo->xlen)
3157 {
3158 ainfo->type = builtin_type (gdbarch)->builtin_long;
3159 ainfo->length = cinfo->xlen;
3160 }
3161 else if (ainfo->length <= (2 * cinfo->xlen))
3162 {
3163 ainfo->type = builtin_type (gdbarch)->builtin_long_long;
3164 ainfo->length = 2 * cinfo->xlen;
3165 }
3166
3167 /* Recalculate the alignment requirement. */
3168 ainfo->align = type_align (ainfo->type);
3169 riscv_call_arg_scalar_int (ainfo, cinfo);
3170 break;
3171
3172 case TYPE_CODE_FLT:
3173 riscv_call_arg_scalar_float (ainfo, cinfo);
3174 break;
3175
3176 case TYPE_CODE_COMPLEX:
3177 riscv_call_arg_complex_float (ainfo, cinfo);
3178 break;
3179
3180 case TYPE_CODE_STRUCT:
3181 if (!TYPE_HAS_DYNAMIC_LENGTH (ainfo->type))
3182 {
3183 riscv_call_arg_struct (ainfo, cinfo);
3184 break;
3185 }
3186 /* FALLTHROUGH */
3187
3188 default:
3189 riscv_call_arg_scalar_int (ainfo, cinfo);
3190 break;
3191 }
3192 }
3193
3194 /* Used for printing debug information about the call argument location in
3195 INFO to STREAM. The addresses in SP_REFS and SP_ARGS are the base
3196 addresses for the location of pass-by-reference and
3197 arguments-on-the-stack memory areas. */
3198
3199 static void
3200 riscv_print_arg_location (ui_file *stream, struct gdbarch *gdbarch,
3201 struct riscv_arg_info *info,
3202 CORE_ADDR sp_refs, CORE_ADDR sp_args)
3203 {
3204 gdb_printf (stream, "type: '%s', length: 0x%x, alignment: 0x%x",
3205 TYPE_SAFE_NAME (info->type), info->length, info->align);
3206 switch (info->argloc[0].loc_type)
3207 {
3208 case riscv_arg_info::location::in_reg:
3209 gdb_printf
3210 (stream, ", register %s",
3211 gdbarch_register_name (gdbarch, info->argloc[0].loc_data.regno));
3212 if (info->argloc[0].c_length < info->length)
3213 {
3214 switch (info->argloc[1].loc_type)
3215 {
3216 case riscv_arg_info::location::in_reg:
3217 gdb_printf
3218 (stream, ", register %s",
3219 gdbarch_register_name (gdbarch,
3220 info->argloc[1].loc_data.regno));
3221 break;
3222
3223 case riscv_arg_info::location::on_stack:
3224 gdb_printf (stream, ", on stack at offset 0x%x",
3225 info->argloc[1].loc_data.offset);
3226 break;
3227
3228 case riscv_arg_info::location::by_ref:
3229 default:
3230 /* The second location should never be a reference, any
3231 argument being passed by reference just places its address
3232 in the first location and is done. */
3233 error (_("invalid argument location"));
3234 break;
3235 }
3236
3237 if (info->argloc[1].c_offset > info->argloc[0].c_length)
3238 gdb_printf (stream, " (offset 0x%x)",
3239 info->argloc[1].c_offset);
3240 }
3241 break;
3242
3243 case riscv_arg_info::location::on_stack:
3244 gdb_printf (stream, ", on stack at offset 0x%x",
3245 info->argloc[0].loc_data.offset);
3246 break;
3247
3248 case riscv_arg_info::location::by_ref:
3249 gdb_printf
3250 (stream, ", by reference, data at offset 0x%x (%s)",
3251 info->argloc[0].loc_data.offset,
3252 core_addr_to_string (sp_refs + info->argloc[0].loc_data.offset));
3253 if (info->argloc[1].loc_type
3254 == riscv_arg_info::location::in_reg)
3255 gdb_printf
3256 (stream, ", address in register %s",
3257 gdbarch_register_name (gdbarch, info->argloc[1].loc_data.regno));
3258 else
3259 {
3260 gdb_assert (info->argloc[1].loc_type
3261 == riscv_arg_info::location::on_stack);
3262 gdb_printf
3263 (stream, ", address on stack at offset 0x%x (%s)",
3264 info->argloc[1].loc_data.offset,
3265 core_addr_to_string (sp_args + info->argloc[1].loc_data.offset));
3266 }
3267 break;
3268
3269 default:
3270 gdb_assert_not_reached ("unknown argument location type");
3271 }
3272 }
3273
3274 /* Wrapper around REGCACHE->cooked_write. Places the LEN bytes of DATA
3275 into a buffer that is at least as big as the register REGNUM, padding
3276 out the DATA with either 0x00, or 0xff. For floating point registers
3277 0xff is used, for everyone else 0x00 is used. */
3278
3279 static void
3280 riscv_regcache_cooked_write (int regnum, const gdb_byte *data, int len,
3281 struct regcache *regcache, int flen)
3282 {
3283 gdb_byte tmp [sizeof (ULONGEST)];
3284
3285 /* FP values in FP registers must be NaN-boxed. */
3286 if (riscv_is_fp_regno_p (regnum) && len < flen)
3287 memset (tmp, -1, sizeof (tmp));
3288 else
3289 memset (tmp, 0, sizeof (tmp));
3290 memcpy (tmp, data, len);
3291 regcache->cooked_write (regnum, tmp);
3292 }
3293
3294 /* Implement the push dummy call gdbarch callback. */
3295
3296 static CORE_ADDR
3297 riscv_push_dummy_call (struct gdbarch *gdbarch,
3298 struct value *function,
3299 struct regcache *regcache,
3300 CORE_ADDR bp_addr,
3301 int nargs,
3302 struct value **args,
3303 CORE_ADDR sp,
3304 function_call_return_method return_method,
3305 CORE_ADDR struct_addr)
3306 {
3307 int i;
3308 CORE_ADDR sp_args, sp_refs;
3309 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
3310
3311 struct riscv_arg_info *arg_info =
3312 (struct riscv_arg_info *) alloca (nargs * sizeof (struct riscv_arg_info));
3313
3314 struct riscv_call_info call_info (gdbarch);
3315
3316 CORE_ADDR osp = sp;
3317
3318 struct type *ftype = check_typedef (function->type ());
3319
3320 if (ftype->code () == TYPE_CODE_PTR)
3321 ftype = check_typedef (ftype->target_type ());
3322
3323 /* We'll use register $a0 if we're returning a struct. */
3324 if (return_method == return_method_struct)
3325 ++call_info.int_regs.next_regnum;
3326
3327 for (i = 0; i < nargs; ++i)
3328 {
3329 struct value *arg_value;
3330 struct type *arg_type;
3331 struct riscv_arg_info *info = &arg_info[i];
3332
3333 arg_value = args[i];
3334 arg_type = check_typedef (arg_value->type ());
3335
3336 riscv_arg_location (gdbarch, info, &call_info, arg_type,
3337 ftype->has_varargs () && i >= ftype->num_fields ());
3338
3339 if (info->type != arg_type)
3340 arg_value = value_cast (info->type, arg_value);
3341 info->contents = arg_value->contents ().data ();
3342 }
3343
3344 /* Adjust the stack pointer and align it. */
3345 sp = sp_refs = align_down (sp - call_info.memory.ref_offset, SP_ALIGNMENT);
3346 sp = sp_args = align_down (sp - call_info.memory.arg_offset, SP_ALIGNMENT);
3347
3348 if (riscv_debug_infcall)
3349 {
3350 RISCV_INFCALL_SCOPED_DEBUG_START_END ("dummy call args");
3351 riscv_infcall_debug_printf ("floating point ABI %s in use",
3352 (riscv_has_fp_abi (gdbarch)
3353 ? "is" : "is not"));
3354 riscv_infcall_debug_printf ("xlen: %d", call_info.xlen);
3355 riscv_infcall_debug_printf ("flen: %d", call_info.flen);
3356 if (return_method == return_method_struct)
3357 riscv_infcall_debug_printf
3358 ("[**] struct return pointer in register $A0");
3359 for (i = 0; i < nargs; ++i)
3360 {
3361 struct riscv_arg_info *info = &arg_info [i];
3362 string_file tmp;
3363
3364 riscv_print_arg_location (&tmp, gdbarch, info, sp_refs, sp_args);
3365 riscv_infcall_debug_printf ("[%2d] %s", i, tmp.string ().c_str ());
3366 }
3367 if (call_info.memory.arg_offset > 0
3368 || call_info.memory.ref_offset > 0)
3369 {
3370 riscv_infcall_debug_printf (" Original sp: %s",
3371 core_addr_to_string (osp));
3372 riscv_infcall_debug_printf ("Stack required (for args): 0x%x",
3373 call_info.memory.arg_offset);
3374 riscv_infcall_debug_printf ("Stack required (for refs): 0x%x",
3375 call_info.memory.ref_offset);
3376 riscv_infcall_debug_printf (" Stack allocated: %s",
3377 core_addr_to_string_nz (osp - sp));
3378 }
3379 }
3380
3381 /* Now load the argument into registers, or onto the stack. */
3382
3383 if (return_method == return_method_struct)
3384 {
3385 gdb_byte buf[sizeof (LONGEST)];
3386
3387 store_unsigned_integer (buf, call_info.xlen, byte_order, struct_addr);
3388 regcache->cooked_write (RISCV_A0_REGNUM, buf);
3389 }
3390
3391 for (i = 0; i < nargs; ++i)
3392 {
3393 CORE_ADDR dst;
3394 int second_arg_length = 0;
3395 const gdb_byte *second_arg_data;
3396 struct riscv_arg_info *info = &arg_info [i];
3397
3398 gdb_assert (info->length > 0);
3399
3400 switch (info->argloc[0].loc_type)
3401 {
3402 case riscv_arg_info::location::in_reg:
3403 {
3404 gdb_assert (info->argloc[0].c_length <= info->length);
3405
3406 riscv_regcache_cooked_write (info->argloc[0].loc_data.regno,
3407 (info->contents
3408 + info->argloc[0].c_offset),
3409 info->argloc[0].c_length,
3410 regcache, call_info.flen);
3411 second_arg_length =
3412 (((info->argloc[0].c_length + info->argloc[0].c_offset) < info->length)
3413 ? info->argloc[1].c_length : 0);
3414 second_arg_data = info->contents + info->argloc[1].c_offset;
3415 }
3416 break;
3417
3418 case riscv_arg_info::location::on_stack:
3419 dst = sp_args + info->argloc[0].loc_data.offset;
3420 write_memory (dst, info->contents, info->length);
3421 second_arg_length = 0;
3422 break;
3423
3424 case riscv_arg_info::location::by_ref:
3425 dst = sp_refs + info->argloc[0].loc_data.offset;
3426 write_memory (dst, info->contents, info->length);
3427
3428 second_arg_length = call_info.xlen;
3429 second_arg_data = (gdb_byte *) &dst;
3430 break;
3431
3432 default:
3433 gdb_assert_not_reached ("unknown argument location type");
3434 }
3435
3436 if (second_arg_length > 0)
3437 {
3438 switch (info->argloc[1].loc_type)
3439 {
3440 case riscv_arg_info::location::in_reg:
3441 {
3442 gdb_assert ((riscv_is_fp_regno_p (info->argloc[1].loc_data.regno)
3443 && second_arg_length <= call_info.flen)
3444 || second_arg_length <= call_info.xlen);
3445 riscv_regcache_cooked_write (info->argloc[1].loc_data.regno,
3446 second_arg_data,
3447 second_arg_length,
3448 regcache, call_info.flen);
3449 }
3450 break;
3451
3452 case riscv_arg_info::location::on_stack:
3453 {
3454 CORE_ADDR arg_addr;
3455
3456 arg_addr = sp_args + info->argloc[1].loc_data.offset;
3457 write_memory (arg_addr, second_arg_data, second_arg_length);
3458 break;
3459 }
3460
3461 case riscv_arg_info::location::by_ref:
3462 default:
3463 /* The second location should never be a reference, any
3464 argument being passed by reference just places its address
3465 in the first location and is done. */
3466 error (_("invalid argument location"));
3467 break;
3468 }
3469 }
3470 }
3471
3472 /* Set the dummy return value to bp_addr.
3473 A dummy breakpoint will be setup to execute the call. */
3474
3475 riscv_infcall_debug_printf ("writing $ra = %s",
3476 core_addr_to_string (bp_addr));
3477 regcache_cooked_write_unsigned (regcache, RISCV_RA_REGNUM, bp_addr);
3478
3479 /* Finally, update the stack pointer. */
3480
3481 riscv_infcall_debug_printf ("writing $sp = %s", core_addr_to_string (sp));
3482 regcache_cooked_write_unsigned (regcache, RISCV_SP_REGNUM, sp);
3483
3484 return sp;
3485 }
3486
3487 /* Implement the return_value gdbarch method. */
3488
3489 static enum return_value_convention
3490 riscv_return_value (struct gdbarch *gdbarch,
3491 struct value *function,
3492 struct type *type,
3493 struct regcache *regcache,
3494 struct value **read_value,
3495 const gdb_byte *writebuf)
3496 {
3497 struct riscv_call_info call_info (gdbarch);
3498 struct riscv_arg_info info;
3499 struct type *arg_type;
3500
3501 arg_type = check_typedef (type);
3502 riscv_arg_location (gdbarch, &info, &call_info, arg_type, false);
3503
3504 if (riscv_debug_infcall)
3505 {
3506 string_file tmp;
3507 riscv_print_arg_location (&tmp, gdbarch, &info, 0, 0);
3508 riscv_infcall_debug_printf ("[R] %s", tmp.string ().c_str ());
3509 }
3510
3511 if (read_value != nullptr || writebuf != nullptr)
3512 {
3513 unsigned int arg_len;
3514 struct value *abi_val;
3515 gdb_byte *readbuf = nullptr;
3516 int regnum;
3517
3518 /* We only do one thing at a time. */
3519 gdb_assert (read_value == nullptr || writebuf == nullptr);
3520
3521 /* In some cases the argument is not returned as the declared type,
3522 and we need to cast to or from the ABI type in order to
3523 correctly access the argument. When writing to the machine we
3524 do the cast here, when reading from the machine the cast occurs
3525 later, after extracting the value. As the ABI type can be
3526 larger than the declared type, then the read or write buffers
3527 passed in might be too small. Here we ensure that we are using
3528 buffers of sufficient size. */
3529 if (writebuf != nullptr)
3530 {
3531 struct value *arg_val;
3532
3533 if (is_fixed_point_type (arg_type))
3534 {
3535 /* Convert the argument to the type used to pass
3536 the return value, but being careful to preserve
3537 the fact that the value needs to be returned
3538 unscaled. */
3539 gdb_mpz unscaled;
3540
3541 unscaled.read (gdb::make_array_view (writebuf,
3542 arg_type->length ()),
3543 type_byte_order (arg_type),
3544 arg_type->is_unsigned ());
3545 abi_val = value::allocate (info.type);
3546 unscaled.write (abi_val->contents_raw (),
3547 type_byte_order (info.type),
3548 info.type->is_unsigned ());
3549 }
3550 else
3551 {
3552 arg_val = value_from_contents (arg_type, writebuf);
3553 abi_val = value_cast (info.type, arg_val);
3554 }
3555 writebuf = abi_val->contents_raw ().data ();
3556 }
3557 else
3558 {
3559 abi_val = value::allocate (info.type);
3560 readbuf = abi_val->contents_raw ().data ();
3561 }
3562 arg_len = info.type->length ();
3563
3564 switch (info.argloc[0].loc_type)
3565 {
3566 /* Return value in register(s). */
3567 case riscv_arg_info::location::in_reg:
3568 {
3569 regnum = info.argloc[0].loc_data.regno;
3570 gdb_assert (info.argloc[0].c_length <= arg_len);
3571 gdb_assert (info.argloc[0].c_length
3572 <= register_size (gdbarch, regnum));
3573
3574 if (readbuf)
3575 {
3576 gdb_byte *ptr = readbuf + info.argloc[0].c_offset;
3577 regcache->cooked_read_part (regnum, 0,
3578 info.argloc[0].c_length,
3579 ptr);
3580 }
3581
3582 if (writebuf)
3583 {
3584 const gdb_byte *ptr = writebuf + info.argloc[0].c_offset;
3585 riscv_regcache_cooked_write (regnum, ptr,
3586 info.argloc[0].c_length,
3587 regcache, call_info.flen);
3588 }
3589
3590 /* A return value in register can have a second part in a
3591 second register. */
3592 if (info.argloc[1].c_length > 0)
3593 {
3594 switch (info.argloc[1].loc_type)
3595 {
3596 case riscv_arg_info::location::in_reg:
3597 regnum = info.argloc[1].loc_data.regno;
3598
3599 gdb_assert ((info.argloc[0].c_length
3600 + info.argloc[1].c_length) <= arg_len);
3601 gdb_assert (info.argloc[1].c_length
3602 <= register_size (gdbarch, regnum));
3603
3604 if (readbuf)
3605 {
3606 readbuf += info.argloc[1].c_offset;
3607 regcache->cooked_read_part (regnum, 0,
3608 info.argloc[1].c_length,
3609 readbuf);
3610 }
3611
3612 if (writebuf)
3613 {
3614 const gdb_byte *ptr
3615 = writebuf + info.argloc[1].c_offset;
3616 riscv_regcache_cooked_write
3617 (regnum, ptr, info.argloc[1].c_length,
3618 regcache, call_info.flen);
3619 }
3620 break;
3621
3622 case riscv_arg_info::location::by_ref:
3623 case riscv_arg_info::location::on_stack:
3624 default:
3625 error (_("invalid argument location"));
3626 break;
3627 }
3628 }
3629 }
3630 break;
3631
3632 /* Return value by reference will have its address in A0. */
3633 case riscv_arg_info::location::by_ref:
3634 {
3635 ULONGEST addr;
3636
3637 regcache_cooked_read_unsigned (regcache, RISCV_A0_REGNUM,
3638 &addr);
3639 if (read_value != nullptr)
3640 {
3641 abi_val = value_at_non_lval (type, addr);
3642 /* Also reset the expected type, so that the cast
3643 later on is a no-op. If the cast is not a no-op,
3644 and if the return type is variably-sized, then the
3645 type of ABI_VAL will differ from ARG_TYPE due to
3646 dynamic type resolution, and so will most likely
3647 fail. */
3648 arg_type = abi_val->type ();
3649 }
3650 if (writebuf != nullptr)
3651 write_memory (addr, writebuf, info.length);
3652 }
3653 break;
3654
3655 case riscv_arg_info::location::on_stack:
3656 default:
3657 error (_("invalid argument location"));
3658 break;
3659 }
3660
3661 /* This completes the cast from abi type back to the declared type
3662 in the case that we are reading from the machine. See the
3663 comment at the head of this block for more details. */
3664 if (read_value != nullptr)
3665 {
3666 if (is_fixed_point_type (arg_type))
3667 {
3668 /* Convert abi_val to the actual return type, but
3669 being careful to preserve the fact that abi_val
3670 is unscaled. */
3671 gdb_mpz unscaled;
3672
3673 unscaled.read (abi_val->contents (),
3674 type_byte_order (info.type),
3675 info.type->is_unsigned ());
3676 *read_value = value::allocate (arg_type);
3677 unscaled.write ((*read_value)->contents_raw (),
3678 type_byte_order (arg_type),
3679 arg_type->is_unsigned ());
3680 }
3681 else
3682 *read_value = value_cast (arg_type, abi_val);
3683 }
3684 }
3685
3686 switch (info.argloc[0].loc_type)
3687 {
3688 case riscv_arg_info::location::in_reg:
3689 return RETURN_VALUE_REGISTER_CONVENTION;
3690 case riscv_arg_info::location::by_ref:
3691 return RETURN_VALUE_ABI_PRESERVES_ADDRESS;
3692 case riscv_arg_info::location::on_stack:
3693 default:
3694 error (_("invalid argument location"));
3695 }
3696 }
3697
3698 /* Implement the frame_align gdbarch method. */
3699
3700 static CORE_ADDR
3701 riscv_frame_align (struct gdbarch *gdbarch, CORE_ADDR addr)
3702 {
3703 return align_down (addr, 16);
3704 }
3705
3706 /* Generate, or return the cached frame cache for the RiscV frame
3707 unwinder. */
3708
3709 static struct riscv_unwind_cache *
3710 riscv_frame_cache (frame_info_ptr this_frame, void **this_cache)
3711 {
3712 CORE_ADDR pc, start_addr;
3713 struct riscv_unwind_cache *cache;
3714 struct gdbarch *gdbarch = get_frame_arch (this_frame);
3715 int numregs, regno;
3716
3717 if ((*this_cache) != NULL)
3718 return (struct riscv_unwind_cache *) *this_cache;
3719
3720 cache = FRAME_OBSTACK_ZALLOC (struct riscv_unwind_cache);
3721 cache->regs = trad_frame_alloc_saved_regs (this_frame);
3722 (*this_cache) = cache;
3723
3724 /* Scan the prologue, filling in the cache. */
3725 start_addr = get_frame_func (this_frame);
3726 pc = get_frame_pc (this_frame);
3727 riscv_scan_prologue (gdbarch, start_addr, pc, cache);
3728
3729 /* We can now calculate the frame base address. */
3730 cache->frame_base
3731 = (get_frame_register_unsigned (this_frame, cache->frame_base_reg)
3732 + cache->frame_base_offset);
3733 riscv_unwinder_debug_printf ("frame base is %s ($%s + 0x%x)",
3734 core_addr_to_string (cache->frame_base),
3735 gdbarch_register_name (gdbarch,
3736 cache->frame_base_reg),
3737 cache->frame_base_offset);
3738
3739 /* The prologue scanner sets the address of registers stored to the stack
3740 as the offset of that register from the frame base. The prologue
3741 scanner doesn't know the actual frame base value, and so is unable to
3742 compute the exact address. We do now know the frame base value, so
3743 update the address of registers stored to the stack. */
3744 numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
3745 for (regno = 0; regno < numregs; ++regno)
3746 {
3747 if (cache->regs[regno].is_addr ())
3748 cache->regs[regno].set_addr (cache->regs[regno].addr ()
3749 + cache->frame_base);
3750 }
3751
3752 /* The previous $pc can be found wherever the $ra value can be found.
3753 The previous $ra value is gone, this would have been stored be the
3754 previous frame if required. */
3755 cache->regs[gdbarch_pc_regnum (gdbarch)] = cache->regs[RISCV_RA_REGNUM];
3756 cache->regs[RISCV_RA_REGNUM].set_unknown ();
3757
3758 /* Build the frame id. */
3759 cache->this_id = frame_id_build (cache->frame_base, start_addr);
3760
3761 /* The previous $sp value is the frame base value. */
3762 cache->regs[gdbarch_sp_regnum (gdbarch)].set_value (cache->frame_base);
3763
3764 return cache;
3765 }
3766
3767 /* Implement the this_id callback for RiscV frame unwinder. */
3768
3769 static void
3770 riscv_frame_this_id (frame_info_ptr this_frame,
3771 void **prologue_cache,
3772 struct frame_id *this_id)
3773 {
3774 struct riscv_unwind_cache *cache;
3775
3776 try
3777 {
3778 cache = riscv_frame_cache (this_frame, prologue_cache);
3779 *this_id = cache->this_id;
3780 }
3781 catch (const gdb_exception_error &ex)
3782 {
3783 /* Ignore errors, this leaves the frame id as the predefined outer
3784 frame id which terminates the backtrace at this point. */
3785 }
3786 }
3787
3788 /* Implement the prev_register callback for RiscV frame unwinder. */
3789
3790 static struct value *
3791 riscv_frame_prev_register (frame_info_ptr this_frame,
3792 void **prologue_cache,
3793 int regnum)
3794 {
3795 struct riscv_unwind_cache *cache;
3796
3797 cache = riscv_frame_cache (this_frame, prologue_cache);
3798 return trad_frame_get_prev_register (this_frame, cache->regs, regnum);
3799 }
3800
3801 /* Structure defining the RiscV normal frame unwind functions. Since we
3802 are the fallback unwinder (DWARF unwinder is used first), we use the
3803 default frame sniffer, which always accepts the frame. */
3804
3805 static const struct frame_unwind riscv_frame_unwind =
3806 {
3807 /*.name =*/ "riscv prologue",
3808 /*.type =*/ NORMAL_FRAME,
3809 /*.stop_reason =*/ default_frame_unwind_stop_reason,
3810 /*.this_id =*/ riscv_frame_this_id,
3811 /*.prev_register =*/ riscv_frame_prev_register,
3812 /*.unwind_data =*/ NULL,
3813 /*.sniffer =*/ default_frame_sniffer,
3814 /*.dealloc_cache =*/ NULL,
3815 /*.prev_arch =*/ NULL,
3816 };
3817
3818 /* Extract a set of required target features out of ABFD. If ABFD is
3819 nullptr then a RISCV_GDBARCH_FEATURES is returned in its default state. */
3820
3821 static struct riscv_gdbarch_features
3822 riscv_features_from_bfd (const bfd *abfd)
3823 {
3824 struct riscv_gdbarch_features features;
3825
3826 /* Now try to improve on the defaults by looking at the binary we are
3827 going to execute. We assume the user knows what they are doing and
3828 that the target will match the binary. Remember, this code path is
3829 only used at all if the target hasn't given us a description, so this
3830 is really a last ditched effort to do something sane before giving
3831 up. */
3832 if (abfd != nullptr && bfd_get_flavour (abfd) == bfd_target_elf_flavour)
3833 {
3834 unsigned char eclass = elf_elfheader (abfd)->e_ident[EI_CLASS];
3835 int e_flags = elf_elfheader (abfd)->e_flags;
3836
3837 if (eclass == ELFCLASS32)
3838 features.xlen = 4;
3839 else if (eclass == ELFCLASS64)
3840 features.xlen = 8;
3841 else
3842 internal_error (_("unknown ELF header class %d"), eclass);
3843
3844 if (e_flags & EF_RISCV_FLOAT_ABI_DOUBLE)
3845 features.flen = 8;
3846 else if (e_flags & EF_RISCV_FLOAT_ABI_SINGLE)
3847 features.flen = 4;
3848
3849 if (e_flags & EF_RISCV_RVE)
3850 {
3851 if (features.xlen == 8)
3852 {
3853 warning (_("64-bit ELF with RV32E flag set! Assuming 32-bit"));
3854 features.xlen = 4;
3855 }
3856 features.embedded = true;
3857 }
3858 }
3859
3860 return features;
3861 }
3862
3863 /* Find a suitable default target description. Use the contents of INFO,
3864 specifically the bfd object being executed, to guide the selection of a
3865 suitable default target description. */
3866
3867 static const struct target_desc *
3868 riscv_find_default_target_description (const struct gdbarch_info info)
3869 {
3870 /* Extract desired feature set from INFO. */
3871 struct riscv_gdbarch_features features
3872 = riscv_features_from_bfd (info.abfd);
3873
3874 /* If the XLEN field is still 0 then we got nothing useful from INFO.BFD,
3875 maybe there was no bfd object. In this case we fall back to a minimal
3876 useful target with no floating point, the x-register size is selected
3877 based on the architecture from INFO. */
3878 if (features.xlen == 0)
3879 features.xlen = info.bfd_arch_info->bits_per_word == 32 ? 4 : 8;
3880
3881 /* Now build a target description based on the feature set. */
3882 return riscv_lookup_target_description (features);
3883 }
3884
3885 /* Add all the RISC-V specific register groups into GDBARCH. */
3886
3887 static void
3888 riscv_add_reggroups (struct gdbarch *gdbarch)
3889 {
3890 reggroup_add (gdbarch, csr_reggroup);
3891 }
3892
3893 /* Implement the "dwarf2_reg_to_regnum" gdbarch method. */
3894
3895 static int
3896 riscv_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
3897 {
3898 if (reg <= RISCV_DWARF_REGNUM_X31)
3899 return RISCV_ZERO_REGNUM + (reg - RISCV_DWARF_REGNUM_X0);
3900
3901 else if (reg <= RISCV_DWARF_REGNUM_F31)
3902 return RISCV_FIRST_FP_REGNUM + (reg - RISCV_DWARF_REGNUM_F0);
3903
3904 else if (reg >= RISCV_DWARF_FIRST_CSR && reg <= RISCV_DWARF_LAST_CSR)
3905 return RISCV_FIRST_CSR_REGNUM + (reg - RISCV_DWARF_FIRST_CSR);
3906
3907 else if (reg >= RISCV_DWARF_REGNUM_V0 && reg <= RISCV_DWARF_REGNUM_V31)
3908 return RISCV_V0_REGNUM + (reg - RISCV_DWARF_REGNUM_V0);
3909
3910 return -1;
3911 }
3912
3913 /* Implement the gcc_target_options method. We have to select the arch and abi
3914 from the feature info. We have enough feature info to select the abi, but
3915 not enough info for the arch given all of the possible architecture
3916 extensions. So choose reasonable defaults for now. */
3917
3918 static std::string
3919 riscv_gcc_target_options (struct gdbarch *gdbarch)
3920 {
3921 int isa_xlen = riscv_isa_xlen (gdbarch);
3922 int isa_flen = riscv_isa_flen (gdbarch);
3923 int abi_xlen = riscv_abi_xlen (gdbarch);
3924 int abi_flen = riscv_abi_flen (gdbarch);
3925 std::string target_options;
3926
3927 target_options = "-march=rv";
3928 if (isa_xlen == 8)
3929 target_options += "64";
3930 else
3931 target_options += "32";
3932 if (isa_flen == 8)
3933 target_options += "gc";
3934 else if (isa_flen == 4)
3935 target_options += "imafc";
3936 else
3937 target_options += "imac";
3938
3939 target_options += " -mabi=";
3940 if (abi_xlen == 8)
3941 target_options += "lp64";
3942 else
3943 target_options += "ilp32";
3944 if (abi_flen == 8)
3945 target_options += "d";
3946 else if (abi_flen == 4)
3947 target_options += "f";
3948
3949 /* The gdb loader doesn't handle link-time relaxation relocations. */
3950 target_options += " -mno-relax";
3951
3952 return target_options;
3953 }
3954
3955 /* Call back from tdesc_use_registers, called for each unknown register
3956 found in the target description.
3957
3958 See target-description.h (typedef tdesc_unknown_register_ftype) for a
3959 discussion of the arguments and return values. */
3960
3961 static int
3962 riscv_tdesc_unknown_reg (struct gdbarch *gdbarch, tdesc_feature *feature,
3963 const char *reg_name, int possible_regnum)
3964 {
3965 /* At one point in time GDB had an incorrect default target description
3966 that duplicated the fflags, frm, and fcsr registers in both the FPU
3967 and CSR register sets.
3968
3969 Some targets (QEMU) copied these target descriptions into their source
3970 tree, and so we're now stuck working with some versions of QEMU that
3971 declare the same registers twice.
3972
3973 To make matters worse, if GDB tries to read or write to these
3974 registers using the register number assigned in the FPU feature set,
3975 then QEMU will fail to read the register, so we must use the register
3976 number declared in the CSR feature set.
3977
3978 Luckily, GDB scans the FPU feature first, and then the CSR feature,
3979 which means that the CSR feature will be the one we end up using, the
3980 versions of these registers in the FPU feature will appear as unknown
3981 registers and will be passed through to this code.
3982
3983 To prevent these duplicate registers showing up in any of the register
3984 lists, and to prevent GDB every trying to access the FPU feature copies,
3985 we spot the three problematic registers here, and record the register
3986 number that GDB has assigned them. Then in riscv_register_name we will
3987 return no name for the three duplicates, this hides the duplicates from
3988 the user. */
3989 if (strcmp (tdesc_feature_name (feature), riscv_freg_feature.name ()) == 0)
3990 {
3991 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
3992 int *regnum_ptr = nullptr;
3993
3994 if (strcmp (reg_name, "fflags") == 0)
3995 regnum_ptr = &tdep->duplicate_fflags_regnum;
3996 else if (strcmp (reg_name, "frm") == 0)
3997 regnum_ptr = &tdep->duplicate_frm_regnum;
3998 else if (strcmp (reg_name, "fcsr") == 0)
3999 regnum_ptr = &tdep->duplicate_fcsr_regnum;
4000
4001 if (regnum_ptr != nullptr)
4002 {
4003 /* This means the register appears more than twice in the target
4004 description. Just let GDB add this as another register.
4005 We'll have duplicates in the register name list, but there's
4006 not much more we can do. */
4007 if (*regnum_ptr != -1)
4008 return -1;
4009
4010 /* Record the number assigned to this register, then return the
4011 number (so it actually gets assigned to this register). */
4012 *regnum_ptr = possible_regnum;
4013 return possible_regnum;
4014 }
4015 }
4016
4017 /* Any unknown registers in the CSR feature are recorded within a single
4018 block so we can easily identify these registers when making choices
4019 about register groups in riscv_register_reggroup_p. */
4020 if (strcmp (tdesc_feature_name (feature), riscv_csr_feature.name ()) == 0)
4021 {
4022 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4023 if (tdep->unknown_csrs_first_regnum == -1)
4024 tdep->unknown_csrs_first_regnum = possible_regnum;
4025 gdb_assert (tdep->unknown_csrs_first_regnum
4026 + tdep->unknown_csrs_count == possible_regnum);
4027 tdep->unknown_csrs_count++;
4028 return possible_regnum;
4029 }
4030
4031 /* Some other unknown register. Don't assign this a number now, it will
4032 be assigned a number automatically later by the target description
4033 handling code. */
4034 return -1;
4035 }
4036
4037 /* Implement the gnu_triplet_regexp method. A single compiler supports both
4038 32-bit and 64-bit code, and may be named riscv32 or riscv64 or (not
4039 recommended) riscv. */
4040
4041 static const char *
4042 riscv_gnu_triplet_regexp (struct gdbarch *gdbarch)
4043 {
4044 return "riscv(32|64)?";
4045 }
4046
4047 /* Implementation of `gdbarch_stap_is_single_operand', as defined in
4048 gdbarch.h. */
4049
4050 static int
4051 riscv_stap_is_single_operand (struct gdbarch *gdbarch, const char *s)
4052 {
4053 return (ISDIGIT (*s) /* Literal number. */
4054 || *s == '(' /* Register indirection. */
4055 || ISALPHA (*s)); /* Register value. */
4056 }
4057
4058 /* String that appears before a register name in a SystemTap register
4059 indirect expression. */
4060
4061 static const char *const stap_register_indirection_prefixes[] =
4062 {
4063 "(", nullptr
4064 };
4065
4066 /* String that appears after a register name in a SystemTap register
4067 indirect expression. */
4068
4069 static const char *const stap_register_indirection_suffixes[] =
4070 {
4071 ")", nullptr
4072 };
4073
4074 /* Initialize the current architecture based on INFO. If possible,
4075 re-use an architecture from ARCHES, which is a list of
4076 architectures already created during this debugging session.
4077
4078 Called e.g. at program startup, when reading a core file, and when
4079 reading a binary file. */
4080
4081 static struct gdbarch *
4082 riscv_gdbarch_init (struct gdbarch_info info,
4083 struct gdbarch_list *arches)
4084 {
4085 struct riscv_gdbarch_features features;
4086 const struct target_desc *tdesc = info.target_desc;
4087
4088 /* Ensure we always have a target description. */
4089 if (!tdesc_has_registers (tdesc))
4090 tdesc = riscv_find_default_target_description (info);
4091 gdb_assert (tdesc != nullptr);
4092
4093 riscv_gdbarch_debug_printf ("have got a target description");
4094
4095 tdesc_arch_data_up tdesc_data = tdesc_data_alloc ();
4096 std::vector<riscv_pending_register_alias> pending_aliases;
4097
4098 bool valid_p = (riscv_xreg_feature.check (tdesc, tdesc_data.get (),
4099 &pending_aliases, &features)
4100 && riscv_freg_feature.check (tdesc, tdesc_data.get (),
4101 &pending_aliases, &features)
4102 && riscv_virtual_feature.check (tdesc, tdesc_data.get (),
4103 &pending_aliases, &features)
4104 && riscv_csr_feature.check (tdesc, tdesc_data.get (),
4105 &pending_aliases, &features)
4106 && riscv_vector_feature.check (tdesc, tdesc_data.get (),
4107 &pending_aliases, &features));
4108 if (!valid_p)
4109 {
4110 riscv_gdbarch_debug_printf ("target description is not valid");
4111 return NULL;
4112 }
4113
4114 if (tdesc_found_register (tdesc_data.get (), RISCV_CSR_FFLAGS_REGNUM))
4115 features.has_fflags_reg = true;
4116 if (tdesc_found_register (tdesc_data.get (), RISCV_CSR_FRM_REGNUM))
4117 features.has_frm_reg = true;
4118 if (tdesc_found_register (tdesc_data.get (), RISCV_CSR_FCSR_REGNUM))
4119 features.has_fcsr_reg = true;
4120
4121 /* Have a look at what the supplied (if any) bfd object requires of the
4122 target, then check that this matches with what the target is
4123 providing. */
4124 struct riscv_gdbarch_features abi_features
4125 = riscv_features_from_bfd (info.abfd);
4126
4127 /* If the ABI_FEATURES xlen is 0 then this indicates we got no useful abi
4128 features from the INFO object. In this case we just treat the
4129 hardware features as defining the abi. */
4130 if (abi_features.xlen == 0)
4131 abi_features = features;
4132
4133 /* In theory a binary compiled for RV32 could run on an RV64 target,
4134 however, this has not been tested in GDB yet, so for now we require
4135 that the requested xlen match the targets xlen. */
4136 if (abi_features.xlen != features.xlen)
4137 error (_("bfd requires xlen %d, but target has xlen %d"),
4138 abi_features.xlen, features.xlen);
4139 /* We do support running binaries compiled for 32-bit float on targets
4140 with 64-bit float, so we only complain if the binary requires more
4141 than the target has available. */
4142 if (abi_features.flen > features.flen)
4143 error (_("bfd requires flen %d, but target has flen %d"),
4144 abi_features.flen, features.flen);
4145
4146 /* Find a candidate among the list of pre-declared architectures. */
4147 for (arches = gdbarch_list_lookup_by_info (arches, &info);
4148 arches != NULL;
4149 arches = gdbarch_list_lookup_by_info (arches->next, &info))
4150 {
4151 /* Check that the feature set of the ARCHES matches the feature set
4152 we are looking for. If it doesn't then we can't reuse this
4153 gdbarch. */
4154 riscv_gdbarch_tdep *other_tdep
4155 = gdbarch_tdep<riscv_gdbarch_tdep> (arches->gdbarch);
4156
4157 if (other_tdep->isa_features != features
4158 || other_tdep->abi_features != abi_features)
4159 continue;
4160
4161 break;
4162 }
4163
4164 if (arches != NULL)
4165 return arches->gdbarch;
4166
4167 /* None found, so create a new architecture from the information provided. */
4168 gdbarch *gdbarch
4169 = gdbarch_alloc (&info, gdbarch_tdep_up (new riscv_gdbarch_tdep));
4170 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4171
4172 tdep->isa_features = features;
4173 tdep->abi_features = abi_features;
4174
4175 /* Target data types. */
4176 set_gdbarch_short_bit (gdbarch, 16);
4177 set_gdbarch_int_bit (gdbarch, 32);
4178 set_gdbarch_long_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
4179 set_gdbarch_long_long_bit (gdbarch, 64);
4180 set_gdbarch_float_bit (gdbarch, 32);
4181 set_gdbarch_double_bit (gdbarch, 64);
4182 set_gdbarch_long_double_bit (gdbarch, 128);
4183 set_gdbarch_long_double_format (gdbarch, floatformats_ieee_quad);
4184 set_gdbarch_ptr_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
4185 set_gdbarch_char_signed (gdbarch, 0);
4186 set_gdbarch_type_align (gdbarch, riscv_type_align);
4187
4188 /* Information about the target architecture. */
4189 set_gdbarch_return_value_as_value (gdbarch, riscv_return_value);
4190 set_gdbarch_breakpoint_kind_from_pc (gdbarch, riscv_breakpoint_kind_from_pc);
4191 set_gdbarch_sw_breakpoint_from_kind (gdbarch, riscv_sw_breakpoint_from_kind);
4192 set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
4193
4194 /* Functions to analyze frames. */
4195 set_gdbarch_skip_prologue (gdbarch, riscv_skip_prologue);
4196 set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
4197 set_gdbarch_frame_align (gdbarch, riscv_frame_align);
4198
4199 /* Functions handling dummy frames. */
4200 set_gdbarch_call_dummy_location (gdbarch, ON_STACK);
4201 set_gdbarch_push_dummy_code (gdbarch, riscv_push_dummy_code);
4202 set_gdbarch_push_dummy_call (gdbarch, riscv_push_dummy_call);
4203
4204 /* Frame unwinders. Use DWARF debug info if available, otherwise use our own
4205 unwinder. */
4206 dwarf2_append_unwinders (gdbarch);
4207 frame_unwind_append_unwinder (gdbarch, &riscv_frame_unwind);
4208
4209 /* Register architecture. */
4210 riscv_add_reggroups (gdbarch);
4211
4212 /* Internal <-> external register number maps. */
4213 set_gdbarch_dwarf2_reg_to_regnum (gdbarch, riscv_dwarf_reg_to_regnum);
4214
4215 /* We reserve all possible register numbers for the known registers.
4216 This means the target description mechanism will add any target
4217 specific registers after this number. This helps make debugging GDB
4218 just a little easier. */
4219 set_gdbarch_num_regs (gdbarch, RISCV_LAST_REGNUM + 1);
4220
4221 /* Some specific register numbers GDB likes to know about. */
4222 set_gdbarch_sp_regnum (gdbarch, RISCV_SP_REGNUM);
4223 set_gdbarch_pc_regnum (gdbarch, RISCV_PC_REGNUM);
4224
4225 set_gdbarch_print_registers_info (gdbarch, riscv_print_registers_info);
4226
4227 set_tdesc_pseudo_register_name (gdbarch, riscv_pseudo_register_name);
4228 set_tdesc_pseudo_register_type (gdbarch, riscv_pseudo_register_type);
4229 set_tdesc_pseudo_register_reggroup_p (gdbarch,
4230 riscv_pseudo_register_reggroup_p);
4231 set_gdbarch_pseudo_register_read (gdbarch, riscv_pseudo_register_read);
4232 set_gdbarch_pseudo_register_write (gdbarch, riscv_pseudo_register_write);
4233
4234 /* Finalise the target description registers. */
4235 tdesc_use_registers (gdbarch, tdesc, std::move (tdesc_data),
4236 riscv_tdesc_unknown_reg);
4237
4238 /* Calculate the number of pseudo registers we need. The fflags and frm
4239 registers are sub-fields of the fcsr CSR register (csr3). However,
4240 these registers can also be accessed directly as separate CSR
4241 registers (fflags is csr1, and frm is csr2). And so, some targets
4242 might choose to offer direct access to all three registers in the
4243 target description, while other targets might choose to only offer
4244 access to fcsr.
4245
4246 As we scan the target description we spot which of fcsr, fflags, and
4247 frm are available. If fcsr is available but either of fflags and/or
4248 frm are not available, then we add pseudo-registers to provide the
4249 missing functionality.
4250
4251 This has to be done after the call to tdesc_use_registers as we don't
4252 know the final register number until after that call, and the pseudo
4253 register numbers need to be after the physical registers. */
4254 int num_pseudo_regs = 0;
4255 int next_pseudo_regnum = gdbarch_num_regs (gdbarch);
4256
4257 if (features.has_fflags_reg)
4258 tdep->fflags_regnum = RISCV_CSR_FFLAGS_REGNUM;
4259 else if (features.has_fcsr_reg)
4260 {
4261 tdep->fflags_regnum = next_pseudo_regnum;
4262 pending_aliases.emplace_back ("csr1", (void *) &tdep->fflags_regnum);
4263 next_pseudo_regnum++;
4264 num_pseudo_regs++;
4265 }
4266
4267 if (features.has_frm_reg)
4268 tdep->frm_regnum = RISCV_CSR_FRM_REGNUM;
4269 else if (features.has_fcsr_reg)
4270 {
4271 tdep->frm_regnum = next_pseudo_regnum;
4272 pending_aliases.emplace_back ("csr2", (void *) &tdep->frm_regnum);
4273 next_pseudo_regnum++;
4274 num_pseudo_regs++;
4275 }
4276
4277 set_gdbarch_num_pseudo_regs (gdbarch, num_pseudo_regs);
4278
4279 /* Override the register type callback setup by the target description
4280 mechanism. This allows us to provide special type for floating point
4281 registers. */
4282 set_gdbarch_register_type (gdbarch, riscv_register_type);
4283
4284 /* Override the register name callback setup by the target description
4285 mechanism. This allows us to force our preferred names for the
4286 registers, no matter what the target description called them. */
4287 set_gdbarch_register_name (gdbarch, riscv_register_name);
4288
4289 /* Tell GDB which RISC-V registers are read-only. */
4290 set_gdbarch_cannot_store_register (gdbarch, riscv_cannot_store_register);
4291
4292 /* Override the register group callback setup by the target description
4293 mechanism. This allows us to force registers into the groups we
4294 want, ignoring what the target tells us. */
4295 set_gdbarch_register_reggroup_p (gdbarch, riscv_register_reggroup_p);
4296
4297 /* Create register aliases for alternative register names. We only
4298 create aliases for registers which were mentioned in the target
4299 description. */
4300 for (const auto &alias : pending_aliases)
4301 alias.create (gdbarch);
4302
4303 /* Compile command hooks. */
4304 set_gdbarch_gcc_target_options (gdbarch, riscv_gcc_target_options);
4305 set_gdbarch_gnu_triplet_regexp (gdbarch, riscv_gnu_triplet_regexp);
4306
4307 /* Disassembler options support. */
4308 set_gdbarch_valid_disassembler_options (gdbarch,
4309 disassembler_options_riscv ());
4310 set_gdbarch_disassembler_options (gdbarch, &riscv_disassembler_options);
4311
4312 /* SystemTap Support. */
4313 set_gdbarch_stap_is_single_operand (gdbarch, riscv_stap_is_single_operand);
4314 set_gdbarch_stap_register_indirection_prefixes
4315 (gdbarch, stap_register_indirection_prefixes);
4316 set_gdbarch_stap_register_indirection_suffixes
4317 (gdbarch, stap_register_indirection_suffixes);
4318
4319 /* Hook in OS ABI-specific overrides, if they have been registered. */
4320 gdbarch_init_osabi (info, gdbarch);
4321
4322 register_riscv_ravenscar_ops (gdbarch);
4323
4324 return gdbarch;
4325 }
4326
4327 /* This decodes the current instruction and determines the address of the
4328 next instruction. */
4329
4330 static CORE_ADDR
4331 riscv_next_pc (struct regcache *regcache, CORE_ADDR pc)
4332 {
4333 struct gdbarch *gdbarch = regcache->arch ();
4334 const riscv_gdbarch_tdep *tdep
4335 = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4336 struct riscv_insn insn;
4337 CORE_ADDR next_pc;
4338
4339 insn.decode (gdbarch, pc);
4340 next_pc = pc + insn.length ();
4341
4342 if (insn.opcode () == riscv_insn::JAL)
4343 next_pc = pc + insn.imm_signed ();
4344 else if (insn.opcode () == riscv_insn::JALR)
4345 {
4346 LONGEST source;
4347 regcache->cooked_read (insn.rs1 (), &source);
4348 next_pc = (source + insn.imm_signed ()) & ~(CORE_ADDR) 0x1;
4349 }
4350 else if (insn.opcode () == riscv_insn::BEQ)
4351 {
4352 LONGEST src1, src2;
4353 regcache->cooked_read (insn.rs1 (), &src1);
4354 regcache->cooked_read (insn.rs2 (), &src2);
4355 if (src1 == src2)
4356 next_pc = pc + insn.imm_signed ();
4357 }
4358 else if (insn.opcode () == riscv_insn::BNE)
4359 {
4360 LONGEST src1, src2;
4361 regcache->cooked_read (insn.rs1 (), &src1);
4362 regcache->cooked_read (insn.rs2 (), &src2);
4363 if (src1 != src2)
4364 next_pc = pc + insn.imm_signed ();
4365 }
4366 else if (insn.opcode () == riscv_insn::BLT)
4367 {
4368 LONGEST src1, src2;
4369 regcache->cooked_read (insn.rs1 (), &src1);
4370 regcache->cooked_read (insn.rs2 (), &src2);
4371 if (src1 < src2)
4372 next_pc = pc + insn.imm_signed ();
4373 }
4374 else if (insn.opcode () == riscv_insn::BGE)
4375 {
4376 LONGEST src1, src2;
4377 regcache->cooked_read (insn.rs1 (), &src1);
4378 regcache->cooked_read (insn.rs2 (), &src2);
4379 if (src1 >= src2)
4380 next_pc = pc + insn.imm_signed ();
4381 }
4382 else if (insn.opcode () == riscv_insn::BLTU)
4383 {
4384 ULONGEST src1, src2;
4385 regcache->cooked_read (insn.rs1 (), &src1);
4386 regcache->cooked_read (insn.rs2 (), &src2);
4387 if (src1 < src2)
4388 next_pc = pc + insn.imm_signed ();
4389 }
4390 else if (insn.opcode () == riscv_insn::BGEU)
4391 {
4392 ULONGEST src1, src2;
4393 regcache->cooked_read (insn.rs1 (), &src1);
4394 regcache->cooked_read (insn.rs2 (), &src2);
4395 if (src1 >= src2)
4396 next_pc = pc + insn.imm_signed ();
4397 }
4398 else if (insn.opcode () == riscv_insn::ECALL)
4399 {
4400 if (tdep->syscall_next_pc != nullptr)
4401 next_pc = tdep->syscall_next_pc (get_current_frame ());
4402 }
4403
4404 return next_pc;
4405 }
4406
4407 /* We can't put a breakpoint in the middle of a lr/sc atomic sequence, so look
4408 for the end of the sequence and put the breakpoint there. */
4409
4410 static bool
4411 riscv_next_pc_atomic_sequence (struct regcache *regcache, CORE_ADDR pc,
4412 CORE_ADDR *next_pc)
4413 {
4414 struct gdbarch *gdbarch = regcache->arch ();
4415 struct riscv_insn insn;
4416 CORE_ADDR cur_step_pc = pc;
4417 CORE_ADDR last_addr = 0;
4418
4419 /* First instruction has to be a load reserved. */
4420 insn.decode (gdbarch, cur_step_pc);
4421 if (insn.opcode () != riscv_insn::LR)
4422 return false;
4423 cur_step_pc = cur_step_pc + insn.length ();
4424
4425 /* Next instruction should be branch to exit. */
4426 insn.decode (gdbarch, cur_step_pc);
4427 if (insn.opcode () != riscv_insn::BNE)
4428 return false;
4429 last_addr = cur_step_pc + insn.imm_signed ();
4430 cur_step_pc = cur_step_pc + insn.length ();
4431
4432 /* Next instruction should be store conditional. */
4433 insn.decode (gdbarch, cur_step_pc);
4434 if (insn.opcode () != riscv_insn::SC)
4435 return false;
4436 cur_step_pc = cur_step_pc + insn.length ();
4437
4438 /* Next instruction should be branch to start. */
4439 insn.decode (gdbarch, cur_step_pc);
4440 if (insn.opcode () != riscv_insn::BNE)
4441 return false;
4442 if (pc != (cur_step_pc + insn.imm_signed ()))
4443 return false;
4444 cur_step_pc = cur_step_pc + insn.length ();
4445
4446 /* We should now be at the end of the sequence. */
4447 if (cur_step_pc != last_addr)
4448 return false;
4449
4450 *next_pc = cur_step_pc;
4451 return true;
4452 }
4453
4454 /* This is called just before we want to resume the inferior, if we want to
4455 single-step it but there is no hardware or kernel single-step support. We
4456 find the target of the coming instruction and breakpoint it. */
4457
4458 std::vector<CORE_ADDR>
4459 riscv_software_single_step (struct regcache *regcache)
4460 {
4461 CORE_ADDR pc, next_pc;
4462
4463 pc = regcache_read_pc (regcache);
4464
4465 if (riscv_next_pc_atomic_sequence (regcache, pc, &next_pc))
4466 return {next_pc};
4467
4468 next_pc = riscv_next_pc (regcache, pc);
4469
4470 return {next_pc};
4471 }
4472
4473 /* Create RISC-V specific reggroups. */
4474
4475 static void
4476 riscv_init_reggroups ()
4477 {
4478 csr_reggroup = reggroup_new ("csr", USER_REGGROUP);
4479 }
4480
4481 /* See riscv-tdep.h. */
4482
4483 void
4484 riscv_supply_regset (const struct regset *regset,
4485 struct regcache *regcache, int regnum,
4486 const void *regs, size_t len)
4487 {
4488 regcache->supply_regset (regset, regnum, regs, len);
4489
4490 if (regnum == -1 || regnum == RISCV_ZERO_REGNUM)
4491 regcache->raw_supply_zeroed (RISCV_ZERO_REGNUM);
4492
4493 struct gdbarch *gdbarch = regcache->arch ();
4494 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4495
4496 if (regnum == -1
4497 || regnum == tdep->fflags_regnum
4498 || regnum == tdep->frm_regnum)
4499 {
4500 int fcsr_regnum = RISCV_CSR_FCSR_REGNUM;
4501
4502 /* Ensure that FCSR has been read into REGCACHE. */
4503 if (regnum != -1)
4504 regcache->supply_regset (regset, fcsr_regnum, regs, len);
4505
4506 /* Grab the FCSR value if it is now in the regcache. We must check
4507 the status first as, if the register was not supplied by REGSET,
4508 this call will trigger a recursive attempt to fetch the
4509 registers. */
4510 if (regcache->get_register_status (fcsr_regnum) == REG_VALID)
4511 {
4512 /* If we have an fcsr register then we should have fflags and frm
4513 too, either provided by the target, or provided as a pseudo
4514 register by GDB. */
4515 gdb_assert (tdep->fflags_regnum >= 0);
4516 gdb_assert (tdep->frm_regnum >= 0);
4517
4518 ULONGEST fcsr_val;
4519 regcache->raw_read (fcsr_regnum, &fcsr_val);
4520
4521 /* Extract the fflags and frm values. */
4522 ULONGEST fflags_val = fcsr_val & 0x1f;
4523 ULONGEST frm_val = (fcsr_val >> 5) & 0x7;
4524
4525 /* And supply these if needed. We can only supply real
4526 registers, so don't try to supply fflags or frm if they are
4527 implemented as pseudo-registers. */
4528 if ((regnum == -1 || regnum == tdep->fflags_regnum)
4529 && tdep->fflags_regnum < gdbarch_num_regs (gdbarch))
4530 regcache->raw_supply_integer (tdep->fflags_regnum,
4531 (gdb_byte *) &fflags_val,
4532 sizeof (fflags_val),
4533 /* is_signed */ false);
4534
4535 if ((regnum == -1 || regnum == tdep->frm_regnum)
4536 && tdep->frm_regnum < gdbarch_num_regs (gdbarch))
4537 regcache->raw_supply_integer (tdep->frm_regnum,
4538 (gdb_byte *)&frm_val,
4539 sizeof (fflags_val),
4540 /* is_signed */ false);
4541 }
4542 }
4543 }
4544
4545 void _initialize_riscv_tdep ();
4546 void
4547 _initialize_riscv_tdep ()
4548 {
4549 riscv_init_reggroups ();
4550
4551 gdbarch_register (bfd_arch_riscv, riscv_gdbarch_init, NULL);
4552
4553 /* Add root prefix command for all "set debug riscv" and "show debug
4554 riscv" commands. */
4555 add_setshow_prefix_cmd ("riscv", no_class,
4556 _("RISC-V specific debug commands."),
4557 _("RISC-V specific debug commands."),
4558 &setdebugriscvcmdlist, &showdebugriscvcmdlist,
4559 &setdebuglist, &showdebuglist);
4560
4561 add_setshow_boolean_cmd ("breakpoints", class_maintenance,
4562 &riscv_debug_breakpoints, _("\
4563 Set riscv breakpoint debugging."), _("\
4564 Show riscv breakpoint debugging."), _("\
4565 When non-zero, print debugging information for the riscv specific parts\n\
4566 of the breakpoint mechanism."),
4567 nullptr,
4568 show_riscv_debug_variable,
4569 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4570
4571 add_setshow_boolean_cmd ("infcall", class_maintenance,
4572 &riscv_debug_infcall, _("\
4573 Set riscv inferior call debugging."), _("\
4574 Show riscv inferior call debugging."), _("\
4575 When non-zero, print debugging information for the riscv specific parts\n\
4576 of the inferior call mechanism."),
4577 nullptr,
4578 show_riscv_debug_variable,
4579 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4580
4581 add_setshow_boolean_cmd ("unwinder", class_maintenance,
4582 &riscv_debug_unwinder, _("\
4583 Set riscv stack unwinding debugging."), _("\
4584 Show riscv stack unwinding debugging."), _("\
4585 When on, print debugging information for the riscv specific parts\n\
4586 of the stack unwinding mechanism."),
4587 nullptr,
4588 show_riscv_debug_variable,
4589 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4590
4591 add_setshow_boolean_cmd ("gdbarch", class_maintenance,
4592 &riscv_debug_gdbarch, _("\
4593 Set riscv gdbarch initialisation debugging."), _("\
4594 Show riscv gdbarch initialisation debugging."), _("\
4595 When non-zero, print debugging information for the riscv gdbarch\n\
4596 initialisation process."),
4597 nullptr,
4598 show_riscv_debug_variable,
4599 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4600
4601 /* Add root prefix command for all "set riscv" and "show riscv" commands. */
4602 add_setshow_prefix_cmd ("riscv", no_class,
4603 _("RISC-V specific commands."),
4604 _("RISC-V specific commands."),
4605 &setriscvcmdlist, &showriscvcmdlist,
4606 &setlist, &showlist);
4607
4608
4609 use_compressed_breakpoints = AUTO_BOOLEAN_AUTO;
4610 add_setshow_auto_boolean_cmd ("use-compressed-breakpoints", no_class,
4611 &use_compressed_breakpoints,
4612 _("\
4613 Set debugger's use of compressed breakpoints."), _(" \
4614 Show debugger's use of compressed breakpoints."), _("\
4615 Debugging compressed code requires compressed breakpoints to be used. If\n\
4616 left to 'auto' then gdb will use them if the existing instruction is a\n\
4617 compressed instruction. If that doesn't give the correct behavior, then\n\
4618 this option can be used."),
4619 NULL,
4620 show_use_compressed_breakpoints,
4621 &setriscvcmdlist,
4622 &showriscvcmdlist);
4623 }