Automatic date update in version.in
[external/binutils.git] / gdb / mips-tdep.c
1 /* Target-dependent code for the MIPS architecture, for GDB, the GNU Debugger.
2
3    Copyright (C) 1988-2017 Free Software Foundation, Inc.
4
5    Contributed by Alessandro Forin(af@cs.cmu.edu) at CMU
6    and by Per Bothner(bothner@cs.wisc.edu) at U.Wisconsin.
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 #include "defs.h"
24 #include "frame.h"
25 #include "inferior.h"
26 #include "symtab.h"
27 #include "value.h"
28 #include "gdbcmd.h"
29 #include "language.h"
30 #include "gdbcore.h"
31 #include "symfile.h"
32 #include "objfiles.h"
33 #include "gdbtypes.h"
34 #include "target.h"
35 #include "arch-utils.h"
36 #include "regcache.h"
37 #include "osabi.h"
38 #include "mips-tdep.h"
39 #include "block.h"
40 #include "reggroups.h"
41 #include "opcode/mips.h"
42 #include "elf/mips.h"
43 #include "elf-bfd.h"
44 #include "symcat.h"
45 #include "sim-regno.h"
46 #include "dis-asm.h"
47 #include "disasm.h"
48 #include "frame-unwind.h"
49 #include "frame-base.h"
50 #include "trad-frame.h"
51 #include "infcall.h"
52 #include "remote.h"
53 #include "target-descriptions.h"
54 #include "dwarf2-frame.h"
55 #include "user-regs.h"
56 #include "valprint.h"
57 #include "ax.h"
58 #include <algorithm>
59
60 static const struct objfile_data *mips_pdr_data;
61
62 static struct type *mips_register_type (struct gdbarch *gdbarch, int regnum);
63
64 static int mips32_instruction_has_delay_slot (struct gdbarch *gdbarch,
65                                               ULONGEST inst);
66 static int micromips_instruction_has_delay_slot (ULONGEST insn, int mustbe32);
67 static int mips16_instruction_has_delay_slot (unsigned short inst,
68                                               int mustbe32);
69
70 static int mips32_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch,
71                                              CORE_ADDR addr);
72 static int micromips_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch,
73                                                 CORE_ADDR addr, int mustbe32);
74 static int mips16_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch,
75                                              CORE_ADDR addr, int mustbe32);
76
77 static void mips_print_float_info (struct gdbarch *, struct ui_file *,
78                                    struct frame_info *, const char *);
79
80 /* A useful bit in the CP0 status register (MIPS_PS_REGNUM).  */
81 /* This bit is set if we are emulating 32-bit FPRs on a 64-bit chip.  */
82 #define ST0_FR (1 << 26)
83
84 /* The sizes of floating point registers.  */
85
86 enum
87 {
88   MIPS_FPU_SINGLE_REGSIZE = 4,
89   MIPS_FPU_DOUBLE_REGSIZE = 8
90 };
91
92 enum
93 {
94   MIPS32_REGSIZE = 4,
95   MIPS64_REGSIZE = 8
96 };
97
98 static const char *mips_abi_string;
99
100 static const char *const mips_abi_strings[] = {
101   "auto",
102   "n32",
103   "o32",
104   "n64",
105   "o64",
106   "eabi32",
107   "eabi64",
108   NULL
109 };
110
111 /* Enum describing the different kinds of breakpoints.  */
112
113 enum mips_breakpoint_kind
114 {
115   /* 16-bit MIPS16 mode breakpoint.  */
116   MIPS_BP_KIND_MIPS16 = 2,
117
118   /* 16-bit microMIPS mode breakpoint.  */
119   MIPS_BP_KIND_MICROMIPS16 = 3,
120
121   /* 32-bit standard MIPS mode breakpoint.  */
122   MIPS_BP_KIND_MIPS32 = 4,
123
124   /* 32-bit microMIPS mode breakpoint.  */
125   MIPS_BP_KIND_MICROMIPS32 = 5,
126 };
127
128 /* For backwards compatibility we default to MIPS16.  This flag is
129    overridden as soon as unambiguous ELF file flags tell us the
130    compressed ISA encoding used.  */
131 static const char mips_compression_mips16[] = "mips16";
132 static const char mips_compression_micromips[] = "micromips";
133 static const char *const mips_compression_strings[] =
134 {
135   mips_compression_mips16,
136   mips_compression_micromips,
137   NULL
138 };
139
140 static const char *mips_compression_string = mips_compression_mips16;
141
142 /* The standard register names, and all the valid aliases for them.  */
143 struct register_alias
144 {
145   const char *name;
146   int regnum;
147 };
148
149 /* Aliases for o32 and most other ABIs.  */
150 const struct register_alias mips_o32_aliases[] = {
151   { "ta0", 12 },
152   { "ta1", 13 },
153   { "ta2", 14 },
154   { "ta3", 15 }
155 };
156
157 /* Aliases for n32 and n64.  */
158 const struct register_alias mips_n32_n64_aliases[] = {
159   { "ta0", 8 },
160   { "ta1", 9 },
161   { "ta2", 10 },
162   { "ta3", 11 }
163 };
164
165 /* Aliases for ABI-independent registers.  */
166 const struct register_alias mips_register_aliases[] = {
167   /* The architecture manuals specify these ABI-independent names for
168      the GPRs.  */
169 #define R(n) { "r" #n, n }
170   R(0), R(1), R(2), R(3), R(4), R(5), R(6), R(7),
171   R(8), R(9), R(10), R(11), R(12), R(13), R(14), R(15),
172   R(16), R(17), R(18), R(19), R(20), R(21), R(22), R(23),
173   R(24), R(25), R(26), R(27), R(28), R(29), R(30), R(31),
174 #undef R
175
176   /* k0 and k1 are sometimes called these instead (for "kernel
177      temp").  */
178   { "kt0", 26 },
179   { "kt1", 27 },
180
181   /* This is the traditional GDB name for the CP0 status register.  */
182   { "sr", MIPS_PS_REGNUM },
183
184   /* This is the traditional GDB name for the CP0 BadVAddr register.  */
185   { "bad", MIPS_EMBED_BADVADDR_REGNUM },
186
187   /* This is the traditional GDB name for the FCSR.  */
188   { "fsr", MIPS_EMBED_FP0_REGNUM + 32 }
189 };
190
191 const struct register_alias mips_numeric_register_aliases[] = {
192 #define R(n) { #n, n }
193   R(0), R(1), R(2), R(3), R(4), R(5), R(6), R(7),
194   R(8), R(9), R(10), R(11), R(12), R(13), R(14), R(15),
195   R(16), R(17), R(18), R(19), R(20), R(21), R(22), R(23),
196   R(24), R(25), R(26), R(27), R(28), R(29), R(30), R(31),
197 #undef R
198 };
199
200 #ifndef MIPS_DEFAULT_FPU_TYPE
201 #define MIPS_DEFAULT_FPU_TYPE MIPS_FPU_DOUBLE
202 #endif
203 static int mips_fpu_type_auto = 1;
204 static enum mips_fpu_type mips_fpu_type = MIPS_DEFAULT_FPU_TYPE;
205
206 static unsigned int mips_debug = 0;
207
208 /* Properties (for struct target_desc) describing the g/G packet
209    layout.  */
210 #define PROPERTY_GP32 "internal: transfers-32bit-registers"
211 #define PROPERTY_GP64 "internal: transfers-64bit-registers"
212
213 struct target_desc *mips_tdesc_gp32;
214 struct target_desc *mips_tdesc_gp64;
215
216 const struct mips_regnum *
217 mips_regnum (struct gdbarch *gdbarch)
218 {
219   return gdbarch_tdep (gdbarch)->regnum;
220 }
221
222 static int
223 mips_fpa0_regnum (struct gdbarch *gdbarch)
224 {
225   return mips_regnum (gdbarch)->fp0 + 12;
226 }
227
228 /* Return 1 if REGNUM refers to a floating-point general register, raw
229    or cooked.  Otherwise return 0.  */
230
231 static int
232 mips_float_register_p (struct gdbarch *gdbarch, int regnum)
233 {
234   int rawnum = regnum % gdbarch_num_regs (gdbarch);
235
236   return (rawnum >= mips_regnum (gdbarch)->fp0
237           && rawnum < mips_regnum (gdbarch)->fp0 + 32);
238 }
239
240 #define MIPS_EABI(gdbarch) (gdbarch_tdep (gdbarch)->mips_abi \
241                      == MIPS_ABI_EABI32 \
242                    || gdbarch_tdep (gdbarch)->mips_abi == MIPS_ABI_EABI64)
243
244 #define MIPS_LAST_FP_ARG_REGNUM(gdbarch) \
245   (gdbarch_tdep (gdbarch)->mips_last_fp_arg_regnum)
246
247 #define MIPS_LAST_ARG_REGNUM(gdbarch) \
248   (gdbarch_tdep (gdbarch)->mips_last_arg_regnum)
249
250 #define MIPS_FPU_TYPE(gdbarch) (gdbarch_tdep (gdbarch)->mips_fpu_type)
251
252 /* Return the MIPS ABI associated with GDBARCH.  */
253 enum mips_abi
254 mips_abi (struct gdbarch *gdbarch)
255 {
256   return gdbarch_tdep (gdbarch)->mips_abi;
257 }
258
259 int
260 mips_isa_regsize (struct gdbarch *gdbarch)
261 {
262   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
263
264   /* If we know how big the registers are, use that size.  */
265   if (tdep->register_size_valid_p)
266     return tdep->register_size;
267
268   /* Fall back to the previous behavior.  */
269   return (gdbarch_bfd_arch_info (gdbarch)->bits_per_word
270           / gdbarch_bfd_arch_info (gdbarch)->bits_per_byte);
271 }
272
273 /* Max saved register size.  */
274 #define MAX_MIPS_ABI_REGSIZE 8
275
276 /* Return the currently configured (or set) saved register size.  */
277
278 unsigned int
279 mips_abi_regsize (struct gdbarch *gdbarch)
280 {
281   switch (mips_abi (gdbarch))
282     {
283     case MIPS_ABI_EABI32:
284     case MIPS_ABI_O32:
285       return 4;
286     case MIPS_ABI_N32:
287     case MIPS_ABI_N64:
288     case MIPS_ABI_O64:
289     case MIPS_ABI_EABI64:
290       return 8;
291     case MIPS_ABI_UNKNOWN:
292     case MIPS_ABI_LAST:
293     default:
294       internal_error (__FILE__, __LINE__, _("bad switch"));
295     }
296 }
297
298 /* MIPS16/microMIPS function addresses are odd (bit 0 is set).  Here
299    are some functions to handle addresses associated with compressed
300    code including but not limited to testing, setting, or clearing
301    bit 0 of such addresses.  */
302
303 /* Return one iff compressed code is the MIPS16 instruction set.  */
304
305 static int
306 is_mips16_isa (struct gdbarch *gdbarch)
307 {
308   return gdbarch_tdep (gdbarch)->mips_isa == ISA_MIPS16;
309 }
310
311 /* Return one iff compressed code is the microMIPS instruction set.  */
312
313 static int
314 is_micromips_isa (struct gdbarch *gdbarch)
315 {
316   return gdbarch_tdep (gdbarch)->mips_isa == ISA_MICROMIPS;
317 }
318
319 /* Return one iff ADDR denotes compressed code.  */
320
321 static int
322 is_compact_addr (CORE_ADDR addr)
323 {
324   return ((addr) & 1);
325 }
326
327 /* Return one iff ADDR denotes standard ISA code.  */
328
329 static int
330 is_mips_addr (CORE_ADDR addr)
331 {
332   return !is_compact_addr (addr);
333 }
334
335 /* Return one iff ADDR denotes MIPS16 code.  */
336
337 static int
338 is_mips16_addr (struct gdbarch *gdbarch, CORE_ADDR addr)
339 {
340   return is_compact_addr (addr) && is_mips16_isa (gdbarch);
341 }
342
343 /* Return one iff ADDR denotes microMIPS code.  */
344
345 static int
346 is_micromips_addr (struct gdbarch *gdbarch, CORE_ADDR addr)
347 {
348   return is_compact_addr (addr) && is_micromips_isa (gdbarch);
349 }
350
351 /* Strip the ISA (compression) bit off from ADDR.  */
352
353 static CORE_ADDR
354 unmake_compact_addr (CORE_ADDR addr)
355 {
356   return ((addr) & ~(CORE_ADDR) 1);
357 }
358
359 /* Add the ISA (compression) bit to ADDR.  */
360
361 static CORE_ADDR
362 make_compact_addr (CORE_ADDR addr)
363 {
364   return ((addr) | (CORE_ADDR) 1);
365 }
366
367 /* Extern version of unmake_compact_addr; we use a separate function
368    so that unmake_compact_addr can be inlined throughout this file.  */
369
370 CORE_ADDR
371 mips_unmake_compact_addr (CORE_ADDR addr)
372 {
373   return unmake_compact_addr (addr);
374 }
375
376 /* Functions for setting and testing a bit in a minimal symbol that
377    marks it as MIPS16 or microMIPS function.  The MSB of the minimal
378    symbol's "info" field is used for this purpose.
379
380    gdbarch_elf_make_msymbol_special tests whether an ELF symbol is
381    "special", i.e. refers to a MIPS16 or microMIPS function, and sets
382    one of the "special" bits in a minimal symbol to mark it accordingly.
383    The test checks an ELF-private flag that is valid for true function
384    symbols only; for synthetic symbols such as for PLT stubs that have
385    no ELF-private part at all the MIPS BFD backend arranges for this
386    information to be carried in the asymbol's udata field instead.
387
388    msymbol_is_mips16 and msymbol_is_micromips test the "special" bit
389    in a minimal symbol.  */
390
391 static void
392 mips_elf_make_msymbol_special (asymbol * sym, struct minimal_symbol *msym)
393 {
394   elf_symbol_type *elfsym = (elf_symbol_type *) sym;
395   unsigned char st_other;
396
397   if ((sym->flags & BSF_SYNTHETIC) == 0)
398     st_other = elfsym->internal_elf_sym.st_other;
399   else if ((sym->flags & BSF_FUNCTION) != 0)
400     st_other = sym->udata.i;
401   else
402     return;
403
404   if (ELF_ST_IS_MICROMIPS (st_other))
405     {
406       MSYMBOL_TARGET_FLAG_MICROMIPS (msym) = 1;
407       SET_MSYMBOL_VALUE_ADDRESS (msym, MSYMBOL_VALUE_RAW_ADDRESS (msym) | 1);
408     }
409   else if (ELF_ST_IS_MIPS16 (st_other))
410     {
411       MSYMBOL_TARGET_FLAG_MIPS16 (msym) = 1;
412       SET_MSYMBOL_VALUE_ADDRESS (msym, MSYMBOL_VALUE_RAW_ADDRESS (msym) | 1);
413     }
414 }
415
416 /* Return one iff MSYM refers to standard ISA code.  */
417
418 static int
419 msymbol_is_mips (struct minimal_symbol *msym)
420 {
421   return !(MSYMBOL_TARGET_FLAG_MIPS16 (msym)
422            | MSYMBOL_TARGET_FLAG_MICROMIPS (msym));
423 }
424
425 /* Return one iff MSYM refers to MIPS16 code.  */
426
427 static int
428 msymbol_is_mips16 (struct minimal_symbol *msym)
429 {
430   return MSYMBOL_TARGET_FLAG_MIPS16 (msym);
431 }
432
433 /* Return one iff MSYM refers to microMIPS code.  */
434
435 static int
436 msymbol_is_micromips (struct minimal_symbol *msym)
437 {
438   return MSYMBOL_TARGET_FLAG_MICROMIPS (msym);
439 }
440
441 /* Set the ISA bit in the main symbol too, complementing the corresponding
442    minimal symbol setting and reflecting the run-time value of the symbol.
443    The need for comes from the ISA bit having been cleared as code in
444    `_bfd_mips_elf_symbol_processing' separated it into the ELF symbol's
445    `st_other' STO_MIPS16 or STO_MICROMIPS annotation, making the values
446    of symbols referring to compressed code different in GDB to the values
447    used by actual code.  That in turn makes them evaluate incorrectly in
448    expressions, producing results different to what the same expressions
449    yield when compiled into the program being debugged.  */
450
451 static void
452 mips_make_symbol_special (struct symbol *sym, struct objfile *objfile)
453 {
454   if (SYMBOL_CLASS (sym) == LOC_BLOCK)
455     {
456       /* We are in symbol reading so it is OK to cast away constness.  */
457       struct block *block = (struct block *) SYMBOL_BLOCK_VALUE (sym);
458       CORE_ADDR compact_block_start;
459       struct bound_minimal_symbol msym;
460
461       compact_block_start = BLOCK_START (block) | 1;
462       msym = lookup_minimal_symbol_by_pc (compact_block_start);
463       if (msym.minsym && !msymbol_is_mips (msym.minsym))
464         {
465           BLOCK_START (block) = compact_block_start;
466         }
467     }
468 }
469
470 /* XFER a value from the big/little/left end of the register.
471    Depending on the size of the value it might occupy the entire
472    register or just part of it.  Make an allowance for this, aligning
473    things accordingly.  */
474
475 static void
476 mips_xfer_register (struct gdbarch *gdbarch, struct regcache *regcache,
477                     int reg_num, int length,
478                     enum bfd_endian endian, gdb_byte *in,
479                     const gdb_byte *out, int buf_offset)
480 {
481   int reg_offset = 0;
482
483   gdb_assert (reg_num >= gdbarch_num_regs (gdbarch));
484   /* Need to transfer the left or right part of the register, based on
485      the targets byte order.  */
486   switch (endian)
487     {
488     case BFD_ENDIAN_BIG:
489       reg_offset = register_size (gdbarch, reg_num) - length;
490       break;
491     case BFD_ENDIAN_LITTLE:
492       reg_offset = 0;
493       break;
494     case BFD_ENDIAN_UNKNOWN:    /* Indicates no alignment.  */
495       reg_offset = 0;
496       break;
497     default:
498       internal_error (__FILE__, __LINE__, _("bad switch"));
499     }
500   if (mips_debug)
501     fprintf_unfiltered (gdb_stderr,
502                         "xfer $%d, reg offset %d, buf offset %d, length %d, ",
503                         reg_num, reg_offset, buf_offset, length);
504   if (mips_debug && out != NULL)
505     {
506       int i;
507       fprintf_unfiltered (gdb_stdlog, "out ");
508       for (i = 0; i < length; i++)
509         fprintf_unfiltered (gdb_stdlog, "%02x", out[buf_offset + i]);
510     }
511   if (in != NULL)
512     regcache_cooked_read_part (regcache, reg_num, reg_offset, length,
513                                in + buf_offset);
514   if (out != NULL)
515     regcache_cooked_write_part (regcache, reg_num, reg_offset, length,
516                                 out + buf_offset);
517   if (mips_debug && in != NULL)
518     {
519       int i;
520       fprintf_unfiltered (gdb_stdlog, "in ");
521       for (i = 0; i < length; i++)
522         fprintf_unfiltered (gdb_stdlog, "%02x", in[buf_offset + i]);
523     }
524   if (mips_debug)
525     fprintf_unfiltered (gdb_stdlog, "\n");
526 }
527
528 /* Determine if a MIPS3 or later cpu is operating in MIPS{1,2} FPU
529    compatiblity mode.  A return value of 1 means that we have
530    physical 64-bit registers, but should treat them as 32-bit registers.  */
531
532 static int
533 mips2_fp_compat (struct frame_info *frame)
534 {
535   struct gdbarch *gdbarch = get_frame_arch (frame);
536   /* MIPS1 and MIPS2 have only 32 bit FPRs, and the FR bit is not
537      meaningful.  */
538   if (register_size (gdbarch, mips_regnum (gdbarch)->fp0) == 4)
539     return 0;
540
541 #if 0
542   /* FIXME drow 2002-03-10: This is disabled until we can do it consistently,
543      in all the places we deal with FP registers.  PR gdb/413.  */
544   /* Otherwise check the FR bit in the status register - it controls
545      the FP compatiblity mode.  If it is clear we are in compatibility
546      mode.  */
547   if ((get_frame_register_unsigned (frame, MIPS_PS_REGNUM) & ST0_FR) == 0)
548     return 1;
549 #endif
550
551   return 0;
552 }
553
554 #define VM_MIN_ADDRESS (CORE_ADDR)0x400000
555
556 static CORE_ADDR heuristic_proc_start (struct gdbarch *, CORE_ADDR);
557
558 static void reinit_frame_cache_sfunc (char *, int, struct cmd_list_element *);
559
560 /* The list of available "set mips " and "show mips " commands.  */
561
562 static struct cmd_list_element *setmipscmdlist = NULL;
563 static struct cmd_list_element *showmipscmdlist = NULL;
564
565 /* Integer registers 0 thru 31 are handled explicitly by
566    mips_register_name().  Processor specific registers 32 and above
567    are listed in the following tables.  */
568
569 enum
570 { NUM_MIPS_PROCESSOR_REGS = (90 - 32) };
571
572 /* Generic MIPS.  */
573
574 static const char *mips_generic_reg_names[NUM_MIPS_PROCESSOR_REGS] = {
575   "sr", "lo", "hi", "bad", "cause", "pc",
576   "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
577   "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
578   "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
579   "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
580   "fsr", "fir",
581 };
582
583 /* Names of tx39 registers.  */
584
585 static const char *mips_tx39_reg_names[NUM_MIPS_PROCESSOR_REGS] = {
586   "sr", "lo", "hi", "bad", "cause", "pc",
587   "", "", "", "", "", "", "", "",
588   "", "", "", "", "", "", "", "",
589   "", "", "", "", "", "", "", "",
590   "", "", "", "", "", "", "", "",
591   "", "", "", "",
592   "", "", "", "", "", "", "", "",
593   "", "", "config", "cache", "debug", "depc", "epc",
594 };
595
596 /* Names of registers with Linux kernels.  */
597 static const char *mips_linux_reg_names[NUM_MIPS_PROCESSOR_REGS] = {
598   "sr", "lo", "hi", "bad", "cause", "pc",
599   "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
600   "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
601   "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
602   "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
603   "fsr", "fir"
604 };
605
606
607 /* Return the name of the register corresponding to REGNO.  */
608 static const char *
609 mips_register_name (struct gdbarch *gdbarch, int regno)
610 {
611   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
612   /* GPR names for all ABIs other than n32/n64.  */
613   static const char *mips_gpr_names[] = {
614     "zero", "at", "v0", "v1", "a0", "a1", "a2", "a3",
615     "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7",
616     "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
617     "t8", "t9", "k0", "k1", "gp", "sp", "s8", "ra",
618   };
619
620   /* GPR names for n32 and n64 ABIs.  */
621   static const char *mips_n32_n64_gpr_names[] = {
622     "zero", "at", "v0", "v1", "a0", "a1", "a2", "a3",
623     "a4", "a5", "a6", "a7", "t0", "t1", "t2", "t3",
624     "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
625     "t8", "t9", "k0", "k1", "gp", "sp", "s8", "ra"
626   };
627
628   enum mips_abi abi = mips_abi (gdbarch);
629
630   /* Map [gdbarch_num_regs .. 2*gdbarch_num_regs) onto the raw registers, 
631      but then don't make the raw register names visible.  This (upper)
632      range of user visible register numbers are the pseudo-registers.
633
634      This approach was adopted accommodate the following scenario:
635      It is possible to debug a 64-bit device using a 32-bit
636      programming model.  In such instances, the raw registers are
637      configured to be 64-bits wide, while the pseudo registers are
638      configured to be 32-bits wide.  The registers that the user
639      sees - the pseudo registers - match the users expectations
640      given the programming model being used.  */
641   int rawnum = regno % gdbarch_num_regs (gdbarch);
642   if (regno < gdbarch_num_regs (gdbarch))
643     return "";
644
645   /* The MIPS integer registers are always mapped from 0 to 31.  The
646      names of the registers (which reflects the conventions regarding
647      register use) vary depending on the ABI.  */
648   if (0 <= rawnum && rawnum < 32)
649     {
650       if (abi == MIPS_ABI_N32 || abi == MIPS_ABI_N64)
651         return mips_n32_n64_gpr_names[rawnum];
652       else
653         return mips_gpr_names[rawnum];
654     }
655   else if (tdesc_has_registers (gdbarch_target_desc (gdbarch)))
656     return tdesc_register_name (gdbarch, rawnum);
657   else if (32 <= rawnum && rawnum < gdbarch_num_regs (gdbarch))
658     {
659       gdb_assert (rawnum - 32 < NUM_MIPS_PROCESSOR_REGS);
660       if (tdep->mips_processor_reg_names[rawnum - 32])
661         return tdep->mips_processor_reg_names[rawnum - 32];
662       return "";
663     }
664   else
665     internal_error (__FILE__, __LINE__,
666                     _("mips_register_name: bad register number %d"), rawnum);
667 }
668
669 /* Return the groups that a MIPS register can be categorised into.  */
670
671 static int
672 mips_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
673                           struct reggroup *reggroup)
674 {
675   int vector_p;
676   int float_p;
677   int raw_p;
678   int rawnum = regnum % gdbarch_num_regs (gdbarch);
679   int pseudo = regnum / gdbarch_num_regs (gdbarch);
680   if (reggroup == all_reggroup)
681     return pseudo;
682   vector_p = TYPE_VECTOR (register_type (gdbarch, regnum));
683   float_p = TYPE_CODE (register_type (gdbarch, regnum)) == TYPE_CODE_FLT;
684   /* FIXME: cagney/2003-04-13: Can't yet use gdbarch_num_regs
685      (gdbarch), as not all architectures are multi-arch.  */
686   raw_p = rawnum < gdbarch_num_regs (gdbarch);
687   if (gdbarch_register_name (gdbarch, regnum) == NULL
688       || gdbarch_register_name (gdbarch, regnum)[0] == '\0')
689     return 0;
690   if (reggroup == float_reggroup)
691     return float_p && pseudo;
692   if (reggroup == vector_reggroup)
693     return vector_p && pseudo;
694   if (reggroup == general_reggroup)
695     return (!vector_p && !float_p) && pseudo;
696   /* Save the pseudo registers.  Need to make certain that any code
697      extracting register values from a saved register cache also uses
698      pseudo registers.  */
699   if (reggroup == save_reggroup)
700     return raw_p && pseudo;
701   /* Restore the same pseudo register.  */
702   if (reggroup == restore_reggroup)
703     return raw_p && pseudo;
704   return 0;
705 }
706
707 /* Return the groups that a MIPS register can be categorised into.
708    This version is only used if we have a target description which
709    describes real registers (and their groups).  */
710
711 static int
712 mips_tdesc_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
713                                 struct reggroup *reggroup)
714 {
715   int rawnum = regnum % gdbarch_num_regs (gdbarch);
716   int pseudo = regnum / gdbarch_num_regs (gdbarch);
717   int ret;
718
719   /* Only save, restore, and display the pseudo registers.  Need to
720      make certain that any code extracting register values from a
721      saved register cache also uses pseudo registers.
722
723      Note: saving and restoring the pseudo registers is slightly
724      strange; if we have 64 bits, we should save and restore all
725      64 bits.  But this is hard and has little benefit.  */
726   if (!pseudo)
727     return 0;
728
729   ret = tdesc_register_in_reggroup_p (gdbarch, rawnum, reggroup);
730   if (ret != -1)
731     return ret;
732
733   return mips_register_reggroup_p (gdbarch, regnum, reggroup);
734 }
735
736 /* Map the symbol table registers which live in the range [1 *
737    gdbarch_num_regs .. 2 * gdbarch_num_regs) back onto the corresponding raw
738    registers.  Take care of alignment and size problems.  */
739
740 static enum register_status
741 mips_pseudo_register_read (struct gdbarch *gdbarch, struct regcache *regcache,
742                            int cookednum, gdb_byte *buf)
743 {
744   int rawnum = cookednum % gdbarch_num_regs (gdbarch);
745   gdb_assert (cookednum >= gdbarch_num_regs (gdbarch)
746               && cookednum < 2 * gdbarch_num_regs (gdbarch));
747   if (register_size (gdbarch, rawnum) == register_size (gdbarch, cookednum))
748     return regcache_raw_read (regcache, rawnum, buf);
749   else if (register_size (gdbarch, rawnum) >
750            register_size (gdbarch, cookednum))
751     {
752       if (gdbarch_tdep (gdbarch)->mips64_transfers_32bit_regs_p)
753         return regcache_raw_read_part (regcache, rawnum, 0, 4, buf);
754       else
755         {
756           enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
757           LONGEST regval;
758           enum register_status status;
759
760           status = regcache_raw_read_signed (regcache, rawnum, &regval);
761           if (status == REG_VALID)
762             store_signed_integer (buf, 4, byte_order, regval);
763           return status;
764         }
765     }
766   else
767     internal_error (__FILE__, __LINE__, _("bad register size"));
768 }
769
770 static void
771 mips_pseudo_register_write (struct gdbarch *gdbarch,
772                             struct regcache *regcache, int cookednum,
773                             const gdb_byte *buf)
774 {
775   int rawnum = cookednum % gdbarch_num_regs (gdbarch);
776   gdb_assert (cookednum >= gdbarch_num_regs (gdbarch)
777               && cookednum < 2 * gdbarch_num_regs (gdbarch));
778   if (register_size (gdbarch, rawnum) == register_size (gdbarch, cookednum))
779     regcache_raw_write (regcache, rawnum, buf);
780   else if (register_size (gdbarch, rawnum) >
781            register_size (gdbarch, cookednum))
782     {
783       if (gdbarch_tdep (gdbarch)->mips64_transfers_32bit_regs_p)
784         regcache_raw_write_part (regcache, rawnum, 0, 4, buf);
785       else
786         {
787           /* Sign extend the shortened version of the register prior
788              to placing it in the raw register.  This is required for
789              some mips64 parts in order to avoid unpredictable behavior.  */
790           enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
791           LONGEST regval = extract_signed_integer (buf, 4, byte_order);
792           regcache_raw_write_signed (regcache, rawnum, regval);
793         }
794     }
795   else
796     internal_error (__FILE__, __LINE__, _("bad register size"));
797 }
798
799 static int
800 mips_ax_pseudo_register_collect (struct gdbarch *gdbarch,
801                                  struct agent_expr *ax, int reg)
802 {
803   int rawnum = reg % gdbarch_num_regs (gdbarch);
804   gdb_assert (reg >= gdbarch_num_regs (gdbarch)
805               && reg < 2 * gdbarch_num_regs (gdbarch));
806
807   ax_reg_mask (ax, rawnum);
808
809   return 0;
810 }
811
812 static int
813 mips_ax_pseudo_register_push_stack (struct gdbarch *gdbarch,
814                                     struct agent_expr *ax, int reg)
815 {
816   int rawnum = reg % gdbarch_num_regs (gdbarch);
817   gdb_assert (reg >= gdbarch_num_regs (gdbarch)
818               && reg < 2 * gdbarch_num_regs (gdbarch));
819   if (register_size (gdbarch, rawnum) >= register_size (gdbarch, reg))
820     {
821       ax_reg (ax, rawnum);
822
823       if (register_size (gdbarch, rawnum) > register_size (gdbarch, reg))
824         {
825           if (!gdbarch_tdep (gdbarch)->mips64_transfers_32bit_regs_p
826               || gdbarch_byte_order (gdbarch) != BFD_ENDIAN_BIG)
827             {
828               ax_const_l (ax, 32);
829               ax_simple (ax, aop_lsh);
830             }
831           ax_const_l (ax, 32);
832           ax_simple (ax, aop_rsh_signed);
833         }
834     }
835   else
836     internal_error (__FILE__, __LINE__, _("bad register size"));
837
838   return 0;
839 }
840
841 /* Table to translate 3-bit register field to actual register number.  */
842 static const signed char mips_reg3_to_reg[8] = { 16, 17, 2, 3, 4, 5, 6, 7 };
843
844 /* Heuristic_proc_start may hunt through the text section for a long
845    time across a 2400 baud serial line.  Allows the user to limit this
846    search.  */
847
848 static int heuristic_fence_post = 0;
849
850 /* Number of bytes of storage in the actual machine representation for
851    register N.  NOTE: This defines the pseudo register type so need to
852    rebuild the architecture vector.  */
853
854 static int mips64_transfers_32bit_regs_p = 0;
855
856 static void
857 set_mips64_transfers_32bit_regs (char *args, int from_tty,
858                                  struct cmd_list_element *c)
859 {
860   struct gdbarch_info info;
861   gdbarch_info_init (&info);
862   /* FIXME: cagney/2003-11-15: Should be setting a field in "info"
863      instead of relying on globals.  Doing that would let generic code
864      handle the search for this specific architecture.  */
865   if (!gdbarch_update_p (info))
866     {
867       mips64_transfers_32bit_regs_p = 0;
868       error (_("32-bit compatibility mode not supported"));
869     }
870 }
871
872 /* Convert to/from a register and the corresponding memory value.  */
873
874 /* This predicate tests for the case of an 8 byte floating point
875    value that is being transferred to or from a pair of floating point
876    registers each of which are (or are considered to be) only 4 bytes
877    wide.  */
878 static int
879 mips_convert_register_float_case_p (struct gdbarch *gdbarch, int regnum,
880                                     struct type *type)
881 {
882   return (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG
883           && register_size (gdbarch, regnum) == 4
884           && mips_float_register_p (gdbarch, regnum)
885           && TYPE_CODE (type) == TYPE_CODE_FLT && TYPE_LENGTH (type) == 8);
886 }
887
888 /* This predicate tests for the case of a value of less than 8
889    bytes in width that is being transfered to or from an 8 byte
890    general purpose register.  */
891 static int
892 mips_convert_register_gpreg_case_p (struct gdbarch *gdbarch, int regnum,
893                                     struct type *type)
894 {
895   int num_regs = gdbarch_num_regs (gdbarch);
896
897   return (register_size (gdbarch, regnum) == 8
898           && regnum % num_regs > 0 && regnum % num_regs < 32
899           && TYPE_LENGTH (type) < 8);
900 }
901
902 static int
903 mips_convert_register_p (struct gdbarch *gdbarch,
904                          int regnum, struct type *type)
905 {
906   return (mips_convert_register_float_case_p (gdbarch, regnum, type)
907           || mips_convert_register_gpreg_case_p (gdbarch, regnum, type));
908 }
909
910 static int
911 mips_register_to_value (struct frame_info *frame, int regnum,
912                         struct type *type, gdb_byte *to,
913                         int *optimizedp, int *unavailablep)
914 {
915   struct gdbarch *gdbarch = get_frame_arch (frame);
916
917   if (mips_convert_register_float_case_p (gdbarch, regnum, type))
918     {
919       get_frame_register (frame, regnum + 0, to + 4);
920       get_frame_register (frame, regnum + 1, to + 0);
921
922       if (!get_frame_register_bytes (frame, regnum + 0, 0, 4, to + 4,
923                                      optimizedp, unavailablep))
924         return 0;
925
926       if (!get_frame_register_bytes (frame, regnum + 1, 0, 4, to + 0,
927                                      optimizedp, unavailablep))
928         return 0;
929       *optimizedp = *unavailablep = 0;
930       return 1;
931     }
932   else if (mips_convert_register_gpreg_case_p (gdbarch, regnum, type))
933     {
934       int len = TYPE_LENGTH (type);
935       CORE_ADDR offset;
936
937       offset = gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG ? 8 - len : 0;
938       if (!get_frame_register_bytes (frame, regnum, offset, len, to,
939                                      optimizedp, unavailablep))
940         return 0;
941
942       *optimizedp = *unavailablep = 0;
943       return 1;
944     }
945   else
946     {
947       internal_error (__FILE__, __LINE__,
948                       _("mips_register_to_value: unrecognized case"));
949     }
950 }
951
952 static void
953 mips_value_to_register (struct frame_info *frame, int regnum,
954                         struct type *type, const gdb_byte *from)
955 {
956   struct gdbarch *gdbarch = get_frame_arch (frame);
957
958   if (mips_convert_register_float_case_p (gdbarch, regnum, type))
959     {
960       put_frame_register (frame, regnum + 0, from + 4);
961       put_frame_register (frame, regnum + 1, from + 0);
962     }
963   else if (mips_convert_register_gpreg_case_p (gdbarch, regnum, type))
964     {
965       gdb_byte fill[8];
966       int len = TYPE_LENGTH (type);
967       
968       /* Sign extend values, irrespective of type, that are stored to 
969          a 64-bit general purpose register.  (32-bit unsigned values
970          are stored as signed quantities within a 64-bit register.
971          When performing an operation, in compiled code, that combines
972          a 32-bit unsigned value with a signed 64-bit value, a type
973          conversion is first performed that zeroes out the high 32 bits.)  */
974       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
975         {
976           if (from[0] & 0x80)
977             store_signed_integer (fill, 8, BFD_ENDIAN_BIG, -1);
978           else
979             store_signed_integer (fill, 8, BFD_ENDIAN_BIG, 0);
980           put_frame_register_bytes (frame, regnum, 0, 8 - len, fill);
981           put_frame_register_bytes (frame, regnum, 8 - len, len, from);
982         }
983       else
984         {
985           if (from[len-1] & 0x80)
986             store_signed_integer (fill, 8, BFD_ENDIAN_LITTLE, -1);
987           else
988             store_signed_integer (fill, 8, BFD_ENDIAN_LITTLE, 0);
989           put_frame_register_bytes (frame, regnum, 0, len, from);
990           put_frame_register_bytes (frame, regnum, len, 8 - len, fill);
991         }
992     }
993   else
994     {
995       internal_error (__FILE__, __LINE__,
996                       _("mips_value_to_register: unrecognized case"));
997     }
998 }
999
1000 /* Return the GDB type object for the "standard" data type of data in
1001    register REG.  */
1002
1003 static struct type *
1004 mips_register_type (struct gdbarch *gdbarch, int regnum)
1005 {
1006   gdb_assert (regnum >= 0 && regnum < 2 * gdbarch_num_regs (gdbarch));
1007   if (mips_float_register_p (gdbarch, regnum))
1008     {
1009       /* The floating-point registers raw, or cooked, always match
1010          mips_isa_regsize(), and also map 1:1, byte for byte.  */
1011       if (mips_isa_regsize (gdbarch) == 4)
1012         return builtin_type (gdbarch)->builtin_float;
1013       else
1014         return builtin_type (gdbarch)->builtin_double;
1015     }
1016   else if (regnum < gdbarch_num_regs (gdbarch))
1017     {
1018       /* The raw or ISA registers.  These are all sized according to
1019          the ISA regsize.  */
1020       if (mips_isa_regsize (gdbarch) == 4)
1021         return builtin_type (gdbarch)->builtin_int32;
1022       else
1023         return builtin_type (gdbarch)->builtin_int64;
1024     }
1025   else
1026     {
1027       int rawnum = regnum - gdbarch_num_regs (gdbarch);
1028
1029       /* The cooked or ABI registers.  These are sized according to
1030          the ABI (with a few complications).  */
1031       if (rawnum == mips_regnum (gdbarch)->fp_control_status
1032           || rawnum == mips_regnum (gdbarch)->fp_implementation_revision)
1033         return builtin_type (gdbarch)->builtin_int32;
1034       else if (gdbarch_osabi (gdbarch) != GDB_OSABI_LINUX
1035                && rawnum >= MIPS_FIRST_EMBED_REGNUM
1036                && rawnum <= MIPS_LAST_EMBED_REGNUM)
1037         /* The pseudo/cooked view of the embedded registers is always
1038            32-bit.  The raw view is handled below.  */
1039         return builtin_type (gdbarch)->builtin_int32;
1040       else if (gdbarch_tdep (gdbarch)->mips64_transfers_32bit_regs_p)
1041         /* The target, while possibly using a 64-bit register buffer,
1042            is only transfering 32-bits of each integer register.
1043            Reflect this in the cooked/pseudo (ABI) register value.  */
1044         return builtin_type (gdbarch)->builtin_int32;
1045       else if (mips_abi_regsize (gdbarch) == 4)
1046         /* The ABI is restricted to 32-bit registers (the ISA could be
1047            32- or 64-bit).  */
1048         return builtin_type (gdbarch)->builtin_int32;
1049       else
1050         /* 64-bit ABI.  */
1051         return builtin_type (gdbarch)->builtin_int64;
1052     }
1053 }
1054
1055 /* Return the GDB type for the pseudo register REGNUM, which is the
1056    ABI-level view.  This function is only called if there is a target
1057    description which includes registers, so we know precisely the
1058    types of hardware registers.  */
1059
1060 static struct type *
1061 mips_pseudo_register_type (struct gdbarch *gdbarch, int regnum)
1062 {
1063   const int num_regs = gdbarch_num_regs (gdbarch);
1064   int rawnum = regnum % num_regs;
1065   struct type *rawtype;
1066
1067   gdb_assert (regnum >= num_regs && regnum < 2 * num_regs);
1068
1069   /* Absent registers are still absent.  */
1070   rawtype = gdbarch_register_type (gdbarch, rawnum);
1071   if (TYPE_LENGTH (rawtype) == 0)
1072     return rawtype;
1073
1074   /* Present the floating point registers however the hardware did;
1075      do not try to convert between FPU layouts.  */
1076   if (mips_float_register_p (gdbarch, rawnum))
1077     return rawtype;
1078
1079   /* Floating-point control registers are always 32-bit even though for
1080      backwards compatibility reasons 64-bit targets will transfer them
1081      as 64-bit quantities even if using XML descriptions.  */
1082   if (rawnum == mips_regnum (gdbarch)->fp_control_status
1083       || rawnum == mips_regnum (gdbarch)->fp_implementation_revision)
1084     return builtin_type (gdbarch)->builtin_int32;
1085
1086   /* Use pointer types for registers if we can.  For n32 we can not,
1087      since we do not have a 64-bit pointer type.  */
1088   if (mips_abi_regsize (gdbarch)
1089       == TYPE_LENGTH (builtin_type (gdbarch)->builtin_data_ptr))
1090     {
1091       if (rawnum == MIPS_SP_REGNUM
1092           || rawnum == mips_regnum (gdbarch)->badvaddr)
1093         return builtin_type (gdbarch)->builtin_data_ptr;
1094       else if (rawnum == mips_regnum (gdbarch)->pc)
1095         return builtin_type (gdbarch)->builtin_func_ptr;
1096     }
1097
1098   if (mips_abi_regsize (gdbarch) == 4 && TYPE_LENGTH (rawtype) == 8
1099       && ((rawnum >= MIPS_ZERO_REGNUM && rawnum <= MIPS_PS_REGNUM)
1100           || rawnum == mips_regnum (gdbarch)->lo
1101           || rawnum == mips_regnum (gdbarch)->hi
1102           || rawnum == mips_regnum (gdbarch)->badvaddr
1103           || rawnum == mips_regnum (gdbarch)->cause
1104           || rawnum == mips_regnum (gdbarch)->pc
1105           || (mips_regnum (gdbarch)->dspacc != -1
1106               && rawnum >= mips_regnum (gdbarch)->dspacc
1107               && rawnum < mips_regnum (gdbarch)->dspacc + 6)))
1108     return builtin_type (gdbarch)->builtin_int32;
1109
1110   /* The pseudo/cooked view of embedded registers is always
1111      32-bit, even if the target transfers 64-bit values for them.
1112      New targets relying on XML descriptions should only transfer
1113      the necessary 32 bits, but older versions of GDB expected 64,
1114      so allow the target to provide 64 bits without interfering
1115      with the displayed type.  */
1116   if (gdbarch_osabi (gdbarch) != GDB_OSABI_LINUX
1117       && rawnum >= MIPS_FIRST_EMBED_REGNUM
1118       && rawnum <= MIPS_LAST_EMBED_REGNUM)
1119     return builtin_type (gdbarch)->builtin_int32;
1120
1121   /* For all other registers, pass through the hardware type.  */
1122   return rawtype;
1123 }
1124
1125 /* Should the upper word of 64-bit addresses be zeroed?  */
1126 enum auto_boolean mask_address_var = AUTO_BOOLEAN_AUTO;
1127
1128 static int
1129 mips_mask_address_p (struct gdbarch_tdep *tdep)
1130 {
1131   switch (mask_address_var)
1132     {
1133     case AUTO_BOOLEAN_TRUE:
1134       return 1;
1135     case AUTO_BOOLEAN_FALSE:
1136       return 0;
1137       break;
1138     case AUTO_BOOLEAN_AUTO:
1139       return tdep->default_mask_address_p;
1140     default:
1141       internal_error (__FILE__, __LINE__,
1142                       _("mips_mask_address_p: bad switch"));
1143       return -1;
1144     }
1145 }
1146
1147 static void
1148 show_mask_address (struct ui_file *file, int from_tty,
1149                    struct cmd_list_element *c, const char *value)
1150 {
1151   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch ());
1152
1153   deprecated_show_value_hack (file, from_tty, c, value);
1154   switch (mask_address_var)
1155     {
1156     case AUTO_BOOLEAN_TRUE:
1157       printf_filtered ("The 32 bit mips address mask is enabled\n");
1158       break;
1159     case AUTO_BOOLEAN_FALSE:
1160       printf_filtered ("The 32 bit mips address mask is disabled\n");
1161       break;
1162     case AUTO_BOOLEAN_AUTO:
1163       printf_filtered
1164         ("The 32 bit address mask is set automatically.  Currently %s\n",
1165          mips_mask_address_p (tdep) ? "enabled" : "disabled");
1166       break;
1167     default:
1168       internal_error (__FILE__, __LINE__, _("show_mask_address: bad switch"));
1169       break;
1170     }
1171 }
1172
1173 /* Tell if the program counter value in MEMADDR is in a standard ISA
1174    function.  */
1175
1176 int
1177 mips_pc_is_mips (CORE_ADDR memaddr)
1178 {
1179   struct bound_minimal_symbol sym;
1180
1181   /* Flags indicating that this is a MIPS16 or microMIPS function is
1182      stored by elfread.c in the high bit of the info field.  Use this
1183      to decide if the function is standard MIPS.  Otherwise if bit 0
1184      of the address is clear, then this is a standard MIPS function.  */
1185   sym = lookup_minimal_symbol_by_pc (make_compact_addr (memaddr));
1186   if (sym.minsym)
1187     return msymbol_is_mips (sym.minsym);
1188   else
1189     return is_mips_addr (memaddr);
1190 }
1191
1192 /* Tell if the program counter value in MEMADDR is in a MIPS16 function.  */
1193
1194 int
1195 mips_pc_is_mips16 (struct gdbarch *gdbarch, CORE_ADDR memaddr)
1196 {
1197   struct bound_minimal_symbol sym;
1198
1199   /* A flag indicating that this is a MIPS16 function is stored by
1200      elfread.c in the high bit of the info field.  Use this to decide
1201      if the function is MIPS16.  Otherwise if bit 0 of the address is
1202      set, then ELF file flags will tell if this is a MIPS16 function.  */
1203   sym = lookup_minimal_symbol_by_pc (make_compact_addr (memaddr));
1204   if (sym.minsym)
1205     return msymbol_is_mips16 (sym.minsym);
1206   else
1207     return is_mips16_addr (gdbarch, memaddr);
1208 }
1209
1210 /* Tell if the program counter value in MEMADDR is in a microMIPS function.  */
1211
1212 int
1213 mips_pc_is_micromips (struct gdbarch *gdbarch, CORE_ADDR memaddr)
1214 {
1215   struct bound_minimal_symbol sym;
1216
1217   /* A flag indicating that this is a microMIPS function is stored by
1218      elfread.c in the high bit of the info field.  Use this to decide
1219      if the function is microMIPS.  Otherwise if bit 0 of the address
1220      is set, then ELF file flags will tell if this is a microMIPS
1221      function.  */
1222   sym = lookup_minimal_symbol_by_pc (make_compact_addr (memaddr));
1223   if (sym.minsym)
1224     return msymbol_is_micromips (sym.minsym);
1225   else
1226     return is_micromips_addr (gdbarch, memaddr);
1227 }
1228
1229 /* Tell the ISA type of the function the program counter value in MEMADDR
1230    is in.  */
1231
1232 static enum mips_isa
1233 mips_pc_isa (struct gdbarch *gdbarch, CORE_ADDR memaddr)
1234 {
1235   struct bound_minimal_symbol sym;
1236
1237   /* A flag indicating that this is a MIPS16 or a microMIPS function
1238      is stored by elfread.c in the high bit of the info field.  Use
1239      this to decide if the function is MIPS16 or microMIPS or normal
1240      MIPS.  Otherwise if bit 0 of the address is set, then ELF file
1241      flags will tell if this is a MIPS16 or a microMIPS function.  */
1242   sym = lookup_minimal_symbol_by_pc (make_compact_addr (memaddr));
1243   if (sym.minsym)
1244     {
1245       if (msymbol_is_micromips (sym.minsym))
1246         return ISA_MICROMIPS;
1247       else if (msymbol_is_mips16 (sym.minsym))
1248         return ISA_MIPS16;
1249       else
1250         return ISA_MIPS;
1251     }
1252   else
1253     {
1254       if (is_mips_addr (memaddr))
1255         return ISA_MIPS;
1256       else if (is_micromips_addr (gdbarch, memaddr))
1257         return ISA_MICROMIPS;
1258       else
1259         return ISA_MIPS16;
1260     }
1261 }
1262
1263 /* Set the ISA bit correctly in the PC, used by DWARF-2 machinery.
1264    The need for comes from the ISA bit having been cleared, making
1265    addresses in FDE, range records, etc. referring to compressed code
1266    different to those in line information, the symbol table and finally
1267    the PC register.  That in turn confuses many operations.  */
1268
1269 static CORE_ADDR
1270 mips_adjust_dwarf2_addr (CORE_ADDR pc)
1271 {
1272   pc = unmake_compact_addr (pc);
1273   return mips_pc_is_mips (pc) ? pc : make_compact_addr (pc);
1274 }
1275
1276 /* Recalculate the line record requested so that the resulting PC has
1277    the ISA bit set correctly, used by DWARF-2 machinery.  The need for
1278    this adjustment comes from some records associated with compressed
1279    code having the ISA bit cleared, most notably at function prologue
1280    ends.  The ISA bit is in this context retrieved from the minimal
1281    symbol covering the address requested, which in turn has been
1282    constructed from the binary's symbol table rather than DWARF-2
1283    information.  The correct setting of the ISA bit is required for
1284    breakpoint addresses to correctly match against the stop PC.
1285
1286    As line entries can specify relative address adjustments we need to
1287    keep track of the absolute value of the last line address recorded
1288    in line information, so that we can calculate the actual address to
1289    apply the ISA bit adjustment to.  We use PC for this tracking and
1290    keep the original address there.
1291
1292    As such relative address adjustments can be odd within compressed
1293    code we need to keep track of the last line address with the ISA
1294    bit adjustment applied too, as the original address may or may not
1295    have had the ISA bit set.  We use ADJ_PC for this tracking and keep
1296    the adjusted address there.
1297
1298    For relative address adjustments we then use these variables to
1299    calculate the address intended by line information, which will be
1300    PC-relative, and return an updated adjustment carrying ISA bit
1301    information, which will be ADJ_PC-relative.  For absolute address
1302    adjustments we just return the same address that we store in ADJ_PC
1303    too.
1304
1305    As the first line entry can be relative to an implied address value
1306    of 0 we need to have the initial address set up that we store in PC
1307    and ADJ_PC.  This is arranged with a call from `dwarf_decode_lines_1'
1308    that sets PC to 0 and ADJ_PC accordingly, usually 0 as well.  */
1309
1310 static CORE_ADDR
1311 mips_adjust_dwarf2_line (CORE_ADDR addr, int rel)
1312 {
1313   static CORE_ADDR adj_pc;
1314   static CORE_ADDR pc;
1315   CORE_ADDR isa_pc;
1316
1317   pc = rel ? pc + addr : addr;
1318   isa_pc = mips_adjust_dwarf2_addr (pc);
1319   addr = rel ? isa_pc - adj_pc : isa_pc;
1320   adj_pc = isa_pc;
1321   return addr;
1322 }
1323
1324 /* Various MIPS16 thunk (aka stub or trampoline) names.  */
1325
1326 static const char mips_str_mips16_call_stub[] = "__mips16_call_stub_";
1327 static const char mips_str_mips16_ret_stub[] = "__mips16_ret_";
1328 static const char mips_str_call_fp_stub[] = "__call_stub_fp_";
1329 static const char mips_str_call_stub[] = "__call_stub_";
1330 static const char mips_str_fn_stub[] = "__fn_stub_";
1331
1332 /* This is used as a PIC thunk prefix.  */
1333
1334 static const char mips_str_pic[] = ".pic.";
1335
1336 /* Return non-zero if the PC is inside a call thunk (aka stub or
1337    trampoline) that should be treated as a temporary frame.  */
1338
1339 static int
1340 mips_in_frame_stub (CORE_ADDR pc)
1341 {
1342   CORE_ADDR start_addr;
1343   const char *name;
1344
1345   /* Find the starting address of the function containing the PC.  */
1346   if (find_pc_partial_function (pc, &name, &start_addr, NULL) == 0)
1347     return 0;
1348
1349   /* If the PC is in __mips16_call_stub_*, this is a call/return stub.  */
1350   if (startswith (name, mips_str_mips16_call_stub))
1351     return 1;
1352   /* If the PC is in __call_stub_*, this is a call/return or a call stub.  */
1353   if (startswith (name, mips_str_call_stub))
1354     return 1;
1355   /* If the PC is in __fn_stub_*, this is a call stub.  */
1356   if (startswith (name, mips_str_fn_stub))
1357     return 1;
1358
1359   return 0;                     /* Not a stub.  */
1360 }
1361
1362 /* MIPS believes that the PC has a sign extended value.  Perhaps the
1363    all registers should be sign extended for simplicity?  */
1364
1365 static CORE_ADDR
1366 mips_read_pc (struct regcache *regcache)
1367 {
1368   int regnum = gdbarch_pc_regnum (get_regcache_arch (regcache));
1369   LONGEST pc;
1370
1371   regcache_cooked_read_signed (regcache, regnum, &pc);
1372   return pc;
1373 }
1374
1375 static CORE_ADDR
1376 mips_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
1377 {
1378   CORE_ADDR pc;
1379
1380   pc = frame_unwind_register_signed (next_frame, gdbarch_pc_regnum (gdbarch));
1381   /* macro/2012-04-20: This hack skips over MIPS16 call thunks as
1382      intermediate frames.  In this case we can get the caller's address
1383      from $ra, or if $ra contains an address within a thunk as well, then
1384      it must be in the return path of __mips16_call_stub_{s,d}{f,c}_{0..10}
1385      and thus the caller's address is in $s2.  */
1386   if (frame_relative_level (next_frame) >= 0 && mips_in_frame_stub (pc))
1387     {
1388       pc = frame_unwind_register_signed
1389              (next_frame, gdbarch_num_regs (gdbarch) + MIPS_RA_REGNUM);
1390       if (mips_in_frame_stub (pc))
1391         pc = frame_unwind_register_signed
1392                (next_frame, gdbarch_num_regs (gdbarch) + MIPS_S2_REGNUM);
1393     }
1394   return pc;
1395 }
1396
1397 static CORE_ADDR
1398 mips_unwind_sp (struct gdbarch *gdbarch, struct frame_info *next_frame)
1399 {
1400   return frame_unwind_register_signed
1401            (next_frame, gdbarch_num_regs (gdbarch) + MIPS_SP_REGNUM);
1402 }
1403
1404 /* Assuming THIS_FRAME is a dummy, return the frame ID of that
1405    dummy frame.  The frame ID's base needs to match the TOS value
1406    saved by save_dummy_frame_tos(), and the PC match the dummy frame's
1407    breakpoint.  */
1408
1409 static struct frame_id
1410 mips_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
1411 {
1412   return frame_id_build
1413            (get_frame_register_signed (this_frame,
1414                                        gdbarch_num_regs (gdbarch)
1415                                        + MIPS_SP_REGNUM),
1416             get_frame_pc (this_frame));
1417 }
1418
1419 /* Implement the "write_pc" gdbarch method.  */
1420
1421 void
1422 mips_write_pc (struct regcache *regcache, CORE_ADDR pc)
1423 {
1424   int regnum = gdbarch_pc_regnum (get_regcache_arch (regcache));
1425
1426   regcache_cooked_write_unsigned (regcache, regnum, pc);
1427 }
1428
1429 /* Fetch and return instruction from the specified location.  Handle
1430    MIPS16/microMIPS as appropriate.  */
1431
1432 static ULONGEST
1433 mips_fetch_instruction (struct gdbarch *gdbarch,
1434                         enum mips_isa isa, CORE_ADDR addr, int *errp)
1435 {
1436   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1437   gdb_byte buf[MIPS_INSN32_SIZE];
1438   int instlen;
1439   int err;
1440
1441   switch (isa)
1442     {
1443     case ISA_MICROMIPS:
1444     case ISA_MIPS16:
1445       instlen = MIPS_INSN16_SIZE;
1446       addr = unmake_compact_addr (addr);
1447       break;
1448     case ISA_MIPS:
1449       instlen = MIPS_INSN32_SIZE;
1450       break;
1451     default:
1452       internal_error (__FILE__, __LINE__, _("invalid ISA"));
1453       break;
1454     }
1455   err = target_read_memory (addr, buf, instlen);
1456   if (errp != NULL)
1457     *errp = err;
1458   if (err != 0)
1459     {
1460       if (errp == NULL)
1461         memory_error (TARGET_XFER_E_IO, addr);
1462       return 0;
1463     }
1464   return extract_unsigned_integer (buf, instlen, byte_order);
1465 }
1466
1467 /* These are the fields of 32 bit mips instructions.  */
1468 #define mips32_op(x) (x >> 26)
1469 #define itype_op(x) (x >> 26)
1470 #define itype_rs(x) ((x >> 21) & 0x1f)
1471 #define itype_rt(x) ((x >> 16) & 0x1f)
1472 #define itype_immediate(x) (x & 0xffff)
1473
1474 #define jtype_op(x) (x >> 26)
1475 #define jtype_target(x) (x & 0x03ffffff)
1476
1477 #define rtype_op(x) (x >> 26)
1478 #define rtype_rs(x) ((x >> 21) & 0x1f)
1479 #define rtype_rt(x) ((x >> 16) & 0x1f)
1480 #define rtype_rd(x) ((x >> 11) & 0x1f)
1481 #define rtype_shamt(x) ((x >> 6) & 0x1f)
1482 #define rtype_funct(x) (x & 0x3f)
1483
1484 /* MicroMIPS instruction fields.  */
1485 #define micromips_op(x) ((x) >> 10)
1486
1487 /* 16-bit/32-bit-high-part instruction formats, B and S refer to the lowest
1488    bit and the size respectively of the field extracted.  */
1489 #define b0s4_imm(x) ((x) & 0xf)
1490 #define b0s5_imm(x) ((x) & 0x1f)
1491 #define b0s5_reg(x) ((x) & 0x1f)
1492 #define b0s7_imm(x) ((x) & 0x7f)
1493 #define b0s10_imm(x) ((x) & 0x3ff)
1494 #define b1s4_imm(x) (((x) >> 1) & 0xf)
1495 #define b1s9_imm(x) (((x) >> 1) & 0x1ff)
1496 #define b2s3_cc(x) (((x) >> 2) & 0x7)
1497 #define b4s2_regl(x) (((x) >> 4) & 0x3)
1498 #define b5s5_op(x) (((x) >> 5) & 0x1f)
1499 #define b5s5_reg(x) (((x) >> 5) & 0x1f)
1500 #define b6s4_op(x) (((x) >> 6) & 0xf)
1501 #define b7s3_reg(x) (((x) >> 7) & 0x7)
1502
1503 /* 32-bit instruction formats, B and S refer to the lowest bit and the size
1504    respectively of the field extracted.  */
1505 #define b0s6_op(x) ((x) & 0x3f)
1506 #define b0s11_op(x) ((x) & 0x7ff)
1507 #define b0s12_imm(x) ((x) & 0xfff)
1508 #define b0s16_imm(x) ((x) & 0xffff)
1509 #define b0s26_imm(x) ((x) & 0x3ffffff)
1510 #define b6s10_ext(x) (((x) >> 6) & 0x3ff)
1511 #define b11s5_reg(x) (((x) >> 11) & 0x1f)
1512 #define b12s4_op(x) (((x) >> 12) & 0xf)
1513
1514 /* Return the size in bytes of the instruction INSN encoded in the ISA
1515    instruction set.  */
1516
1517 static int
1518 mips_insn_size (enum mips_isa isa, ULONGEST insn)
1519 {
1520   switch (isa)
1521     {
1522     case ISA_MICROMIPS:
1523       if ((micromips_op (insn) & 0x4) == 0x4
1524           || (micromips_op (insn) & 0x7) == 0x0)
1525         return 2 * MIPS_INSN16_SIZE;
1526       else
1527         return MIPS_INSN16_SIZE;
1528     case ISA_MIPS16:
1529       if ((insn & 0xf800) == 0xf000)
1530         return 2 * MIPS_INSN16_SIZE;
1531       else
1532         return MIPS_INSN16_SIZE;
1533     case ISA_MIPS:
1534         return MIPS_INSN32_SIZE;
1535     }
1536   internal_error (__FILE__, __LINE__, _("invalid ISA"));
1537 }
1538
1539 static LONGEST
1540 mips32_relative_offset (ULONGEST inst)
1541 {
1542   return ((itype_immediate (inst) ^ 0x8000) - 0x8000) << 2;
1543 }
1544
1545 /* Determine the address of the next instruction executed after the INST
1546    floating condition branch instruction at PC.  COUNT specifies the
1547    number of the floating condition bits tested by the branch.  */
1548
1549 static CORE_ADDR
1550 mips32_bc1_pc (struct gdbarch *gdbarch, struct regcache *regcache,
1551                ULONGEST inst, CORE_ADDR pc, int count)
1552 {
1553   int fcsr = mips_regnum (gdbarch)->fp_control_status;
1554   int cnum = (itype_rt (inst) >> 2) & (count - 1);
1555   int tf = itype_rt (inst) & 1;
1556   int mask = (1 << count) - 1;
1557   ULONGEST fcs;
1558   int cond;
1559
1560   if (fcsr == -1)
1561     /* No way to handle; it'll most likely trap anyway.  */
1562     return pc;
1563
1564   fcs = regcache_raw_get_unsigned (regcache, fcsr);
1565   cond = ((fcs >> 24) & 0xfe) | ((fcs >> 23) & 0x01);
1566
1567   if (((cond >> cnum) & mask) != mask * !tf)
1568     pc += mips32_relative_offset (inst);
1569   else
1570     pc += 4;
1571
1572   return pc;
1573 }
1574
1575 /* Return nonzero if the gdbarch is an Octeon series.  */
1576
1577 static int
1578 is_octeon (struct gdbarch *gdbarch)
1579 {
1580   const struct bfd_arch_info *info = gdbarch_bfd_arch_info (gdbarch);
1581
1582   return (info->mach == bfd_mach_mips_octeon
1583          || info->mach == bfd_mach_mips_octeonp
1584          || info->mach == bfd_mach_mips_octeon2);
1585 }
1586
1587 /* Return true if the OP represents the Octeon's BBIT instruction.  */
1588
1589 static int
1590 is_octeon_bbit_op (int op, struct gdbarch *gdbarch)
1591 {
1592   if (!is_octeon (gdbarch))
1593     return 0;
1594   /* BBIT0 is encoded as LWC2: 110 010.  */
1595   /* BBIT032 is encoded as LDC2: 110 110.  */
1596   /* BBIT1 is encoded as SWC2: 111 010.  */
1597   /* BBIT132 is encoded as SDC2: 111 110.  */
1598   if (op == 50 || op == 54 || op == 58 || op == 62)
1599     return 1;
1600   return 0;
1601 }
1602
1603
1604 /* Determine where to set a single step breakpoint while considering
1605    branch prediction.  */
1606
1607 static CORE_ADDR
1608 mips32_next_pc (struct regcache *regcache, CORE_ADDR pc)
1609 {
1610   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1611   unsigned long inst;
1612   int op;
1613   inst = mips_fetch_instruction (gdbarch, ISA_MIPS, pc, NULL);
1614   op = itype_op (inst);
1615   if ((inst & 0xe0000000) != 0)         /* Not a special, jump or branch
1616                                            instruction.  */
1617     {
1618       if (op >> 2 == 5)
1619         /* BEQL, BNEL, BLEZL, BGTZL: bits 0101xx */
1620         {
1621           switch (op & 0x03)
1622             {
1623             case 0:             /* BEQL */
1624               goto equal_branch;
1625             case 1:             /* BNEL */
1626               goto neq_branch;
1627             case 2:             /* BLEZL */
1628               goto less_branch;
1629             case 3:             /* BGTZL */
1630               goto greater_branch;
1631             default:
1632               pc += 4;
1633             }
1634         }
1635       else if (op == 17 && itype_rs (inst) == 8)
1636         /* BC1F, BC1FL, BC1T, BC1TL: 010001 01000 */
1637         pc = mips32_bc1_pc (gdbarch, regcache, inst, pc + 4, 1);
1638       else if (op == 17 && itype_rs (inst) == 9
1639                && (itype_rt (inst) & 2) == 0)
1640         /* BC1ANY2F, BC1ANY2T: 010001 01001 xxx0x */
1641         pc = mips32_bc1_pc (gdbarch, regcache, inst, pc + 4, 2);
1642       else if (op == 17 && itype_rs (inst) == 10
1643                && (itype_rt (inst) & 2) == 0)
1644         /* BC1ANY4F, BC1ANY4T: 010001 01010 xxx0x */
1645         pc = mips32_bc1_pc (gdbarch, regcache, inst, pc + 4, 4);
1646       else if (op == 29)
1647         /* JALX: 011101 */
1648         /* The new PC will be alternate mode.  */
1649         {
1650           unsigned long reg;
1651
1652           reg = jtype_target (inst) << 2;
1653           /* Add 1 to indicate 16-bit mode -- invert ISA mode.  */
1654           pc = ((pc + 4) & ~(CORE_ADDR) 0x0fffffff) + reg + 1;
1655         }
1656       else if (is_octeon_bbit_op (op, gdbarch))
1657         {
1658           int bit, branch_if;
1659
1660           branch_if = op == 58 || op == 62;
1661           bit = itype_rt (inst);
1662
1663           /* Take into account the *32 instructions.  */
1664           if (op == 54 || op == 62)
1665             bit += 32;
1666
1667           if (((regcache_raw_get_signed (regcache,
1668                                          itype_rs (inst)) >> bit) & 1)
1669               == branch_if)
1670             pc += mips32_relative_offset (inst) + 4;
1671           else
1672             pc += 8;        /* After the delay slot.  */
1673         }
1674
1675       else
1676         pc += 4;                /* Not a branch, next instruction is easy.  */
1677     }
1678   else
1679     {                           /* This gets way messy.  */
1680
1681       /* Further subdivide into SPECIAL, REGIMM and other.  */
1682       switch (op & 0x07)        /* Extract bits 28,27,26.  */
1683         {
1684         case 0:         /* SPECIAL */
1685           op = rtype_funct (inst);
1686           switch (op)
1687             {
1688             case 8:             /* JR */
1689             case 9:             /* JALR */
1690               /* Set PC to that address.  */
1691               pc = regcache_raw_get_signed (regcache, rtype_rs (inst));
1692               break;
1693             case 12:            /* SYSCALL */
1694               {
1695                 struct gdbarch_tdep *tdep;
1696
1697                 tdep = gdbarch_tdep (gdbarch);
1698                 if (tdep->syscall_next_pc != NULL)
1699                   pc = tdep->syscall_next_pc (get_current_frame ());
1700                 else
1701                   pc += 4;
1702               }
1703               break;
1704             default:
1705               pc += 4;
1706             }
1707
1708           break;                /* end SPECIAL */
1709         case 1:                 /* REGIMM */
1710           {
1711             op = itype_rt (inst);       /* branch condition */
1712             switch (op)
1713               {
1714               case 0:           /* BLTZ */
1715               case 2:           /* BLTZL */
1716               case 16:          /* BLTZAL */
1717               case 18:          /* BLTZALL */
1718               less_branch:
1719                 if (regcache_raw_get_signed (regcache, itype_rs (inst)) < 0)
1720                   pc += mips32_relative_offset (inst) + 4;
1721                 else
1722                   pc += 8;      /* after the delay slot */
1723                 break;
1724               case 1:           /* BGEZ */
1725               case 3:           /* BGEZL */
1726               case 17:          /* BGEZAL */
1727               case 19:          /* BGEZALL */
1728                 if (regcache_raw_get_signed (regcache, itype_rs (inst)) >= 0)
1729                   pc += mips32_relative_offset (inst) + 4;
1730                 else
1731                   pc += 8;      /* after the delay slot */
1732                 break;
1733               case 0x1c:        /* BPOSGE32 */
1734               case 0x1e:        /* BPOSGE64 */
1735                 pc += 4;
1736                 if (itype_rs (inst) == 0)
1737                   {
1738                     unsigned int pos = (op & 2) ? 64 : 32;
1739                     int dspctl = mips_regnum (gdbarch)->dspctl;
1740
1741                     if (dspctl == -1)
1742                       /* No way to handle; it'll most likely trap anyway.  */
1743                       break;
1744
1745                     if ((regcache_raw_get_unsigned (regcache,
1746                                                     dspctl) & 0x7f) >= pos)
1747                       pc += mips32_relative_offset (inst);
1748                     else
1749                       pc += 4;
1750                   }
1751                 break;
1752                 /* All of the other instructions in the REGIMM category */
1753               default:
1754                 pc += 4;
1755               }
1756           }
1757           break;                /* end REGIMM */
1758         case 2:         /* J */
1759         case 3:         /* JAL */
1760           {
1761             unsigned long reg;
1762             reg = jtype_target (inst) << 2;
1763             /* Upper four bits get never changed...  */
1764             pc = reg + ((pc + 4) & ~(CORE_ADDR) 0x0fffffff);
1765           }
1766           break;
1767         case 4:         /* BEQ, BEQL */
1768         equal_branch:
1769           if (regcache_raw_get_signed (regcache, itype_rs (inst)) ==
1770               regcache_raw_get_signed (regcache, itype_rt (inst)))
1771             pc += mips32_relative_offset (inst) + 4;
1772           else
1773             pc += 8;
1774           break;
1775         case 5:         /* BNE, BNEL */
1776         neq_branch:
1777           if (regcache_raw_get_signed (regcache, itype_rs (inst)) !=
1778               regcache_raw_get_signed (regcache, itype_rt (inst)))
1779             pc += mips32_relative_offset (inst) + 4;
1780           else
1781             pc += 8;
1782           break;
1783         case 6:         /* BLEZ, BLEZL */
1784           if (regcache_raw_get_signed (regcache, itype_rs (inst)) <= 0)
1785             pc += mips32_relative_offset (inst) + 4;
1786           else
1787             pc += 8;
1788           break;
1789         case 7:
1790         default:
1791         greater_branch: /* BGTZ, BGTZL */
1792           if (regcache_raw_get_signed (regcache, itype_rs (inst)) > 0)
1793             pc += mips32_relative_offset (inst) + 4;
1794           else
1795             pc += 8;
1796           break;
1797         }                       /* switch */
1798     }                           /* else */
1799   return pc;
1800 }                               /* mips32_next_pc */
1801
1802 /* Extract the 7-bit signed immediate offset from the microMIPS instruction
1803    INSN.  */
1804
1805 static LONGEST
1806 micromips_relative_offset7 (ULONGEST insn)
1807 {
1808   return ((b0s7_imm (insn) ^ 0x40) - 0x40) << 1;
1809 }
1810
1811 /* Extract the 10-bit signed immediate offset from the microMIPS instruction
1812    INSN.  */
1813
1814 static LONGEST
1815 micromips_relative_offset10 (ULONGEST insn)
1816 {
1817   return ((b0s10_imm (insn) ^ 0x200) - 0x200) << 1;
1818 }
1819
1820 /* Extract the 16-bit signed immediate offset from the microMIPS instruction
1821    INSN.  */
1822
1823 static LONGEST
1824 micromips_relative_offset16 (ULONGEST insn)
1825 {
1826   return ((b0s16_imm (insn) ^ 0x8000) - 0x8000) << 1;
1827 }
1828
1829 /* Return the size in bytes of the microMIPS instruction at the address PC.  */
1830
1831 static int
1832 micromips_pc_insn_size (struct gdbarch *gdbarch, CORE_ADDR pc)
1833 {
1834   ULONGEST insn;
1835
1836   insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, NULL);
1837   return mips_insn_size (ISA_MICROMIPS, insn);
1838 }
1839
1840 /* Calculate the address of the next microMIPS instruction to execute
1841    after the INSN coprocessor 1 conditional branch instruction at the
1842    address PC.  COUNT denotes the number of coprocessor condition bits
1843    examined by the branch.  */
1844
1845 static CORE_ADDR
1846 micromips_bc1_pc (struct gdbarch *gdbarch, struct regcache *regcache,
1847                   ULONGEST insn, CORE_ADDR pc, int count)
1848 {
1849   int fcsr = mips_regnum (gdbarch)->fp_control_status;
1850   int cnum = b2s3_cc (insn >> 16) & (count - 1);
1851   int tf = b5s5_op (insn >> 16) & 1;
1852   int mask = (1 << count) - 1;
1853   ULONGEST fcs;
1854   int cond;
1855
1856   if (fcsr == -1)
1857     /* No way to handle; it'll most likely trap anyway.  */
1858     return pc;
1859
1860   fcs = regcache_raw_get_unsigned (regcache, fcsr);
1861   cond = ((fcs >> 24) & 0xfe) | ((fcs >> 23) & 0x01);
1862
1863   if (((cond >> cnum) & mask) != mask * !tf)
1864     pc += micromips_relative_offset16 (insn);
1865   else
1866     pc += micromips_pc_insn_size (gdbarch, pc);
1867
1868   return pc;
1869 }
1870
1871 /* Calculate the address of the next microMIPS instruction to execute
1872    after the instruction at the address PC.  */
1873
1874 static CORE_ADDR
1875 micromips_next_pc (struct regcache *regcache, CORE_ADDR pc)
1876 {
1877   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1878   ULONGEST insn;
1879
1880   insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, NULL);
1881   pc += MIPS_INSN16_SIZE;
1882   switch (mips_insn_size (ISA_MICROMIPS, insn))
1883     {
1884     /* 32-bit instructions.  */
1885     case 2 * MIPS_INSN16_SIZE:
1886       insn <<= 16;
1887       insn |= mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, NULL);
1888       pc += MIPS_INSN16_SIZE;
1889       switch (micromips_op (insn >> 16))
1890         {
1891         case 0x00: /* POOL32A: bits 000000 */
1892           if (b0s6_op (insn) == 0x3c
1893                                 /* POOL32Axf: bits 000000 ... 111100 */
1894               && (b6s10_ext (insn) & 0x2bf) == 0x3c)
1895                                 /* JALR, JALR.HB: 000000 000x111100 111100 */
1896                                 /* JALRS, JALRS.HB: 000000 010x111100 111100 */
1897             pc = regcache_raw_get_signed (regcache, b0s5_reg (insn >> 16));
1898           break;
1899
1900         case 0x10: /* POOL32I: bits 010000 */
1901           switch (b5s5_op (insn >> 16))
1902             {
1903             case 0x00: /* BLTZ: bits 010000 00000 */
1904             case 0x01: /* BLTZAL: bits 010000 00001 */
1905             case 0x11: /* BLTZALS: bits 010000 10001 */
1906               if (regcache_raw_get_signed (regcache,
1907                                            b0s5_reg (insn >> 16)) < 0)
1908                 pc += micromips_relative_offset16 (insn);
1909               else
1910                 pc += micromips_pc_insn_size (gdbarch, pc);
1911               break;
1912
1913             case 0x02: /* BGEZ: bits 010000 00010 */
1914             case 0x03: /* BGEZAL: bits 010000 00011 */
1915             case 0x13: /* BGEZALS: bits 010000 10011 */
1916               if (regcache_raw_get_signed (regcache,
1917                                            b0s5_reg (insn >> 16)) >= 0)
1918                 pc += micromips_relative_offset16 (insn);
1919               else
1920                 pc += micromips_pc_insn_size (gdbarch, pc);
1921               break;
1922
1923             case 0x04: /* BLEZ: bits 010000 00100 */
1924               if (regcache_raw_get_signed (regcache,
1925                                            b0s5_reg (insn >> 16)) <= 0)
1926                 pc += micromips_relative_offset16 (insn);
1927               else
1928                 pc += micromips_pc_insn_size (gdbarch, pc);
1929               break;
1930
1931             case 0x05: /* BNEZC: bits 010000 00101 */
1932               if (regcache_raw_get_signed (regcache,
1933                                            b0s5_reg (insn >> 16)) != 0)
1934                 pc += micromips_relative_offset16 (insn);
1935               break;
1936
1937             case 0x06: /* BGTZ: bits 010000 00110 */
1938               if (regcache_raw_get_signed (regcache,
1939                                            b0s5_reg (insn >> 16)) > 0)
1940                 pc += micromips_relative_offset16 (insn);
1941               else
1942                 pc += micromips_pc_insn_size (gdbarch, pc);
1943               break;
1944
1945             case 0x07: /* BEQZC: bits 010000 00111 */
1946               if (regcache_raw_get_signed (regcache,
1947                                            b0s5_reg (insn >> 16)) == 0)
1948                 pc += micromips_relative_offset16 (insn);
1949               break;
1950
1951             case 0x14: /* BC2F: bits 010000 10100 xxx00 */
1952             case 0x15: /* BC2T: bits 010000 10101 xxx00 */
1953               if (((insn >> 16) & 0x3) == 0x0)
1954                 /* BC2F, BC2T: don't know how to handle these.  */
1955                 break;
1956               break;
1957
1958             case 0x1a: /* BPOSGE64: bits 010000 11010 */
1959             case 0x1b: /* BPOSGE32: bits 010000 11011 */
1960               {
1961                 unsigned int pos = (b5s5_op (insn >> 16) & 1) ? 32 : 64;
1962                 int dspctl = mips_regnum (gdbarch)->dspctl;
1963
1964                 if (dspctl == -1)
1965                   /* No way to handle; it'll most likely trap anyway.  */
1966                   break;
1967
1968                 if ((regcache_raw_get_unsigned (regcache,
1969                                                 dspctl) & 0x7f) >= pos)
1970                   pc += micromips_relative_offset16 (insn);
1971                 else
1972                   pc += micromips_pc_insn_size (gdbarch, pc);
1973               }
1974               break;
1975
1976             case 0x1c: /* BC1F: bits 010000 11100 xxx00 */
1977                        /* BC1ANY2F: bits 010000 11100 xxx01 */
1978             case 0x1d: /* BC1T: bits 010000 11101 xxx00 */
1979                        /* BC1ANY2T: bits 010000 11101 xxx01 */
1980               if (((insn >> 16) & 0x2) == 0x0)
1981                 pc = micromips_bc1_pc (gdbarch, regcache, insn, pc,
1982                                        ((insn >> 16) & 0x1) + 1);
1983               break;
1984
1985             case 0x1e: /* BC1ANY4F: bits 010000 11110 xxx01 */
1986             case 0x1f: /* BC1ANY4T: bits 010000 11111 xxx01 */
1987               if (((insn >> 16) & 0x3) == 0x1)
1988                 pc = micromips_bc1_pc (gdbarch, regcache, insn, pc, 4);
1989               break;
1990             }
1991           break;
1992
1993         case 0x1d: /* JALS: bits 011101 */
1994         case 0x35: /* J: bits 110101 */
1995         case 0x3d: /* JAL: bits 111101 */
1996             pc = ((pc | 0x7fffffe) ^ 0x7fffffe) | (b0s26_imm (insn) << 1);
1997           break;
1998
1999         case 0x25: /* BEQ: bits 100101 */
2000             if (regcache_raw_get_signed (regcache, b0s5_reg (insn >> 16))
2001                 == regcache_raw_get_signed (regcache, b5s5_reg (insn >> 16)))
2002               pc += micromips_relative_offset16 (insn);
2003             else
2004               pc += micromips_pc_insn_size (gdbarch, pc);
2005           break;
2006
2007         case 0x2d: /* BNE: bits 101101 */
2008           if (regcache_raw_get_signed (regcache, b0s5_reg (insn >> 16))
2009                 != regcache_raw_get_signed (regcache, b5s5_reg (insn >> 16)))
2010               pc += micromips_relative_offset16 (insn);
2011             else
2012               pc += micromips_pc_insn_size (gdbarch, pc);
2013           break;
2014
2015         case 0x3c: /* JALX: bits 111100 */
2016             pc = ((pc | 0xfffffff) ^ 0xfffffff) | (b0s26_imm (insn) << 2);
2017           break;
2018         }
2019       break;
2020
2021     /* 16-bit instructions.  */
2022     case MIPS_INSN16_SIZE:
2023       switch (micromips_op (insn))
2024         {
2025         case 0x11: /* POOL16C: bits 010001 */
2026           if ((b5s5_op (insn) & 0x1c) == 0xc)
2027             /* JR16, JRC, JALR16, JALRS16: 010001 011xx */
2028             pc = regcache_raw_get_signed (regcache, b0s5_reg (insn));
2029           else if (b5s5_op (insn) == 0x18)
2030             /* JRADDIUSP: bits 010001 11000 */
2031             pc = regcache_raw_get_signed (regcache, MIPS_RA_REGNUM);
2032           break;
2033
2034         case 0x23: /* BEQZ16: bits 100011 */
2035           {
2036             int rs = mips_reg3_to_reg[b7s3_reg (insn)];
2037
2038             if (regcache_raw_get_signed (regcache, rs) == 0)
2039               pc += micromips_relative_offset7 (insn);
2040             else
2041               pc += micromips_pc_insn_size (gdbarch, pc);
2042           }
2043           break;
2044
2045         case 0x2b: /* BNEZ16: bits 101011 */
2046           {
2047             int rs = mips_reg3_to_reg[b7s3_reg (insn)];
2048
2049             if (regcache_raw_get_signed (regcache, rs) != 0)
2050               pc += micromips_relative_offset7 (insn);
2051             else
2052               pc += micromips_pc_insn_size (gdbarch, pc);
2053           }
2054           break;
2055
2056         case 0x33: /* B16: bits 110011 */
2057           pc += micromips_relative_offset10 (insn);
2058           break;
2059         }
2060       break;
2061     }
2062
2063   return pc;
2064 }
2065
2066 /* Decoding the next place to set a breakpoint is irregular for the
2067    mips 16 variant, but fortunately, there fewer instructions.  We have
2068    to cope ith extensions for 16 bit instructions and a pair of actual
2069    32 bit instructions.  We dont want to set a single step instruction
2070    on the extend instruction either.  */
2071
2072 /* Lots of mips16 instruction formats */
2073 /* Predicting jumps requires itype,ritype,i8type
2074    and their extensions      extItype,extritype,extI8type.  */
2075 enum mips16_inst_fmts
2076 {
2077   itype,                        /* 0  immediate 5,10 */
2078   ritype,                       /* 1   5,3,8 */
2079   rrtype,                       /* 2   5,3,3,5 */
2080   rritype,                      /* 3   5,3,3,5 */
2081   rrrtype,                      /* 4   5,3,3,3,2 */
2082   rriatype,                     /* 5   5,3,3,1,4 */
2083   shifttype,                    /* 6   5,3,3,3,2 */
2084   i8type,                       /* 7   5,3,8 */
2085   i8movtype,                    /* 8   5,3,3,5 */
2086   i8mov32rtype,                 /* 9   5,3,5,3 */
2087   i64type,                      /* 10  5,3,8 */
2088   ri64type,                     /* 11  5,3,3,5 */
2089   jalxtype,                     /* 12  5,1,5,5,16 - a 32 bit instruction */
2090   exiItype,                     /* 13  5,6,5,5,1,1,1,1,1,1,5 */
2091   extRitype,                    /* 14  5,6,5,5,3,1,1,1,5 */
2092   extRRItype,                   /* 15  5,5,5,5,3,3,5 */
2093   extRRIAtype,                  /* 16  5,7,4,5,3,3,1,4 */
2094   EXTshifttype,                 /* 17  5,5,1,1,1,1,1,1,5,3,3,1,1,1,2 */
2095   extI8type,                    /* 18  5,6,5,5,3,1,1,1,5 */
2096   extI64type,                   /* 19  5,6,5,5,3,1,1,1,5 */
2097   extRi64type,                  /* 20  5,6,5,5,3,3,5 */
2098   extshift64type                /* 21  5,5,1,1,1,1,1,1,5,1,1,1,3,5 */
2099 };
2100 /* I am heaping all the fields of the formats into one structure and
2101    then, only the fields which are involved in instruction extension.  */
2102 struct upk_mips16
2103 {
2104   CORE_ADDR offset;
2105   unsigned int regx;            /* Function in i8 type.  */
2106   unsigned int regy;
2107 };
2108
2109
2110 /* The EXT-I, EXT-ri nad EXT-I8 instructions all have the same format
2111    for the bits which make up the immediate extension.  */
2112
2113 static CORE_ADDR
2114 extended_offset (unsigned int extension)
2115 {
2116   CORE_ADDR value;
2117
2118   value = (extension >> 16) & 0x1f;     /* Extract 15:11.  */
2119   value = value << 6;
2120   value |= (extension >> 21) & 0x3f;    /* Extract 10:5.  */
2121   value = value << 5;
2122   value |= extension & 0x1f;            /* Extract 4:0.  */
2123
2124   return value;
2125 }
2126
2127 /* Only call this function if you know that this is an extendable
2128    instruction.  It won't malfunction, but why make excess remote memory
2129    references?  If the immediate operands get sign extended or something,
2130    do it after the extension is performed.  */
2131 /* FIXME: Every one of these cases needs to worry about sign extension
2132    when the offset is to be used in relative addressing.  */
2133
2134 static unsigned int
2135 fetch_mips_16 (struct gdbarch *gdbarch, CORE_ADDR pc)
2136 {
2137   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2138   gdb_byte buf[8];
2139
2140   pc = unmake_compact_addr (pc);        /* Clear the low order bit.  */
2141   target_read_memory (pc, buf, 2);
2142   return extract_unsigned_integer (buf, 2, byte_order);
2143 }
2144
2145 static void
2146 unpack_mips16 (struct gdbarch *gdbarch, CORE_ADDR pc,
2147                unsigned int extension,
2148                unsigned int inst,
2149                enum mips16_inst_fmts insn_format, struct upk_mips16 *upk)
2150 {
2151   CORE_ADDR offset;
2152   int regx;
2153   int regy;
2154   switch (insn_format)
2155     {
2156     case itype:
2157       {
2158         CORE_ADDR value;
2159         if (extension)
2160           {
2161             value = extended_offset ((extension << 16) | inst);
2162             value = (value ^ 0x8000) - 0x8000;          /* Sign-extend.  */
2163           }
2164         else
2165           {
2166             value = inst & 0x7ff;
2167             value = (value ^ 0x400) - 0x400;            /* Sign-extend.  */
2168           }
2169         offset = value;
2170         regx = -1;
2171         regy = -1;
2172       }
2173       break;
2174     case ritype:
2175     case i8type:
2176       {                         /* A register identifier and an offset.  */
2177         /* Most of the fields are the same as I type but the
2178            immediate value is of a different length.  */
2179         CORE_ADDR value;
2180         if (extension)
2181           {
2182             value = extended_offset ((extension << 16) | inst);
2183             value = (value ^ 0x8000) - 0x8000;          /* Sign-extend.  */
2184           }
2185         else
2186           {
2187             value = inst & 0xff;                        /* 8 bits */
2188             value = (value ^ 0x80) - 0x80;              /* Sign-extend.  */
2189           }
2190         offset = value;
2191         regx = (inst >> 8) & 0x07;                      /* i8 funct */
2192         regy = -1;
2193         break;
2194       }
2195     case jalxtype:
2196       {
2197         unsigned long value;
2198         unsigned int nexthalf;
2199         value = ((inst & 0x1f) << 5) | ((inst >> 5) & 0x1f);
2200         value = value << 16;
2201         nexthalf = mips_fetch_instruction (gdbarch, ISA_MIPS16, pc + 2, NULL);
2202                                                 /* Low bit still set.  */
2203         value |= nexthalf;
2204         offset = value;
2205         regx = -1;
2206         regy = -1;
2207         break;
2208       }
2209     default:
2210       internal_error (__FILE__, __LINE__, _("bad switch"));
2211     }
2212   upk->offset = offset;
2213   upk->regx = regx;
2214   upk->regy = regy;
2215 }
2216
2217
2218 /* Calculate the destination of a branch whose 16-bit opcode word is at PC,
2219    and having a signed 16-bit OFFSET.  */
2220
2221 static CORE_ADDR
2222 add_offset_16 (CORE_ADDR pc, int offset)
2223 {
2224   return pc + (offset << 1) + 2;
2225 }
2226
2227 static CORE_ADDR
2228 extended_mips16_next_pc (regcache *regcache, CORE_ADDR pc,
2229                          unsigned int extension, unsigned int insn)
2230 {
2231   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2232   int op = (insn >> 11);
2233   switch (op)
2234     {
2235     case 2:                     /* Branch */
2236       {
2237         struct upk_mips16 upk;
2238         unpack_mips16 (gdbarch, pc, extension, insn, itype, &upk);
2239         pc = add_offset_16 (pc, upk.offset);
2240         break;
2241       }
2242     case 3:                     /* JAL , JALX - Watch out, these are 32 bit
2243                                    instructions.  */
2244       {
2245         struct upk_mips16 upk;
2246         unpack_mips16 (gdbarch, pc, extension, insn, jalxtype, &upk);
2247         pc = ((pc + 2) & (~(CORE_ADDR) 0x0fffffff)) | (upk.offset << 2);
2248         if ((insn >> 10) & 0x01)        /* Exchange mode */
2249           pc = pc & ~0x01;      /* Clear low bit, indicate 32 bit mode.  */
2250         else
2251           pc |= 0x01;
2252         break;
2253       }
2254     case 4:                     /* beqz */
2255       {
2256         struct upk_mips16 upk;
2257         int reg;
2258         unpack_mips16 (gdbarch, pc, extension, insn, ritype, &upk);
2259         reg = regcache_raw_get_signed (regcache, mips_reg3_to_reg[upk.regx]);
2260         if (reg == 0)
2261           pc = add_offset_16 (pc, upk.offset);
2262         else
2263           pc += 2;
2264         break;
2265       }
2266     case 5:                     /* bnez */
2267       {
2268         struct upk_mips16 upk;
2269         int reg;
2270         unpack_mips16 (gdbarch, pc, extension, insn, ritype, &upk);
2271         reg = regcache_raw_get_signed (regcache, mips_reg3_to_reg[upk.regx]);
2272         if (reg != 0)
2273           pc = add_offset_16 (pc, upk.offset);
2274         else
2275           pc += 2;
2276         break;
2277       }
2278     case 12:                    /* I8 Formats btez btnez */
2279       {
2280         struct upk_mips16 upk;
2281         int reg;
2282         unpack_mips16 (gdbarch, pc, extension, insn, i8type, &upk);
2283         /* upk.regx contains the opcode */
2284         /* Test register is 24 */
2285         reg = regcache_raw_get_signed (regcache, 24);
2286         if (((upk.regx == 0) && (reg == 0))     /* BTEZ */
2287             || ((upk.regx == 1) && (reg != 0))) /* BTNEZ */
2288           pc = add_offset_16 (pc, upk.offset);
2289         else
2290           pc += 2;
2291         break;
2292       }
2293     case 29:                    /* RR Formats JR, JALR, JALR-RA */
2294       {
2295         struct upk_mips16 upk;
2296         /* upk.fmt = rrtype; */
2297         op = insn & 0x1f;
2298         if (op == 0)
2299           {
2300             int reg;
2301             upk.regx = (insn >> 8) & 0x07;
2302             upk.regy = (insn >> 5) & 0x07;
2303             if ((upk.regy & 1) == 0)
2304               reg = mips_reg3_to_reg[upk.regx];
2305             else
2306               reg = 31;         /* Function return instruction.  */
2307             pc = regcache_raw_get_signed (regcache, reg);
2308           }
2309         else
2310           pc += 2;
2311         break;
2312       }
2313     case 30:
2314       /* This is an instruction extension.  Fetch the real instruction
2315          (which follows the extension) and decode things based on
2316          that.  */
2317       {
2318         pc += 2;
2319         pc = extended_mips16_next_pc (regcache, pc, insn,
2320                                       fetch_mips_16 (gdbarch, pc));
2321         break;
2322       }
2323     default:
2324       {
2325         pc += 2;
2326         break;
2327       }
2328     }
2329   return pc;
2330 }
2331
2332 static CORE_ADDR
2333 mips16_next_pc (struct regcache *regcache, CORE_ADDR pc)
2334 {
2335   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2336   unsigned int insn = fetch_mips_16 (gdbarch, pc);
2337   return extended_mips16_next_pc (regcache, pc, 0, insn);
2338 }
2339
2340 /* The mips_next_pc function supports single_step when the remote
2341    target monitor or stub is not developed enough to do a single_step.
2342    It works by decoding the current instruction and predicting where a
2343    branch will go.  This isn't hard because all the data is available.
2344    The MIPS32, MIPS16 and microMIPS variants are quite different.  */
2345 static CORE_ADDR
2346 mips_next_pc (struct regcache *regcache, CORE_ADDR pc)
2347 {
2348   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2349
2350   if (mips_pc_is_mips16 (gdbarch, pc))
2351     return mips16_next_pc (regcache, pc);
2352   else if (mips_pc_is_micromips (gdbarch, pc))
2353     return micromips_next_pc (regcache, pc);
2354   else
2355     return mips32_next_pc (regcache, pc);
2356 }
2357
2358 /* Return non-zero if the MIPS16 instruction INSN is a compact branch
2359    or jump.  */
2360
2361 static int
2362 mips16_instruction_is_compact_branch (unsigned short insn)
2363 {
2364   switch (insn & 0xf800)
2365     {
2366     case 0xe800:
2367       return (insn & 0x009f) == 0x80;   /* JALRC/JRC */
2368     case 0x6000:
2369       return (insn & 0x0600) == 0;      /* BTNEZ/BTEQZ */
2370     case 0x2800:                        /* BNEZ */
2371     case 0x2000:                        /* BEQZ */
2372     case 0x1000:                        /* B */
2373       return 1;
2374     default:
2375       return 0;
2376     }
2377 }
2378
2379 /* Return non-zero if the microMIPS instruction INSN is a compact branch
2380    or jump.  */
2381
2382 static int
2383 micromips_instruction_is_compact_branch (unsigned short insn)
2384 {
2385   switch (micromips_op (insn))
2386     {
2387     case 0x11:                  /* POOL16C: bits 010001 */
2388       return (b5s5_op (insn) == 0x18
2389                                 /* JRADDIUSP: bits 010001 11000 */
2390               || b5s5_op (insn) == 0xd);
2391                                 /* JRC: bits 010011 01101 */
2392     case 0x10:                  /* POOL32I: bits 010000 */
2393       return (b5s5_op (insn) & 0x1d) == 0x5;
2394                                 /* BEQZC/BNEZC: bits 010000 001x1 */
2395     default:
2396       return 0;
2397     }
2398 }
2399
2400 struct mips_frame_cache
2401 {
2402   CORE_ADDR base;
2403   struct trad_frame_saved_reg *saved_regs;
2404 };
2405
2406 /* Set a register's saved stack address in temp_saved_regs.  If an
2407    address has already been set for this register, do nothing; this
2408    way we will only recognize the first save of a given register in a
2409    function prologue.
2410
2411    For simplicity, save the address in both [0 .. gdbarch_num_regs) and
2412    [gdbarch_num_regs .. 2*gdbarch_num_regs).
2413    Strictly speaking, only the second range is used as it is only second
2414    range (the ABI instead of ISA registers) that comes into play when finding
2415    saved registers in a frame.  */
2416
2417 static void
2418 set_reg_offset (struct gdbarch *gdbarch, struct mips_frame_cache *this_cache,
2419                 int regnum, CORE_ADDR offset)
2420 {
2421   if (this_cache != NULL
2422       && this_cache->saved_regs[regnum].addr == -1)
2423     {
2424       this_cache->saved_regs[regnum + 0 * gdbarch_num_regs (gdbarch)].addr
2425         = offset;
2426       this_cache->saved_regs[regnum + 1 * gdbarch_num_regs (gdbarch)].addr
2427         = offset;
2428     }
2429 }
2430
2431
2432 /* Fetch the immediate value from a MIPS16 instruction.
2433    If the previous instruction was an EXTEND, use it to extend
2434    the upper bits of the immediate value.  This is a helper function
2435    for mips16_scan_prologue.  */
2436
2437 static int
2438 mips16_get_imm (unsigned short prev_inst,       /* previous instruction */
2439                 unsigned short inst,    /* current instruction */
2440                 int nbits,      /* number of bits in imm field */
2441                 int scale,      /* scale factor to be applied to imm */
2442                 int is_signed)  /* is the imm field signed?  */
2443 {
2444   int offset;
2445
2446   if ((prev_inst & 0xf800) == 0xf000)   /* prev instruction was EXTEND? */
2447     {
2448       offset = ((prev_inst & 0x1f) << 11) | (prev_inst & 0x7e0);
2449       if (offset & 0x8000)      /* check for negative extend */
2450         offset = 0 - (0x10000 - (offset & 0xffff));
2451       return offset | (inst & 0x1f);
2452     }
2453   else
2454     {
2455       int max_imm = 1 << nbits;
2456       int mask = max_imm - 1;
2457       int sign_bit = max_imm >> 1;
2458
2459       offset = inst & mask;
2460       if (is_signed && (offset & sign_bit))
2461         offset = 0 - (max_imm - offset);
2462       return offset * scale;
2463     }
2464 }
2465
2466
2467 /* Analyze the function prologue from START_PC to LIMIT_PC. Builds
2468    the associated FRAME_CACHE if not null.
2469    Return the address of the first instruction past the prologue.  */
2470
2471 static CORE_ADDR
2472 mips16_scan_prologue (struct gdbarch *gdbarch,
2473                       CORE_ADDR start_pc, CORE_ADDR limit_pc,
2474                       struct frame_info *this_frame,
2475                       struct mips_frame_cache *this_cache)
2476 {
2477   int prev_non_prologue_insn = 0;
2478   int this_non_prologue_insn;
2479   int non_prologue_insns = 0;
2480   CORE_ADDR prev_pc;
2481   CORE_ADDR cur_pc;
2482   CORE_ADDR frame_addr = 0;     /* Value of $r17, used as frame pointer.  */
2483   CORE_ADDR sp;
2484   long frame_offset = 0;        /* Size of stack frame.  */
2485   long frame_adjust = 0;        /* Offset of FP from SP.  */
2486   int frame_reg = MIPS_SP_REGNUM;
2487   unsigned short prev_inst = 0; /* saved copy of previous instruction.  */
2488   unsigned inst = 0;            /* current instruction */
2489   unsigned entry_inst = 0;      /* the entry instruction */
2490   unsigned save_inst = 0;       /* the save instruction */
2491   int prev_delay_slot = 0;
2492   int in_delay_slot;
2493   int reg, offset;
2494
2495   int extend_bytes = 0;
2496   int prev_extend_bytes = 0;
2497   CORE_ADDR end_prologue_addr;
2498
2499   /* Can be called when there's no process, and hence when there's no
2500      THIS_FRAME.  */
2501   if (this_frame != NULL)
2502     sp = get_frame_register_signed (this_frame,
2503                                     gdbarch_num_regs (gdbarch)
2504                                     + MIPS_SP_REGNUM);
2505   else
2506     sp = 0;
2507
2508   if (limit_pc > start_pc + 200)
2509     limit_pc = start_pc + 200;
2510   prev_pc = start_pc;
2511
2512   /* Permit at most one non-prologue non-control-transfer instruction
2513      in the middle which may have been reordered by the compiler for
2514      optimisation.  */
2515   for (cur_pc = start_pc; cur_pc < limit_pc; cur_pc += MIPS_INSN16_SIZE)
2516     {
2517       this_non_prologue_insn = 0;
2518       in_delay_slot = 0;
2519
2520       /* Save the previous instruction.  If it's an EXTEND, we'll extract
2521          the immediate offset extension from it in mips16_get_imm.  */
2522       prev_inst = inst;
2523
2524       /* Fetch and decode the instruction.  */
2525       inst = (unsigned short) mips_fetch_instruction (gdbarch, ISA_MIPS16,
2526                                                       cur_pc, NULL);
2527
2528       /* Normally we ignore extend instructions.  However, if it is
2529          not followed by a valid prologue instruction, then this
2530          instruction is not part of the prologue either.  We must
2531          remember in this case to adjust the end_prologue_addr back
2532          over the extend.  */
2533       if ((inst & 0xf800) == 0xf000)    /* extend */
2534         {
2535           extend_bytes = MIPS_INSN16_SIZE;
2536           continue;
2537         }
2538
2539       prev_extend_bytes = extend_bytes;
2540       extend_bytes = 0;
2541
2542       if ((inst & 0xff00) == 0x6300     /* addiu sp */
2543           || (inst & 0xff00) == 0xfb00) /* daddiu sp */
2544         {
2545           offset = mips16_get_imm (prev_inst, inst, 8, 8, 1);
2546           if (offset < 0)       /* Negative stack adjustment?  */
2547             frame_offset -= offset;
2548           else
2549             /* Exit loop if a positive stack adjustment is found, which
2550                usually means that the stack cleanup code in the function
2551                epilogue is reached.  */
2552             break;
2553         }
2554       else if ((inst & 0xf800) == 0xd000)       /* sw reg,n($sp) */
2555         {
2556           offset = mips16_get_imm (prev_inst, inst, 8, 4, 0);
2557           reg = mips_reg3_to_reg[(inst & 0x700) >> 8];
2558           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2559         }
2560       else if ((inst & 0xff00) == 0xf900)       /* sd reg,n($sp) */
2561         {
2562           offset = mips16_get_imm (prev_inst, inst, 5, 8, 0);
2563           reg = mips_reg3_to_reg[(inst & 0xe0) >> 5];
2564           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2565         }
2566       else if ((inst & 0xff00) == 0x6200)       /* sw $ra,n($sp) */
2567         {
2568           offset = mips16_get_imm (prev_inst, inst, 8, 4, 0);
2569           set_reg_offset (gdbarch, this_cache, MIPS_RA_REGNUM, sp + offset);
2570         }
2571       else if ((inst & 0xff00) == 0xfa00)       /* sd $ra,n($sp) */
2572         {
2573           offset = mips16_get_imm (prev_inst, inst, 8, 8, 0);
2574           set_reg_offset (gdbarch, this_cache, MIPS_RA_REGNUM, sp + offset);
2575         }
2576       else if (inst == 0x673d)  /* move $s1, $sp */
2577         {
2578           frame_addr = sp;
2579           frame_reg = 17;
2580         }
2581       else if ((inst & 0xff00) == 0x0100)       /* addiu $s1,sp,n */
2582         {
2583           offset = mips16_get_imm (prev_inst, inst, 8, 4, 0);
2584           frame_addr = sp + offset;
2585           frame_reg = 17;
2586           frame_adjust = offset;
2587         }
2588       else if ((inst & 0xFF00) == 0xd900)       /* sw reg,offset($s1) */
2589         {
2590           offset = mips16_get_imm (prev_inst, inst, 5, 4, 0);
2591           reg = mips_reg3_to_reg[(inst & 0xe0) >> 5];
2592           set_reg_offset (gdbarch, this_cache, reg, frame_addr + offset);
2593         }
2594       else if ((inst & 0xFF00) == 0x7900)       /* sd reg,offset($s1) */
2595         {
2596           offset = mips16_get_imm (prev_inst, inst, 5, 8, 0);
2597           reg = mips_reg3_to_reg[(inst & 0xe0) >> 5];
2598           set_reg_offset (gdbarch, this_cache, reg, frame_addr + offset);
2599         }
2600       else if ((inst & 0xf81f) == 0xe809
2601                && (inst & 0x700) != 0x700)      /* entry */
2602         entry_inst = inst;      /* Save for later processing.  */
2603       else if ((inst & 0xff80) == 0x6480)       /* save */
2604         {
2605           save_inst = inst;     /* Save for later processing.  */
2606           if (prev_extend_bytes)                /* extend */
2607             save_inst |= prev_inst << 16;
2608         }
2609       else if ((inst & 0xff1c) == 0x6704)       /* move reg,$a0-$a3 */
2610         {
2611           /* This instruction is part of the prologue, but we don't
2612              need to do anything special to handle it.  */
2613         }
2614       else if (mips16_instruction_has_delay_slot (inst, 0))
2615                                                 /* JAL/JALR/JALX/JR */
2616         {
2617           /* The instruction in the delay slot can be a part
2618              of the prologue, so move forward once more.  */
2619           in_delay_slot = 1;
2620           if (mips16_instruction_has_delay_slot (inst, 1))
2621                                                 /* JAL/JALX */
2622             {
2623               prev_extend_bytes = MIPS_INSN16_SIZE;
2624               cur_pc += MIPS_INSN16_SIZE;       /* 32-bit instruction */
2625             }
2626         }
2627       else
2628         {
2629           this_non_prologue_insn = 1;
2630         }
2631
2632       non_prologue_insns += this_non_prologue_insn;
2633
2634       /* A jump or branch, or enough non-prologue insns seen?  If so,
2635          then we must have reached the end of the prologue by now.  */
2636       if (prev_delay_slot || non_prologue_insns > 1
2637           || mips16_instruction_is_compact_branch (inst))
2638         break;
2639
2640       prev_non_prologue_insn = this_non_prologue_insn;
2641       prev_delay_slot = in_delay_slot;
2642       prev_pc = cur_pc - prev_extend_bytes;
2643     }
2644
2645   /* The entry instruction is typically the first instruction in a function,
2646      and it stores registers at offsets relative to the value of the old SP
2647      (before the prologue).  But the value of the sp parameter to this
2648      function is the new SP (after the prologue has been executed).  So we
2649      can't calculate those offsets until we've seen the entire prologue,
2650      and can calculate what the old SP must have been.  */
2651   if (entry_inst != 0)
2652     {
2653       int areg_count = (entry_inst >> 8) & 7;
2654       int sreg_count = (entry_inst >> 6) & 3;
2655
2656       /* The entry instruction always subtracts 32 from the SP.  */
2657       frame_offset += 32;
2658
2659       /* Now we can calculate what the SP must have been at the
2660          start of the function prologue.  */
2661       sp += frame_offset;
2662
2663       /* Check if a0-a3 were saved in the caller's argument save area.  */
2664       for (reg = 4, offset = 0; reg < areg_count + 4; reg++)
2665         {
2666           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2667           offset += mips_abi_regsize (gdbarch);
2668         }
2669
2670       /* Check if the ra register was pushed on the stack.  */
2671       offset = -4;
2672       if (entry_inst & 0x20)
2673         {
2674           set_reg_offset (gdbarch, this_cache, MIPS_RA_REGNUM, sp + offset);
2675           offset -= mips_abi_regsize (gdbarch);
2676         }
2677
2678       /* Check if the s0 and s1 registers were pushed on the stack.  */
2679       for (reg = 16; reg < sreg_count + 16; reg++)
2680         {
2681           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2682           offset -= mips_abi_regsize (gdbarch);
2683         }
2684     }
2685
2686   /* The SAVE instruction is similar to ENTRY, except that defined by the
2687      MIPS16e ASE of the MIPS Architecture.  Unlike with ENTRY though, the
2688      size of the frame is specified as an immediate field of instruction
2689      and an extended variation exists which lets additional registers and
2690      frame space to be specified.  The instruction always treats registers
2691      as 32-bit so its usefulness for 64-bit ABIs is questionable.  */
2692   if (save_inst != 0 && mips_abi_regsize (gdbarch) == 4)
2693     {
2694       static int args_table[16] = {
2695         0, 0, 0, 0, 1, 1, 1, 1,
2696         2, 2, 2, 0, 3, 3, 4, -1,
2697       };
2698       static int astatic_table[16] = {
2699         0, 1, 2, 3, 0, 1, 2, 3,
2700         0, 1, 2, 4, 0, 1, 0, -1,
2701       };
2702       int aregs = (save_inst >> 16) & 0xf;
2703       int xsregs = (save_inst >> 24) & 0x7;
2704       int args = args_table[aregs];
2705       int astatic = astatic_table[aregs];
2706       long frame_size;
2707
2708       if (args < 0)
2709         {
2710           warning (_("Invalid number of argument registers encoded in SAVE."));
2711           args = 0;
2712         }
2713       if (astatic < 0)
2714         {
2715           warning (_("Invalid number of static registers encoded in SAVE."));
2716           astatic = 0;
2717         }
2718
2719       /* For standard SAVE the frame size of 0 means 128.  */
2720       frame_size = ((save_inst >> 16) & 0xf0) | (save_inst & 0xf);
2721       if (frame_size == 0 && (save_inst >> 16) == 0)
2722         frame_size = 16;
2723       frame_size *= 8;
2724       frame_offset += frame_size;
2725
2726       /* Now we can calculate what the SP must have been at the
2727          start of the function prologue.  */
2728       sp += frame_offset;
2729
2730       /* Check if A0-A3 were saved in the caller's argument save area.  */
2731       for (reg = MIPS_A0_REGNUM, offset = 0; reg < args + 4; reg++)
2732         {
2733           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2734           offset += mips_abi_regsize (gdbarch);
2735         }
2736
2737       offset = -4;
2738
2739       /* Check if the RA register was pushed on the stack.  */
2740       if (save_inst & 0x40)
2741         {
2742           set_reg_offset (gdbarch, this_cache, MIPS_RA_REGNUM, sp + offset);
2743           offset -= mips_abi_regsize (gdbarch);
2744         }
2745
2746       /* Check if the S8 register was pushed on the stack.  */
2747       if (xsregs > 6)
2748         {
2749           set_reg_offset (gdbarch, this_cache, 30, sp + offset);
2750           offset -= mips_abi_regsize (gdbarch);
2751           xsregs--;
2752         }
2753       /* Check if S2-S7 were pushed on the stack.  */
2754       for (reg = 18 + xsregs - 1; reg > 18 - 1; reg--)
2755         {
2756           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2757           offset -= mips_abi_regsize (gdbarch);
2758         }
2759
2760       /* Check if the S1 register was pushed on the stack.  */
2761       if (save_inst & 0x10)
2762         {
2763           set_reg_offset (gdbarch, this_cache, 17, sp + offset);
2764           offset -= mips_abi_regsize (gdbarch);
2765         }
2766       /* Check if the S0 register was pushed on the stack.  */
2767       if (save_inst & 0x20)
2768         {
2769           set_reg_offset (gdbarch, this_cache, 16, sp + offset);
2770           offset -= mips_abi_regsize (gdbarch);
2771         }
2772
2773       /* Check if A0-A3 were pushed on the stack.  */
2774       for (reg = MIPS_A0_REGNUM + 3; reg > MIPS_A0_REGNUM + 3 - astatic; reg--)
2775         {
2776           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2777           offset -= mips_abi_regsize (gdbarch);
2778         }
2779     }
2780
2781   if (this_cache != NULL)
2782     {
2783       this_cache->base =
2784         (get_frame_register_signed (this_frame,
2785                                     gdbarch_num_regs (gdbarch) + frame_reg)
2786          + frame_offset - frame_adjust);
2787       /* FIXME: brobecker/2004-10-10: Just as in the mips32 case, we should
2788          be able to get rid of the assignment below, evetually.  But it's
2789          still needed for now.  */
2790       this_cache->saved_regs[gdbarch_num_regs (gdbarch)
2791                              + mips_regnum (gdbarch)->pc]
2792         = this_cache->saved_regs[gdbarch_num_regs (gdbarch) + MIPS_RA_REGNUM];
2793     }
2794
2795   /* Set end_prologue_addr to the address of the instruction immediately
2796      after the last one we scanned.  Unless the last one looked like a
2797      non-prologue instruction (and we looked ahead), in which case use
2798      its address instead.  */
2799   end_prologue_addr = (prev_non_prologue_insn || prev_delay_slot
2800                        ? prev_pc : cur_pc - prev_extend_bytes);
2801
2802   return end_prologue_addr;
2803 }
2804
2805 /* Heuristic unwinder for 16-bit MIPS instruction set (aka MIPS16).
2806    Procedures that use the 32-bit instruction set are handled by the
2807    mips_insn32 unwinder.  */
2808
2809 static struct mips_frame_cache *
2810 mips_insn16_frame_cache (struct frame_info *this_frame, void **this_cache)
2811 {
2812   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2813   struct mips_frame_cache *cache;
2814
2815   if ((*this_cache) != NULL)
2816     return (struct mips_frame_cache *) (*this_cache);
2817   cache = FRAME_OBSTACK_ZALLOC (struct mips_frame_cache);
2818   (*this_cache) = cache;
2819   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2820
2821   /* Analyze the function prologue.  */
2822   {
2823     const CORE_ADDR pc = get_frame_address_in_block (this_frame);
2824     CORE_ADDR start_addr;
2825
2826     find_pc_partial_function (pc, NULL, &start_addr, NULL);
2827     if (start_addr == 0)
2828       start_addr = heuristic_proc_start (gdbarch, pc);
2829     /* We can't analyze the prologue if we couldn't find the begining
2830        of the function.  */
2831     if (start_addr == 0)
2832       return cache;
2833
2834     mips16_scan_prologue (gdbarch, start_addr, pc, this_frame,
2835                           (struct mips_frame_cache *) *this_cache);
2836   }
2837   
2838   /* gdbarch_sp_regnum contains the value and not the address.  */
2839   trad_frame_set_value (cache->saved_regs,
2840                         gdbarch_num_regs (gdbarch) + MIPS_SP_REGNUM,
2841                         cache->base);
2842
2843   return (struct mips_frame_cache *) (*this_cache);
2844 }
2845
2846 static void
2847 mips_insn16_frame_this_id (struct frame_info *this_frame, void **this_cache,
2848                            struct frame_id *this_id)
2849 {
2850   struct mips_frame_cache *info = mips_insn16_frame_cache (this_frame,
2851                                                            this_cache);
2852   /* This marks the outermost frame.  */
2853   if (info->base == 0)
2854     return;
2855   (*this_id) = frame_id_build (info->base, get_frame_func (this_frame));
2856 }
2857
2858 static struct value *
2859 mips_insn16_frame_prev_register (struct frame_info *this_frame,
2860                                  void **this_cache, int regnum)
2861 {
2862   struct mips_frame_cache *info = mips_insn16_frame_cache (this_frame,
2863                                                            this_cache);
2864   return trad_frame_get_prev_register (this_frame, info->saved_regs, regnum);
2865 }
2866
2867 static int
2868 mips_insn16_frame_sniffer (const struct frame_unwind *self,
2869                            struct frame_info *this_frame, void **this_cache)
2870 {
2871   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2872   CORE_ADDR pc = get_frame_pc (this_frame);
2873   if (mips_pc_is_mips16 (gdbarch, pc))
2874     return 1;
2875   return 0;
2876 }
2877
2878 static const struct frame_unwind mips_insn16_frame_unwind =
2879 {
2880   NORMAL_FRAME,
2881   default_frame_unwind_stop_reason,
2882   mips_insn16_frame_this_id,
2883   mips_insn16_frame_prev_register,
2884   NULL,
2885   mips_insn16_frame_sniffer
2886 };
2887
2888 static CORE_ADDR
2889 mips_insn16_frame_base_address (struct frame_info *this_frame,
2890                                 void **this_cache)
2891 {
2892   struct mips_frame_cache *info = mips_insn16_frame_cache (this_frame,
2893                                                            this_cache);
2894   return info->base;
2895 }
2896
2897 static const struct frame_base mips_insn16_frame_base =
2898 {
2899   &mips_insn16_frame_unwind,
2900   mips_insn16_frame_base_address,
2901   mips_insn16_frame_base_address,
2902   mips_insn16_frame_base_address
2903 };
2904
2905 static const struct frame_base *
2906 mips_insn16_frame_base_sniffer (struct frame_info *this_frame)
2907 {
2908   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2909   CORE_ADDR pc = get_frame_pc (this_frame);
2910   if (mips_pc_is_mips16 (gdbarch, pc))
2911     return &mips_insn16_frame_base;
2912   else
2913     return NULL;
2914 }
2915
2916 /* Decode a 9-bit signed immediate argument of ADDIUSP -- -2 is mapped
2917    to -258, -1 -- to -257, 0 -- to 256, 1 -- to 257 and other values are
2918    interpreted directly, and then multiplied by 4.  */
2919
2920 static int
2921 micromips_decode_imm9 (int imm)
2922 {
2923   imm = (imm ^ 0x100) - 0x100;
2924   if (imm > -3 && imm < 2)
2925     imm ^= 0x100;
2926   return imm << 2;
2927 }
2928
2929 /* Analyze the function prologue from START_PC to LIMIT_PC.  Return
2930    the address of the first instruction past the prologue.  */
2931
2932 static CORE_ADDR
2933 micromips_scan_prologue (struct gdbarch *gdbarch,
2934                          CORE_ADDR start_pc, CORE_ADDR limit_pc,
2935                          struct frame_info *this_frame,
2936                          struct mips_frame_cache *this_cache)
2937 {
2938   CORE_ADDR end_prologue_addr;
2939   int prev_non_prologue_insn = 0;
2940   int frame_reg = MIPS_SP_REGNUM;
2941   int this_non_prologue_insn;
2942   int non_prologue_insns = 0;
2943   long frame_offset = 0;        /* Size of stack frame.  */
2944   long frame_adjust = 0;        /* Offset of FP from SP.  */
2945   int prev_delay_slot = 0;
2946   int in_delay_slot;
2947   CORE_ADDR prev_pc;
2948   CORE_ADDR cur_pc;
2949   ULONGEST insn;                /* current instruction */
2950   CORE_ADDR sp;
2951   long offset;
2952   long sp_adj;
2953   long v1_off = 0;              /* The assumption is LUI will replace it.  */
2954   int reglist;
2955   int breg;
2956   int dreg;
2957   int sreg;
2958   int treg;
2959   int loc;
2960   int op;
2961   int s;
2962   int i;
2963
2964   /* Can be called when there's no process, and hence when there's no
2965      THIS_FRAME.  */
2966   if (this_frame != NULL)
2967     sp = get_frame_register_signed (this_frame,
2968                                     gdbarch_num_regs (gdbarch)
2969                                     + MIPS_SP_REGNUM);
2970   else
2971     sp = 0;
2972
2973   if (limit_pc > start_pc + 200)
2974     limit_pc = start_pc + 200;
2975   prev_pc = start_pc;
2976
2977   /* Permit at most one non-prologue non-control-transfer instruction
2978      in the middle which may have been reordered by the compiler for
2979      optimisation.  */
2980   for (cur_pc = start_pc; cur_pc < limit_pc; cur_pc += loc)
2981     {
2982       this_non_prologue_insn = 0;
2983       in_delay_slot = 0;
2984       sp_adj = 0;
2985       loc = 0;
2986       insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, cur_pc, NULL);
2987       loc += MIPS_INSN16_SIZE;
2988       switch (mips_insn_size (ISA_MICROMIPS, insn))
2989         {
2990         /* 32-bit instructions.  */
2991         case 2 * MIPS_INSN16_SIZE:
2992           insn <<= 16;
2993           insn |= mips_fetch_instruction (gdbarch,
2994                                           ISA_MICROMIPS, cur_pc + loc, NULL);
2995           loc += MIPS_INSN16_SIZE;
2996           switch (micromips_op (insn >> 16))
2997             {
2998             /* Record $sp/$fp adjustment.  */
2999             /* Discard (D)ADDU $gp,$jp used for PIC code.  */
3000             case 0x0: /* POOL32A: bits 000000 */
3001             case 0x16: /* POOL32S: bits 010110 */
3002               op = b0s11_op (insn);
3003               sreg = b0s5_reg (insn >> 16);
3004               treg = b5s5_reg (insn >> 16);
3005               dreg = b11s5_reg (insn);
3006               if (op == 0x1d0
3007                                 /* SUBU: bits 000000 00111010000 */
3008                                 /* DSUBU: bits 010110 00111010000 */
3009                   && dreg == MIPS_SP_REGNUM && sreg == MIPS_SP_REGNUM
3010                   && treg == 3)
3011                                 /* (D)SUBU $sp, $v1 */
3012                     sp_adj = v1_off;
3013               else if (op != 0x150
3014                                 /* ADDU: bits 000000 00101010000 */
3015                                 /* DADDU: bits 010110 00101010000 */
3016                        || dreg != 28 || sreg != 28 || treg != MIPS_T9_REGNUM)
3017                 this_non_prologue_insn = 1;
3018               break;
3019
3020             case 0x8: /* POOL32B: bits 001000 */
3021               op = b12s4_op (insn);
3022               breg = b0s5_reg (insn >> 16);
3023               reglist = sreg = b5s5_reg (insn >> 16);
3024               offset = (b0s12_imm (insn) ^ 0x800) - 0x800;
3025               if ((op == 0x9 || op == 0xc)
3026                                 /* SWP: bits 001000 1001 */
3027                                 /* SDP: bits 001000 1100 */
3028                   && breg == MIPS_SP_REGNUM && sreg < MIPS_RA_REGNUM)
3029                                 /* S[DW]P reg,offset($sp) */
3030                 {
3031                   s = 4 << ((b12s4_op (insn) & 0x4) == 0x4);
3032                   set_reg_offset (gdbarch, this_cache,
3033                                   sreg, sp + offset);
3034                   set_reg_offset (gdbarch, this_cache,
3035                                   sreg + 1, sp + offset + s);
3036                 }
3037               else if ((op == 0xd || op == 0xf)
3038                                 /* SWM: bits 001000 1101 */
3039                                 /* SDM: bits 001000 1111 */
3040                        && breg == MIPS_SP_REGNUM
3041                                 /* SWM reglist,offset($sp) */
3042                        && ((reglist >= 1 && reglist <= 9)
3043                            || (reglist >= 16 && reglist <= 25)))
3044                 {
3045                   int sreglist = std::min(reglist & 0xf, 8);
3046
3047                   s = 4 << ((b12s4_op (insn) & 0x2) == 0x2);
3048                   for (i = 0; i < sreglist; i++)
3049                     set_reg_offset (gdbarch, this_cache, 16 + i, sp + s * i);
3050                   if ((reglist & 0xf) > 8)
3051                     set_reg_offset (gdbarch, this_cache, 30, sp + s * i++);
3052                   if ((reglist & 0x10) == 0x10)
3053                     set_reg_offset (gdbarch, this_cache,
3054                                     MIPS_RA_REGNUM, sp + s * i++);
3055                 }
3056               else
3057                 this_non_prologue_insn = 1;
3058               break;
3059
3060             /* Record $sp/$fp adjustment.  */
3061             /* Discard (D)ADDIU $gp used for PIC code.  */
3062             case 0xc: /* ADDIU: bits 001100 */
3063             case 0x17: /* DADDIU: bits 010111 */
3064               sreg = b0s5_reg (insn >> 16);
3065               dreg = b5s5_reg (insn >> 16);
3066               offset = (b0s16_imm (insn) ^ 0x8000) - 0x8000;
3067               if (sreg == MIPS_SP_REGNUM && dreg == MIPS_SP_REGNUM)
3068                                 /* (D)ADDIU $sp, imm */
3069                 sp_adj = offset;
3070               else if (sreg == MIPS_SP_REGNUM && dreg == 30)
3071                                 /* (D)ADDIU $fp, $sp, imm */
3072                 {
3073                   frame_adjust = offset;
3074                   frame_reg = 30;
3075                 }
3076               else if (sreg != 28 || dreg != 28)
3077                                 /* (D)ADDIU $gp, imm */
3078                 this_non_prologue_insn = 1;
3079               break;
3080
3081             /* LUI $v1 is used for larger $sp adjustments.  */
3082             /* Discard LUI $gp used for PIC code.  */
3083             case 0x10: /* POOL32I: bits 010000 */
3084               if (b5s5_op (insn >> 16) == 0xd
3085                                 /* LUI: bits 010000 001101 */
3086                   && b0s5_reg (insn >> 16) == 3)
3087                                 /* LUI $v1, imm */
3088                 v1_off = ((b0s16_imm (insn) << 16) ^ 0x80000000) - 0x80000000;
3089               else if (b5s5_op (insn >> 16) != 0xd
3090                                 /* LUI: bits 010000 001101 */
3091                        || b0s5_reg (insn >> 16) != 28)
3092                                 /* LUI $gp, imm */
3093                 this_non_prologue_insn = 1;
3094               break;
3095
3096             /* ORI $v1 is used for larger $sp adjustments.  */
3097             case 0x14: /* ORI: bits 010100 */
3098               sreg = b0s5_reg (insn >> 16);
3099               dreg = b5s5_reg (insn >> 16);
3100               if (sreg == 3 && dreg == 3)
3101                                 /* ORI $v1, imm */
3102                 v1_off |= b0s16_imm (insn);
3103               else
3104                 this_non_prologue_insn = 1;
3105               break;
3106
3107             case 0x26: /* SWC1: bits 100110 */
3108             case 0x2e: /* SDC1: bits 101110 */
3109               breg = b0s5_reg (insn >> 16);
3110               if (breg != MIPS_SP_REGNUM)
3111                                 /* S[DW]C1 reg,offset($sp) */
3112                 this_non_prologue_insn = 1;
3113               break;
3114
3115             case 0x36: /* SD: bits 110110 */
3116             case 0x3e: /* SW: bits 111110 */
3117               breg = b0s5_reg (insn >> 16);
3118               sreg = b5s5_reg (insn >> 16);
3119               offset = (b0s16_imm (insn) ^ 0x8000) - 0x8000;
3120               if (breg == MIPS_SP_REGNUM)
3121                                 /* S[DW] reg,offset($sp) */
3122                 set_reg_offset (gdbarch, this_cache, sreg, sp + offset);
3123               else
3124                 this_non_prologue_insn = 1;
3125               break;
3126
3127             default:
3128               /* The instruction in the delay slot can be a part
3129                  of the prologue, so move forward once more.  */
3130               if (micromips_instruction_has_delay_slot (insn, 0))
3131                 in_delay_slot = 1;
3132               else
3133                 this_non_prologue_insn = 1;
3134               break;
3135             }
3136           insn >>= 16;
3137           break;
3138
3139         /* 16-bit instructions.  */
3140         case MIPS_INSN16_SIZE:
3141           switch (micromips_op (insn))
3142             {
3143             case 0x3: /* MOVE: bits 000011 */
3144               sreg = b0s5_reg (insn);
3145               dreg = b5s5_reg (insn);
3146               if (sreg == MIPS_SP_REGNUM && dreg == 30)
3147                                 /* MOVE  $fp, $sp */
3148                 frame_reg = 30;
3149               else if ((sreg & 0x1c) != 0x4)
3150                                 /* MOVE  reg, $a0-$a3 */
3151                 this_non_prologue_insn = 1;
3152               break;
3153
3154             case 0x11: /* POOL16C: bits 010001 */
3155               if (b6s4_op (insn) == 0x5)
3156                                 /* SWM: bits 010001 0101 */
3157                 {
3158                   offset = ((b0s4_imm (insn) << 2) ^ 0x20) - 0x20;
3159                   reglist = b4s2_regl (insn);
3160                   for (i = 0; i <= reglist; i++)
3161                     set_reg_offset (gdbarch, this_cache, 16 + i, sp + 4 * i);
3162                   set_reg_offset (gdbarch, this_cache,
3163                                   MIPS_RA_REGNUM, sp + 4 * i++);
3164                 }
3165               else
3166                 this_non_prologue_insn = 1;
3167               break;
3168
3169             case 0x13: /* POOL16D: bits 010011 */
3170               if ((insn & 0x1) == 0x1)
3171                                 /* ADDIUSP: bits 010011 1 */
3172                 sp_adj = micromips_decode_imm9 (b1s9_imm (insn));
3173               else if (b5s5_reg (insn) == MIPS_SP_REGNUM)
3174                                 /* ADDIUS5: bits 010011 0 */
3175                                 /* ADDIUS5 $sp, imm */
3176                 sp_adj = (b1s4_imm (insn) ^ 8) - 8;
3177               else
3178                 this_non_prologue_insn = 1;
3179               break;
3180
3181             case 0x32: /* SWSP: bits 110010 */
3182               offset = b0s5_imm (insn) << 2;
3183               sreg = b5s5_reg (insn);
3184               set_reg_offset (gdbarch, this_cache, sreg, sp + offset);
3185               break;
3186
3187             default:
3188               /* The instruction in the delay slot can be a part
3189                  of the prologue, so move forward once more.  */
3190               if (micromips_instruction_has_delay_slot (insn << 16, 0))
3191                 in_delay_slot = 1;
3192               else
3193                 this_non_prologue_insn = 1;
3194               break;
3195             }
3196           break;
3197         }
3198       if (sp_adj < 0)
3199         frame_offset -= sp_adj;
3200
3201       non_prologue_insns += this_non_prologue_insn;
3202
3203       /* A jump or branch, enough non-prologue insns seen or positive
3204          stack adjustment?  If so, then we must have reached the end
3205          of the prologue by now.  */
3206       if (prev_delay_slot || non_prologue_insns > 1 || sp_adj > 0
3207           || micromips_instruction_is_compact_branch (insn))
3208         break;
3209
3210       prev_non_prologue_insn = this_non_prologue_insn;
3211       prev_delay_slot = in_delay_slot;
3212       prev_pc = cur_pc;
3213     }
3214
3215   if (this_cache != NULL)
3216     {
3217       this_cache->base =
3218         (get_frame_register_signed (this_frame,
3219                                     gdbarch_num_regs (gdbarch) + frame_reg)
3220          + frame_offset - frame_adjust);
3221       /* FIXME: brobecker/2004-10-10: Just as in the mips32 case, we should
3222          be able to get rid of the assignment below, evetually. But it's
3223          still needed for now.  */
3224       this_cache->saved_regs[gdbarch_num_regs (gdbarch)
3225                              + mips_regnum (gdbarch)->pc]
3226         = this_cache->saved_regs[gdbarch_num_regs (gdbarch) + MIPS_RA_REGNUM];
3227     }
3228
3229   /* Set end_prologue_addr to the address of the instruction immediately
3230      after the last one we scanned.  Unless the last one looked like a
3231      non-prologue instruction (and we looked ahead), in which case use
3232      its address instead.  */
3233   end_prologue_addr
3234     = prev_non_prologue_insn || prev_delay_slot ? prev_pc : cur_pc;
3235
3236   return end_prologue_addr;
3237 }
3238
3239 /* Heuristic unwinder for procedures using microMIPS instructions.
3240    Procedures that use the 32-bit instruction set are handled by the
3241    mips_insn32 unwinder.  Likewise MIPS16 and the mips_insn16 unwinder. */
3242
3243 static struct mips_frame_cache *
3244 mips_micro_frame_cache (struct frame_info *this_frame, void **this_cache)
3245 {
3246   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3247   struct mips_frame_cache *cache;
3248
3249   if ((*this_cache) != NULL)
3250     return (struct mips_frame_cache *) (*this_cache);
3251
3252   cache = FRAME_OBSTACK_ZALLOC (struct mips_frame_cache);
3253   (*this_cache) = cache;
3254   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
3255
3256   /* Analyze the function prologue.  */
3257   {
3258     const CORE_ADDR pc = get_frame_address_in_block (this_frame);
3259     CORE_ADDR start_addr;
3260
3261     find_pc_partial_function (pc, NULL, &start_addr, NULL);
3262     if (start_addr == 0)
3263       start_addr = heuristic_proc_start (get_frame_arch (this_frame), pc);
3264     /* We can't analyze the prologue if we couldn't find the begining
3265        of the function.  */
3266     if (start_addr == 0)
3267       return cache;
3268
3269     micromips_scan_prologue (gdbarch, start_addr, pc, this_frame,
3270                              (struct mips_frame_cache *) *this_cache);
3271   }
3272
3273   /* gdbarch_sp_regnum contains the value and not the address.  */
3274   trad_frame_set_value (cache->saved_regs,
3275                         gdbarch_num_regs (gdbarch) + MIPS_SP_REGNUM,
3276                         cache->base);
3277
3278   return (struct mips_frame_cache *) (*this_cache);
3279 }
3280
3281 static void
3282 mips_micro_frame_this_id (struct frame_info *this_frame, void **this_cache,
3283                           struct frame_id *this_id)
3284 {
3285   struct mips_frame_cache *info = mips_micro_frame_cache (this_frame,
3286                                                           this_cache);
3287   /* This marks the outermost frame.  */
3288   if (info->base == 0)
3289     return;
3290   (*this_id) = frame_id_build (info->base, get_frame_func (this_frame));
3291 }
3292
3293 static struct value *
3294 mips_micro_frame_prev_register (struct frame_info *this_frame,
3295                                 void **this_cache, int regnum)
3296 {
3297   struct mips_frame_cache *info = mips_micro_frame_cache (this_frame,
3298                                                           this_cache);
3299   return trad_frame_get_prev_register (this_frame, info->saved_regs, regnum);
3300 }
3301
3302 static int
3303 mips_micro_frame_sniffer (const struct frame_unwind *self,
3304                           struct frame_info *this_frame, void **this_cache)
3305 {
3306   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3307   CORE_ADDR pc = get_frame_pc (this_frame);
3308
3309   if (mips_pc_is_micromips (gdbarch, pc))
3310     return 1;
3311   return 0;
3312 }
3313
3314 static const struct frame_unwind mips_micro_frame_unwind =
3315 {
3316   NORMAL_FRAME,
3317   default_frame_unwind_stop_reason,
3318   mips_micro_frame_this_id,
3319   mips_micro_frame_prev_register,
3320   NULL,
3321   mips_micro_frame_sniffer
3322 };
3323
3324 static CORE_ADDR
3325 mips_micro_frame_base_address (struct frame_info *this_frame,
3326                                void **this_cache)
3327 {
3328   struct mips_frame_cache *info = mips_micro_frame_cache (this_frame,
3329                                                           this_cache);
3330   return info->base;
3331 }
3332
3333 static const struct frame_base mips_micro_frame_base =
3334 {
3335   &mips_micro_frame_unwind,
3336   mips_micro_frame_base_address,
3337   mips_micro_frame_base_address,
3338   mips_micro_frame_base_address
3339 };
3340
3341 static const struct frame_base *
3342 mips_micro_frame_base_sniffer (struct frame_info *this_frame)
3343 {
3344   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3345   CORE_ADDR pc = get_frame_pc (this_frame);
3346
3347   if (mips_pc_is_micromips (gdbarch, pc))
3348     return &mips_micro_frame_base;
3349   else
3350     return NULL;
3351 }
3352
3353 /* Mark all the registers as unset in the saved_regs array
3354    of THIS_CACHE.  Do nothing if THIS_CACHE is null.  */
3355
3356 static void
3357 reset_saved_regs (struct gdbarch *gdbarch, struct mips_frame_cache *this_cache)
3358 {
3359   if (this_cache == NULL || this_cache->saved_regs == NULL)
3360     return;
3361
3362   {
3363     const int num_regs = gdbarch_num_regs (gdbarch);
3364     int i;
3365
3366     for (i = 0; i < num_regs; i++)
3367       {
3368         this_cache->saved_regs[i].addr = -1;
3369       }
3370   }
3371 }
3372
3373 /* Analyze the function prologue from START_PC to LIMIT_PC.  Builds
3374    the associated FRAME_CACHE if not null.  
3375    Return the address of the first instruction past the prologue.  */
3376
3377 static CORE_ADDR
3378 mips32_scan_prologue (struct gdbarch *gdbarch,
3379                       CORE_ADDR start_pc, CORE_ADDR limit_pc,
3380                       struct frame_info *this_frame,
3381                       struct mips_frame_cache *this_cache)
3382 {
3383   int prev_non_prologue_insn;
3384   int this_non_prologue_insn;
3385   int non_prologue_insns;
3386   CORE_ADDR frame_addr = 0; /* Value of $r30. Used by gcc for
3387                                frame-pointer.  */
3388   int prev_delay_slot;
3389   CORE_ADDR prev_pc;
3390   CORE_ADDR cur_pc;
3391   CORE_ADDR sp;
3392   long frame_offset;
3393   int  frame_reg = MIPS_SP_REGNUM;
3394
3395   CORE_ADDR end_prologue_addr;
3396   int seen_sp_adjust = 0;
3397   int load_immediate_bytes = 0;
3398   int in_delay_slot;
3399   int regsize_is_64_bits = (mips_abi_regsize (gdbarch) == 8);
3400
3401   /* Can be called when there's no process, and hence when there's no
3402      THIS_FRAME.  */
3403   if (this_frame != NULL)
3404     sp = get_frame_register_signed (this_frame,
3405                                     gdbarch_num_regs (gdbarch)
3406                                     + MIPS_SP_REGNUM);
3407   else
3408     sp = 0;
3409
3410   if (limit_pc > start_pc + 200)
3411     limit_pc = start_pc + 200;
3412
3413 restart:
3414   prev_non_prologue_insn = 0;
3415   non_prologue_insns = 0;
3416   prev_delay_slot = 0;
3417   prev_pc = start_pc;
3418
3419   /* Permit at most one non-prologue non-control-transfer instruction
3420      in the middle which may have been reordered by the compiler for
3421      optimisation.  */
3422   frame_offset = 0;
3423   for (cur_pc = start_pc; cur_pc < limit_pc; cur_pc += MIPS_INSN32_SIZE)
3424     {
3425       unsigned long inst, high_word;
3426       long offset;
3427       int reg;
3428
3429       this_non_prologue_insn = 0;
3430       in_delay_slot = 0;
3431
3432       /* Fetch the instruction.  */
3433       inst = (unsigned long) mips_fetch_instruction (gdbarch, ISA_MIPS,
3434                                                      cur_pc, NULL);
3435
3436       /* Save some code by pre-extracting some useful fields.  */
3437       high_word = (inst >> 16) & 0xffff;
3438       offset = ((inst & 0xffff) ^ 0x8000) - 0x8000;
3439       reg = high_word & 0x1f;
3440
3441       if (high_word == 0x27bd           /* addiu $sp,$sp,-i */
3442           || high_word == 0x23bd        /* addi $sp,$sp,-i */
3443           || high_word == 0x67bd)       /* daddiu $sp,$sp,-i */
3444         {
3445           if (offset < 0)               /* Negative stack adjustment?  */
3446             frame_offset -= offset;
3447           else
3448             /* Exit loop if a positive stack adjustment is found, which
3449                usually means that the stack cleanup code in the function
3450                epilogue is reached.  */
3451             break;
3452           seen_sp_adjust = 1;
3453         }
3454       else if (((high_word & 0xFFE0) == 0xafa0) /* sw reg,offset($sp) */
3455                && !regsize_is_64_bits)
3456         {
3457           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
3458         }
3459       else if (((high_word & 0xFFE0) == 0xffa0) /* sd reg,offset($sp) */
3460                && regsize_is_64_bits)
3461         {
3462           /* Irix 6.2 N32 ABI uses sd instructions for saving $gp and $ra.  */
3463           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
3464         }
3465       else if (high_word == 0x27be)     /* addiu $30,$sp,size */
3466         {
3467           /* Old gcc frame, r30 is virtual frame pointer.  */
3468           if (offset != frame_offset)
3469             frame_addr = sp + offset;
3470           else if (this_frame && frame_reg == MIPS_SP_REGNUM)
3471             {
3472               unsigned alloca_adjust;
3473
3474               frame_reg = 30;
3475               frame_addr = get_frame_register_signed
3476                 (this_frame, gdbarch_num_regs (gdbarch) + 30);
3477               frame_offset = 0;
3478
3479               alloca_adjust = (unsigned) (frame_addr - (sp + offset));
3480               if (alloca_adjust > 0)
3481                 {
3482                   /* FP > SP + frame_size.  This may be because of
3483                      an alloca or somethings similar.  Fix sp to
3484                      "pre-alloca" value, and try again.  */
3485                   sp += alloca_adjust;
3486                   /* Need to reset the status of all registers.  Otherwise,
3487                      we will hit a guard that prevents the new address
3488                      for each register to be recomputed during the second
3489                      pass.  */
3490                   reset_saved_regs (gdbarch, this_cache);
3491                   goto restart;
3492                 }
3493             }
3494         }
3495       /* move $30,$sp.  With different versions of gas this will be either
3496          `addu $30,$sp,$zero' or `or $30,$sp,$zero' or `daddu 30,sp,$0'.
3497          Accept any one of these.  */
3498       else if (inst == 0x03A0F021 || inst == 0x03a0f025 || inst == 0x03a0f02d)
3499         {
3500           /* New gcc frame, virtual frame pointer is at r30 + frame_size.  */
3501           if (this_frame && frame_reg == MIPS_SP_REGNUM)
3502             {
3503               unsigned alloca_adjust;
3504
3505               frame_reg = 30;
3506               frame_addr = get_frame_register_signed
3507                 (this_frame, gdbarch_num_regs (gdbarch) + 30);
3508
3509               alloca_adjust = (unsigned) (frame_addr - sp);
3510               if (alloca_adjust > 0)
3511                 {
3512                   /* FP > SP + frame_size.  This may be because of
3513                      an alloca or somethings similar.  Fix sp to
3514                      "pre-alloca" value, and try again.  */
3515                   sp = frame_addr;
3516                   /* Need to reset the status of all registers.  Otherwise,
3517                      we will hit a guard that prevents the new address
3518                      for each register to be recomputed during the second
3519                      pass.  */
3520                   reset_saved_regs (gdbarch, this_cache);
3521                   goto restart;
3522                 }
3523             }
3524         }
3525       else if ((high_word & 0xFFE0) == 0xafc0   /* sw reg,offset($30) */
3526                && !regsize_is_64_bits)
3527         {
3528           set_reg_offset (gdbarch, this_cache, reg, frame_addr + offset);
3529         }
3530       else if ((high_word & 0xFFE0) == 0xE7A0 /* swc1 freg,n($sp) */
3531                || (high_word & 0xF3E0) == 0xA3C0 /* sx reg,n($s8) */
3532                || (inst & 0xFF9F07FF) == 0x00800021 /* move reg,$a0-$a3 */
3533                || high_word == 0x3c1c /* lui $gp,n */
3534                || high_word == 0x279c /* addiu $gp,$gp,n */
3535                || inst == 0x0399e021 /* addu $gp,$gp,$t9 */
3536                || inst == 0x033ce021 /* addu $gp,$t9,$gp */
3537               )
3538         {
3539           /* These instructions are part of the prologue, but we don't
3540              need to do anything special to handle them.  */
3541         }
3542       /* The instructions below load $at or $t0 with an immediate
3543          value in preparation for a stack adjustment via
3544          subu $sp,$sp,[$at,$t0].  These instructions could also
3545          initialize a local variable, so we accept them only before
3546          a stack adjustment instruction was seen.  */
3547       else if (!seen_sp_adjust
3548                && !prev_delay_slot
3549                && (high_word == 0x3c01 /* lui $at,n */
3550                    || high_word == 0x3c08 /* lui $t0,n */
3551                    || high_word == 0x3421 /* ori $at,$at,n */
3552                    || high_word == 0x3508 /* ori $t0,$t0,n */
3553                    || high_word == 0x3401 /* ori $at,$zero,n */
3554                    || high_word == 0x3408 /* ori $t0,$zero,n */
3555                   ))
3556         {
3557           load_immediate_bytes += MIPS_INSN32_SIZE;             /* FIXME!  */
3558         }
3559       /* Check for branches and jumps.  The instruction in the delay
3560          slot can be a part of the prologue, so move forward once more.  */
3561       else if (mips32_instruction_has_delay_slot (gdbarch, inst))
3562         {
3563           in_delay_slot = 1;
3564         }
3565       /* This instruction is not an instruction typically found
3566          in a prologue, so we must have reached the end of the
3567          prologue.  */
3568       else
3569         {
3570           this_non_prologue_insn = 1;
3571         }
3572
3573       non_prologue_insns += this_non_prologue_insn;
3574
3575       /* A jump or branch, or enough non-prologue insns seen?  If so,
3576          then we must have reached the end of the prologue by now.  */
3577       if (prev_delay_slot || non_prologue_insns > 1)
3578         break;
3579
3580       prev_non_prologue_insn = this_non_prologue_insn;
3581       prev_delay_slot = in_delay_slot;
3582       prev_pc = cur_pc;
3583     }
3584
3585   if (this_cache != NULL)
3586     {
3587       this_cache->base = 
3588         (get_frame_register_signed (this_frame,
3589                                     gdbarch_num_regs (gdbarch) + frame_reg)
3590          + frame_offset);
3591       /* FIXME: brobecker/2004-09-15: We should be able to get rid of
3592          this assignment below, eventually.  But it's still needed
3593          for now.  */
3594       this_cache->saved_regs[gdbarch_num_regs (gdbarch)
3595                              + mips_regnum (gdbarch)->pc]
3596         = this_cache->saved_regs[gdbarch_num_regs (gdbarch)
3597                                  + MIPS_RA_REGNUM];
3598     }
3599
3600   /* Set end_prologue_addr to the address of the instruction immediately
3601      after the last one we scanned.  Unless the last one looked like a
3602      non-prologue instruction (and we looked ahead), in which case use
3603      its address instead.  */
3604   end_prologue_addr
3605     = prev_non_prologue_insn || prev_delay_slot ? prev_pc : cur_pc;
3606      
3607   /* In a frameless function, we might have incorrectly
3608      skipped some load immediate instructions.  Undo the skipping
3609      if the load immediate was not followed by a stack adjustment.  */
3610   if (load_immediate_bytes && !seen_sp_adjust)
3611     end_prologue_addr -= load_immediate_bytes;
3612
3613   return end_prologue_addr;
3614 }
3615
3616 /* Heuristic unwinder for procedures using 32-bit instructions (covers
3617    both 32-bit and 64-bit MIPS ISAs).  Procedures using 16-bit
3618    instructions (a.k.a. MIPS16) are handled by the mips_insn16
3619    unwinder.  Likewise microMIPS and the mips_micro unwinder. */
3620
3621 static struct mips_frame_cache *
3622 mips_insn32_frame_cache (struct frame_info *this_frame, void **this_cache)
3623 {
3624   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3625   struct mips_frame_cache *cache;
3626
3627   if ((*this_cache) != NULL)
3628     return (struct mips_frame_cache *) (*this_cache);
3629
3630   cache = FRAME_OBSTACK_ZALLOC (struct mips_frame_cache);
3631   (*this_cache) = cache;
3632   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
3633
3634   /* Analyze the function prologue.  */
3635   {
3636     const CORE_ADDR pc = get_frame_address_in_block (this_frame);
3637     CORE_ADDR start_addr;
3638
3639     find_pc_partial_function (pc, NULL, &start_addr, NULL);
3640     if (start_addr == 0)
3641       start_addr = heuristic_proc_start (gdbarch, pc);
3642     /* We can't analyze the prologue if we couldn't find the begining
3643        of the function.  */
3644     if (start_addr == 0)
3645       return cache;
3646
3647     mips32_scan_prologue (gdbarch, start_addr, pc, this_frame,
3648                           (struct mips_frame_cache *) *this_cache);
3649   }
3650   
3651   /* gdbarch_sp_regnum contains the value and not the address.  */
3652   trad_frame_set_value (cache->saved_regs,
3653                         gdbarch_num_regs (gdbarch) + MIPS_SP_REGNUM,
3654                         cache->base);
3655
3656   return (struct mips_frame_cache *) (*this_cache);
3657 }
3658
3659 static void
3660 mips_insn32_frame_this_id (struct frame_info *this_frame, void **this_cache,
3661                            struct frame_id *this_id)
3662 {
3663   struct mips_frame_cache *info = mips_insn32_frame_cache (this_frame,
3664                                                            this_cache);
3665   /* This marks the outermost frame.  */
3666   if (info->base == 0)
3667     return;
3668   (*this_id) = frame_id_build (info->base, get_frame_func (this_frame));
3669 }
3670
3671 static struct value *
3672 mips_insn32_frame_prev_register (struct frame_info *this_frame,
3673                                  void **this_cache, int regnum)
3674 {
3675   struct mips_frame_cache *info = mips_insn32_frame_cache (this_frame,
3676                                                            this_cache);
3677   return trad_frame_get_prev_register (this_frame, info->saved_regs, regnum);
3678 }
3679
3680 static int
3681 mips_insn32_frame_sniffer (const struct frame_unwind *self,
3682                            struct frame_info *this_frame, void **this_cache)
3683 {
3684   CORE_ADDR pc = get_frame_pc (this_frame);
3685   if (mips_pc_is_mips (pc))
3686     return 1;
3687   return 0;
3688 }
3689
3690 static const struct frame_unwind mips_insn32_frame_unwind =
3691 {
3692   NORMAL_FRAME,
3693   default_frame_unwind_stop_reason,
3694   mips_insn32_frame_this_id,
3695   mips_insn32_frame_prev_register,
3696   NULL,
3697   mips_insn32_frame_sniffer
3698 };
3699
3700 static CORE_ADDR
3701 mips_insn32_frame_base_address (struct frame_info *this_frame,
3702                                 void **this_cache)
3703 {
3704   struct mips_frame_cache *info = mips_insn32_frame_cache (this_frame,
3705                                                            this_cache);
3706   return info->base;
3707 }
3708
3709 static const struct frame_base mips_insn32_frame_base =
3710 {
3711   &mips_insn32_frame_unwind,
3712   mips_insn32_frame_base_address,
3713   mips_insn32_frame_base_address,
3714   mips_insn32_frame_base_address
3715 };
3716
3717 static const struct frame_base *
3718 mips_insn32_frame_base_sniffer (struct frame_info *this_frame)
3719 {
3720   CORE_ADDR pc = get_frame_pc (this_frame);
3721   if (mips_pc_is_mips (pc))
3722     return &mips_insn32_frame_base;
3723   else
3724     return NULL;
3725 }
3726
3727 static struct trad_frame_cache *
3728 mips_stub_frame_cache (struct frame_info *this_frame, void **this_cache)
3729 {
3730   CORE_ADDR pc;
3731   CORE_ADDR start_addr;
3732   CORE_ADDR stack_addr;
3733   struct trad_frame_cache *this_trad_cache;
3734   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3735   int num_regs = gdbarch_num_regs (gdbarch);
3736
3737   if ((*this_cache) != NULL)
3738     return (struct trad_frame_cache *) (*this_cache);
3739   this_trad_cache = trad_frame_cache_zalloc (this_frame);
3740   (*this_cache) = this_trad_cache;
3741
3742   /* The return address is in the link register.  */
3743   trad_frame_set_reg_realreg (this_trad_cache,
3744                               gdbarch_pc_regnum (gdbarch),
3745                               num_regs + MIPS_RA_REGNUM);
3746
3747   /* Frame ID, since it's a frameless / stackless function, no stack
3748      space is allocated and SP on entry is the current SP.  */
3749   pc = get_frame_pc (this_frame);
3750   find_pc_partial_function (pc, NULL, &start_addr, NULL);
3751   stack_addr = get_frame_register_signed (this_frame,
3752                                           num_regs + MIPS_SP_REGNUM);
3753   trad_frame_set_id (this_trad_cache, frame_id_build (stack_addr, start_addr));
3754
3755   /* Assume that the frame's base is the same as the
3756      stack-pointer.  */
3757   trad_frame_set_this_base (this_trad_cache, stack_addr);
3758
3759   return this_trad_cache;
3760 }
3761
3762 static void
3763 mips_stub_frame_this_id (struct frame_info *this_frame, void **this_cache,
3764                          struct frame_id *this_id)
3765 {
3766   struct trad_frame_cache *this_trad_cache
3767     = mips_stub_frame_cache (this_frame, this_cache);
3768   trad_frame_get_id (this_trad_cache, this_id);
3769 }
3770
3771 static struct value *
3772 mips_stub_frame_prev_register (struct frame_info *this_frame,
3773                                void **this_cache, int regnum)
3774 {
3775   struct trad_frame_cache *this_trad_cache
3776     = mips_stub_frame_cache (this_frame, this_cache);
3777   return trad_frame_get_register (this_trad_cache, this_frame, regnum);
3778 }
3779
3780 static int
3781 mips_stub_frame_sniffer (const struct frame_unwind *self,
3782                          struct frame_info *this_frame, void **this_cache)
3783 {
3784   gdb_byte dummy[4];
3785   struct obj_section *s;
3786   CORE_ADDR pc = get_frame_address_in_block (this_frame);
3787   struct bound_minimal_symbol msym;
3788
3789   /* Use the stub unwinder for unreadable code.  */
3790   if (target_read_memory (get_frame_pc (this_frame), dummy, 4) != 0)
3791     return 1;
3792
3793   if (in_plt_section (pc) || in_mips_stubs_section (pc))
3794     return 1;
3795
3796   /* Calling a PIC function from a non-PIC function passes through a
3797      stub.  The stub for foo is named ".pic.foo".  */
3798   msym = lookup_minimal_symbol_by_pc (pc);
3799   if (msym.minsym != NULL
3800       && MSYMBOL_LINKAGE_NAME (msym.minsym) != NULL
3801       && startswith (MSYMBOL_LINKAGE_NAME (msym.minsym), ".pic."))
3802     return 1;
3803
3804   return 0;
3805 }
3806
3807 static const struct frame_unwind mips_stub_frame_unwind =
3808 {
3809   NORMAL_FRAME,
3810   default_frame_unwind_stop_reason,
3811   mips_stub_frame_this_id,
3812   mips_stub_frame_prev_register,
3813   NULL,
3814   mips_stub_frame_sniffer
3815 };
3816
3817 static CORE_ADDR
3818 mips_stub_frame_base_address (struct frame_info *this_frame,
3819                               void **this_cache)
3820 {
3821   struct trad_frame_cache *this_trad_cache
3822     = mips_stub_frame_cache (this_frame, this_cache);
3823   return trad_frame_get_this_base (this_trad_cache);
3824 }
3825
3826 static const struct frame_base mips_stub_frame_base =
3827 {
3828   &mips_stub_frame_unwind,
3829   mips_stub_frame_base_address,
3830   mips_stub_frame_base_address,
3831   mips_stub_frame_base_address
3832 };
3833
3834 static const struct frame_base *
3835 mips_stub_frame_base_sniffer (struct frame_info *this_frame)
3836 {
3837   if (mips_stub_frame_sniffer (&mips_stub_frame_unwind, this_frame, NULL))
3838     return &mips_stub_frame_base;
3839   else
3840     return NULL;
3841 }
3842
3843 /* mips_addr_bits_remove - remove useless address bits  */
3844
3845 static CORE_ADDR
3846 mips_addr_bits_remove (struct gdbarch *gdbarch, CORE_ADDR addr)
3847 {
3848   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3849
3850   if (mips_mask_address_p (tdep) && (((ULONGEST) addr) >> 32 == 0xffffffffUL))
3851     /* This hack is a work-around for existing boards using PMON, the
3852        simulator, and any other 64-bit targets that doesn't have true
3853        64-bit addressing.  On these targets, the upper 32 bits of
3854        addresses are ignored by the hardware.  Thus, the PC or SP are
3855        likely to have been sign extended to all 1s by instruction
3856        sequences that load 32-bit addresses.  For example, a typical
3857        piece of code that loads an address is this:
3858
3859        lui $r2, <upper 16 bits>
3860        ori $r2, <lower 16 bits>
3861
3862        But the lui sign-extends the value such that the upper 32 bits
3863        may be all 1s.  The workaround is simply to mask off these
3864        bits.  In the future, gcc may be changed to support true 64-bit
3865        addressing, and this masking will have to be disabled.  */
3866     return addr &= 0xffffffffUL;
3867   else
3868     return addr;
3869 }
3870
3871
3872 /* Checks for an atomic sequence of instructions beginning with a LL/LLD
3873    instruction and ending with a SC/SCD instruction.  If such a sequence
3874    is found, attempt to step through it.  A breakpoint is placed at the end of 
3875    the sequence.  */
3876
3877 /* Instructions used during single-stepping of atomic sequences, standard
3878    ISA version.  */
3879 #define LL_OPCODE 0x30
3880 #define LLD_OPCODE 0x34
3881 #define SC_OPCODE 0x38
3882 #define SCD_OPCODE 0x3c
3883
3884 static std::vector<CORE_ADDR>
3885 mips_deal_with_atomic_sequence (struct gdbarch *gdbarch, CORE_ADDR pc)
3886 {
3887   CORE_ADDR breaks[2] = {-1, -1};
3888   CORE_ADDR loc = pc;
3889   CORE_ADDR branch_bp; /* Breakpoint at branch instruction's destination.  */
3890   ULONGEST insn;
3891   int insn_count;
3892   int index;
3893   int last_breakpoint = 0; /* Defaults to 0 (no breakpoints placed).  */  
3894   const int atomic_sequence_length = 16; /* Instruction sequence length.  */
3895
3896   insn = mips_fetch_instruction (gdbarch, ISA_MIPS, loc, NULL);
3897   /* Assume all atomic sequences start with a ll/lld instruction.  */
3898   if (itype_op (insn) != LL_OPCODE && itype_op (insn) != LLD_OPCODE)
3899     return {};
3900
3901   /* Assume that no atomic sequence is longer than "atomic_sequence_length" 
3902      instructions.  */
3903   for (insn_count = 0; insn_count < atomic_sequence_length; ++insn_count)
3904     {
3905       int is_branch = 0;
3906       loc += MIPS_INSN32_SIZE;
3907       insn = mips_fetch_instruction (gdbarch, ISA_MIPS, loc, NULL);
3908
3909       /* Assume that there is at most one branch in the atomic
3910          sequence.  If a branch is found, put a breakpoint in its
3911          destination address.  */
3912       switch (itype_op (insn))
3913         {
3914         case 0: /* SPECIAL */
3915           if (rtype_funct (insn) >> 1 == 4) /* JR, JALR */
3916             return {}; /* fallback to the standard single-step code.  */
3917           break;
3918         case 1: /* REGIMM */
3919           is_branch = ((itype_rt (insn) & 0xc) == 0 /* B{LT,GE}Z* */
3920                        || ((itype_rt (insn) & 0x1e) == 0
3921                            && itype_rs (insn) == 0)); /* BPOSGE* */
3922           break;
3923         case 2: /* J */
3924         case 3: /* JAL */
3925           return {}; /* fallback to the standard single-step code.  */
3926         case 4: /* BEQ */
3927         case 5: /* BNE */
3928         case 6: /* BLEZ */
3929         case 7: /* BGTZ */
3930         case 20: /* BEQL */
3931         case 21: /* BNEL */
3932         case 22: /* BLEZL */
3933         case 23: /* BGTTL */
3934           is_branch = 1;
3935           break;
3936         case 17: /* COP1 */
3937           is_branch = ((itype_rs (insn) == 9 || itype_rs (insn) == 10)
3938                        && (itype_rt (insn) & 0x2) == 0);
3939           if (is_branch) /* BC1ANY2F, BC1ANY2T, BC1ANY4F, BC1ANY4T */
3940             break;
3941         /* Fall through.  */
3942         case 18: /* COP2 */
3943         case 19: /* COP3 */
3944           is_branch = (itype_rs (insn) == 8); /* BCzF, BCzFL, BCzT, BCzTL */
3945           break;
3946         }
3947       if (is_branch)
3948         {
3949           branch_bp = loc + mips32_relative_offset (insn) + 4;
3950           if (last_breakpoint >= 1)
3951             return {}; /* More than one branch found, fallback to the
3952                           standard single-step code.  */
3953           breaks[1] = branch_bp;
3954           last_breakpoint++;
3955         }
3956
3957       if (itype_op (insn) == SC_OPCODE || itype_op (insn) == SCD_OPCODE)
3958         break;
3959     }
3960
3961   /* Assume that the atomic sequence ends with a sc/scd instruction.  */
3962   if (itype_op (insn) != SC_OPCODE && itype_op (insn) != SCD_OPCODE)
3963     return {};
3964
3965   loc += MIPS_INSN32_SIZE;
3966
3967   /* Insert a breakpoint right after the end of the atomic sequence.  */
3968   breaks[0] = loc;
3969
3970   /* Check for duplicated breakpoints.  Check also for a breakpoint
3971      placed (branch instruction's destination) in the atomic sequence.  */
3972   if (last_breakpoint && pc <= breaks[1] && breaks[1] <= breaks[0])
3973     last_breakpoint = 0;
3974
3975   std::vector<CORE_ADDR> next_pcs;
3976
3977   /* Effectively inserts the breakpoints.  */
3978   for (index = 0; index <= last_breakpoint; index++)
3979     next_pcs.push_back (breaks[index]);
3980
3981   return next_pcs;
3982 }
3983
3984 static std::vector<CORE_ADDR>
3985 micromips_deal_with_atomic_sequence (struct gdbarch *gdbarch,
3986                                      CORE_ADDR pc)
3987 {
3988   const int atomic_sequence_length = 16; /* Instruction sequence length.  */
3989   int last_breakpoint = 0; /* Defaults to 0 (no breakpoints placed).  */
3990   CORE_ADDR breaks[2] = {-1, -1};
3991   CORE_ADDR branch_bp = 0; /* Breakpoint at branch instruction's
3992                               destination.  */
3993   CORE_ADDR loc = pc;
3994   int sc_found = 0;
3995   ULONGEST insn;
3996   int insn_count;
3997   int index;
3998
3999   /* Assume all atomic sequences start with a ll/lld instruction.  */
4000   insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, loc, NULL);
4001   if (micromips_op (insn) != 0x18)      /* POOL32C: bits 011000 */
4002     return {};
4003   loc += MIPS_INSN16_SIZE;
4004   insn <<= 16;
4005   insn |= mips_fetch_instruction (gdbarch, ISA_MICROMIPS, loc, NULL);
4006   if ((b12s4_op (insn) & 0xb) != 0x3)   /* LL, LLD: bits 011000 0x11 */
4007     return {};
4008   loc += MIPS_INSN16_SIZE;
4009
4010   /* Assume all atomic sequences end with an sc/scd instruction.  Assume
4011      that no atomic sequence is longer than "atomic_sequence_length"
4012      instructions.  */
4013   for (insn_count = 0;
4014        !sc_found && insn_count < atomic_sequence_length;
4015        ++insn_count)
4016     {
4017       int is_branch = 0;
4018
4019       insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, loc, NULL);
4020       loc += MIPS_INSN16_SIZE;
4021
4022       /* Assume that there is at most one conditional branch in the
4023          atomic sequence.  If a branch is found, put a breakpoint in
4024          its destination address.  */
4025       switch (mips_insn_size (ISA_MICROMIPS, insn))
4026         {
4027         /* 32-bit instructions.  */
4028         case 2 * MIPS_INSN16_SIZE:
4029           switch (micromips_op (insn))
4030             {
4031             case 0x10: /* POOL32I: bits 010000 */
4032               if ((b5s5_op (insn) & 0x18) != 0x0
4033                                 /* BLTZ, BLTZAL, BGEZ, BGEZAL: 010000 000xx */
4034                                 /* BLEZ, BNEZC, BGTZ, BEQZC: 010000 001xx */
4035                   && (b5s5_op (insn) & 0x1d) != 0x11
4036                                 /* BLTZALS, BGEZALS: bits 010000 100x1 */
4037                   && ((b5s5_op (insn) & 0x1e) != 0x14
4038                       || (insn & 0x3) != 0x0)
4039                                 /* BC2F, BC2T: bits 010000 1010x xxx00 */
4040                   && (b5s5_op (insn) & 0x1e) != 0x1a
4041                                 /* BPOSGE64, BPOSGE32: bits 010000 1101x */
4042                   && ((b5s5_op (insn) & 0x1e) != 0x1c
4043                       || (insn & 0x3) != 0x0)
4044                                 /* BC1F, BC1T: bits 010000 1110x xxx00 */
4045                   && ((b5s5_op (insn) & 0x1c) != 0x1c
4046                       || (insn & 0x3) != 0x1))
4047                                 /* BC1ANY*: bits 010000 111xx xxx01 */
4048                 break;
4049               /* Fall through.  */
4050
4051             case 0x25: /* BEQ: bits 100101 */
4052             case 0x2d: /* BNE: bits 101101 */
4053               insn <<= 16;
4054               insn |= mips_fetch_instruction (gdbarch,
4055                                               ISA_MICROMIPS, loc, NULL);
4056               branch_bp = (loc + MIPS_INSN16_SIZE
4057                            + micromips_relative_offset16 (insn));
4058               is_branch = 1;
4059               break;
4060
4061             case 0x00: /* POOL32A: bits 000000 */
4062               insn <<= 16;
4063               insn |= mips_fetch_instruction (gdbarch,
4064                                               ISA_MICROMIPS, loc, NULL);
4065               if (b0s6_op (insn) != 0x3c
4066                                 /* POOL32Axf: bits 000000 ... 111100 */
4067                   || (b6s10_ext (insn) & 0x2bf) != 0x3c)
4068                                 /* JALR, JALR.HB: 000000 000x111100 111100 */
4069                                 /* JALRS, JALRS.HB: 000000 010x111100 111100 */
4070                 break;
4071               /* Fall through.  */
4072
4073             case 0x1d: /* JALS: bits 011101 */
4074             case 0x35: /* J: bits 110101 */
4075             case 0x3d: /* JAL: bits 111101 */
4076             case 0x3c: /* JALX: bits 111100 */
4077               return {}; /* Fall back to the standard single-step code. */
4078
4079             case 0x18: /* POOL32C: bits 011000 */
4080               if ((b12s4_op (insn) & 0xb) == 0xb)
4081                                 /* SC, SCD: bits 011000 1x11 */
4082                 sc_found = 1;
4083               break;
4084             }
4085           loc += MIPS_INSN16_SIZE;
4086           break;
4087
4088         /* 16-bit instructions.  */
4089         case MIPS_INSN16_SIZE:
4090           switch (micromips_op (insn))
4091             {
4092             case 0x23: /* BEQZ16: bits 100011 */
4093             case 0x2b: /* BNEZ16: bits 101011 */
4094               branch_bp = loc + micromips_relative_offset7 (insn);
4095               is_branch = 1;
4096               break;
4097
4098             case 0x11: /* POOL16C: bits 010001 */
4099               if ((b5s5_op (insn) & 0x1c) != 0xc
4100                                 /* JR16, JRC, JALR16, JALRS16: 010001 011xx */
4101                   && b5s5_op (insn) != 0x18)
4102                                 /* JRADDIUSP: bits 010001 11000 */
4103                 break;
4104               return {}; /* Fall back to the standard single-step code. */
4105
4106             case 0x33: /* B16: bits 110011 */
4107               return {}; /* Fall back to the standard single-step code. */
4108             }
4109           break;
4110         }
4111       if (is_branch)
4112         {
4113           if (last_breakpoint >= 1)
4114             return {}; /* More than one branch found, fallback to the
4115                           standard single-step code.  */
4116           breaks[1] = branch_bp;
4117           last_breakpoint++;
4118         }
4119     }
4120   if (!sc_found)
4121     return {};
4122
4123   /* Insert a breakpoint right after the end of the atomic sequence.  */
4124   breaks[0] = loc;
4125
4126   /* Check for duplicated breakpoints.  Check also for a breakpoint
4127      placed (branch instruction's destination) in the atomic sequence */
4128   if (last_breakpoint && pc <= breaks[1] && breaks[1] <= breaks[0])
4129     last_breakpoint = 0;
4130
4131   std::vector<CORE_ADDR> next_pcs;
4132
4133   /* Effectively inserts the breakpoints.  */
4134   for (index = 0; index <= last_breakpoint; index++)
4135     next_pcs.push_back (breaks[index]);
4136
4137   return next_pcs;
4138 }
4139
4140 static std::vector<CORE_ADDR>
4141 deal_with_atomic_sequence (struct gdbarch *gdbarch, CORE_ADDR pc)
4142 {
4143   if (mips_pc_is_mips (pc))
4144     return mips_deal_with_atomic_sequence (gdbarch, pc);
4145   else if (mips_pc_is_micromips (gdbarch, pc))
4146     return micromips_deal_with_atomic_sequence (gdbarch, pc);
4147   else
4148     return {};
4149 }
4150
4151 /* mips_software_single_step() is called just before we want to resume
4152    the inferior, if we want to single-step it but there is no hardware
4153    or kernel single-step support (MIPS on GNU/Linux for example).  We find
4154    the target of the coming instruction and breakpoint it.  */
4155
4156 std::vector<CORE_ADDR>
4157 mips_software_single_step (struct regcache *regcache)
4158 {
4159   struct gdbarch *gdbarch = get_regcache_arch (regcache);
4160   CORE_ADDR pc, next_pc;
4161
4162   pc = regcache_read_pc (regcache);
4163   std::vector<CORE_ADDR> next_pcs = deal_with_atomic_sequence (gdbarch, pc);
4164
4165   if (!next_pcs.empty ())
4166     return next_pcs;
4167
4168   next_pc = mips_next_pc (regcache, pc);
4169
4170   return {next_pc};
4171 }
4172
4173 /* Test whether the PC points to the return instruction at the
4174    end of a function.  */
4175
4176 static int
4177 mips_about_to_return (struct gdbarch *gdbarch, CORE_ADDR pc)
4178 {
4179   ULONGEST insn;
4180   ULONGEST hint;
4181
4182   /* This used to check for MIPS16, but this piece of code is never
4183      called for MIPS16 functions.  And likewise microMIPS ones.  */
4184   gdb_assert (mips_pc_is_mips (pc));
4185
4186   insn = mips_fetch_instruction (gdbarch, ISA_MIPS, pc, NULL);
4187   hint = 0x7c0;
4188   return (insn & ~hint) == 0x3e00008;                   /* jr(.hb) $ra */
4189 }
4190
4191
4192 /* This fencepost looks highly suspicious to me.  Removing it also
4193    seems suspicious as it could affect remote debugging across serial
4194    lines.  */
4195
4196 static CORE_ADDR
4197 heuristic_proc_start (struct gdbarch *gdbarch, CORE_ADDR pc)
4198 {
4199   CORE_ADDR start_pc;
4200   CORE_ADDR fence;
4201   int instlen;
4202   int seen_adjsp = 0;
4203   struct inferior *inf;
4204
4205   pc = gdbarch_addr_bits_remove (gdbarch, pc);
4206   start_pc = pc;
4207   fence = start_pc - heuristic_fence_post;
4208   if (start_pc == 0)
4209     return 0;
4210
4211   if (heuristic_fence_post == -1 || fence < VM_MIN_ADDRESS)
4212     fence = VM_MIN_ADDRESS;
4213
4214   instlen = mips_pc_is_mips (pc) ? MIPS_INSN32_SIZE : MIPS_INSN16_SIZE;
4215
4216   inf = current_inferior ();
4217
4218   /* Search back for previous return.  */
4219   for (start_pc -= instlen;; start_pc -= instlen)
4220     if (start_pc < fence)
4221       {
4222         /* It's not clear to me why we reach this point when
4223            stop_soon, but with this test, at least we
4224            don't print out warnings for every child forked (eg, on
4225            decstation).  22apr93 rich@cygnus.com.  */
4226         if (inf->control.stop_soon == NO_STOP_QUIETLY)
4227           {
4228             static int blurb_printed = 0;
4229
4230             warning (_("GDB can't find the start of the function at %s."),
4231                      paddress (gdbarch, pc));
4232
4233             if (!blurb_printed)
4234               {
4235                 /* This actually happens frequently in embedded
4236                    development, when you first connect to a board
4237                    and your stack pointer and pc are nowhere in
4238                    particular.  This message needs to give people
4239                    in that situation enough information to
4240                    determine that it's no big deal.  */
4241                 printf_filtered ("\n\
4242     GDB is unable to find the start of the function at %s\n\
4243 and thus can't determine the size of that function's stack frame.\n\
4244 This means that GDB may be unable to access that stack frame, or\n\
4245 the frames below it.\n\
4246     This problem is most likely caused by an invalid program counter or\n\
4247 stack pointer.\n\
4248     However, if you think GDB should simply search farther back\n\
4249 from %s for code which looks like the beginning of a\n\
4250 function, you can increase the range of the search using the `set\n\
4251 heuristic-fence-post' command.\n",
4252                         paddress (gdbarch, pc), paddress (gdbarch, pc));
4253                 blurb_printed = 1;
4254               }
4255           }
4256
4257         return 0;
4258       }
4259     else if (mips_pc_is_mips16 (gdbarch, start_pc))
4260       {
4261         unsigned short inst;
4262
4263         /* On MIPS16, any one of the following is likely to be the
4264            start of a function:
4265            extend save
4266            save
4267            entry
4268            addiu sp,-n
4269            daddiu sp,-n
4270            extend -n followed by 'addiu sp,+n' or 'daddiu sp,+n'.  */
4271         inst = mips_fetch_instruction (gdbarch, ISA_MIPS16, start_pc, NULL);
4272         if ((inst & 0xff80) == 0x6480)          /* save */
4273           {
4274             if (start_pc - instlen >= fence)
4275               {
4276                 inst = mips_fetch_instruction (gdbarch, ISA_MIPS16,
4277                                                start_pc - instlen, NULL);
4278                 if ((inst & 0xf800) == 0xf000)  /* extend */
4279                   start_pc -= instlen;
4280               }
4281             break;
4282           }
4283         else if (((inst & 0xf81f) == 0xe809
4284                   && (inst & 0x700) != 0x700)   /* entry */
4285                  || (inst & 0xff80) == 0x6380   /* addiu sp,-n */
4286                  || (inst & 0xff80) == 0xfb80   /* daddiu sp,-n */
4287                  || ((inst & 0xf810) == 0xf010 && seen_adjsp))  /* extend -n */
4288           break;
4289         else if ((inst & 0xff00) == 0x6300      /* addiu sp */
4290                  || (inst & 0xff00) == 0xfb00)  /* daddiu sp */
4291           seen_adjsp = 1;
4292         else
4293           seen_adjsp = 0;
4294       }
4295     else if (mips_pc_is_micromips (gdbarch, start_pc))
4296       {
4297         ULONGEST insn;
4298         int stop = 0;
4299         long offset;
4300         int dreg;
4301         int sreg;
4302
4303         /* On microMIPS, any one of the following is likely to be the
4304            start of a function:
4305            ADDIUSP -imm
4306            (D)ADDIU $sp, -imm
4307            LUI $gp, imm  */
4308         insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, NULL);
4309         switch (micromips_op (insn))
4310           {
4311           case 0xc: /* ADDIU: bits 001100 */
4312           case 0x17: /* DADDIU: bits 010111 */
4313             sreg = b0s5_reg (insn);
4314             dreg = b5s5_reg (insn);
4315             insn <<= 16;
4316             insn |= mips_fetch_instruction (gdbarch, ISA_MICROMIPS,
4317                                             pc + MIPS_INSN16_SIZE, NULL);
4318             offset = (b0s16_imm (insn) ^ 0x8000) - 0x8000;
4319             if (sreg == MIPS_SP_REGNUM && dreg == MIPS_SP_REGNUM
4320                                 /* (D)ADDIU $sp, imm */
4321                 && offset < 0)
4322               stop = 1;
4323             break;
4324
4325           case 0x10: /* POOL32I: bits 010000 */
4326             if (b5s5_op (insn) == 0xd
4327                                 /* LUI: bits 010000 001101 */
4328                 && b0s5_reg (insn >> 16) == 28)
4329                                 /* LUI $gp, imm */
4330               stop = 1;
4331             break;
4332
4333           case 0x13: /* POOL16D: bits 010011 */
4334             if ((insn & 0x1) == 0x1)
4335                                 /* ADDIUSP: bits 010011 1 */
4336               {
4337                 offset = micromips_decode_imm9 (b1s9_imm (insn));
4338                 if (offset < 0)
4339                                 /* ADDIUSP -imm */
4340                   stop = 1;
4341               }
4342             else
4343                                 /* ADDIUS5: bits 010011 0 */
4344               {
4345                 dreg = b5s5_reg (insn);
4346                 offset = (b1s4_imm (insn) ^ 8) - 8;
4347                 if (dreg == MIPS_SP_REGNUM && offset < 0)
4348                                 /* ADDIUS5  $sp, -imm */
4349                   stop = 1;
4350               }
4351             break;
4352           }
4353         if (stop)
4354           break;
4355       }
4356     else if (mips_about_to_return (gdbarch, start_pc))
4357       {
4358         /* Skip return and its delay slot.  */
4359         start_pc += 2 * MIPS_INSN32_SIZE;
4360         break;
4361       }
4362
4363   return start_pc;
4364 }
4365
4366 struct mips_objfile_private
4367 {
4368   bfd_size_type size;
4369   char *contents;
4370 };
4371
4372 /* According to the current ABI, should the type be passed in a
4373    floating-point register (assuming that there is space)?  When there
4374    is no FPU, FP are not even considered as possible candidates for
4375    FP registers and, consequently this returns false - forces FP
4376    arguments into integer registers.  */
4377
4378 static int
4379 fp_register_arg_p (struct gdbarch *gdbarch, enum type_code typecode,
4380                    struct type *arg_type)
4381 {
4382   return ((typecode == TYPE_CODE_FLT
4383            || (MIPS_EABI (gdbarch)
4384                && (typecode == TYPE_CODE_STRUCT
4385                    || typecode == TYPE_CODE_UNION)
4386                && TYPE_NFIELDS (arg_type) == 1
4387                && TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (arg_type, 0))) 
4388                == TYPE_CODE_FLT))
4389           && MIPS_FPU_TYPE(gdbarch) != MIPS_FPU_NONE);
4390 }
4391
4392 /* On o32, argument passing in GPRs depends on the alignment of the type being
4393    passed.  Return 1 if this type must be aligned to a doubleword boundary.  */
4394
4395 static int
4396 mips_type_needs_double_align (struct type *type)
4397 {
4398   enum type_code typecode = TYPE_CODE (type);
4399
4400   if (typecode == TYPE_CODE_FLT && TYPE_LENGTH (type) == 8)
4401     return 1;
4402   else if (typecode == TYPE_CODE_STRUCT)
4403     {
4404       if (TYPE_NFIELDS (type) < 1)
4405         return 0;
4406       return mips_type_needs_double_align (TYPE_FIELD_TYPE (type, 0));
4407     }
4408   else if (typecode == TYPE_CODE_UNION)
4409     {
4410       int i, n;
4411
4412       n = TYPE_NFIELDS (type);
4413       for (i = 0; i < n; i++)
4414         if (mips_type_needs_double_align (TYPE_FIELD_TYPE (type, i)))
4415           return 1;
4416       return 0;
4417     }
4418   return 0;
4419 }
4420
4421 /* Adjust the address downward (direction of stack growth) so that it
4422    is correctly aligned for a new stack frame.  */
4423 static CORE_ADDR
4424 mips_frame_align (struct gdbarch *gdbarch, CORE_ADDR addr)
4425 {
4426   return align_down (addr, 16);
4427 }
4428
4429 /* Implement the "push_dummy_code" gdbarch method.  */
4430
4431 static CORE_ADDR
4432 mips_push_dummy_code (struct gdbarch *gdbarch, CORE_ADDR sp,
4433                       CORE_ADDR funaddr, struct value **args,
4434                       int nargs, struct type *value_type,
4435                       CORE_ADDR *real_pc, CORE_ADDR *bp_addr,
4436                       struct regcache *regcache)
4437 {
4438   static gdb_byte nop_insn[] = { 0, 0, 0, 0 };
4439   CORE_ADDR nop_addr;
4440   CORE_ADDR bp_slot;
4441
4442   /* Reserve enough room on the stack for our breakpoint instruction.  */
4443   bp_slot = sp - sizeof (nop_insn);
4444
4445   /* Return to microMIPS mode if calling microMIPS code to avoid
4446      triggering an address error exception on processors that only
4447      support microMIPS execution.  */
4448   *bp_addr = (mips_pc_is_micromips (gdbarch, funaddr)
4449               ? make_compact_addr (bp_slot) : bp_slot);
4450
4451   /* The breakpoint layer automatically adjusts the address of
4452      breakpoints inserted in a branch delay slot.  With enough
4453      bad luck, the 4 bytes located just before our breakpoint
4454      instruction could look like a branch instruction, and thus
4455      trigger the adjustement, and break the function call entirely.
4456      So, we reserve those 4 bytes and write a nop instruction
4457      to prevent that from happening.  */
4458   nop_addr = bp_slot - sizeof (nop_insn);
4459   write_memory (nop_addr, nop_insn, sizeof (nop_insn));
4460   sp = mips_frame_align (gdbarch, nop_addr);
4461
4462   /* Inferior resumes at the function entry point.  */
4463   *real_pc = funaddr;
4464
4465   return sp;
4466 }
4467
4468 static CORE_ADDR
4469 mips_eabi_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
4470                            struct regcache *regcache, CORE_ADDR bp_addr,
4471                            int nargs, struct value **args, CORE_ADDR sp,
4472                            int struct_return, CORE_ADDR struct_addr)
4473 {
4474   int argreg;
4475   int float_argreg;
4476   int argnum;
4477   int len = 0;
4478   int stack_offset = 0;
4479   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4480   CORE_ADDR func_addr = find_function_addr (function, NULL);
4481   int abi_regsize = mips_abi_regsize (gdbarch);
4482
4483   /* For shared libraries, "t9" needs to point at the function
4484      address.  */
4485   regcache_cooked_write_signed (regcache, MIPS_T9_REGNUM, func_addr);
4486
4487   /* Set the return address register to point to the entry point of
4488      the program, where a breakpoint lies in wait.  */
4489   regcache_cooked_write_signed (regcache, MIPS_RA_REGNUM, bp_addr);
4490
4491   /* First ensure that the stack and structure return address (if any)
4492      are properly aligned.  The stack has to be at least 64-bit
4493      aligned even on 32-bit machines, because doubles must be 64-bit
4494      aligned.  For n32 and n64, stack frames need to be 128-bit
4495      aligned, so we round to this widest known alignment.  */
4496
4497   sp = align_down (sp, 16);
4498   struct_addr = align_down (struct_addr, 16);
4499
4500   /* Now make space on the stack for the args.  We allocate more
4501      than necessary for EABI, because the first few arguments are
4502      passed in registers, but that's OK.  */
4503   for (argnum = 0; argnum < nargs; argnum++)
4504     len += align_up (TYPE_LENGTH (value_type (args[argnum])), abi_regsize);
4505   sp -= align_up (len, 16);
4506
4507   if (mips_debug)
4508     fprintf_unfiltered (gdb_stdlog,
4509                         "mips_eabi_push_dummy_call: sp=%s allocated %ld\n",
4510                         paddress (gdbarch, sp), (long) align_up (len, 16));
4511
4512   /* Initialize the integer and float register pointers.  */
4513   argreg = MIPS_A0_REGNUM;
4514   float_argreg = mips_fpa0_regnum (gdbarch);
4515
4516   /* The struct_return pointer occupies the first parameter-passing reg.  */
4517   if (struct_return)
4518     {
4519       if (mips_debug)
4520         fprintf_unfiltered (gdb_stdlog,
4521                             "mips_eabi_push_dummy_call: "
4522                             "struct_return reg=%d %s\n",
4523                             argreg, paddress (gdbarch, struct_addr));
4524       regcache_cooked_write_unsigned (regcache, argreg++, struct_addr);
4525     }
4526
4527   /* Now load as many as possible of the first arguments into
4528      registers, and push the rest onto the stack.  Loop thru args
4529      from first to last.  */
4530   for (argnum = 0; argnum < nargs; argnum++)
4531     {
4532       const gdb_byte *val;
4533       /* This holds the address of structures that are passed by
4534          reference.  */
4535       gdb_byte ref_valbuf[MAX_MIPS_ABI_REGSIZE];
4536       struct value *arg = args[argnum];
4537       struct type *arg_type = check_typedef (value_type (arg));
4538       int len = TYPE_LENGTH (arg_type);
4539       enum type_code typecode = TYPE_CODE (arg_type);
4540
4541       if (mips_debug)
4542         fprintf_unfiltered (gdb_stdlog,
4543                             "mips_eabi_push_dummy_call: %d len=%d type=%d",
4544                             argnum + 1, len, (int) typecode);
4545
4546       /* The EABI passes structures that do not fit in a register by
4547          reference.  */
4548       if (len > abi_regsize
4549           && (typecode == TYPE_CODE_STRUCT || typecode == TYPE_CODE_UNION))
4550         {
4551           gdb_assert (abi_regsize <= ARRAY_SIZE (ref_valbuf));
4552           store_unsigned_integer (ref_valbuf, abi_regsize, byte_order,
4553                                   value_address (arg));
4554           typecode = TYPE_CODE_PTR;
4555           len = abi_regsize;
4556           val = ref_valbuf;
4557           if (mips_debug)
4558             fprintf_unfiltered (gdb_stdlog, " push");
4559         }
4560       else
4561         val = value_contents (arg);
4562
4563       /* 32-bit ABIs always start floating point arguments in an
4564          even-numbered floating point register.  Round the FP register
4565          up before the check to see if there are any FP registers
4566          left.  Non MIPS_EABI targets also pass the FP in the integer
4567          registers so also round up normal registers.  */
4568       if (abi_regsize < 8 && fp_register_arg_p (gdbarch, typecode, arg_type))
4569         {
4570           if ((float_argreg & 1))
4571             float_argreg++;
4572         }
4573
4574       /* Floating point arguments passed in registers have to be
4575          treated specially.  On 32-bit architectures, doubles
4576          are passed in register pairs; the even register gets
4577          the low word, and the odd register gets the high word.
4578          On non-EABI processors, the first two floating point arguments are
4579          also copied to general registers, because MIPS16 functions
4580          don't use float registers for arguments.  This duplication of
4581          arguments in general registers can't hurt non-MIPS16 functions
4582          because those registers are normally skipped.  */
4583       /* MIPS_EABI squeezes a struct that contains a single floating
4584          point value into an FP register instead of pushing it onto the
4585          stack.  */
4586       if (fp_register_arg_p (gdbarch, typecode, arg_type)
4587           && float_argreg <= MIPS_LAST_FP_ARG_REGNUM (gdbarch))
4588         {
4589           /* EABI32 will pass doubles in consecutive registers, even on
4590              64-bit cores.  At one time, we used to check the size of
4591              `float_argreg' to determine whether or not to pass doubles
4592              in consecutive registers, but this is not sufficient for
4593              making the ABI determination.  */
4594           if (len == 8 && mips_abi (gdbarch) == MIPS_ABI_EABI32)
4595             {
4596               int low_offset = gdbarch_byte_order (gdbarch)
4597                                == BFD_ENDIAN_BIG ? 4 : 0;
4598               long regval;
4599
4600               /* Write the low word of the double to the even register(s).  */
4601               regval = extract_signed_integer (val + low_offset,
4602                                                4, byte_order);
4603               if (mips_debug)
4604                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
4605                                     float_argreg, phex (regval, 4));
4606               regcache_cooked_write_signed (regcache, float_argreg++, regval);
4607
4608               /* Write the high word of the double to the odd register(s).  */
4609               regval = extract_signed_integer (val + 4 - low_offset,
4610                                                4, byte_order);
4611               if (mips_debug)
4612                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
4613                                     float_argreg, phex (regval, 4));
4614               regcache_cooked_write_signed (regcache, float_argreg++, regval);
4615             }
4616           else
4617             {
4618               /* This is a floating point value that fits entirely
4619                  in a single register.  */
4620               /* On 32 bit ABI's the float_argreg is further adjusted
4621                  above to ensure that it is even register aligned.  */
4622               LONGEST regval = extract_signed_integer (val, len, byte_order);
4623               if (mips_debug)
4624                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
4625                                     float_argreg, phex (regval, len));
4626               regcache_cooked_write_signed (regcache, float_argreg++, regval);
4627             }
4628         }
4629       else
4630         {
4631           /* Copy the argument to general registers or the stack in
4632              register-sized pieces.  Large arguments are split between
4633              registers and stack.  */
4634           /* Note: structs whose size is not a multiple of abi_regsize
4635              are treated specially: Irix cc passes
4636              them in registers where gcc sometimes puts them on the
4637              stack.  For maximum compatibility, we will put them in
4638              both places.  */
4639           int odd_sized_struct = (len > abi_regsize && len % abi_regsize != 0);
4640
4641           /* Note: Floating-point values that didn't fit into an FP
4642              register are only written to memory.  */
4643           while (len > 0)
4644             {
4645               /* Remember if the argument was written to the stack.  */
4646               int stack_used_p = 0;
4647               int partial_len = (len < abi_regsize ? len : abi_regsize);
4648
4649               if (mips_debug)
4650                 fprintf_unfiltered (gdb_stdlog, " -- partial=%d",
4651                                     partial_len);
4652
4653               /* Write this portion of the argument to the stack.  */
4654               if (argreg > MIPS_LAST_ARG_REGNUM (gdbarch)
4655                   || odd_sized_struct
4656                   || fp_register_arg_p (gdbarch, typecode, arg_type))
4657                 {
4658                   /* Should shorter than int integer values be
4659                      promoted to int before being stored?  */
4660                   int longword_offset = 0;
4661                   CORE_ADDR addr;
4662                   stack_used_p = 1;
4663                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
4664                     {
4665                       if (abi_regsize == 8
4666                           && (typecode == TYPE_CODE_INT
4667                               || typecode == TYPE_CODE_PTR
4668                               || typecode == TYPE_CODE_FLT) && len <= 4)
4669                         longword_offset = abi_regsize - len;
4670                       else if ((typecode == TYPE_CODE_STRUCT
4671                                 || typecode == TYPE_CODE_UNION)
4672                                && TYPE_LENGTH (arg_type) < abi_regsize)
4673                         longword_offset = abi_regsize - len;
4674                     }
4675
4676                   if (mips_debug)
4677                     {
4678                       fprintf_unfiltered (gdb_stdlog, " - stack_offset=%s",
4679                                           paddress (gdbarch, stack_offset));
4680                       fprintf_unfiltered (gdb_stdlog, " longword_offset=%s",
4681                                           paddress (gdbarch, longword_offset));
4682                     }
4683
4684                   addr = sp + stack_offset + longword_offset;
4685
4686                   if (mips_debug)
4687                     {
4688                       int i;
4689                       fprintf_unfiltered (gdb_stdlog, " @%s ",
4690                                           paddress (gdbarch, addr));
4691                       for (i = 0; i < partial_len; i++)
4692                         {
4693                           fprintf_unfiltered (gdb_stdlog, "%02x",
4694                                               val[i] & 0xff);
4695                         }
4696                     }
4697                   write_memory (addr, val, partial_len);
4698                 }
4699
4700               /* Note!!! This is NOT an else clause.  Odd sized
4701                  structs may go thru BOTH paths.  Floating point
4702                  arguments will not.  */
4703               /* Write this portion of the argument to a general
4704                  purpose register.  */
4705               if (argreg <= MIPS_LAST_ARG_REGNUM (gdbarch)
4706                   && !fp_register_arg_p (gdbarch, typecode, arg_type))
4707                 {
4708                   LONGEST regval =
4709                     extract_signed_integer (val, partial_len, byte_order);
4710
4711                   if (mips_debug)
4712                     fprintf_filtered (gdb_stdlog, " - reg=%d val=%s",
4713                                       argreg,
4714                                       phex (regval, abi_regsize));
4715                   regcache_cooked_write_signed (regcache, argreg, regval);
4716                   argreg++;
4717                 }
4718
4719               len -= partial_len;
4720               val += partial_len;
4721
4722               /* Compute the offset into the stack at which we will
4723                  copy the next parameter.
4724
4725                  In the new EABI (and the NABI32), the stack_offset
4726                  only needs to be adjusted when it has been used.  */
4727
4728               if (stack_used_p)
4729                 stack_offset += align_up (partial_len, abi_regsize);
4730             }
4731         }
4732       if (mips_debug)
4733         fprintf_unfiltered (gdb_stdlog, "\n");
4734     }
4735
4736   regcache_cooked_write_signed (regcache, MIPS_SP_REGNUM, sp);
4737
4738   /* Return adjusted stack pointer.  */
4739   return sp;
4740 }
4741
4742 /* Determine the return value convention being used.  */
4743
4744 static enum return_value_convention
4745 mips_eabi_return_value (struct gdbarch *gdbarch, struct value *function,
4746                         struct type *type, struct regcache *regcache,
4747                         gdb_byte *readbuf, const gdb_byte *writebuf)
4748 {
4749   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
4750   int fp_return_type = 0;
4751   int offset, regnum, xfer;
4752
4753   if (TYPE_LENGTH (type) > 2 * mips_abi_regsize (gdbarch))
4754     return RETURN_VALUE_STRUCT_CONVENTION;
4755
4756   /* Floating point type?  */
4757   if (tdep->mips_fpu_type != MIPS_FPU_NONE)
4758     {
4759       if (TYPE_CODE (type) == TYPE_CODE_FLT)
4760         fp_return_type = 1;
4761       /* Structs with a single field of float type 
4762          are returned in a floating point register.  */
4763       if ((TYPE_CODE (type) == TYPE_CODE_STRUCT
4764            || TYPE_CODE (type) == TYPE_CODE_UNION)
4765           && TYPE_NFIELDS (type) == 1)
4766         {
4767           struct type *fieldtype = TYPE_FIELD_TYPE (type, 0);
4768
4769           if (TYPE_CODE (check_typedef (fieldtype)) == TYPE_CODE_FLT)
4770             fp_return_type = 1;
4771         }
4772     }
4773
4774   if (fp_return_type)      
4775     {
4776       /* A floating-point value belongs in the least significant part
4777          of FP0/FP1.  */
4778       if (mips_debug)
4779         fprintf_unfiltered (gdb_stderr, "Return float in $fp0\n");
4780       regnum = mips_regnum (gdbarch)->fp0;
4781     }
4782   else 
4783     {
4784       /* An integer value goes in V0/V1.  */
4785       if (mips_debug)
4786         fprintf_unfiltered (gdb_stderr, "Return scalar in $v0\n");
4787       regnum = MIPS_V0_REGNUM;
4788     }
4789   for (offset = 0;
4790        offset < TYPE_LENGTH (type);
4791        offset += mips_abi_regsize (gdbarch), regnum++)
4792     {
4793       xfer = mips_abi_regsize (gdbarch);
4794       if (offset + xfer > TYPE_LENGTH (type))
4795         xfer = TYPE_LENGTH (type) - offset;
4796       mips_xfer_register (gdbarch, regcache,
4797                           gdbarch_num_regs (gdbarch) + regnum, xfer,
4798                           gdbarch_byte_order (gdbarch), readbuf, writebuf,
4799                           offset);
4800     }
4801
4802   return RETURN_VALUE_REGISTER_CONVENTION;
4803 }
4804
4805
4806 /* N32/N64 ABI stuff.  */
4807
4808 /* Search for a naturally aligned double at OFFSET inside a struct
4809    ARG_TYPE.  The N32 / N64 ABIs pass these in floating point
4810    registers.  */
4811
4812 static int
4813 mips_n32n64_fp_arg_chunk_p (struct gdbarch *gdbarch, struct type *arg_type,
4814                             int offset)
4815 {
4816   int i;
4817
4818   if (TYPE_CODE (arg_type) != TYPE_CODE_STRUCT)
4819     return 0;
4820
4821   if (MIPS_FPU_TYPE (gdbarch) != MIPS_FPU_DOUBLE)
4822     return 0;
4823
4824   if (TYPE_LENGTH (arg_type) < offset + MIPS64_REGSIZE)
4825     return 0;
4826
4827   for (i = 0; i < TYPE_NFIELDS (arg_type); i++)
4828     {
4829       int pos;
4830       struct type *field_type;
4831
4832       /* We're only looking at normal fields.  */
4833       if (field_is_static (&TYPE_FIELD (arg_type, i))
4834           || (TYPE_FIELD_BITPOS (arg_type, i) % 8) != 0)
4835         continue;
4836
4837       /* If we have gone past the offset, there is no double to pass.  */
4838       pos = TYPE_FIELD_BITPOS (arg_type, i) / 8;
4839       if (pos > offset)
4840         return 0;
4841
4842       field_type = check_typedef (TYPE_FIELD_TYPE (arg_type, i));
4843
4844       /* If this field is entirely before the requested offset, go
4845          on to the next one.  */
4846       if (pos + TYPE_LENGTH (field_type) <= offset)
4847         continue;
4848
4849       /* If this is our special aligned double, we can stop.  */
4850       if (TYPE_CODE (field_type) == TYPE_CODE_FLT
4851           && TYPE_LENGTH (field_type) == MIPS64_REGSIZE)
4852         return 1;
4853
4854       /* This field starts at or before the requested offset, and
4855          overlaps it.  If it is a structure, recurse inwards.  */
4856       return mips_n32n64_fp_arg_chunk_p (gdbarch, field_type, offset - pos);
4857     }
4858
4859   return 0;
4860 }
4861
4862 static CORE_ADDR
4863 mips_n32n64_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
4864                              struct regcache *regcache, CORE_ADDR bp_addr,
4865                              int nargs, struct value **args, CORE_ADDR sp,
4866                              int struct_return, CORE_ADDR struct_addr)
4867 {
4868   int argreg;
4869   int float_argreg;
4870   int argnum;
4871   int len = 0;
4872   int stack_offset = 0;
4873   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4874   CORE_ADDR func_addr = find_function_addr (function, NULL);
4875
4876   /* For shared libraries, "t9" needs to point at the function
4877      address.  */
4878   regcache_cooked_write_signed (regcache, MIPS_T9_REGNUM, func_addr);
4879
4880   /* Set the return address register to point to the entry point of
4881      the program, where a breakpoint lies in wait.  */
4882   regcache_cooked_write_signed (regcache, MIPS_RA_REGNUM, bp_addr);
4883
4884   /* First ensure that the stack and structure return address (if any)
4885      are properly aligned.  The stack has to be at least 64-bit
4886      aligned even on 32-bit machines, because doubles must be 64-bit
4887      aligned.  For n32 and n64, stack frames need to be 128-bit
4888      aligned, so we round to this widest known alignment.  */
4889
4890   sp = align_down (sp, 16);
4891   struct_addr = align_down (struct_addr, 16);
4892
4893   /* Now make space on the stack for the args.  */
4894   for (argnum = 0; argnum < nargs; argnum++)
4895     len += align_up (TYPE_LENGTH (value_type (args[argnum])), MIPS64_REGSIZE);
4896   sp -= align_up (len, 16);
4897
4898   if (mips_debug)
4899     fprintf_unfiltered (gdb_stdlog,
4900                         "mips_n32n64_push_dummy_call: sp=%s allocated %ld\n",
4901                         paddress (gdbarch, sp), (long) align_up (len, 16));
4902
4903   /* Initialize the integer and float register pointers.  */
4904   argreg = MIPS_A0_REGNUM;
4905   float_argreg = mips_fpa0_regnum (gdbarch);
4906
4907   /* The struct_return pointer occupies the first parameter-passing reg.  */
4908   if (struct_return)
4909     {
4910       if (mips_debug)
4911         fprintf_unfiltered (gdb_stdlog,
4912                             "mips_n32n64_push_dummy_call: "
4913                             "struct_return reg=%d %s\n",
4914                             argreg, paddress (gdbarch, struct_addr));
4915       regcache_cooked_write_unsigned (regcache, argreg++, struct_addr);
4916     }
4917
4918   /* Now load as many as possible of the first arguments into
4919      registers, and push the rest onto the stack.  Loop thru args
4920      from first to last.  */
4921   for (argnum = 0; argnum < nargs; argnum++)
4922     {
4923       const gdb_byte *val;
4924       struct value *arg = args[argnum];
4925       struct type *arg_type = check_typedef (value_type (arg));
4926       int len = TYPE_LENGTH (arg_type);
4927       enum type_code typecode = TYPE_CODE (arg_type);
4928
4929       if (mips_debug)
4930         fprintf_unfiltered (gdb_stdlog,
4931                             "mips_n32n64_push_dummy_call: %d len=%d type=%d",
4932                             argnum + 1, len, (int) typecode);
4933
4934       val = value_contents (arg);
4935
4936       /* A 128-bit long double value requires an even-odd pair of
4937          floating-point registers.  */
4938       if (len == 16
4939           && fp_register_arg_p (gdbarch, typecode, arg_type)
4940           && (float_argreg & 1))
4941         {
4942           float_argreg++;
4943           argreg++;
4944         }
4945
4946       if (fp_register_arg_p (gdbarch, typecode, arg_type)
4947           && argreg <= MIPS_LAST_ARG_REGNUM (gdbarch))
4948         {
4949           /* This is a floating point value that fits entirely
4950              in a single register or a pair of registers.  */
4951           int reglen = (len <= MIPS64_REGSIZE ? len : MIPS64_REGSIZE);
4952           LONGEST regval = extract_unsigned_integer (val, reglen, byte_order);
4953           if (mips_debug)
4954             fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
4955                                 float_argreg, phex (regval, reglen));
4956           regcache_cooked_write_unsigned (regcache, float_argreg, regval);
4957
4958           if (mips_debug)
4959             fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
4960                                 argreg, phex (regval, reglen));
4961           regcache_cooked_write_unsigned (regcache, argreg, regval);
4962           float_argreg++;
4963           argreg++;
4964           if (len == 16)
4965             {
4966               regval = extract_unsigned_integer (val + reglen,
4967                                                  reglen, byte_order);
4968               if (mips_debug)
4969                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
4970                                     float_argreg, phex (regval, reglen));
4971               regcache_cooked_write_unsigned (regcache, float_argreg, regval);
4972
4973               if (mips_debug)
4974                 fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
4975                                     argreg, phex (regval, reglen));
4976               regcache_cooked_write_unsigned (regcache, argreg, regval);
4977               float_argreg++;
4978               argreg++;
4979             }
4980         }
4981       else
4982         {
4983           /* Copy the argument to general registers or the stack in
4984              register-sized pieces.  Large arguments are split between
4985              registers and stack.  */
4986           /* For N32/N64, structs, unions, or other composite types are
4987              treated as a sequence of doublewords, and are passed in integer
4988              or floating point registers as though they were simple scalar
4989              parameters to the extent that they fit, with any excess on the
4990              stack packed according to the normal memory layout of the
4991              object.
4992              The caller does not reserve space for the register arguments;
4993              the callee is responsible for reserving it if required.  */
4994           /* Note: Floating-point values that didn't fit into an FP
4995              register are only written to memory.  */
4996           while (len > 0)
4997             {
4998               /* Remember if the argument was written to the stack.  */
4999               int stack_used_p = 0;
5000               int partial_len = (len < MIPS64_REGSIZE ? len : MIPS64_REGSIZE);
5001
5002               if (mips_debug)
5003                 fprintf_unfiltered (gdb_stdlog, " -- partial=%d",
5004                                     partial_len);
5005
5006               if (fp_register_arg_p (gdbarch, typecode, arg_type))
5007                 gdb_assert (argreg > MIPS_LAST_ARG_REGNUM (gdbarch));
5008
5009               /* Write this portion of the argument to the stack.  */
5010               if (argreg > MIPS_LAST_ARG_REGNUM (gdbarch))
5011                 {
5012                   /* Should shorter than int integer values be
5013                      promoted to int before being stored?  */
5014                   int longword_offset = 0;
5015                   CORE_ADDR addr;
5016                   stack_used_p = 1;
5017                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
5018                     {
5019                       if ((typecode == TYPE_CODE_INT
5020                            || typecode == TYPE_CODE_PTR)
5021                           && len <= 4)
5022                         longword_offset = MIPS64_REGSIZE - len;
5023                     }
5024
5025                   if (mips_debug)
5026                     {
5027                       fprintf_unfiltered (gdb_stdlog, " - stack_offset=%s",
5028                                           paddress (gdbarch, stack_offset));
5029                       fprintf_unfiltered (gdb_stdlog, " longword_offset=%s",
5030                                           paddress (gdbarch, longword_offset));
5031                     }
5032
5033                   addr = sp + stack_offset + longword_offset;
5034
5035                   if (mips_debug)
5036                     {
5037                       int i;
5038                       fprintf_unfiltered (gdb_stdlog, " @%s ",
5039                                           paddress (gdbarch, addr));
5040                       for (i = 0; i < partial_len; i++)
5041                         {
5042                           fprintf_unfiltered (gdb_stdlog, "%02x",
5043                                               val[i] & 0xff);
5044                         }
5045                     }
5046                   write_memory (addr, val, partial_len);
5047                 }
5048
5049               /* Note!!! This is NOT an else clause.  Odd sized
5050                  structs may go thru BOTH paths.  */
5051               /* Write this portion of the argument to a general
5052                  purpose register.  */
5053               if (argreg <= MIPS_LAST_ARG_REGNUM (gdbarch))
5054                 {
5055                   LONGEST regval;
5056
5057                   /* Sign extend pointers, 32-bit integers and signed
5058                      16-bit and 8-bit integers; everything else is taken
5059                      as is.  */
5060
5061                   if ((partial_len == 4
5062                        && (typecode == TYPE_CODE_PTR
5063                            || typecode == TYPE_CODE_INT))
5064                       || (partial_len < 4
5065                           && typecode == TYPE_CODE_INT
5066                           && !TYPE_UNSIGNED (arg_type)))
5067                     regval = extract_signed_integer (val, partial_len,
5068                                                      byte_order);
5069                   else
5070                     regval = extract_unsigned_integer (val, partial_len,
5071                                                        byte_order);
5072
5073                   /* A non-floating-point argument being passed in a
5074                      general register.  If a struct or union, and if
5075                      the remaining length is smaller than the register
5076                      size, we have to adjust the register value on
5077                      big endian targets.
5078
5079                      It does not seem to be necessary to do the
5080                      same for integral types.  */
5081
5082                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG
5083                       && partial_len < MIPS64_REGSIZE
5084                       && (typecode == TYPE_CODE_STRUCT
5085                           || typecode == TYPE_CODE_UNION))
5086                     regval <<= ((MIPS64_REGSIZE - partial_len)
5087                                 * TARGET_CHAR_BIT);
5088
5089                   if (mips_debug)
5090                     fprintf_filtered (gdb_stdlog, " - reg=%d val=%s",
5091                                       argreg,
5092                                       phex (regval, MIPS64_REGSIZE));
5093                   regcache_cooked_write_unsigned (regcache, argreg, regval);
5094
5095                   if (mips_n32n64_fp_arg_chunk_p (gdbarch, arg_type,
5096                                                   TYPE_LENGTH (arg_type) - len))
5097                     {
5098                       if (mips_debug)
5099                         fprintf_filtered (gdb_stdlog, " - fpreg=%d val=%s",
5100                                           float_argreg,
5101                                           phex (regval, MIPS64_REGSIZE));
5102                       regcache_cooked_write_unsigned (regcache, float_argreg,
5103                                                       regval);
5104                     }
5105
5106                   float_argreg++;
5107                   argreg++;
5108                 }
5109
5110               len -= partial_len;
5111               val += partial_len;
5112
5113               /* Compute the offset into the stack at which we will
5114                  copy the next parameter.
5115
5116                  In N32 (N64?), the stack_offset only needs to be
5117                  adjusted when it has been used.  */
5118
5119               if (stack_used_p)
5120                 stack_offset += align_up (partial_len, MIPS64_REGSIZE);
5121             }
5122         }
5123       if (mips_debug)
5124         fprintf_unfiltered (gdb_stdlog, "\n");
5125     }
5126
5127   regcache_cooked_write_signed (regcache, MIPS_SP_REGNUM, sp);
5128
5129   /* Return adjusted stack pointer.  */
5130   return sp;
5131 }
5132
5133 static enum return_value_convention
5134 mips_n32n64_return_value (struct gdbarch *gdbarch, struct value *function,
5135                           struct type *type, struct regcache *regcache,
5136                           gdb_byte *readbuf, const gdb_byte *writebuf)
5137 {
5138   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
5139
5140   /* From MIPSpro N32 ABI Handbook, Document Number: 007-2816-004
5141
5142      Function results are returned in $2 (and $3 if needed), or $f0 (and $f2
5143      if needed), as appropriate for the type.  Composite results (struct,
5144      union, or array) are returned in $2/$f0 and $3/$f2 according to the
5145      following rules:
5146
5147      * A struct with only one or two floating point fields is returned in $f0
5148      (and $f2 if necessary).  This is a generalization of the Fortran COMPLEX
5149      case.
5150
5151      * Any other composite results of at most 128 bits are returned in
5152      $2 (first 64 bits) and $3 (remainder, if necessary).
5153
5154      * Larger composite results are handled by converting the function to a
5155      procedure with an implicit first parameter, which is a pointer to an area
5156      reserved by the caller to receive the result.  [The o32-bit ABI requires
5157      that all composite results be handled by conversion to implicit first
5158      parameters.  The MIPS/SGI Fortran implementation has always made a
5159      specific exception to return COMPLEX results in the floating point
5160      registers.]  */
5161
5162   if (TYPE_LENGTH (type) > 2 * MIPS64_REGSIZE)
5163     return RETURN_VALUE_STRUCT_CONVENTION;
5164   else if (TYPE_CODE (type) == TYPE_CODE_FLT
5165            && TYPE_LENGTH (type) == 16
5166            && tdep->mips_fpu_type != MIPS_FPU_NONE)
5167     {
5168       /* A 128-bit floating-point value fills both $f0 and $f2.  The
5169          two registers are used in the same as memory order, so the
5170          eight bytes with the lower memory address are in $f0.  */
5171       if (mips_debug)
5172         fprintf_unfiltered (gdb_stderr, "Return float in $f0 and $f2\n");
5173       mips_xfer_register (gdbarch, regcache,
5174                           (gdbarch_num_regs (gdbarch)
5175                            + mips_regnum (gdbarch)->fp0),
5176                           8, gdbarch_byte_order (gdbarch),
5177                           readbuf, writebuf, 0);
5178       mips_xfer_register (gdbarch, regcache,
5179                           (gdbarch_num_regs (gdbarch)
5180                            + mips_regnum (gdbarch)->fp0 + 2),
5181                           8, gdbarch_byte_order (gdbarch),
5182                           readbuf ? readbuf + 8 : readbuf,
5183                           writebuf ? writebuf + 8 : writebuf, 0);
5184       return RETURN_VALUE_REGISTER_CONVENTION;
5185     }
5186   else if (TYPE_CODE (type) == TYPE_CODE_FLT
5187            && tdep->mips_fpu_type != MIPS_FPU_NONE)
5188     {
5189       /* A single or double floating-point value that fits in FP0.  */
5190       if (mips_debug)
5191         fprintf_unfiltered (gdb_stderr, "Return float in $fp0\n");
5192       mips_xfer_register (gdbarch, regcache,
5193                           (gdbarch_num_regs (gdbarch)
5194                            + mips_regnum (gdbarch)->fp0),
5195                           TYPE_LENGTH (type),
5196                           gdbarch_byte_order (gdbarch),
5197                           readbuf, writebuf, 0);
5198       return RETURN_VALUE_REGISTER_CONVENTION;
5199     }
5200   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT
5201            && TYPE_NFIELDS (type) <= 2
5202            && TYPE_NFIELDS (type) >= 1
5203            && ((TYPE_NFIELDS (type) == 1
5204                 && (TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (type, 0)))
5205                     == TYPE_CODE_FLT))
5206                || (TYPE_NFIELDS (type) == 2
5207                    && (TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (type, 0)))
5208                        == TYPE_CODE_FLT)
5209                    && (TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (type, 1)))
5210                        == TYPE_CODE_FLT))))
5211     {
5212       /* A struct that contains one or two floats.  Each value is part
5213          in the least significant part of their floating point
5214          register (or GPR, for soft float).  */
5215       int regnum;
5216       int field;
5217       for (field = 0, regnum = (tdep->mips_fpu_type != MIPS_FPU_NONE
5218                                 ? mips_regnum (gdbarch)->fp0
5219                                 : MIPS_V0_REGNUM);
5220            field < TYPE_NFIELDS (type); field++, regnum += 2)
5221         {
5222           int offset = (FIELD_BITPOS (TYPE_FIELDS (type)[field])
5223                         / TARGET_CHAR_BIT);
5224           if (mips_debug)
5225             fprintf_unfiltered (gdb_stderr, "Return float struct+%d\n",
5226                                 offset);
5227           if (TYPE_LENGTH (TYPE_FIELD_TYPE (type, field)) == 16)
5228             {
5229               /* A 16-byte long double field goes in two consecutive
5230                  registers.  */
5231               mips_xfer_register (gdbarch, regcache,
5232                                   gdbarch_num_regs (gdbarch) + regnum,
5233                                   8,
5234                                   gdbarch_byte_order (gdbarch),
5235                                   readbuf, writebuf, offset);
5236               mips_xfer_register (gdbarch, regcache,
5237                                   gdbarch_num_regs (gdbarch) + regnum + 1,
5238                                   8,
5239                                   gdbarch_byte_order (gdbarch),
5240                                   readbuf, writebuf, offset + 8);
5241             }
5242           else
5243             mips_xfer_register (gdbarch, regcache,
5244                                 gdbarch_num_regs (gdbarch) + regnum,
5245                                 TYPE_LENGTH (TYPE_FIELD_TYPE (type, field)),
5246                                 gdbarch_byte_order (gdbarch),
5247                                 readbuf, writebuf, offset);
5248         }
5249       return RETURN_VALUE_REGISTER_CONVENTION;
5250     }
5251   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT
5252            || TYPE_CODE (type) == TYPE_CODE_UNION
5253            || TYPE_CODE (type) == TYPE_CODE_ARRAY)
5254     {
5255       /* A composite type.  Extract the left justified value,
5256          regardless of the byte order.  I.e. DO NOT USE
5257          mips_xfer_lower.  */
5258       int offset;
5259       int regnum;
5260       for (offset = 0, regnum = MIPS_V0_REGNUM;
5261            offset < TYPE_LENGTH (type);
5262            offset += register_size (gdbarch, regnum), regnum++)
5263         {
5264           int xfer = register_size (gdbarch, regnum);
5265           if (offset + xfer > TYPE_LENGTH (type))
5266             xfer = TYPE_LENGTH (type) - offset;
5267           if (mips_debug)
5268             fprintf_unfiltered (gdb_stderr, "Return struct+%d:%d in $%d\n",
5269                                 offset, xfer, regnum);
5270           mips_xfer_register (gdbarch, regcache,
5271                               gdbarch_num_regs (gdbarch) + regnum,
5272                               xfer, BFD_ENDIAN_UNKNOWN, readbuf, writebuf,
5273                               offset);
5274         }
5275       return RETURN_VALUE_REGISTER_CONVENTION;
5276     }
5277   else
5278     {
5279       /* A scalar extract each part but least-significant-byte
5280          justified.  */
5281       int offset;
5282       int regnum;
5283       for (offset = 0, regnum = MIPS_V0_REGNUM;
5284            offset < TYPE_LENGTH (type);
5285            offset += register_size (gdbarch, regnum), regnum++)
5286         {
5287           int xfer = register_size (gdbarch, regnum);
5288           if (offset + xfer > TYPE_LENGTH (type))
5289             xfer = TYPE_LENGTH (type) - offset;
5290           if (mips_debug)
5291             fprintf_unfiltered (gdb_stderr, "Return scalar+%d:%d in $%d\n",
5292                                 offset, xfer, regnum);
5293           mips_xfer_register (gdbarch, regcache,
5294                               gdbarch_num_regs (gdbarch) + regnum,
5295                               xfer, gdbarch_byte_order (gdbarch),
5296                               readbuf, writebuf, offset);
5297         }
5298       return RETURN_VALUE_REGISTER_CONVENTION;
5299     }
5300 }
5301
5302 /* Which registers to use for passing floating-point values between
5303    function calls, one of floating-point, general and both kinds of
5304    registers.  O32 and O64 use different register kinds for standard
5305    MIPS and MIPS16 code; to make the handling of cases where we may
5306    not know what kind of code is being used (e.g. no debug information)
5307    easier we sometimes use both kinds.  */
5308
5309 enum mips_fval_reg
5310 {
5311   mips_fval_fpr,
5312   mips_fval_gpr,
5313   mips_fval_both
5314 };
5315
5316 /* O32 ABI stuff.  */
5317
5318 static CORE_ADDR
5319 mips_o32_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
5320                           struct regcache *regcache, CORE_ADDR bp_addr,
5321                           int nargs, struct value **args, CORE_ADDR sp,
5322                           int struct_return, CORE_ADDR struct_addr)
5323 {
5324   int argreg;
5325   int float_argreg;
5326   int argnum;
5327   int len = 0;
5328   int stack_offset = 0;
5329   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
5330   CORE_ADDR func_addr = find_function_addr (function, NULL);
5331
5332   /* For shared libraries, "t9" needs to point at the function
5333      address.  */
5334   regcache_cooked_write_signed (regcache, MIPS_T9_REGNUM, func_addr);
5335
5336   /* Set the return address register to point to the entry point of
5337      the program, where a breakpoint lies in wait.  */
5338   regcache_cooked_write_signed (regcache, MIPS_RA_REGNUM, bp_addr);
5339
5340   /* First ensure that the stack and structure return address (if any)
5341      are properly aligned.  The stack has to be at least 64-bit
5342      aligned even on 32-bit machines, because doubles must be 64-bit
5343      aligned.  For n32 and n64, stack frames need to be 128-bit
5344      aligned, so we round to this widest known alignment.  */
5345
5346   sp = align_down (sp, 16);
5347   struct_addr = align_down (struct_addr, 16);
5348
5349   /* Now make space on the stack for the args.  */
5350   for (argnum = 0; argnum < nargs; argnum++)
5351     {
5352       struct type *arg_type = check_typedef (value_type (args[argnum]));
5353
5354       /* Align to double-word if necessary.  */
5355       if (mips_type_needs_double_align (arg_type))
5356         len = align_up (len, MIPS32_REGSIZE * 2);
5357       /* Allocate space on the stack.  */
5358       len += align_up (TYPE_LENGTH (arg_type), MIPS32_REGSIZE);
5359     }
5360   sp -= align_up (len, 16);
5361
5362   if (mips_debug)
5363     fprintf_unfiltered (gdb_stdlog,
5364                         "mips_o32_push_dummy_call: sp=%s allocated %ld\n",
5365                         paddress (gdbarch, sp), (long) align_up (len, 16));
5366
5367   /* Initialize the integer and float register pointers.  */
5368   argreg = MIPS_A0_REGNUM;
5369   float_argreg = mips_fpa0_regnum (gdbarch);
5370
5371   /* The struct_return pointer occupies the first parameter-passing reg.  */
5372   if (struct_return)
5373     {
5374       if (mips_debug)
5375         fprintf_unfiltered (gdb_stdlog,
5376                             "mips_o32_push_dummy_call: "
5377                             "struct_return reg=%d %s\n",
5378                             argreg, paddress (gdbarch, struct_addr));
5379       regcache_cooked_write_unsigned (regcache, argreg++, struct_addr);
5380       stack_offset += MIPS32_REGSIZE;
5381     }
5382
5383   /* Now load as many as possible of the first arguments into
5384      registers, and push the rest onto the stack.  Loop thru args
5385      from first to last.  */
5386   for (argnum = 0; argnum < nargs; argnum++)
5387     {
5388       const gdb_byte *val;
5389       struct value *arg = args[argnum];
5390       struct type *arg_type = check_typedef (value_type (arg));
5391       int len = TYPE_LENGTH (arg_type);
5392       enum type_code typecode = TYPE_CODE (arg_type);
5393
5394       if (mips_debug)
5395         fprintf_unfiltered (gdb_stdlog,
5396                             "mips_o32_push_dummy_call: %d len=%d type=%d",
5397                             argnum + 1, len, (int) typecode);
5398
5399       val = value_contents (arg);
5400
5401       /* 32-bit ABIs always start floating point arguments in an
5402          even-numbered floating point register.  Round the FP register
5403          up before the check to see if there are any FP registers
5404          left.  O32 targets also pass the FP in the integer registers
5405          so also round up normal registers.  */
5406       if (fp_register_arg_p (gdbarch, typecode, arg_type))
5407         {
5408           if ((float_argreg & 1))
5409             float_argreg++;
5410         }
5411
5412       /* Floating point arguments passed in registers have to be
5413          treated specially.  On 32-bit architectures, doubles are
5414          passed in register pairs; the even FP register gets the
5415          low word, and the odd FP register gets the high word.
5416          On O32, the first two floating point arguments are also
5417          copied to general registers, following their memory order,
5418          because MIPS16 functions don't use float registers for
5419          arguments.  This duplication of arguments in general
5420          registers can't hurt non-MIPS16 functions, because those
5421          registers are normally skipped.  */
5422
5423       if (fp_register_arg_p (gdbarch, typecode, arg_type)
5424           && float_argreg <= MIPS_LAST_FP_ARG_REGNUM (gdbarch))
5425         {
5426           if (register_size (gdbarch, float_argreg) < 8 && len == 8)
5427             {
5428               int freg_offset = gdbarch_byte_order (gdbarch)
5429                                 == BFD_ENDIAN_BIG ? 1 : 0;
5430               unsigned long regval;
5431
5432               /* First word.  */
5433               regval = extract_unsigned_integer (val, 4, byte_order);
5434               if (mips_debug)
5435                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
5436                                     float_argreg + freg_offset,
5437                                     phex (regval, 4));
5438               regcache_cooked_write_unsigned (regcache,
5439                                               float_argreg++ + freg_offset,
5440                                               regval);
5441               if (mips_debug)
5442                 fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
5443                                     argreg, phex (regval, 4));
5444               regcache_cooked_write_unsigned (regcache, argreg++, regval);
5445
5446               /* Second word.  */
5447               regval = extract_unsigned_integer (val + 4, 4, byte_order);
5448               if (mips_debug)
5449                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
5450                                     float_argreg - freg_offset,
5451                                     phex (regval, 4));
5452               regcache_cooked_write_unsigned (regcache,
5453                                               float_argreg++ - freg_offset,
5454                                               regval);
5455               if (mips_debug)
5456                 fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
5457                                     argreg, phex (regval, 4));
5458               regcache_cooked_write_unsigned (regcache, argreg++, regval);
5459             }
5460           else
5461             {
5462               /* This is a floating point value that fits entirely
5463                  in a single register.  */
5464               /* On 32 bit ABI's the float_argreg is further adjusted
5465                  above to ensure that it is even register aligned.  */
5466               LONGEST regval = extract_unsigned_integer (val, len, byte_order);
5467               if (mips_debug)
5468                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
5469                                     float_argreg, phex (regval, len));
5470               regcache_cooked_write_unsigned (regcache,
5471                                               float_argreg++, regval);
5472               /* Although two FP registers are reserved for each
5473                  argument, only one corresponding integer register is
5474                  reserved.  */
5475               if (mips_debug)
5476                 fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
5477                                     argreg, phex (regval, len));
5478               regcache_cooked_write_unsigned (regcache, argreg++, regval);
5479             }
5480           /* Reserve space for the FP register.  */
5481           stack_offset += align_up (len, MIPS32_REGSIZE);
5482         }
5483       else
5484         {
5485           /* Copy the argument to general registers or the stack in
5486              register-sized pieces.  Large arguments are split between
5487              registers and stack.  */
5488           /* Note: structs whose size is not a multiple of MIPS32_REGSIZE
5489              are treated specially: Irix cc passes
5490              them in registers where gcc sometimes puts them on the
5491              stack.  For maximum compatibility, we will put them in
5492              both places.  */
5493           int odd_sized_struct = (len > MIPS32_REGSIZE
5494                                   && len % MIPS32_REGSIZE != 0);
5495           /* Structures should be aligned to eight bytes (even arg registers)
5496              on MIPS_ABI_O32, if their first member has double precision.  */
5497           if (mips_type_needs_double_align (arg_type))
5498             {
5499               if ((argreg & 1))
5500                 {
5501                   argreg++;
5502                   stack_offset += MIPS32_REGSIZE;
5503                 }
5504             }
5505           while (len > 0)
5506             {
5507               int partial_len = (len < MIPS32_REGSIZE ? len : MIPS32_REGSIZE);
5508
5509               if (mips_debug)
5510                 fprintf_unfiltered (gdb_stdlog, " -- partial=%d",
5511                                     partial_len);
5512
5513               /* Write this portion of the argument to the stack.  */
5514               if (argreg > MIPS_LAST_ARG_REGNUM (gdbarch)
5515                   || odd_sized_struct)
5516                 {
5517                   /* Should shorter than int integer values be
5518                      promoted to int before being stored?  */
5519                   int longword_offset = 0;
5520                   CORE_ADDR addr;
5521
5522                   if (mips_debug)
5523                     {
5524                       fprintf_unfiltered (gdb_stdlog, " - stack_offset=%s",
5525                                           paddress (gdbarch, stack_offset));
5526                       fprintf_unfiltered (gdb_stdlog, " longword_offset=%s",
5527                                           paddress (gdbarch, longword_offset));
5528                     }
5529
5530                   addr = sp + stack_offset + longword_offset;
5531
5532                   if (mips_debug)
5533                     {
5534                       int i;
5535                       fprintf_unfiltered (gdb_stdlog, " @%s ",
5536                                           paddress (gdbarch, addr));
5537                       for (i = 0; i < partial_len; i++)
5538                         {
5539                           fprintf_unfiltered (gdb_stdlog, "%02x",
5540                                               val[i] & 0xff);
5541                         }
5542                     }
5543                   write_memory (addr, val, partial_len);
5544                 }
5545
5546               /* Note!!! This is NOT an else clause.  Odd sized
5547                  structs may go thru BOTH paths.  */
5548               /* Write this portion of the argument to a general
5549                  purpose register.  */
5550               if (argreg <= MIPS_LAST_ARG_REGNUM (gdbarch))
5551                 {
5552                   LONGEST regval = extract_signed_integer (val, partial_len,
5553                                                            byte_order);
5554                   /* Value may need to be sign extended, because
5555                      mips_isa_regsize() != mips_abi_regsize().  */
5556
5557                   /* A non-floating-point argument being passed in a
5558                      general register.  If a struct or union, and if
5559                      the remaining length is smaller than the register
5560                      size, we have to adjust the register value on
5561                      big endian targets.
5562
5563                      It does not seem to be necessary to do the
5564                      same for integral types.
5565
5566                      Also don't do this adjustment on O64 binaries.
5567
5568                      cagney/2001-07-23: gdb/179: Also, GCC, when
5569                      outputting LE O32 with sizeof (struct) <
5570                      mips_abi_regsize(), generates a left shift
5571                      as part of storing the argument in a register
5572                      (the left shift isn't generated when
5573                      sizeof (struct) >= mips_abi_regsize()).  Since
5574                      it is quite possible that this is GCC
5575                      contradicting the LE/O32 ABI, GDB has not been
5576                      adjusted to accommodate this.  Either someone
5577                      needs to demonstrate that the LE/O32 ABI
5578                      specifies such a left shift OR this new ABI gets
5579                      identified as such and GDB gets tweaked
5580                      accordingly.  */
5581
5582                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG
5583                       && partial_len < MIPS32_REGSIZE
5584                       && (typecode == TYPE_CODE_STRUCT
5585                           || typecode == TYPE_CODE_UNION))
5586                     regval <<= ((MIPS32_REGSIZE - partial_len)
5587                                 * TARGET_CHAR_BIT);
5588
5589                   if (mips_debug)
5590                     fprintf_filtered (gdb_stdlog, " - reg=%d val=%s",
5591                                       argreg,
5592                                       phex (regval, MIPS32_REGSIZE));
5593                   regcache_cooked_write_unsigned (regcache, argreg, regval);
5594                   argreg++;
5595
5596                   /* Prevent subsequent floating point arguments from
5597                      being passed in floating point registers.  */
5598                   float_argreg = MIPS_LAST_FP_ARG_REGNUM (gdbarch) + 1;
5599                 }
5600
5601               len -= partial_len;
5602               val += partial_len;
5603
5604               /* Compute the offset into the stack at which we will
5605                  copy the next parameter.
5606
5607                  In older ABIs, the caller reserved space for
5608                  registers that contained arguments.  This was loosely
5609                  refered to as their "home".  Consequently, space is
5610                  always allocated.  */
5611
5612               stack_offset += align_up (partial_len, MIPS32_REGSIZE);
5613             }
5614         }
5615       if (mips_debug)
5616         fprintf_unfiltered (gdb_stdlog, "\n");
5617     }
5618
5619   regcache_cooked_write_signed (regcache, MIPS_SP_REGNUM, sp);
5620
5621   /* Return adjusted stack pointer.  */
5622   return sp;
5623 }
5624
5625 static enum return_value_convention
5626 mips_o32_return_value (struct gdbarch *gdbarch, struct value *function,
5627                        struct type *type, struct regcache *regcache,
5628                        gdb_byte *readbuf, const gdb_byte *writebuf)
5629 {
5630   CORE_ADDR func_addr = function ? find_function_addr (function, NULL) : 0;
5631   int mips16 = mips_pc_is_mips16 (gdbarch, func_addr);
5632   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
5633   enum mips_fval_reg fval_reg;
5634
5635   fval_reg = readbuf ? mips16 ? mips_fval_gpr : mips_fval_fpr : mips_fval_both;
5636   if (TYPE_CODE (type) == TYPE_CODE_STRUCT
5637       || TYPE_CODE (type) == TYPE_CODE_UNION
5638       || TYPE_CODE (type) == TYPE_CODE_ARRAY)
5639     return RETURN_VALUE_STRUCT_CONVENTION;
5640   else if (TYPE_CODE (type) == TYPE_CODE_FLT
5641            && TYPE_LENGTH (type) == 4 && tdep->mips_fpu_type != MIPS_FPU_NONE)
5642     {
5643       /* A single-precision floating-point value.  If reading in or copying,
5644          then we get it from/put it to FP0 for standard MIPS code or GPR2
5645          for MIPS16 code.  If writing out only, then we put it to both FP0
5646          and GPR2.  We do not support reading in with no function known, if
5647          this safety check ever triggers, then we'll have to try harder.  */
5648       gdb_assert (function || !readbuf);
5649       if (mips_debug)
5650         switch (fval_reg)
5651           {
5652           case mips_fval_fpr:
5653             fprintf_unfiltered (gdb_stderr, "Return float in $fp0\n");
5654             break;
5655           case mips_fval_gpr:
5656             fprintf_unfiltered (gdb_stderr, "Return float in $2\n");
5657             break;
5658           case mips_fval_both:
5659             fprintf_unfiltered (gdb_stderr, "Return float in $fp0 and $2\n");
5660             break;
5661           }
5662       if (fval_reg != mips_fval_gpr)
5663         mips_xfer_register (gdbarch, regcache,
5664                             (gdbarch_num_regs (gdbarch)
5665                              + mips_regnum (gdbarch)->fp0),
5666                             TYPE_LENGTH (type),
5667                             gdbarch_byte_order (gdbarch),
5668                             readbuf, writebuf, 0);
5669       if (fval_reg != mips_fval_fpr)
5670         mips_xfer_register (gdbarch, regcache,
5671                             gdbarch_num_regs (gdbarch) + 2,
5672                             TYPE_LENGTH (type),
5673                             gdbarch_byte_order (gdbarch),
5674                             readbuf, writebuf, 0);
5675       return RETURN_VALUE_REGISTER_CONVENTION;
5676     }
5677   else if (TYPE_CODE (type) == TYPE_CODE_FLT
5678            && TYPE_LENGTH (type) == 8 && tdep->mips_fpu_type != MIPS_FPU_NONE)
5679     {
5680       /* A double-precision floating-point value.  If reading in or copying,
5681          then we get it from/put it to FP1 and FP0 for standard MIPS code or
5682          GPR2 and GPR3 for MIPS16 code.  If writing out only, then we put it
5683          to both FP1/FP0 and GPR2/GPR3.  We do not support reading in with
5684          no function known, if this safety check ever triggers, then we'll
5685          have to try harder.  */
5686       gdb_assert (function || !readbuf);
5687       if (mips_debug)
5688         switch (fval_reg)
5689           {
5690           case mips_fval_fpr:
5691             fprintf_unfiltered (gdb_stderr, "Return float in $fp1/$fp0\n");
5692             break;
5693           case mips_fval_gpr:
5694             fprintf_unfiltered (gdb_stderr, "Return float in $2/$3\n");
5695             break;
5696           case mips_fval_both:
5697             fprintf_unfiltered (gdb_stderr,
5698                                 "Return float in $fp1/$fp0 and $2/$3\n");
5699             break;
5700           }
5701       if (fval_reg != mips_fval_gpr)
5702         {
5703           /* The most significant part goes in FP1, and the least significant
5704              in FP0.  */
5705           switch (gdbarch_byte_order (gdbarch))
5706             {
5707             case BFD_ENDIAN_LITTLE:
5708               mips_xfer_register (gdbarch, regcache,
5709                                   (gdbarch_num_regs (gdbarch)
5710                                    + mips_regnum (gdbarch)->fp0 + 0),
5711                                   4, gdbarch_byte_order (gdbarch),
5712                                   readbuf, writebuf, 0);
5713               mips_xfer_register (gdbarch, regcache,
5714                                   (gdbarch_num_regs (gdbarch)
5715                                    + mips_regnum (gdbarch)->fp0 + 1),
5716                                   4, gdbarch_byte_order (gdbarch),
5717                                   readbuf, writebuf, 4);
5718               break;
5719             case BFD_ENDIAN_BIG:
5720               mips_xfer_register (gdbarch, regcache,
5721                                   (gdbarch_num_regs (gdbarch)
5722                                    + mips_regnum (gdbarch)->fp0 + 1),
5723                                   4, gdbarch_byte_order (gdbarch),
5724                                   readbuf, writebuf, 0);
5725               mips_xfer_register (gdbarch, regcache,
5726                                   (gdbarch_num_regs (gdbarch)
5727                                    + mips_regnum (gdbarch)->fp0 + 0),
5728                                   4, gdbarch_byte_order (gdbarch),
5729                                   readbuf, writebuf, 4);
5730               break;
5731             default:
5732               internal_error (__FILE__, __LINE__, _("bad switch"));
5733             }
5734         }
5735       if (fval_reg != mips_fval_fpr)
5736         {
5737           /* The two 32-bit parts are always placed in GPR2 and GPR3
5738              following these registers' memory order.  */
5739           mips_xfer_register (gdbarch, regcache,
5740                               gdbarch_num_regs (gdbarch) + 2,
5741                               4, gdbarch_byte_order (gdbarch),
5742                               readbuf, writebuf, 0);
5743           mips_xfer_register (gdbarch, regcache,
5744                               gdbarch_num_regs (gdbarch) + 3,
5745                               4, gdbarch_byte_order (gdbarch),
5746                               readbuf, writebuf, 4);
5747         }
5748       return RETURN_VALUE_REGISTER_CONVENTION;
5749     }
5750 #if 0
5751   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT
5752            && TYPE_NFIELDS (type) <= 2
5753            && TYPE_NFIELDS (type) >= 1
5754            && ((TYPE_NFIELDS (type) == 1
5755                 && (TYPE_CODE (TYPE_FIELD_TYPE (type, 0))
5756                     == TYPE_CODE_FLT))
5757                || (TYPE_NFIELDS (type) == 2
5758                    && (TYPE_CODE (TYPE_FIELD_TYPE (type, 0))
5759                        == TYPE_CODE_FLT)
5760                    && (TYPE_CODE (TYPE_FIELD_TYPE (type, 1))
5761                        == TYPE_CODE_FLT)))
5762            && tdep->mips_fpu_type != MIPS_FPU_NONE)
5763     {
5764       /* A struct that contains one or two floats.  Each value is part
5765          in the least significant part of their floating point
5766          register..  */
5767       int regnum;
5768       int field;
5769       for (field = 0, regnum = mips_regnum (gdbarch)->fp0;
5770            field < TYPE_NFIELDS (type); field++, regnum += 2)
5771         {
5772           int offset = (FIELD_BITPOS (TYPE_FIELDS (type)[field])
5773                         / TARGET_CHAR_BIT);
5774           if (mips_debug)
5775             fprintf_unfiltered (gdb_stderr, "Return float struct+%d\n",
5776                                 offset);
5777           mips_xfer_register (gdbarch, regcache,
5778                               gdbarch_num_regs (gdbarch) + regnum,
5779                               TYPE_LENGTH (TYPE_FIELD_TYPE (type, field)),
5780                               gdbarch_byte_order (gdbarch),
5781                               readbuf, writebuf, offset);
5782         }
5783       return RETURN_VALUE_REGISTER_CONVENTION;
5784     }
5785 #endif
5786 #if 0
5787   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT
5788            || TYPE_CODE (type) == TYPE_CODE_UNION)
5789     {
5790       /* A structure or union.  Extract the left justified value,
5791          regardless of the byte order.  I.e. DO NOT USE
5792          mips_xfer_lower.  */
5793       int offset;
5794       int regnum;
5795       for (offset = 0, regnum = MIPS_V0_REGNUM;
5796            offset < TYPE_LENGTH (type);
5797            offset += register_size (gdbarch, regnum), regnum++)
5798         {
5799           int xfer = register_size (gdbarch, regnum);
5800           if (offset + xfer > TYPE_LENGTH (type))
5801             xfer = TYPE_LENGTH (type) - offset;
5802           if (mips_debug)
5803             fprintf_unfiltered (gdb_stderr, "Return struct+%d:%d in $%d\n",
5804                                 offset, xfer, regnum);
5805           mips_xfer_register (gdbarch, regcache,
5806                               gdbarch_num_regs (gdbarch) + regnum, xfer,
5807                               BFD_ENDIAN_UNKNOWN, readbuf, writebuf, offset);
5808         }
5809       return RETURN_VALUE_REGISTER_CONVENTION;
5810     }
5811 #endif
5812   else
5813     {
5814       /* A scalar extract each part but least-significant-byte
5815          justified.  o32 thinks registers are 4 byte, regardless of
5816          the ISA.  */
5817       int offset;
5818       int regnum;
5819       for (offset = 0, regnum = MIPS_V0_REGNUM;
5820            offset < TYPE_LENGTH (type);
5821            offset += MIPS32_REGSIZE, regnum++)
5822         {
5823           int xfer = MIPS32_REGSIZE;
5824           if (offset + xfer > TYPE_LENGTH (type))
5825             xfer = TYPE_LENGTH (type) - offset;
5826           if (mips_debug)
5827             fprintf_unfiltered (gdb_stderr, "Return scalar+%d:%d in $%d\n",
5828                                 offset, xfer, regnum);
5829           mips_xfer_register (gdbarch, regcache,
5830                               gdbarch_num_regs (gdbarch) + regnum, xfer,
5831                               gdbarch_byte_order (gdbarch),
5832                               readbuf, writebuf, offset);
5833         }
5834       return RETURN_VALUE_REGISTER_CONVENTION;
5835     }
5836 }
5837
5838 /* O64 ABI.  This is a hacked up kind of 64-bit version of the o32
5839    ABI.  */
5840
5841 static CORE_ADDR
5842 mips_o64_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
5843                           struct regcache *regcache, CORE_ADDR bp_addr,
5844                           int nargs,
5845                           struct value **args, CORE_ADDR sp,
5846                           int struct_return, CORE_ADDR struct_addr)
5847 {
5848   int argreg;
5849   int float_argreg;
5850   int argnum;
5851   int len = 0;
5852   int stack_offset = 0;
5853   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
5854   CORE_ADDR func_addr = find_function_addr (function, NULL);
5855
5856   /* For shared libraries, "t9" needs to point at the function
5857      address.  */
5858   regcache_cooked_write_signed (regcache, MIPS_T9_REGNUM, func_addr);
5859
5860   /* Set the return address register to point to the entry point of
5861      the program, where a breakpoint lies in wait.  */
5862   regcache_cooked_write_signed (regcache, MIPS_RA_REGNUM, bp_addr);
5863
5864   /* First ensure that the stack and structure return address (if any)
5865      are properly aligned.  The stack has to be at least 64-bit
5866      aligned even on 32-bit machines, because doubles must be 64-bit
5867      aligned.  For n32 and n64, stack frames need to be 128-bit
5868      aligned, so we round to this widest known alignment.  */
5869
5870   sp = align_down (sp, 16);
5871   struct_addr = align_down (struct_addr, 16);
5872
5873   /* Now make space on the stack for the args.  */
5874   for (argnum = 0; argnum < nargs; argnum++)
5875     {
5876       struct type *arg_type = check_typedef (value_type (args[argnum]));
5877
5878       /* Allocate space on the stack.  */
5879       len += align_up (TYPE_LENGTH (arg_type), MIPS64_REGSIZE);
5880     }
5881   sp -= align_up (len, 16);
5882
5883   if (mips_debug)
5884     fprintf_unfiltered (gdb_stdlog,
5885                         "mips_o64_push_dummy_call: sp=%s allocated %ld\n",
5886                         paddress (gdbarch, sp), (long) align_up (len, 16));
5887
5888   /* Initialize the integer and float register pointers.  */
5889   argreg = MIPS_A0_REGNUM;
5890   float_argreg = mips_fpa0_regnum (gdbarch);
5891
5892   /* The struct_return pointer occupies the first parameter-passing reg.  */
5893   if (struct_return)
5894     {
5895       if (mips_debug)
5896         fprintf_unfiltered (gdb_stdlog,
5897                             "mips_o64_push_dummy_call: "
5898                             "struct_return reg=%d %s\n",
5899                             argreg, paddress (gdbarch, struct_addr));
5900       regcache_cooked_write_unsigned (regcache, argreg++, struct_addr);
5901       stack_offset += MIPS64_REGSIZE;
5902     }
5903
5904   /* Now load as many as possible of the first arguments into
5905      registers, and push the rest onto the stack.  Loop thru args
5906      from first to last.  */
5907   for (argnum = 0; argnum < nargs; argnum++)
5908     {
5909       const gdb_byte *val;
5910       struct value *arg = args[argnum];
5911       struct type *arg_type = check_typedef (value_type (arg));
5912       int len = TYPE_LENGTH (arg_type);
5913       enum type_code typecode = TYPE_CODE (arg_type);
5914
5915       if (mips_debug)
5916         fprintf_unfiltered (gdb_stdlog,
5917                             "mips_o64_push_dummy_call: %d len=%d type=%d",
5918                             argnum + 1, len, (int) typecode);
5919
5920       val = value_contents (arg);
5921
5922       /* Floating point arguments passed in registers have to be
5923          treated specially.  On 32-bit architectures, doubles are
5924          passed in register pairs; the even FP register gets the
5925          low word, and the odd FP register gets the high word.
5926          On O64, the first two floating point arguments are also
5927          copied to general registers, because MIPS16 functions
5928          don't use float registers for arguments.  This duplication
5929          of arguments in general registers can't hurt non-MIPS16
5930          functions because those registers are normally skipped.  */
5931
5932       if (fp_register_arg_p (gdbarch, typecode, arg_type)
5933           && float_argreg <= MIPS_LAST_FP_ARG_REGNUM (gdbarch))
5934         {
5935           LONGEST regval = extract_unsigned_integer (val, len, byte_order);
5936           if (mips_debug)
5937             fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
5938                                 float_argreg, phex (regval, len));
5939           regcache_cooked_write_unsigned (regcache, float_argreg++, regval);
5940           if (mips_debug)
5941             fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
5942                                 argreg, phex (regval, len));
5943           regcache_cooked_write_unsigned (regcache, argreg, regval);
5944           argreg++;
5945           /* Reserve space for the FP register.  */
5946           stack_offset += align_up (len, MIPS64_REGSIZE);
5947         }
5948       else
5949         {
5950           /* Copy the argument to general registers or the stack in
5951              register-sized pieces.  Large arguments are split between
5952              registers and stack.  */
5953           /* Note: structs whose size is not a multiple of MIPS64_REGSIZE
5954              are treated specially: Irix cc passes them in registers
5955              where gcc sometimes puts them on the stack.  For maximum
5956              compatibility, we will put them in both places.  */
5957           int odd_sized_struct = (len > MIPS64_REGSIZE
5958                                   && len % MIPS64_REGSIZE != 0);
5959           while (len > 0)
5960             {
5961               int partial_len = (len < MIPS64_REGSIZE ? len : MIPS64_REGSIZE);
5962
5963               if (mips_debug)
5964                 fprintf_unfiltered (gdb_stdlog, " -- partial=%d",
5965                                     partial_len);
5966
5967               /* Write this portion of the argument to the stack.  */
5968               if (argreg > MIPS_LAST_ARG_REGNUM (gdbarch)
5969                   || odd_sized_struct)
5970                 {
5971                   /* Should shorter than int integer values be
5972                      promoted to int before being stored?  */
5973                   int longword_offset = 0;
5974                   CORE_ADDR addr;
5975                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
5976                     {
5977                       if ((typecode == TYPE_CODE_INT
5978                            || typecode == TYPE_CODE_PTR
5979                            || typecode == TYPE_CODE_FLT)
5980                           && len <= 4)
5981                         longword_offset = MIPS64_REGSIZE - len;
5982                     }
5983
5984                   if (mips_debug)
5985                     {
5986                       fprintf_unfiltered (gdb_stdlog, " - stack_offset=%s",
5987                                           paddress (gdbarch, stack_offset));
5988                       fprintf_unfiltered (gdb_stdlog, " longword_offset=%s",
5989                                           paddress (gdbarch, longword_offset));
5990                     }
5991
5992                   addr = sp + stack_offset + longword_offset;
5993
5994                   if (mips_debug)
5995                     {
5996                       int i;
5997                       fprintf_unfiltered (gdb_stdlog, " @%s ",
5998                                           paddress (gdbarch, addr));
5999                       for (i = 0; i < partial_len; i++)
6000                         {
6001                           fprintf_unfiltered (gdb_stdlog, "%02x",
6002                                               val[i] & 0xff);
6003                         }
6004                     }
6005                   write_memory (addr, val, partial_len);
6006                 }
6007
6008               /* Note!!! This is NOT an else clause.  Odd sized
6009                  structs may go thru BOTH paths.  */
6010               /* Write this portion of the argument to a general
6011                  purpose register.  */
6012               if (argreg <= MIPS_LAST_ARG_REGNUM (gdbarch))
6013                 {
6014                   LONGEST regval = extract_signed_integer (val, partial_len,
6015                                                            byte_order);
6016                   /* Value may need to be sign extended, because
6017                      mips_isa_regsize() != mips_abi_regsize().  */
6018
6019                   /* A non-floating-point argument being passed in a
6020                      general register.  If a struct or union, and if
6021                      the remaining length is smaller than the register
6022                      size, we have to adjust the register value on
6023                      big endian targets.
6024
6025                      It does not seem to be necessary to do the
6026                      same for integral types.  */
6027
6028                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG
6029                       && partial_len < MIPS64_REGSIZE
6030                       && (typecode == TYPE_CODE_STRUCT
6031                           || typecode == TYPE_CODE_UNION))
6032                     regval <<= ((MIPS64_REGSIZE - partial_len)
6033                                 * TARGET_CHAR_BIT);
6034
6035                   if (mips_debug)
6036                     fprintf_filtered (gdb_stdlog, " - reg=%d val=%s",
6037                                       argreg,
6038                                       phex (regval, MIPS64_REGSIZE));
6039                   regcache_cooked_write_unsigned (regcache, argreg, regval);
6040                   argreg++;
6041
6042                   /* Prevent subsequent floating point arguments from
6043                      being passed in floating point registers.  */
6044                   float_argreg = MIPS_LAST_FP_ARG_REGNUM (gdbarch) + 1;
6045                 }
6046
6047               len -= partial_len;
6048               val += partial_len;
6049
6050               /* Compute the offset into the stack at which we will
6051                  copy the next parameter.
6052
6053                  In older ABIs, the caller reserved space for
6054                  registers that contained arguments.  This was loosely
6055                  refered to as their "home".  Consequently, space is
6056                  always allocated.  */
6057
6058               stack_offset += align_up (partial_len, MIPS64_REGSIZE);
6059             }
6060         }
6061       if (mips_debug)
6062         fprintf_unfiltered (gdb_stdlog, "\n");
6063     }
6064
6065   regcache_cooked_write_signed (regcache, MIPS_SP_REGNUM, sp);
6066
6067   /* Return adjusted stack pointer.  */
6068   return sp;
6069 }
6070
6071 static enum return_value_convention
6072 mips_o64_return_value (struct gdbarch *gdbarch, struct value *function,
6073                        struct type *type, struct regcache *regcache,
6074                        gdb_byte *readbuf, const gdb_byte *writebuf)
6075 {
6076   CORE_ADDR func_addr = function ? find_function_addr (function, NULL) : 0;
6077   int mips16 = mips_pc_is_mips16 (gdbarch, func_addr);
6078   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
6079   enum mips_fval_reg fval_reg;
6080
6081   fval_reg = readbuf ? mips16 ? mips_fval_gpr : mips_fval_fpr : mips_fval_both;
6082   if (TYPE_CODE (type) == TYPE_CODE_STRUCT
6083       || TYPE_CODE (type) == TYPE_CODE_UNION
6084       || TYPE_CODE (type) == TYPE_CODE_ARRAY)
6085     return RETURN_VALUE_STRUCT_CONVENTION;
6086   else if (fp_register_arg_p (gdbarch, TYPE_CODE (type), type))
6087     {
6088       /* A floating-point value.  If reading in or copying, then we get it
6089          from/put it to FP0 for standard MIPS code or GPR2 for MIPS16 code.
6090          If writing out only, then we put it to both FP0 and GPR2.  We do
6091          not support reading in with no function known, if this safety
6092          check ever triggers, then we'll have to try harder.  */
6093       gdb_assert (function || !readbuf);
6094       if (mips_debug)
6095         switch (fval_reg)
6096           {
6097           case mips_fval_fpr:
6098             fprintf_unfiltered (gdb_stderr, "Return float in $fp0\n");
6099             break;
6100           case mips_fval_gpr:
6101             fprintf_unfiltered (gdb_stderr, "Return float in $2\n");
6102             break;
6103           case mips_fval_both:
6104             fprintf_unfiltered (gdb_stderr, "Return float in $fp0 and $2\n");
6105             break;
6106           }
6107       if (fval_reg != mips_fval_gpr)
6108         mips_xfer_register (gdbarch, regcache,
6109                             (gdbarch_num_regs (gdbarch)
6110                              + mips_regnum (gdbarch)->fp0),
6111                             TYPE_LENGTH (type),
6112                             gdbarch_byte_order (gdbarch),
6113                             readbuf, writebuf, 0);
6114       if (fval_reg != mips_fval_fpr)
6115         mips_xfer_register (gdbarch, regcache,
6116                             gdbarch_num_regs (gdbarch) + 2,
6117                             TYPE_LENGTH (type),
6118                             gdbarch_byte_order (gdbarch),
6119                             readbuf, writebuf, 0);
6120       return RETURN_VALUE_REGISTER_CONVENTION;
6121     }
6122   else
6123     {
6124       /* A scalar extract each part but least-significant-byte
6125          justified.  */
6126       int offset;
6127       int regnum;
6128       for (offset = 0, regnum = MIPS_V0_REGNUM;
6129            offset < TYPE_LENGTH (type);
6130            offset += MIPS64_REGSIZE, regnum++)
6131         {
6132           int xfer = MIPS64_REGSIZE;
6133           if (offset + xfer > TYPE_LENGTH (type))
6134             xfer = TYPE_LENGTH (type) - offset;
6135           if (mips_debug)
6136             fprintf_unfiltered (gdb_stderr, "Return scalar+%d:%d in $%d\n",
6137                                 offset, xfer, regnum);
6138           mips_xfer_register (gdbarch, regcache,
6139                               gdbarch_num_regs (gdbarch) + regnum,
6140                               xfer, gdbarch_byte_order (gdbarch),
6141                               readbuf, writebuf, offset);
6142         }
6143       return RETURN_VALUE_REGISTER_CONVENTION;
6144     }
6145 }
6146
6147 /* Floating point register management.
6148
6149    Background: MIPS1 & 2 fp registers are 32 bits wide.  To support
6150    64bit operations, these early MIPS cpus treat fp register pairs
6151    (f0,f1) as a single register (d0).  Later MIPS cpu's have 64 bit fp
6152    registers and offer a compatibility mode that emulates the MIPS2 fp
6153    model.  When operating in MIPS2 fp compat mode, later cpu's split
6154    double precision floats into two 32-bit chunks and store them in
6155    consecutive fp regs.  To display 64-bit floats stored in this
6156    fashion, we have to combine 32 bits from f0 and 32 bits from f1.
6157    Throw in user-configurable endianness and you have a real mess.
6158
6159    The way this works is:
6160      - If we are in 32-bit mode or on a 32-bit processor, then a 64-bit
6161        double-precision value will be split across two logical registers.
6162        The lower-numbered logical register will hold the low-order bits,
6163        regardless of the processor's endianness.
6164      - If we are on a 64-bit processor, and we are looking for a
6165        single-precision value, it will be in the low ordered bits
6166        of a 64-bit GPR (after mfc1, for example) or a 64-bit register
6167        save slot in memory.
6168      - If we are in 64-bit mode, everything is straightforward.
6169
6170    Note that this code only deals with "live" registers at the top of the
6171    stack.  We will attempt to deal with saved registers later, when
6172    the raw/cooked register interface is in place.  (We need a general
6173    interface that can deal with dynamic saved register sizes -- fp
6174    regs could be 32 bits wide in one frame and 64 on the frame above
6175    and below).  */
6176
6177 /* Copy a 32-bit single-precision value from the current frame
6178    into rare_buffer.  */
6179
6180 static void
6181 mips_read_fp_register_single (struct frame_info *frame, int regno,
6182                               gdb_byte *rare_buffer)
6183 {
6184   struct gdbarch *gdbarch = get_frame_arch (frame);
6185   int raw_size = register_size (gdbarch, regno);
6186   gdb_byte *raw_buffer = (gdb_byte *) alloca (raw_size);
6187
6188   if (!deprecated_frame_register_read (frame, regno, raw_buffer))
6189     error (_("can't read register %d (%s)"),
6190            regno, gdbarch_register_name (gdbarch, regno));
6191   if (raw_size == 8)
6192     {
6193       /* We have a 64-bit value for this register.  Find the low-order
6194          32 bits.  */
6195       int offset;
6196
6197       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
6198         offset = 4;
6199       else
6200         offset = 0;
6201
6202       memcpy (rare_buffer, raw_buffer + offset, 4);
6203     }
6204   else
6205     {
6206       memcpy (rare_buffer, raw_buffer, 4);
6207     }
6208 }
6209
6210 /* Copy a 64-bit double-precision value from the current frame into
6211    rare_buffer.  This may include getting half of it from the next
6212    register.  */
6213
6214 static void
6215 mips_read_fp_register_double (struct frame_info *frame, int regno,
6216                               gdb_byte *rare_buffer)
6217 {
6218   struct gdbarch *gdbarch = get_frame_arch (frame);
6219   int raw_size = register_size (gdbarch, regno);
6220
6221   if (raw_size == 8 && !mips2_fp_compat (frame))
6222     {
6223       /* We have a 64-bit value for this register, and we should use
6224          all 64 bits.  */
6225       if (!deprecated_frame_register_read (frame, regno, rare_buffer))
6226         error (_("can't read register %d (%s)"),
6227                regno, gdbarch_register_name (gdbarch, regno));
6228     }
6229   else
6230     {
6231       int rawnum = regno % gdbarch_num_regs (gdbarch);
6232
6233       if ((rawnum - mips_regnum (gdbarch)->fp0) & 1)
6234         internal_error (__FILE__, __LINE__,
6235                         _("mips_read_fp_register_double: bad access to "
6236                         "odd-numbered FP register"));
6237
6238       /* mips_read_fp_register_single will find the correct 32 bits from
6239          each register.  */
6240       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
6241         {
6242           mips_read_fp_register_single (frame, regno, rare_buffer + 4);
6243           mips_read_fp_register_single (frame, regno + 1, rare_buffer);
6244         }
6245       else
6246         {
6247           mips_read_fp_register_single (frame, regno, rare_buffer);
6248           mips_read_fp_register_single (frame, regno + 1, rare_buffer + 4);
6249         }
6250     }
6251 }
6252
6253 static void
6254 mips_print_fp_register (struct ui_file *file, struct frame_info *frame,
6255                         int regnum)
6256 {                               /* Do values for FP (float) regs.  */
6257   struct gdbarch *gdbarch = get_frame_arch (frame);
6258   gdb_byte *raw_buffer;
6259   double doub, flt1;    /* Doubles extracted from raw hex data.  */
6260   int inv1, inv2;
6261
6262   raw_buffer
6263     = ((gdb_byte *)
6264        alloca (2 * register_size (gdbarch, mips_regnum (gdbarch)->fp0)));
6265
6266   fprintf_filtered (file, "%s:", gdbarch_register_name (gdbarch, regnum));
6267   fprintf_filtered (file, "%*s",
6268                     4 - (int) strlen (gdbarch_register_name (gdbarch, regnum)),
6269                     "");
6270
6271   if (register_size (gdbarch, regnum) == 4 || mips2_fp_compat (frame))
6272     {
6273       struct value_print_options opts;
6274
6275       /* 4-byte registers: Print hex and floating.  Also print even
6276          numbered registers as doubles.  */
6277       mips_read_fp_register_single (frame, regnum, raw_buffer);
6278       flt1 = unpack_double (builtin_type (gdbarch)->builtin_float,
6279                             raw_buffer, &inv1);
6280
6281       get_formatted_print_options (&opts, 'x');
6282       print_scalar_formatted (raw_buffer,
6283                               builtin_type (gdbarch)->builtin_uint32,
6284                               &opts, 'w', file);
6285
6286       fprintf_filtered (file, " flt: ");
6287       if (inv1)
6288         fprintf_filtered (file, " <invalid float> ");
6289       else
6290         fprintf_filtered (file, "%-17.9g", flt1);
6291
6292       if ((regnum - gdbarch_num_regs (gdbarch)) % 2 == 0)
6293         {
6294           mips_read_fp_register_double (frame, regnum, raw_buffer);
6295           doub = unpack_double (builtin_type (gdbarch)->builtin_double,
6296                                 raw_buffer, &inv2);
6297
6298           fprintf_filtered (file, " dbl: ");
6299           if (inv2)
6300             fprintf_filtered (file, "<invalid double>");
6301           else
6302             fprintf_filtered (file, "%-24.17g", doub);
6303         }
6304     }
6305   else
6306     {
6307       struct value_print_options opts;
6308
6309       /* Eight byte registers: print each one as hex, float and double.  */
6310       mips_read_fp_register_single (frame, regnum, raw_buffer);
6311       flt1 = unpack_double (builtin_type (gdbarch)->builtin_float,
6312                             raw_buffer, &inv1);
6313
6314       mips_read_fp_register_double (frame, regnum, raw_buffer);
6315       doub = unpack_double (builtin_type (gdbarch)->builtin_double,
6316                             raw_buffer, &inv2);
6317
6318       get_formatted_print_options (&opts, 'x');
6319       print_scalar_formatted (raw_buffer,
6320                               builtin_type (gdbarch)->builtin_uint64,
6321                               &opts, 'g', file);
6322
6323       fprintf_filtered (file, " flt: ");
6324       if (inv1)
6325         fprintf_filtered (file, "<invalid float>");
6326       else
6327         fprintf_filtered (file, "%-17.9g", flt1);
6328
6329       fprintf_filtered (file, " dbl: ");
6330       if (inv2)
6331         fprintf_filtered (file, "<invalid double>");
6332       else
6333         fprintf_filtered (file, "%-24.17g", doub);
6334     }
6335 }
6336
6337 static void
6338 mips_print_register (struct ui_file *file, struct frame_info *frame,
6339                      int regnum)
6340 {
6341   struct gdbarch *gdbarch = get_frame_arch (frame);
6342   struct value_print_options opts;
6343   struct value *val;
6344
6345   if (mips_float_register_p (gdbarch, regnum))
6346     {
6347       mips_print_fp_register (file, frame, regnum);
6348       return;
6349     }
6350
6351   val = get_frame_register_value (frame, regnum);
6352
6353   fputs_filtered (gdbarch_register_name (gdbarch, regnum), file);
6354
6355   /* The problem with printing numeric register names (r26, etc.) is that
6356      the user can't use them on input.  Probably the best solution is to
6357      fix it so that either the numeric or the funky (a2, etc.) names
6358      are accepted on input.  */
6359   if (regnum < MIPS_NUMREGS)
6360     fprintf_filtered (file, "(r%d): ", regnum);
6361   else
6362     fprintf_filtered (file, ": ");
6363
6364   get_formatted_print_options (&opts, 'x');
6365   val_print_scalar_formatted (value_type (val),
6366                               value_embedded_offset (val),
6367                               val,
6368                               &opts, 0, file);
6369 }
6370
6371 /* Print IEEE exception condition bits in FLAGS.  */
6372
6373 static void
6374 print_fpu_flags (struct ui_file *file, int flags)
6375 {
6376   if (flags & (1 << 0))
6377     fputs_filtered (" inexact", file);
6378   if (flags & (1 << 1))
6379     fputs_filtered (" uflow", file);
6380   if (flags & (1 << 2))
6381     fputs_filtered (" oflow", file);
6382   if (flags & (1 << 3))
6383     fputs_filtered (" div0", file);
6384   if (flags & (1 << 4))
6385     fputs_filtered (" inval", file);
6386   if (flags & (1 << 5))
6387     fputs_filtered (" unimp", file);
6388   fputc_filtered ('\n', file);
6389 }
6390
6391 /* Print interesting information about the floating point processor
6392    (if present) or emulator.  */
6393
6394 static void
6395 mips_print_float_info (struct gdbarch *gdbarch, struct ui_file *file,
6396                       struct frame_info *frame, const char *args)
6397 {
6398   int fcsr = mips_regnum (gdbarch)->fp_control_status;
6399   enum mips_fpu_type type = MIPS_FPU_TYPE (gdbarch);
6400   ULONGEST fcs = 0;
6401   int i;
6402
6403   if (fcsr == -1 || !read_frame_register_unsigned (frame, fcsr, &fcs))
6404     type = MIPS_FPU_NONE;
6405
6406   fprintf_filtered (file, "fpu type: %s\n",
6407                     type == MIPS_FPU_DOUBLE ? "double-precision"
6408                     : type == MIPS_FPU_SINGLE ? "single-precision"
6409                     : "none / unused");
6410
6411   if (type == MIPS_FPU_NONE)
6412     return;
6413
6414   fprintf_filtered (file, "reg size: %d bits\n",
6415                     register_size (gdbarch, mips_regnum (gdbarch)->fp0) * 8);
6416
6417   fputs_filtered ("cond    :", file);
6418   if (fcs & (1 << 23))
6419     fputs_filtered (" 0", file);
6420   for (i = 1; i <= 7; i++)
6421     if (fcs & (1 << (24 + i)))
6422       fprintf_filtered (file, " %d", i);
6423   fputc_filtered ('\n', file);
6424
6425   fputs_filtered ("cause   :", file);
6426   print_fpu_flags (file, (fcs >> 12) & 0x3f);
6427   fputs ("mask    :", stdout);
6428   print_fpu_flags (file, (fcs >> 7) & 0x1f);
6429   fputs ("flags   :", stdout);
6430   print_fpu_flags (file, (fcs >> 2) & 0x1f);
6431
6432   fputs_filtered ("rounding: ", file);
6433   switch (fcs & 3)
6434     {
6435     case 0: fputs_filtered ("nearest\n", file); break;
6436     case 1: fputs_filtered ("zero\n", file); break;
6437     case 2: fputs_filtered ("+inf\n", file); break;
6438     case 3: fputs_filtered ("-inf\n", file); break;
6439     }
6440
6441   fputs_filtered ("flush   :", file);
6442   if (fcs & (1 << 21))
6443     fputs_filtered (" nearest", file);
6444   if (fcs & (1 << 22))
6445     fputs_filtered (" override", file);
6446   if (fcs & (1 << 24))
6447     fputs_filtered (" zero", file);
6448   if ((fcs & (0xb << 21)) == 0)
6449     fputs_filtered (" no", file);
6450   fputc_filtered ('\n', file);
6451
6452   fprintf_filtered (file, "nan2008 : %s\n", fcs & (1 << 18) ? "yes" : "no");
6453   fprintf_filtered (file, "abs2008 : %s\n", fcs & (1 << 19) ? "yes" : "no");
6454   fputc_filtered ('\n', file);
6455
6456   default_print_float_info (gdbarch, file, frame, args);
6457 }
6458
6459 /* Replacement for generic do_registers_info.
6460    Print regs in pretty columns.  */
6461
6462 static int
6463 print_fp_register_row (struct ui_file *file, struct frame_info *frame,
6464                        int regnum)
6465 {
6466   fprintf_filtered (file, " ");
6467   mips_print_fp_register (file, frame, regnum);
6468   fprintf_filtered (file, "\n");
6469   return regnum + 1;
6470 }
6471
6472
6473 /* Print a row's worth of GP (int) registers, with name labels above.  */
6474
6475 static int
6476 print_gp_register_row (struct ui_file *file, struct frame_info *frame,
6477                        int start_regnum)
6478 {
6479   struct gdbarch *gdbarch = get_frame_arch (frame);
6480   /* Do values for GP (int) regs.  */
6481   const gdb_byte *raw_buffer;
6482   struct value *value;
6483   int ncols = (mips_abi_regsize (gdbarch) == 8 ? 4 : 8);    /* display cols
6484                                                                per row.  */
6485   int col, byte;
6486   int regnum;
6487
6488   /* For GP registers, we print a separate row of names above the vals.  */
6489   for (col = 0, regnum = start_regnum;
6490        col < ncols && regnum < gdbarch_num_regs (gdbarch)
6491                                + gdbarch_num_pseudo_regs (gdbarch);
6492        regnum++)
6493     {
6494       if (*gdbarch_register_name (gdbarch, regnum) == '\0')
6495         continue;               /* unused register */
6496       if (mips_float_register_p (gdbarch, regnum))
6497         break;                  /* End the row: reached FP register.  */
6498       /* Large registers are handled separately.  */
6499       if (register_size (gdbarch, regnum) > mips_abi_regsize (gdbarch))
6500         {
6501           if (col > 0)
6502             break;              /* End the row before this register.  */
6503
6504           /* Print this register on a row by itself.  */
6505           mips_print_register (file, frame, regnum);
6506           fprintf_filtered (file, "\n");
6507           return regnum + 1;
6508         }
6509       if (col == 0)
6510         fprintf_filtered (file, "     ");
6511       fprintf_filtered (file,
6512                         mips_abi_regsize (gdbarch) == 8 ? "%17s" : "%9s",
6513                         gdbarch_register_name (gdbarch, regnum));
6514       col++;
6515     }
6516
6517   if (col == 0)
6518     return regnum;
6519
6520   /* Print the R0 to R31 names.  */
6521   if ((start_regnum % gdbarch_num_regs (gdbarch)) < MIPS_NUMREGS)
6522     fprintf_filtered (file, "\n R%-4d",
6523                       start_regnum % gdbarch_num_regs (gdbarch));
6524   else
6525     fprintf_filtered (file, "\n      ");
6526
6527   /* Now print the values in hex, 4 or 8 to the row.  */
6528   for (col = 0, regnum = start_regnum;
6529        col < ncols && regnum < gdbarch_num_regs (gdbarch)
6530                                + gdbarch_num_pseudo_regs (gdbarch);
6531        regnum++)
6532     {
6533       if (*gdbarch_register_name (gdbarch, regnum) == '\0')
6534         continue;               /* unused register */
6535       if (mips_float_register_p (gdbarch, regnum))
6536         break;                  /* End row: reached FP register.  */
6537       if (register_size (gdbarch, regnum) > mips_abi_regsize (gdbarch))
6538         break;                  /* End row: large register.  */
6539
6540       /* OK: get the data in raw format.  */
6541       value = get_frame_register_value (frame, regnum);
6542       if (value_optimized_out (value)
6543         || !value_entirely_available (value))
6544         {
6545           fprintf_filtered (file, "%*s ",
6546                             (int) mips_abi_regsize (gdbarch) * 2,
6547                             (mips_abi_regsize (gdbarch) == 4 ? "<unavl>"
6548                              : "<unavailable>"));
6549           col++;
6550           continue;
6551         }
6552       raw_buffer = value_contents_all (value);
6553       /* pad small registers */
6554       for (byte = 0;
6555            byte < (mips_abi_regsize (gdbarch)
6556                    - register_size (gdbarch, regnum)); byte++)
6557         fprintf_filtered (file, "  ");
6558       /* Now print the register value in hex, endian order.  */
6559       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
6560         for (byte =
6561              register_size (gdbarch, regnum) - register_size (gdbarch, regnum);
6562              byte < register_size (gdbarch, regnum); byte++)
6563           fprintf_filtered (file, "%02x", raw_buffer[byte]);
6564       else
6565         for (byte = register_size (gdbarch, regnum) - 1;
6566              byte >= 0; byte--)
6567           fprintf_filtered (file, "%02x", raw_buffer[byte]);
6568       fprintf_filtered (file, " ");
6569       col++;
6570     }
6571   if (col > 0)                  /* ie. if we actually printed anything...  */
6572     fprintf_filtered (file, "\n");
6573
6574   return regnum;
6575 }
6576
6577 /* MIPS_DO_REGISTERS_INFO(): called by "info register" command.  */
6578
6579 static void
6580 mips_print_registers_info (struct gdbarch *gdbarch, struct ui_file *file,
6581                            struct frame_info *frame, int regnum, int all)
6582 {
6583   if (regnum != -1)             /* Do one specified register.  */
6584     {
6585       gdb_assert (regnum >= gdbarch_num_regs (gdbarch));
6586       if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
6587         error (_("Not a valid register for the current processor type"));
6588
6589       mips_print_register (file, frame, regnum);
6590       fprintf_filtered (file, "\n");
6591     }
6592   else
6593     /* Do all (or most) registers.  */
6594     {
6595       regnum = gdbarch_num_regs (gdbarch);
6596       while (regnum < gdbarch_num_regs (gdbarch)
6597                       + gdbarch_num_pseudo_regs (gdbarch))
6598         {
6599           if (mips_float_register_p (gdbarch, regnum))
6600             {
6601               if (all)          /* True for "INFO ALL-REGISTERS" command.  */
6602                 regnum = print_fp_register_row (file, frame, regnum);
6603               else
6604                 regnum += MIPS_NUMREGS; /* Skip floating point regs.  */
6605             }
6606           else
6607             regnum = print_gp_register_row (file, frame, regnum);
6608         }
6609     }
6610 }
6611
6612 static int
6613 mips_single_step_through_delay (struct gdbarch *gdbarch,
6614                                 struct frame_info *frame)
6615 {
6616   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
6617   CORE_ADDR pc = get_frame_pc (frame);
6618   struct address_space *aspace;
6619   enum mips_isa isa;
6620   ULONGEST insn;
6621   int status;
6622   int size;
6623
6624   if ((mips_pc_is_mips (pc)
6625        && !mips32_insn_at_pc_has_delay_slot (gdbarch, pc))
6626       || (mips_pc_is_micromips (gdbarch, pc)
6627           && !micromips_insn_at_pc_has_delay_slot (gdbarch, pc, 0))
6628       || (mips_pc_is_mips16 (gdbarch, pc)
6629           && !mips16_insn_at_pc_has_delay_slot (gdbarch, pc, 0)))
6630     return 0;
6631
6632   isa = mips_pc_isa (gdbarch, pc);
6633   /* _has_delay_slot above will have validated the read.  */
6634   insn = mips_fetch_instruction (gdbarch, isa, pc, NULL);
6635   size = mips_insn_size (isa, insn);
6636   aspace = get_frame_address_space (frame);
6637   return breakpoint_here_p (aspace, pc + size) != no_breakpoint_here;
6638 }
6639
6640 /* To skip prologues, I use this predicate.  Returns either PC itself
6641    if the code at PC does not look like a function prologue; otherwise
6642    returns an address that (if we're lucky) follows the prologue.  If
6643    LENIENT, then we must skip everything which is involved in setting
6644    up the frame (it's OK to skip more, just so long as we don't skip
6645    anything which might clobber the registers which are being saved.
6646    We must skip more in the case where part of the prologue is in the
6647    delay slot of a non-prologue instruction).  */
6648
6649 static CORE_ADDR
6650 mips_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
6651 {
6652   CORE_ADDR limit_pc;
6653   CORE_ADDR func_addr;
6654
6655   /* See if we can determine the end of the prologue via the symbol table.
6656      If so, then return either PC, or the PC after the prologue, whichever
6657      is greater.  */
6658   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
6659     {
6660       CORE_ADDR post_prologue_pc
6661         = skip_prologue_using_sal (gdbarch, func_addr);
6662       if (post_prologue_pc != 0)
6663         return std::max (pc, post_prologue_pc);
6664     }
6665
6666   /* Can't determine prologue from the symbol table, need to examine
6667      instructions.  */
6668
6669   /* Find an upper limit on the function prologue using the debug
6670      information.  If the debug information could not be used to provide
6671      that bound, then use an arbitrary large number as the upper bound.  */
6672   limit_pc = skip_prologue_using_sal (gdbarch, pc);
6673   if (limit_pc == 0)
6674     limit_pc = pc + 100;          /* Magic.  */
6675
6676   if (mips_pc_is_mips16 (gdbarch, pc))
6677     return mips16_scan_prologue (gdbarch, pc, limit_pc, NULL, NULL);
6678   else if (mips_pc_is_micromips (gdbarch, pc))
6679     return micromips_scan_prologue (gdbarch, pc, limit_pc, NULL, NULL);
6680   else
6681     return mips32_scan_prologue (gdbarch, pc, limit_pc, NULL, NULL);
6682 }
6683
6684 /* Implement the stack_frame_destroyed_p gdbarch method (32-bit version).
6685    This is a helper function for mips_stack_frame_destroyed_p.  */
6686
6687 static int
6688 mips32_stack_frame_destroyed_p (struct gdbarch *gdbarch, CORE_ADDR pc)
6689 {
6690   CORE_ADDR func_addr = 0, func_end = 0;
6691
6692   if (find_pc_partial_function (pc, NULL, &func_addr, &func_end))
6693     {
6694       /* The MIPS epilogue is max. 12 bytes long.  */
6695       CORE_ADDR addr = func_end - 12;
6696
6697       if (addr < func_addr + 4)
6698         addr = func_addr + 4;
6699       if (pc < addr)
6700         return 0;
6701
6702       for (; pc < func_end; pc += MIPS_INSN32_SIZE)
6703         {
6704           unsigned long high_word;
6705           unsigned long inst;
6706
6707           inst = mips_fetch_instruction (gdbarch, ISA_MIPS, pc, NULL);
6708           high_word = (inst >> 16) & 0xffff;
6709
6710           if (high_word != 0x27bd       /* addiu $sp,$sp,offset */
6711               && high_word != 0x67bd    /* daddiu $sp,$sp,offset */
6712               && inst != 0x03e00008     /* jr $ra */
6713               && inst != 0x00000000)    /* nop */
6714             return 0;
6715         }
6716
6717       return 1;
6718     }
6719
6720   return 0;
6721 }
6722
6723 /* Implement the stack_frame_destroyed_p gdbarch method (microMIPS version).
6724    This is a helper function for mips_stack_frame_destroyed_p.  */
6725
6726 static int
6727 micromips_stack_frame_destroyed_p (struct gdbarch *gdbarch, CORE_ADDR pc)
6728 {
6729   CORE_ADDR func_addr = 0;
6730   CORE_ADDR func_end = 0;
6731   CORE_ADDR addr;
6732   ULONGEST insn;
6733   long offset;
6734   int dreg;
6735   int sreg;
6736   int loc;
6737
6738   if (!find_pc_partial_function (pc, NULL, &func_addr, &func_end))
6739     return 0;
6740
6741   /* The microMIPS epilogue is max. 12 bytes long.  */
6742   addr = func_end - 12;
6743
6744   if (addr < func_addr + 2)
6745     addr = func_addr + 2;
6746   if (pc < addr)
6747     return 0;
6748
6749   for (; pc < func_end; pc += loc)
6750     {
6751       loc = 0;
6752       insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, NULL);
6753       loc += MIPS_INSN16_SIZE;
6754       switch (mips_insn_size (ISA_MICROMIPS, insn))
6755         {
6756         /* 32-bit instructions.  */
6757         case 2 * MIPS_INSN16_SIZE:
6758           insn <<= 16;
6759           insn |= mips_fetch_instruction (gdbarch,
6760                                           ISA_MICROMIPS, pc + loc, NULL);
6761           loc += MIPS_INSN16_SIZE;
6762           switch (micromips_op (insn >> 16))
6763             {
6764             case 0xc: /* ADDIU: bits 001100 */
6765             case 0x17: /* DADDIU: bits 010111 */
6766               sreg = b0s5_reg (insn >> 16);
6767               dreg = b5s5_reg (insn >> 16);
6768               offset = (b0s16_imm (insn) ^ 0x8000) - 0x8000;
6769               if (sreg == MIPS_SP_REGNUM && dreg == MIPS_SP_REGNUM
6770                             /* (D)ADDIU $sp, imm */
6771                   && offset >= 0)
6772                 break;
6773               return 0;
6774
6775             default:
6776               return 0;
6777             }
6778           break;
6779
6780         /* 16-bit instructions.  */
6781         case MIPS_INSN16_SIZE:
6782           switch (micromips_op (insn))
6783             {
6784             case 0x3: /* MOVE: bits 000011 */
6785               sreg = b0s5_reg (insn);
6786               dreg = b5s5_reg (insn);
6787               if (sreg == 0 && dreg == 0)
6788                                 /* MOVE $zero, $zero aka NOP */
6789                 break;
6790               return 0;
6791
6792             case 0x11: /* POOL16C: bits 010001 */
6793               if (b5s5_op (insn) == 0x18
6794                                 /* JRADDIUSP: bits 010011 11000 */
6795                   || (b5s5_op (insn) == 0xd
6796                                 /* JRC: bits 010011 01101 */
6797                       && b0s5_reg (insn) == MIPS_RA_REGNUM))
6798                                 /* JRC $ra */
6799                 break;
6800               return 0;
6801
6802             case 0x13: /* POOL16D: bits 010011 */
6803               offset = micromips_decode_imm9 (b1s9_imm (insn));
6804               if ((insn & 0x1) == 0x1
6805                                 /* ADDIUSP: bits 010011 1 */
6806                   && offset > 0)
6807                 break;
6808               return 0;
6809
6810             default:
6811               return 0;
6812             }
6813         }
6814     }
6815
6816   return 1;
6817 }
6818
6819 /* Implement the stack_frame_destroyed_p gdbarch method (16-bit version).
6820    This is a helper function for mips_stack_frame_destroyed_p.  */
6821
6822 static int
6823 mips16_stack_frame_destroyed_p (struct gdbarch *gdbarch, CORE_ADDR pc)
6824 {
6825   CORE_ADDR func_addr = 0, func_end = 0;
6826
6827   if (find_pc_partial_function (pc, NULL, &func_addr, &func_end))
6828     {
6829       /* The MIPS epilogue is max. 12 bytes long.  */
6830       CORE_ADDR addr = func_end - 12;
6831
6832       if (addr < func_addr + 4)
6833         addr = func_addr + 4;
6834       if (pc < addr)
6835         return 0;
6836
6837       for (; pc < func_end; pc += MIPS_INSN16_SIZE)
6838         {
6839           unsigned short inst;
6840
6841           inst = mips_fetch_instruction (gdbarch, ISA_MIPS16, pc, NULL);
6842
6843           if ((inst & 0xf800) == 0xf000)        /* extend */
6844             continue;
6845
6846           if (inst != 0x6300            /* addiu $sp,offset */
6847               && inst != 0xfb00         /* daddiu $sp,$sp,offset */
6848               && inst != 0xe820         /* jr $ra */
6849               && inst != 0xe8a0         /* jrc $ra */
6850               && inst != 0x6500)        /* nop */
6851             return 0;
6852         }
6853
6854       return 1;
6855     }
6856
6857   return 0;
6858 }
6859
6860 /* Implement the stack_frame_destroyed_p gdbarch method.
6861
6862    The epilogue is defined here as the area at the end of a function,
6863    after an instruction which destroys the function's stack frame.  */
6864
6865 static int
6866 mips_stack_frame_destroyed_p (struct gdbarch *gdbarch, CORE_ADDR pc)
6867 {
6868   if (mips_pc_is_mips16 (gdbarch, pc))
6869     return mips16_stack_frame_destroyed_p (gdbarch, pc);
6870   else if (mips_pc_is_micromips (gdbarch, pc))
6871     return micromips_stack_frame_destroyed_p (gdbarch, pc);
6872   else
6873     return mips32_stack_frame_destroyed_p (gdbarch, pc);
6874 }
6875
6876 /* Root of all "set mips "/"show mips " commands.  This will eventually be
6877    used for all MIPS-specific commands.  */
6878
6879 static void
6880 show_mips_command (const char *args, int from_tty)
6881 {
6882   help_list (showmipscmdlist, "show mips ", all_commands, gdb_stdout);
6883 }
6884
6885 static void
6886 set_mips_command (const char *args, int from_tty)
6887 {
6888   printf_unfiltered
6889     ("\"set mips\" must be followed by an appropriate subcommand.\n");
6890   help_list (setmipscmdlist, "set mips ", all_commands, gdb_stdout);
6891 }
6892
6893 /* Commands to show/set the MIPS FPU type.  */
6894
6895 static void
6896 show_mipsfpu_command (const char *args, int from_tty)
6897 {
6898   const char *fpu;
6899
6900   if (gdbarch_bfd_arch_info (target_gdbarch ())->arch != bfd_arch_mips)
6901     {
6902       printf_unfiltered
6903         ("The MIPS floating-point coprocessor is unknown "
6904          "because the current architecture is not MIPS.\n");
6905       return;
6906     }
6907
6908   switch (MIPS_FPU_TYPE (target_gdbarch ()))
6909     {
6910     case MIPS_FPU_SINGLE:
6911       fpu = "single-precision";
6912       break;
6913     case MIPS_FPU_DOUBLE:
6914       fpu = "double-precision";
6915       break;
6916     case MIPS_FPU_NONE:
6917       fpu = "absent (none)";
6918       break;
6919     default:
6920       internal_error (__FILE__, __LINE__, _("bad switch"));
6921     }
6922   if (mips_fpu_type_auto)
6923     printf_unfiltered ("The MIPS floating-point coprocessor "
6924                        "is set automatically (currently %s)\n",
6925                        fpu);
6926   else
6927     printf_unfiltered
6928       ("The MIPS floating-point coprocessor is assumed to be %s\n", fpu);
6929 }
6930
6931
6932 static void
6933 set_mipsfpu_command (const char *args, int from_tty)
6934 {
6935   printf_unfiltered ("\"set mipsfpu\" must be followed by \"double\", "
6936                      "\"single\",\"none\" or \"auto\".\n");
6937   show_mipsfpu_command (args, from_tty);
6938 }
6939
6940 static void
6941 set_mipsfpu_single_command (const char *args, int from_tty)
6942 {
6943   struct gdbarch_info info;
6944   gdbarch_info_init (&info);
6945   mips_fpu_type = MIPS_FPU_SINGLE;
6946   mips_fpu_type_auto = 0;
6947   /* FIXME: cagney/2003-11-15: Should be setting a field in "info"
6948      instead of relying on globals.  Doing that would let generic code
6949      handle the search for this specific architecture.  */
6950   if (!gdbarch_update_p (info))
6951     internal_error (__FILE__, __LINE__, _("set mipsfpu failed"));
6952 }
6953
6954 static void
6955 set_mipsfpu_double_command (const char *args, int from_tty)
6956 {
6957   struct gdbarch_info info;
6958   gdbarch_info_init (&info);
6959   mips_fpu_type = MIPS_FPU_DOUBLE;
6960   mips_fpu_type_auto = 0;
6961   /* FIXME: cagney/2003-11-15: Should be setting a field in "info"
6962      instead of relying on globals.  Doing that would let generic code
6963      handle the search for this specific architecture.  */
6964   if (!gdbarch_update_p (info))
6965     internal_error (__FILE__, __LINE__, _("set mipsfpu failed"));
6966 }
6967
6968 static void
6969 set_mipsfpu_none_command (const char *args, int from_tty)
6970 {
6971   struct gdbarch_info info;
6972   gdbarch_info_init (&info);
6973   mips_fpu_type = MIPS_FPU_NONE;
6974   mips_fpu_type_auto = 0;
6975   /* FIXME: cagney/2003-11-15: Should be setting a field in "info"
6976      instead of relying on globals.  Doing that would let generic code
6977      handle the search for this specific architecture.  */
6978   if (!gdbarch_update_p (info))
6979     internal_error (__FILE__, __LINE__, _("set mipsfpu failed"));
6980 }
6981
6982 static void
6983 set_mipsfpu_auto_command (const char *args, int from_tty)
6984 {
6985   mips_fpu_type_auto = 1;
6986 }
6987
6988 /* Just like reinit_frame_cache, but with the right arguments to be
6989    callable as an sfunc.  */
6990
6991 static void
6992 reinit_frame_cache_sfunc (char *args, int from_tty,
6993                           struct cmd_list_element *c)
6994 {
6995   reinit_frame_cache ();
6996 }
6997
6998 static int
6999 gdb_print_insn_mips (bfd_vma memaddr, struct disassemble_info *info)
7000 {
7001   gdb_disassembler *di
7002     = static_cast<gdb_disassembler *>(info->application_data);
7003   struct gdbarch *gdbarch = di->arch ();
7004
7005   /* FIXME: cagney/2003-06-26: Is this even necessary?  The
7006      disassembler needs to be able to locally determine the ISA, and
7007      not rely on GDB.  Otherwize the stand-alone 'objdump -d' will not
7008      work.  */
7009   if (mips_pc_is_mips16 (gdbarch, memaddr))
7010     info->mach = bfd_mach_mips16;
7011   else if (mips_pc_is_micromips (gdbarch, memaddr))
7012     info->mach = bfd_mach_mips_micromips;
7013
7014   /* Round down the instruction address to the appropriate boundary.  */
7015   memaddr &= (info->mach == bfd_mach_mips16
7016               || info->mach == bfd_mach_mips_micromips) ? ~1 : ~3;
7017
7018   /* Set the disassembler options.  */
7019   if (!info->disassembler_options)
7020     /* This string is not recognized explicitly by the disassembler,
7021        but it tells the disassembler to not try to guess the ABI from
7022        the bfd elf headers, such that, if the user overrides the ABI
7023        of a program linked as NewABI, the disassembly will follow the
7024        register naming conventions specified by the user.  */
7025     info->disassembler_options = "gpr-names=32";
7026
7027   return default_print_insn (memaddr, info);
7028 }
7029
7030 static int
7031 gdb_print_insn_mips_n32 (bfd_vma memaddr, struct disassemble_info *info)
7032 {
7033   /* Set up the disassembler info, so that we get the right
7034      register names from libopcodes.  */
7035   info->disassembler_options = "gpr-names=n32";
7036   info->flavour = bfd_target_elf_flavour;
7037
7038   return gdb_print_insn_mips (memaddr, info);
7039 }
7040
7041 static int
7042 gdb_print_insn_mips_n64 (bfd_vma memaddr, struct disassemble_info *info)
7043 {
7044   /* Set up the disassembler info, so that we get the right
7045      register names from libopcodes.  */
7046   info->disassembler_options = "gpr-names=64";
7047   info->flavour = bfd_target_elf_flavour;
7048
7049   return gdb_print_insn_mips (memaddr, info);
7050 }
7051
7052 /* Implement the breakpoint_kind_from_pc gdbarch method.  */
7053
7054 static int
7055 mips_breakpoint_kind_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr)
7056 {
7057   CORE_ADDR pc = *pcptr;
7058
7059   if (mips_pc_is_mips16 (gdbarch, pc))
7060     {
7061       *pcptr = unmake_compact_addr (pc);
7062       return MIPS_BP_KIND_MIPS16;
7063     }
7064   else if (mips_pc_is_micromips (gdbarch, pc))
7065     {
7066       ULONGEST insn;
7067       int status;
7068
7069       *pcptr = unmake_compact_addr (pc);
7070       insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, &status);
7071       if (status || (mips_insn_size (ISA_MICROMIPS, insn) == 2))
7072         return MIPS_BP_KIND_MICROMIPS16;
7073       else
7074         return MIPS_BP_KIND_MICROMIPS32;
7075     }
7076   else
7077     return MIPS_BP_KIND_MIPS32;
7078 }
7079
7080 /* Implement the sw_breakpoint_from_kind gdbarch method.  */
7081
7082 static const gdb_byte *
7083 mips_sw_breakpoint_from_kind (struct gdbarch *gdbarch, int kind, int *size)
7084 {
7085   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
7086
7087   switch (kind)
7088     {
7089     case MIPS_BP_KIND_MIPS16:
7090       {
7091         static gdb_byte mips16_big_breakpoint[] = { 0xe8, 0xa5 };
7092         static gdb_byte mips16_little_breakpoint[] = { 0xa5, 0xe8 };
7093
7094         *size = 2;
7095         if (byte_order_for_code == BFD_ENDIAN_BIG)
7096           return mips16_big_breakpoint;
7097         else
7098           return mips16_little_breakpoint;
7099       }
7100     case MIPS_BP_KIND_MICROMIPS16:
7101       {
7102         static gdb_byte micromips16_big_breakpoint[] = { 0x46, 0x85 };
7103         static gdb_byte micromips16_little_breakpoint[] = { 0x85, 0x46 };
7104
7105         *size = 2;
7106
7107         if (byte_order_for_code == BFD_ENDIAN_BIG)
7108           return micromips16_big_breakpoint;
7109         else
7110           return micromips16_little_breakpoint;
7111       }
7112     case MIPS_BP_KIND_MICROMIPS32:
7113       {
7114         static gdb_byte micromips32_big_breakpoint[] = { 0, 0x5, 0, 0x7 };
7115         static gdb_byte micromips32_little_breakpoint[] = { 0x5, 0, 0x7, 0 };
7116
7117         *size = 4;
7118         if (byte_order_for_code == BFD_ENDIAN_BIG)
7119           return micromips32_big_breakpoint;
7120         else
7121           return micromips32_little_breakpoint;
7122       }
7123     case MIPS_BP_KIND_MIPS32:
7124       {
7125         static gdb_byte big_breakpoint[] = { 0, 0x5, 0, 0xd };
7126         static gdb_byte little_breakpoint[] = { 0xd, 0, 0x5, 0 };
7127
7128         *size = 4;
7129         if (byte_order_for_code == BFD_ENDIAN_BIG)
7130           return big_breakpoint;
7131         else
7132           return little_breakpoint;
7133       }
7134     default:
7135       gdb_assert_not_reached ("unexpected mips breakpoint kind");
7136     };
7137 }
7138
7139 /* Return non-zero if the standard MIPS instruction INST has a branch
7140    delay slot (i.e. it is a jump or branch instruction).  This function
7141    is based on mips32_next_pc.  */
7142
7143 static int
7144 mips32_instruction_has_delay_slot (struct gdbarch *gdbarch, ULONGEST inst)
7145 {
7146   int op;
7147   int rs;
7148   int rt;
7149
7150   op = itype_op (inst);
7151   if ((inst & 0xe0000000) != 0)
7152     {
7153       rs = itype_rs (inst);
7154       rt = itype_rt (inst);
7155       return (is_octeon_bbit_op (op, gdbarch) 
7156               || op >> 2 == 5   /* BEQL, BNEL, BLEZL, BGTZL: bits 0101xx  */
7157               || op == 29       /* JALX: bits 011101  */
7158               || (op == 17
7159                   && (rs == 8
7160                                 /* BC1F, BC1FL, BC1T, BC1TL: 010001 01000  */
7161                       || (rs == 9 && (rt & 0x2) == 0)
7162                                 /* BC1ANY2F, BC1ANY2T: bits 010001 01001  */
7163                       || (rs == 10 && (rt & 0x2) == 0))));
7164                                 /* BC1ANY4F, BC1ANY4T: bits 010001 01010  */
7165     }
7166   else
7167     switch (op & 0x07)          /* extract bits 28,27,26  */
7168       {
7169       case 0:                   /* SPECIAL  */
7170         op = rtype_funct (inst);
7171         return (op == 8         /* JR  */
7172                 || op == 9);    /* JALR  */
7173         break;                  /* end SPECIAL  */
7174       case 1:                   /* REGIMM  */
7175         rs = itype_rs (inst);
7176         rt = itype_rt (inst);   /* branch condition  */
7177         return ((rt & 0xc) == 0
7178                                 /* BLTZ, BLTZL, BGEZ, BGEZL: bits 000xx  */
7179                                 /* BLTZAL, BLTZALL, BGEZAL, BGEZALL: 100xx  */
7180                 || ((rt & 0x1e) == 0x1c && rs == 0));
7181                                 /* BPOSGE32, BPOSGE64: bits 1110x  */
7182         break;                  /* end REGIMM  */
7183       default:                  /* J, JAL, BEQ, BNE, BLEZ, BGTZ  */
7184         return 1;
7185         break;
7186       }
7187 }
7188
7189 /* Return non-zero if a standard MIPS instruction at ADDR has a branch
7190    delay slot (i.e. it is a jump or branch instruction).  */
7191
7192 static int
7193 mips32_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch, CORE_ADDR addr)
7194 {
7195   ULONGEST insn;
7196   int status;
7197
7198   insn = mips_fetch_instruction (gdbarch, ISA_MIPS, addr, &status);
7199   if (status)
7200     return 0;
7201
7202   return mips32_instruction_has_delay_slot (gdbarch, insn);
7203 }
7204
7205 /* Return non-zero if the microMIPS instruction INSN, comprising the
7206    16-bit major opcode word in the high 16 bits and any second word
7207    in the low 16 bits, has a branch delay slot (i.e. it is a non-compact
7208    jump or branch instruction).  The instruction must be 32-bit if
7209    MUSTBE32 is set or can be any instruction otherwise.  */
7210
7211 static int
7212 micromips_instruction_has_delay_slot (ULONGEST insn, int mustbe32)
7213 {
7214   ULONGEST major = insn >> 16;
7215
7216   switch (micromips_op (major))
7217     {
7218     /* 16-bit instructions.  */
7219     case 0x33:                  /* B16: bits 110011 */
7220     case 0x2b:                  /* BNEZ16: bits 101011 */
7221     case 0x23:                  /* BEQZ16: bits 100011 */
7222       return !mustbe32;
7223     case 0x11:                  /* POOL16C: bits 010001 */
7224       return (!mustbe32
7225               && ((b5s5_op (major) == 0xc
7226                                 /* JR16: bits 010001 01100 */
7227                   || (b5s5_op (major) & 0x1e) == 0xe)));
7228                                 /* JALR16, JALRS16: bits 010001 0111x */
7229     /* 32-bit instructions.  */
7230     case 0x3d:                  /* JAL: bits 111101 */
7231     case 0x3c:                  /* JALX: bits 111100 */
7232     case 0x35:                  /* J: bits 110101 */
7233     case 0x2d:                  /* BNE: bits 101101 */
7234     case 0x25:                  /* BEQ: bits 100101 */
7235     case 0x1d:                  /* JALS: bits 011101 */
7236       return 1;
7237     case 0x10:                  /* POOL32I: bits 010000 */
7238       return ((b5s5_op (major) & 0x1c) == 0x0
7239                                 /* BLTZ, BLTZAL, BGEZ, BGEZAL: 010000 000xx */
7240               || (b5s5_op (major) & 0x1d) == 0x4
7241                                 /* BLEZ, BGTZ: bits 010000 001x0 */
7242               || (b5s5_op (major) & 0x1d) == 0x11
7243                                 /* BLTZALS, BGEZALS: bits 010000 100x1 */
7244               || ((b5s5_op (major) & 0x1e) == 0x14
7245                   && (major & 0x3) == 0x0)
7246                                 /* BC2F, BC2T: bits 010000 1010x xxx00 */
7247               || (b5s5_op (major) & 0x1e) == 0x1a
7248                                 /* BPOSGE64, BPOSGE32: bits 010000 1101x */
7249               || ((b5s5_op (major) & 0x1e) == 0x1c
7250                   && (major & 0x3) == 0x0)
7251                                 /* BC1F, BC1T: bits 010000 1110x xxx00 */
7252               || ((b5s5_op (major) & 0x1c) == 0x1c
7253                   && (major & 0x3) == 0x1));
7254                                 /* BC1ANY*: bits 010000 111xx xxx01 */
7255     case 0x0:                   /* POOL32A: bits 000000 */
7256       return (b0s6_op (insn) == 0x3c
7257                                 /* POOL32Axf: bits 000000 ... 111100 */
7258               && (b6s10_ext (insn) & 0x2bf) == 0x3c);
7259                                 /* JALR, JALR.HB: 000000 000x111100 111100 */
7260                                 /* JALRS, JALRS.HB: 000000 010x111100 111100 */
7261     default:
7262       return 0;
7263     }
7264 }
7265
7266 /* Return non-zero if a microMIPS instruction at ADDR has a branch delay
7267    slot (i.e. it is a non-compact jump instruction).  The instruction
7268    must be 32-bit if MUSTBE32 is set or can be any instruction otherwise.  */
7269
7270 static int
7271 micromips_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch,
7272                                      CORE_ADDR addr, int mustbe32)
7273 {
7274   ULONGEST insn;
7275   int status;
7276   int size;
7277
7278   insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, addr, &status);
7279   if (status)
7280     return 0;
7281   size = mips_insn_size (ISA_MICROMIPS, insn);
7282   insn <<= 16;
7283   if (size == 2 * MIPS_INSN16_SIZE)
7284     {
7285       insn |= mips_fetch_instruction (gdbarch, ISA_MICROMIPS, addr, &status);
7286       if (status)
7287         return 0;
7288     }
7289
7290   return micromips_instruction_has_delay_slot (insn, mustbe32);
7291 }
7292
7293 /* Return non-zero if the MIPS16 instruction INST, which must be
7294    a 32-bit instruction if MUSTBE32 is set or can be any instruction
7295    otherwise, has a branch delay slot (i.e. it is a non-compact jump
7296    instruction).  This function is based on mips16_next_pc.  */
7297
7298 static int
7299 mips16_instruction_has_delay_slot (unsigned short inst, int mustbe32)
7300 {
7301   if ((inst & 0xf89f) == 0xe800)        /* JR/JALR (16-bit instruction)  */
7302     return !mustbe32;
7303   return (inst & 0xf800) == 0x1800;     /* JAL/JALX (32-bit instruction)  */
7304 }
7305
7306 /* Return non-zero if a MIPS16 instruction at ADDR has a branch delay
7307    slot (i.e. it is a non-compact jump instruction).  The instruction
7308    must be 32-bit if MUSTBE32 is set or can be any instruction otherwise.  */
7309
7310 static int
7311 mips16_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch,
7312                                   CORE_ADDR addr, int mustbe32)
7313 {
7314   unsigned short insn;
7315   int status;
7316
7317   insn = mips_fetch_instruction (gdbarch, ISA_MIPS16, addr, &status);
7318   if (status)
7319     return 0;
7320
7321   return mips16_instruction_has_delay_slot (insn, mustbe32);
7322 }
7323
7324 /* Calculate the starting address of the MIPS memory segment BPADDR is in.
7325    This assumes KSSEG exists.  */
7326
7327 static CORE_ADDR
7328 mips_segment_boundary (CORE_ADDR bpaddr)
7329 {
7330   CORE_ADDR mask = CORE_ADDR_MAX;
7331   int segsize;
7332
7333   if (sizeof (CORE_ADDR) == 8)
7334     /* Get the topmost two bits of bpaddr in a 32-bit safe manner (avoid
7335        a compiler warning produced where CORE_ADDR is a 32-bit type even
7336        though in that case this is dead code).  */
7337     switch (bpaddr >> ((sizeof (CORE_ADDR) << 3) - 2) & 3)
7338       {
7339       case 3:
7340         if (bpaddr == (bfd_signed_vma) (int32_t) bpaddr)
7341           segsize = 29;                 /* 32-bit compatibility segment  */
7342         else
7343           segsize = 62;                 /* xkseg  */
7344         break;
7345       case 2:                           /* xkphys  */
7346         segsize = 59;
7347         break;
7348       default:                          /* xksseg (1), xkuseg/kuseg (0)  */
7349         segsize = 62;
7350         break;
7351       }
7352   else if (bpaddr & 0x80000000)         /* kernel segment  */
7353     segsize = 29;
7354   else
7355     segsize = 31;                       /* user segment  */
7356   mask <<= segsize;
7357   return bpaddr & mask;
7358 }
7359
7360 /* Move the breakpoint at BPADDR out of any branch delay slot by shifting
7361    it backwards if necessary.  Return the address of the new location.  */
7362
7363 static CORE_ADDR
7364 mips_adjust_breakpoint_address (struct gdbarch *gdbarch, CORE_ADDR bpaddr)
7365 {
7366   CORE_ADDR prev_addr;
7367   CORE_ADDR boundary;
7368   CORE_ADDR func_addr;
7369
7370   /* If a breakpoint is set on the instruction in a branch delay slot,
7371      GDB gets confused.  When the breakpoint is hit, the PC isn't on
7372      the instruction in the branch delay slot, the PC will point to
7373      the branch instruction.  Since the PC doesn't match any known
7374      breakpoints, GDB reports a trap exception.
7375
7376      There are two possible fixes for this problem.
7377
7378      1) When the breakpoint gets hit, see if the BD bit is set in the
7379      Cause register (which indicates the last exception occurred in a
7380      branch delay slot).  If the BD bit is set, fix the PC to point to
7381      the instruction in the branch delay slot.
7382
7383      2) When the user sets the breakpoint, don't allow him to set the
7384      breakpoint on the instruction in the branch delay slot.  Instead
7385      move the breakpoint to the branch instruction (which will have
7386      the same result).
7387
7388      The problem with the first solution is that if the user then
7389      single-steps the processor, the branch instruction will get
7390      skipped (since GDB thinks the PC is on the instruction in the
7391      branch delay slot).
7392
7393      So, we'll use the second solution.  To do this we need to know if
7394      the instruction we're trying to set the breakpoint on is in the
7395      branch delay slot.  */
7396
7397   boundary = mips_segment_boundary (bpaddr);
7398
7399   /* Make sure we don't scan back before the beginning of the current
7400      function, since we may fetch constant data or insns that look like
7401      a jump.  Of course we might do that anyway if the compiler has
7402      moved constants inline. :-(  */
7403   if (find_pc_partial_function (bpaddr, NULL, &func_addr, NULL)
7404       && func_addr > boundary && func_addr <= bpaddr)
7405     boundary = func_addr;
7406
7407   if (mips_pc_is_mips (bpaddr))
7408     {
7409       if (bpaddr == boundary)
7410         return bpaddr;
7411
7412       /* If the previous instruction has a branch delay slot, we have
7413          to move the breakpoint to the branch instruction. */
7414       prev_addr = bpaddr - 4;
7415       if (mips32_insn_at_pc_has_delay_slot (gdbarch, prev_addr))
7416         bpaddr = prev_addr;
7417     }
7418   else
7419     {
7420       int (*insn_at_pc_has_delay_slot) (struct gdbarch *, CORE_ADDR, int);
7421       CORE_ADDR addr, jmpaddr;
7422       int i;
7423
7424       boundary = unmake_compact_addr (boundary);
7425
7426       /* The only MIPS16 instructions with delay slots are JAL, JALX,
7427          JALR and JR.  An absolute JAL/JALX is always 4 bytes long,
7428          so try for that first, then try the 2 byte JALR/JR.
7429          The microMIPS ASE has a whole range of jumps and branches
7430          with delay slots, some of which take 4 bytes and some take
7431          2 bytes, so the idea is the same.
7432          FIXME: We have to assume that bpaddr is not the second half
7433          of an extended instruction.  */
7434       insn_at_pc_has_delay_slot = (mips_pc_is_micromips (gdbarch, bpaddr)
7435                                    ? micromips_insn_at_pc_has_delay_slot
7436                                    : mips16_insn_at_pc_has_delay_slot);
7437
7438       jmpaddr = 0;
7439       addr = bpaddr;
7440       for (i = 1; i < 4; i++)
7441         {
7442           if (unmake_compact_addr (addr) == boundary)
7443             break;
7444           addr -= MIPS_INSN16_SIZE;
7445           if (i == 1 && insn_at_pc_has_delay_slot (gdbarch, addr, 0))
7446             /* Looks like a JR/JALR at [target-1], but it could be
7447                the second word of a previous JAL/JALX, so record it
7448                and check back one more.  */
7449             jmpaddr = addr;
7450           else if (i > 1 && insn_at_pc_has_delay_slot (gdbarch, addr, 1))
7451             {
7452               if (i == 2)
7453                 /* Looks like a JAL/JALX at [target-2], but it could also
7454                    be the second word of a previous JAL/JALX, record it,
7455                    and check back one more.  */
7456                 jmpaddr = addr;
7457               else
7458                 /* Looks like a JAL/JALX at [target-3], so any previously
7459                    recorded JAL/JALX or JR/JALR must be wrong, because:
7460
7461                    >-3: JAL
7462                     -2: JAL-ext (can't be JAL/JALX)
7463                     -1: bdslot (can't be JR/JALR)
7464                      0: target insn
7465
7466                    Of course it could be another JAL-ext which looks
7467                    like a JAL, but in that case we'd have broken out
7468                    of this loop at [target-2]:
7469
7470                     -4: JAL
7471                    >-3: JAL-ext
7472                     -2: bdslot (can't be jmp)
7473                     -1: JR/JALR
7474                      0: target insn  */
7475                 jmpaddr = 0;
7476             }
7477           else
7478             {
7479               /* Not a jump instruction: if we're at [target-1] this
7480                  could be the second word of a JAL/JALX, so continue;
7481                  otherwise we're done.  */
7482               if (i > 1)
7483                 break;
7484             }
7485         }
7486
7487       if (jmpaddr)
7488         bpaddr = jmpaddr;
7489     }
7490
7491   return bpaddr;
7492 }
7493
7494 /* Return non-zero if SUFFIX is one of the numeric suffixes used for MIPS16
7495    call stubs, one of 1, 2, 5, 6, 9, 10, or, if ZERO is non-zero, also 0.  */
7496
7497 static int
7498 mips_is_stub_suffix (const char *suffix, int zero)
7499 {
7500   switch (suffix[0])
7501    {
7502    case '0':
7503      return zero && suffix[1] == '\0';
7504    case '1':
7505      return suffix[1] == '\0' || (suffix[1] == '0' && suffix[2] == '\0');
7506    case '2':
7507    case '5':
7508    case '6':
7509    case '9':
7510      return suffix[1] == '\0';
7511    default:
7512      return 0;
7513    }
7514 }
7515
7516 /* Return non-zero if MODE is one of the mode infixes used for MIPS16
7517    call stubs, one of sf, df, sc, or dc.  */
7518
7519 static int
7520 mips_is_stub_mode (const char *mode)
7521 {
7522   return ((mode[0] == 's' || mode[0] == 'd')
7523           && (mode[1] == 'f' || mode[1] == 'c'));
7524 }
7525
7526 /* Code at PC is a compiler-generated stub.  Such a stub for a function
7527    bar might have a name like __fn_stub_bar, and might look like this:
7528
7529       mfc1    $4, $f13
7530       mfc1    $5, $f12
7531       mfc1    $6, $f15
7532       mfc1    $7, $f14
7533
7534    followed by (or interspersed with):
7535
7536       j       bar
7537
7538    or:
7539
7540       lui     $25, %hi(bar)
7541       addiu   $25, $25, %lo(bar)
7542       jr      $25
7543
7544    ($1 may be used in old code; for robustness we accept any register)
7545    or, in PIC code:
7546
7547       lui     $28, %hi(_gp_disp)
7548       addiu   $28, $28, %lo(_gp_disp)
7549       addu    $28, $28, $25
7550       lw      $25, %got(bar)
7551       addiu   $25, $25, %lo(bar)
7552       jr      $25
7553
7554    In the case of a __call_stub_bar stub, the sequence to set up
7555    arguments might look like this:
7556
7557       mtc1    $4, $f13
7558       mtc1    $5, $f12
7559       mtc1    $6, $f15
7560       mtc1    $7, $f14
7561
7562    followed by (or interspersed with) one of the jump sequences above.
7563
7564    In the case of a __call_stub_fp_bar stub, JAL or JALR is used instead
7565    of J or JR, respectively, followed by:
7566
7567       mfc1    $2, $f0
7568       mfc1    $3, $f1
7569       jr      $18
7570
7571    We are at the beginning of the stub here, and scan down and extract
7572    the target address from the jump immediate instruction or, if a jump
7573    register instruction is used, from the register referred.  Return
7574    the value of PC calculated or 0 if inconclusive.
7575
7576    The limit on the search is arbitrarily set to 20 instructions.  FIXME.  */
7577
7578 static CORE_ADDR
7579 mips_get_mips16_fn_stub_pc (struct frame_info *frame, CORE_ADDR pc)
7580 {
7581   struct gdbarch *gdbarch = get_frame_arch (frame);
7582   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
7583   int addrreg = MIPS_ZERO_REGNUM;
7584   CORE_ADDR start_pc = pc;
7585   CORE_ADDR target_pc = 0;
7586   CORE_ADDR addr = 0;
7587   CORE_ADDR gp = 0;
7588   int status = 0;
7589   int i;
7590
7591   for (i = 0;
7592        status == 0 && target_pc == 0 && i < 20;
7593        i++, pc += MIPS_INSN32_SIZE)
7594     {
7595       ULONGEST inst = mips_fetch_instruction (gdbarch, ISA_MIPS, pc, NULL);
7596       CORE_ADDR imm;
7597       int rt;
7598       int rs;
7599       int rd;
7600
7601       switch (itype_op (inst))
7602         {
7603         case 0:         /* SPECIAL */
7604           switch (rtype_funct (inst))
7605             {
7606             case 8:             /* JR */
7607             case 9:             /* JALR */
7608               rs = rtype_rs (inst);
7609               if (rs == MIPS_GP_REGNUM)
7610                 target_pc = gp;                         /* Hmm...  */
7611               else if (rs == addrreg)
7612                 target_pc = addr;
7613               break;
7614
7615             case 0x21:          /* ADDU */
7616               rt = rtype_rt (inst);
7617               rs = rtype_rs (inst);
7618               rd = rtype_rd (inst);
7619               if (rd == MIPS_GP_REGNUM
7620                   && ((rs == MIPS_GP_REGNUM && rt == MIPS_T9_REGNUM)
7621                       || (rs == MIPS_T9_REGNUM && rt == MIPS_GP_REGNUM)))
7622                 gp += start_pc;
7623               break;
7624             }
7625           break;
7626
7627         case 2:         /* J */
7628         case 3:         /* JAL */
7629           target_pc = jtype_target (inst) << 2;
7630           target_pc += ((pc + 4) & ~(CORE_ADDR) 0x0fffffff);
7631           break;
7632
7633         case 9:         /* ADDIU */
7634           rt = itype_rt (inst);
7635           rs = itype_rs (inst);
7636           if (rt == rs)
7637             {
7638               imm = (itype_immediate (inst) ^ 0x8000) - 0x8000;
7639               if (rt == MIPS_GP_REGNUM)
7640                 gp += imm;
7641               else if (rt == addrreg)
7642                 addr += imm;
7643             }
7644           break;
7645
7646         case 0xf:       /* LUI */
7647           rt = itype_rt (inst);
7648           imm = ((itype_immediate (inst) ^ 0x8000) - 0x8000) << 16;
7649           if (rt == MIPS_GP_REGNUM)
7650             gp = imm;
7651           else if (rt != MIPS_ZERO_REGNUM)
7652             {
7653               addrreg = rt;
7654               addr = imm;
7655             }
7656           break;
7657
7658         case 0x23:      /* LW */
7659           rt = itype_rt (inst);
7660           rs = itype_rs (inst);
7661           imm = (itype_immediate (inst) ^ 0x8000) - 0x8000;
7662           if (gp != 0 && rs == MIPS_GP_REGNUM)
7663             {
7664               gdb_byte buf[4];
7665
7666               memset (buf, 0, sizeof (buf));
7667               status = target_read_memory (gp + imm, buf, sizeof (buf));
7668               addrreg = rt;
7669               addr = extract_signed_integer (buf, sizeof (buf), byte_order);
7670             }
7671           break;
7672         }
7673     }
7674
7675   return target_pc;
7676 }
7677
7678 /* If PC is in a MIPS16 call or return stub, return the address of the
7679    target PC, which is either the callee or the caller.  There are several
7680    cases which must be handled:
7681
7682    * If the PC is in __mips16_ret_{d,s}{f,c}, this is a return stub
7683      and the target PC is in $31 ($ra).
7684    * If the PC is in __mips16_call_stub_{1..10}, this is a call stub
7685      and the target PC is in $2.
7686    * If the PC at the start of __mips16_call_stub_{s,d}{f,c}_{0..10},
7687      i.e. before the JALR instruction, this is effectively a call stub
7688      and the target PC is in $2.  Otherwise this is effectively
7689      a return stub and the target PC is in $18.
7690    * If the PC is at the start of __call_stub_fp_*, i.e. before the
7691      JAL or JALR instruction, this is effectively a call stub and the
7692      target PC is buried in the instruction stream.  Otherwise this
7693      is effectively a return stub and the target PC is in $18.
7694    * If the PC is in __call_stub_* or in __fn_stub_*, this is a call
7695      stub and the target PC is buried in the instruction stream.
7696
7697    See the source code for the stubs in gcc/config/mips/mips16.S, or the
7698    stub builder in gcc/config/mips/mips.c (mips16_build_call_stub) for the
7699    gory details.  */
7700
7701 static CORE_ADDR
7702 mips_skip_mips16_trampoline_code (struct frame_info *frame, CORE_ADDR pc)
7703 {
7704   struct gdbarch *gdbarch = get_frame_arch (frame);
7705   CORE_ADDR start_addr;
7706   const char *name;
7707   size_t prefixlen;
7708
7709   /* Find the starting address and name of the function containing the PC.  */
7710   if (find_pc_partial_function (pc, &name, &start_addr, NULL) == 0)
7711     return 0;
7712
7713   /* If the PC is in __mips16_ret_{d,s}{f,c}, this is a return stub
7714      and the target PC is in $31 ($ra).  */
7715   prefixlen = strlen (mips_str_mips16_ret_stub);
7716   if (strncmp (name, mips_str_mips16_ret_stub, prefixlen) == 0
7717       && mips_is_stub_mode (name + prefixlen)
7718       && name[prefixlen + 2] == '\0')
7719     return get_frame_register_signed
7720              (frame, gdbarch_num_regs (gdbarch) + MIPS_RA_REGNUM);
7721
7722   /* If the PC is in __mips16_call_stub_*, this is one of the call
7723      call/return stubs.  */
7724   prefixlen = strlen (mips_str_mips16_call_stub);
7725   if (strncmp (name, mips_str_mips16_call_stub, prefixlen) == 0)
7726     {
7727       /* If the PC is in __mips16_call_stub_{1..10}, this is a call stub
7728          and the target PC is in $2.  */
7729       if (mips_is_stub_suffix (name + prefixlen, 0))
7730         return get_frame_register_signed
7731                  (frame, gdbarch_num_regs (gdbarch) + MIPS_V0_REGNUM);
7732
7733       /* If the PC at the start of __mips16_call_stub_{s,d}{f,c}_{0..10},
7734          i.e. before the JALR instruction, this is effectively a call stub
7735          and the target PC is in $2.  Otherwise this is effectively
7736          a return stub and the target PC is in $18.  */
7737       else if (mips_is_stub_mode (name + prefixlen)
7738                && name[prefixlen + 2] == '_'
7739                && mips_is_stub_suffix (name + prefixlen + 3, 0))
7740         {
7741           if (pc == start_addr)
7742             /* This is the 'call' part of a call stub.  The return
7743                address is in $2.  */
7744             return get_frame_register_signed
7745                      (frame, gdbarch_num_regs (gdbarch) + MIPS_V0_REGNUM);
7746           else
7747             /* This is the 'return' part of a call stub.  The return
7748                address is in $18.  */
7749             return get_frame_register_signed
7750                      (frame, gdbarch_num_regs (gdbarch) + MIPS_S2_REGNUM);
7751         }
7752       else
7753         return 0;               /* Not a stub.  */
7754     }
7755
7756   /* If the PC is in __call_stub_* or __fn_stub*, this is one of the
7757      compiler-generated call or call/return stubs.  */
7758   if (startswith (name, mips_str_fn_stub)
7759       || startswith (name, mips_str_call_stub))
7760     {
7761       if (pc == start_addr)
7762         /* This is the 'call' part of a call stub.  Call this helper
7763            to scan through this code for interesting instructions
7764            and determine the final PC.  */
7765         return mips_get_mips16_fn_stub_pc (frame, pc);
7766       else
7767         /* This is the 'return' part of a call stub.  The return address
7768            is in $18.  */
7769         return get_frame_register_signed
7770                  (frame, gdbarch_num_regs (gdbarch) + MIPS_S2_REGNUM);
7771     }
7772
7773   return 0;                     /* Not a stub.  */
7774 }
7775
7776 /* Return non-zero if the PC is inside a return thunk (aka stub or trampoline).
7777    This implements the IN_SOLIB_RETURN_TRAMPOLINE macro.  */
7778
7779 static int
7780 mips_in_return_stub (struct gdbarch *gdbarch, CORE_ADDR pc, const char *name)
7781 {
7782   CORE_ADDR start_addr;
7783   size_t prefixlen;
7784
7785   /* Find the starting address of the function containing the PC.  */
7786   if (find_pc_partial_function (pc, NULL, &start_addr, NULL) == 0)
7787     return 0;
7788
7789   /* If the PC is in __mips16_call_stub_{s,d}{f,c}_{0..10} but not at
7790      the start, i.e. after the JALR instruction, this is effectively
7791      a return stub.  */
7792   prefixlen = strlen (mips_str_mips16_call_stub);
7793   if (pc != start_addr
7794       && strncmp (name, mips_str_mips16_call_stub, prefixlen) == 0
7795       && mips_is_stub_mode (name + prefixlen)
7796       && name[prefixlen + 2] == '_'
7797       && mips_is_stub_suffix (name + prefixlen + 3, 1))
7798     return 1;
7799
7800   /* If the PC is in __call_stub_fp_* but not at the start, i.e. after
7801      the JAL or JALR instruction, this is effectively a return stub.  */
7802   prefixlen = strlen (mips_str_call_fp_stub);
7803   if (pc != start_addr
7804       && strncmp (name, mips_str_call_fp_stub, prefixlen) == 0)
7805     return 1;
7806
7807   /* Consume the .pic. prefix of any PIC stub, this function must return
7808      true when the PC is in a PIC stub of a __mips16_ret_{d,s}{f,c} stub
7809      or the call stub path will trigger in handle_inferior_event causing
7810      it to go astray.  */
7811   prefixlen = strlen (mips_str_pic);
7812   if (strncmp (name, mips_str_pic, prefixlen) == 0)
7813     name += prefixlen;
7814
7815   /* If the PC is in __mips16_ret_{d,s}{f,c}, this is a return stub.  */
7816   prefixlen = strlen (mips_str_mips16_ret_stub);
7817   if (strncmp (name, mips_str_mips16_ret_stub, prefixlen) == 0
7818       && mips_is_stub_mode (name + prefixlen)
7819       && name[prefixlen + 2] == '\0')
7820     return 1;
7821
7822   return 0;                     /* Not a stub.  */
7823 }
7824
7825 /* If the current PC is the start of a non-PIC-to-PIC stub, return the
7826    PC of the stub target.  The stub just loads $t9 and jumps to it,
7827    so that $t9 has the correct value at function entry.  */
7828
7829 static CORE_ADDR
7830 mips_skip_pic_trampoline_code (struct frame_info *frame, CORE_ADDR pc)
7831 {
7832   struct gdbarch *gdbarch = get_frame_arch (frame);
7833   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
7834   struct bound_minimal_symbol msym;
7835   int i;
7836   gdb_byte stub_code[16];
7837   int32_t stub_words[4];
7838
7839   /* The stub for foo is named ".pic.foo", and is either two
7840      instructions inserted before foo or a three instruction sequence
7841      which jumps to foo.  */
7842   msym = lookup_minimal_symbol_by_pc (pc);
7843   if (msym.minsym == NULL
7844       || BMSYMBOL_VALUE_ADDRESS (msym) != pc
7845       || MSYMBOL_LINKAGE_NAME (msym.minsym) == NULL
7846       || !startswith (MSYMBOL_LINKAGE_NAME (msym.minsym), ".pic."))
7847     return 0;
7848
7849   /* A two-instruction header.  */
7850   if (MSYMBOL_SIZE (msym.minsym) == 8)
7851     return pc + 8;
7852
7853   /* A three-instruction (plus delay slot) trampoline.  */
7854   if (MSYMBOL_SIZE (msym.minsym) == 16)
7855     {
7856       if (target_read_memory (pc, stub_code, 16) != 0)
7857         return 0;
7858       for (i = 0; i < 4; i++)
7859         stub_words[i] = extract_unsigned_integer (stub_code + i * 4,
7860                                                   4, byte_order);
7861
7862       /* A stub contains these instructions:
7863          lui    t9, %hi(target)
7864          j      target
7865           addiu t9, t9, %lo(target)
7866          nop
7867
7868          This works even for N64, since stubs are only generated with
7869          -msym32.  */
7870       if ((stub_words[0] & 0xffff0000U) == 0x3c190000
7871           && (stub_words[1] & 0xfc000000U) == 0x08000000
7872           && (stub_words[2] & 0xffff0000U) == 0x27390000
7873           && stub_words[3] == 0x00000000)
7874         return ((((stub_words[0] & 0x0000ffff) << 16)
7875                  + (stub_words[2] & 0x0000ffff)) ^ 0x8000) - 0x8000;
7876     }
7877
7878   /* Not a recognized stub.  */
7879   return 0;
7880 }
7881
7882 static CORE_ADDR
7883 mips_skip_trampoline_code (struct frame_info *frame, CORE_ADDR pc)
7884 {
7885   CORE_ADDR requested_pc = pc;
7886   CORE_ADDR target_pc;
7887   CORE_ADDR new_pc;
7888
7889   do
7890     {
7891       target_pc = pc;
7892
7893       new_pc = mips_skip_mips16_trampoline_code (frame, pc);
7894       if (new_pc)
7895         pc = new_pc;
7896
7897       new_pc = find_solib_trampoline_target (frame, pc);
7898       if (new_pc)
7899         pc = new_pc;
7900
7901       new_pc = mips_skip_pic_trampoline_code (frame, pc);
7902       if (new_pc)
7903         pc = new_pc;
7904     }
7905   while (pc != target_pc);
7906
7907   return pc != requested_pc ? pc : 0;
7908 }
7909
7910 /* Convert a dbx stab register number (from `r' declaration) to a GDB
7911    [1 * gdbarch_num_regs .. 2 * gdbarch_num_regs) REGNUM.  */
7912
7913 static int
7914 mips_stab_reg_to_regnum (struct gdbarch *gdbarch, int num)
7915 {
7916   int regnum;
7917   if (num >= 0 && num < 32)
7918     regnum = num;
7919   else if (num >= 38 && num < 70)
7920     regnum = num + mips_regnum (gdbarch)->fp0 - 38;
7921   else if (num == 70)
7922     regnum = mips_regnum (gdbarch)->hi;
7923   else if (num == 71)
7924     regnum = mips_regnum (gdbarch)->lo;
7925   else if (mips_regnum (gdbarch)->dspacc != -1 && num >= 72 && num < 78)
7926     regnum = num + mips_regnum (gdbarch)->dspacc - 72;
7927   else
7928     return -1;
7929   return gdbarch_num_regs (gdbarch) + regnum;
7930 }
7931
7932
7933 /* Convert a dwarf, dwarf2, or ecoff register number to a GDB [1 *
7934    gdbarch_num_regs .. 2 * gdbarch_num_regs) REGNUM.  */
7935
7936 static int
7937 mips_dwarf_dwarf2_ecoff_reg_to_regnum (struct gdbarch *gdbarch, int num)
7938 {
7939   int regnum;
7940   if (num >= 0 && num < 32)
7941     regnum = num;
7942   else if (num >= 32 && num < 64)
7943     regnum = num + mips_regnum (gdbarch)->fp0 - 32;
7944   else if (num == 64)
7945     regnum = mips_regnum (gdbarch)->hi;
7946   else if (num == 65)
7947     regnum = mips_regnum (gdbarch)->lo;
7948   else if (mips_regnum (gdbarch)->dspacc != -1 && num >= 66 && num < 72)
7949     regnum = num + mips_regnum (gdbarch)->dspacc - 66;
7950   else
7951     return -1;
7952   return gdbarch_num_regs (gdbarch) + regnum;
7953 }
7954
7955 static int
7956 mips_register_sim_regno (struct gdbarch *gdbarch, int regnum)
7957 {
7958   /* Only makes sense to supply raw registers.  */
7959   gdb_assert (regnum >= 0 && regnum < gdbarch_num_regs (gdbarch));
7960   /* FIXME: cagney/2002-05-13: Need to look at the pseudo register to
7961      decide if it is valid.  Should instead define a standard sim/gdb
7962      register numbering scheme.  */
7963   if (gdbarch_register_name (gdbarch,
7964                              gdbarch_num_regs (gdbarch) + regnum) != NULL
7965       && gdbarch_register_name (gdbarch,
7966                                 gdbarch_num_regs (gdbarch)
7967                                 + regnum)[0] != '\0')
7968     return regnum;
7969   else
7970     return LEGACY_SIM_REGNO_IGNORE;
7971 }
7972
7973
7974 /* Convert an integer into an address.  Extracting the value signed
7975    guarantees a correctly sign extended address.  */
7976
7977 static CORE_ADDR
7978 mips_integer_to_address (struct gdbarch *gdbarch,
7979                          struct type *type, const gdb_byte *buf)
7980 {
7981   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
7982   return extract_signed_integer (buf, TYPE_LENGTH (type), byte_order);
7983 }
7984
7985 /* Dummy virtual frame pointer method.  This is no more or less accurate
7986    than most other architectures; we just need to be explicit about it,
7987    because the pseudo-register gdbarch_sp_regnum will otherwise lead to
7988    an assertion failure.  */
7989
7990 static void
7991 mips_virtual_frame_pointer (struct gdbarch *gdbarch, 
7992                             CORE_ADDR pc, int *reg, LONGEST *offset)
7993 {
7994   *reg = MIPS_SP_REGNUM;
7995   *offset = 0;
7996 }
7997
7998 static void
7999 mips_find_abi_section (bfd *abfd, asection *sect, void *obj)
8000 {
8001   enum mips_abi *abip = (enum mips_abi *) obj;
8002   const char *name = bfd_get_section_name (abfd, sect);
8003
8004   if (*abip != MIPS_ABI_UNKNOWN)
8005     return;
8006
8007   if (!startswith (name, ".mdebug."))
8008     return;
8009
8010   if (strcmp (name, ".mdebug.abi32") == 0)
8011     *abip = MIPS_ABI_O32;
8012   else if (strcmp (name, ".mdebug.abiN32") == 0)
8013     *abip = MIPS_ABI_N32;
8014   else if (strcmp (name, ".mdebug.abi64") == 0)
8015     *abip = MIPS_ABI_N64;
8016   else if (strcmp (name, ".mdebug.abiO64") == 0)
8017     *abip = MIPS_ABI_O64;
8018   else if (strcmp (name, ".mdebug.eabi32") == 0)
8019     *abip = MIPS_ABI_EABI32;
8020   else if (strcmp (name, ".mdebug.eabi64") == 0)
8021     *abip = MIPS_ABI_EABI64;
8022   else
8023     warning (_("unsupported ABI %s."), name + 8);
8024 }
8025
8026 static void
8027 mips_find_long_section (bfd *abfd, asection *sect, void *obj)
8028 {
8029   int *lbp = (int *) obj;
8030   const char *name = bfd_get_section_name (abfd, sect);
8031
8032   if (startswith (name, ".gcc_compiled_long32"))
8033     *lbp = 32;
8034   else if (startswith (name, ".gcc_compiled_long64"))
8035     *lbp = 64;
8036   else if (startswith (name, ".gcc_compiled_long"))
8037     warning (_("unrecognized .gcc_compiled_longXX"));
8038 }
8039
8040 static enum mips_abi
8041 global_mips_abi (void)
8042 {
8043   int i;
8044
8045   for (i = 0; mips_abi_strings[i] != NULL; i++)
8046     if (mips_abi_strings[i] == mips_abi_string)
8047       return (enum mips_abi) i;
8048
8049   internal_error (__FILE__, __LINE__, _("unknown ABI string"));
8050 }
8051
8052 /* Return the default compressed instruction set, either of MIPS16
8053    or microMIPS, selected when none could have been determined from
8054    the ELF header of the binary being executed (or no binary has been
8055    selected.  */
8056
8057 static enum mips_isa
8058 global_mips_compression (void)
8059 {
8060   int i;
8061
8062   for (i = 0; mips_compression_strings[i] != NULL; i++)
8063     if (mips_compression_strings[i] == mips_compression_string)
8064       return (enum mips_isa) i;
8065
8066   internal_error (__FILE__, __LINE__, _("unknown compressed ISA string"));
8067 }
8068
8069 static void
8070 mips_register_g_packet_guesses (struct gdbarch *gdbarch)
8071 {
8072   /* If the size matches the set of 32-bit or 64-bit integer registers,
8073      assume that's what we've got.  */
8074   register_remote_g_packet_guess (gdbarch, 38 * 4, mips_tdesc_gp32);
8075   register_remote_g_packet_guess (gdbarch, 38 * 8, mips_tdesc_gp64);
8076
8077   /* If the size matches the full set of registers GDB traditionally
8078      knows about, including floating point, for either 32-bit or
8079      64-bit, assume that's what we've got.  */
8080   register_remote_g_packet_guess (gdbarch, 90 * 4, mips_tdesc_gp32);
8081   register_remote_g_packet_guess (gdbarch, 90 * 8, mips_tdesc_gp64);
8082
8083   /* Otherwise we don't have a useful guess.  */
8084 }
8085
8086 static struct value *
8087 value_of_mips_user_reg (struct frame_info *frame, const void *baton)
8088 {
8089   const int *reg_p = (const int *) baton;
8090   return value_of_register (*reg_p, frame);
8091 }
8092
8093 static struct gdbarch *
8094 mips_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
8095 {
8096   struct gdbarch *gdbarch;
8097   struct gdbarch_tdep *tdep;
8098   int elf_flags;
8099   enum mips_abi mips_abi, found_abi, wanted_abi;
8100   int i, num_regs;
8101   enum mips_fpu_type fpu_type;
8102   struct tdesc_arch_data *tdesc_data = NULL;
8103   int elf_fpu_type = Val_GNU_MIPS_ABI_FP_ANY;
8104   const char **reg_names;
8105   struct mips_regnum mips_regnum, *regnum;
8106   enum mips_isa mips_isa;
8107   int dspacc;
8108   int dspctl;
8109
8110   /* Fill in the OS dependent register numbers and names.  */
8111   if (info.osabi == GDB_OSABI_LINUX)
8112     {
8113       mips_regnum.fp0 = 38;
8114       mips_regnum.pc = 37;
8115       mips_regnum.cause = 36;
8116       mips_regnum.badvaddr = 35;
8117       mips_regnum.hi = 34;
8118       mips_regnum.lo = 33;
8119       mips_regnum.fp_control_status = 70;
8120       mips_regnum.fp_implementation_revision = 71;
8121       mips_regnum.dspacc = -1;
8122       mips_regnum.dspctl = -1;
8123       dspacc = 72;
8124       dspctl = 78;
8125       num_regs = 90;
8126       reg_names = mips_linux_reg_names;
8127     }
8128   else
8129     {
8130       mips_regnum.lo = MIPS_EMBED_LO_REGNUM;
8131       mips_regnum.hi = MIPS_EMBED_HI_REGNUM;
8132       mips_regnum.badvaddr = MIPS_EMBED_BADVADDR_REGNUM;
8133       mips_regnum.cause = MIPS_EMBED_CAUSE_REGNUM;
8134       mips_regnum.pc = MIPS_EMBED_PC_REGNUM;
8135       mips_regnum.fp0 = MIPS_EMBED_FP0_REGNUM;
8136       mips_regnum.fp_control_status = 70;
8137       mips_regnum.fp_implementation_revision = 71;
8138       mips_regnum.dspacc = dspacc = -1;
8139       mips_regnum.dspctl = dspctl = -1;
8140       num_regs = MIPS_LAST_EMBED_REGNUM + 1;
8141       if (info.bfd_arch_info != NULL
8142           && info.bfd_arch_info->mach == bfd_mach_mips3900)
8143         reg_names = mips_tx39_reg_names;
8144       else
8145         reg_names = mips_generic_reg_names;
8146     }
8147
8148   /* Check any target description for validity.  */
8149   if (tdesc_has_registers (info.target_desc))
8150     {
8151       static const char *const mips_gprs[] = {
8152         "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
8153         "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
8154         "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
8155         "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31"
8156       };
8157       static const char *const mips_fprs[] = {
8158         "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
8159         "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
8160         "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
8161         "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
8162       };
8163
8164       const struct tdesc_feature *feature;
8165       int valid_p;
8166
8167       feature = tdesc_find_feature (info.target_desc,
8168                                     "org.gnu.gdb.mips.cpu");
8169       if (feature == NULL)
8170         return NULL;
8171
8172       tdesc_data = tdesc_data_alloc ();
8173
8174       valid_p = 1;
8175       for (i = MIPS_ZERO_REGNUM; i <= MIPS_RA_REGNUM; i++)
8176         valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
8177                                             mips_gprs[i]);
8178
8179
8180       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8181                                           mips_regnum.lo, "lo");
8182       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8183                                           mips_regnum.hi, "hi");
8184       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8185                                           mips_regnum.pc, "pc");
8186
8187       if (!valid_p)
8188         {
8189           tdesc_data_cleanup (tdesc_data);
8190           return NULL;
8191         }
8192
8193       feature = tdesc_find_feature (info.target_desc,
8194                                     "org.gnu.gdb.mips.cp0");
8195       if (feature == NULL)
8196         {
8197           tdesc_data_cleanup (tdesc_data);
8198           return NULL;
8199         }
8200
8201       valid_p = 1;
8202       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8203                                           mips_regnum.badvaddr, "badvaddr");
8204       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8205                                           MIPS_PS_REGNUM, "status");
8206       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8207                                           mips_regnum.cause, "cause");
8208
8209       if (!valid_p)
8210         {
8211           tdesc_data_cleanup (tdesc_data);
8212           return NULL;
8213         }
8214
8215       /* FIXME drow/2007-05-17: The FPU should be optional.  The MIPS
8216          backend is not prepared for that, though.  */
8217       feature = tdesc_find_feature (info.target_desc,
8218                                     "org.gnu.gdb.mips.fpu");
8219       if (feature == NULL)
8220         {
8221           tdesc_data_cleanup (tdesc_data);
8222           return NULL;
8223         }
8224
8225       valid_p = 1;
8226       for (i = 0; i < 32; i++)
8227         valid_p &= tdesc_numbered_register (feature, tdesc_data,
8228                                             i + mips_regnum.fp0, mips_fprs[i]);
8229
8230       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8231                                           mips_regnum.fp_control_status,
8232                                           "fcsr");
8233       valid_p
8234         &= tdesc_numbered_register (feature, tdesc_data,
8235                                     mips_regnum.fp_implementation_revision,
8236                                     "fir");
8237
8238       if (!valid_p)
8239         {
8240           tdesc_data_cleanup (tdesc_data);
8241           return NULL;
8242         }
8243
8244       num_regs = mips_regnum.fp_implementation_revision + 1;
8245
8246       if (dspacc >= 0)
8247         {
8248           feature = tdesc_find_feature (info.target_desc,
8249                                         "org.gnu.gdb.mips.dsp");
8250           /* The DSP registers are optional; it's OK if they are absent.  */
8251           if (feature != NULL)
8252             {
8253               i = 0;
8254               valid_p = 1;
8255               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8256                                                   dspacc + i++, "hi1");
8257               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8258                                                   dspacc + i++, "lo1");
8259               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8260                                                   dspacc + i++, "hi2");
8261               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8262                                                   dspacc + i++, "lo2");
8263               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8264                                                   dspacc + i++, "hi3");
8265               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8266                                                   dspacc + i++, "lo3");
8267
8268               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8269                                                   dspctl, "dspctl");
8270
8271               if (!valid_p)
8272                 {
8273                   tdesc_data_cleanup (tdesc_data);
8274                   return NULL;
8275                 }
8276
8277               mips_regnum.dspacc = dspacc;
8278               mips_regnum.dspctl = dspctl;
8279
8280               num_regs = mips_regnum.dspctl + 1;
8281             }
8282         }
8283
8284       /* It would be nice to detect an attempt to use a 64-bit ABI
8285          when only 32-bit registers are provided.  */
8286       reg_names = NULL;
8287     }
8288
8289   /* First of all, extract the elf_flags, if available.  */
8290   if (info.abfd && bfd_get_flavour (info.abfd) == bfd_target_elf_flavour)
8291     elf_flags = elf_elfheader (info.abfd)->e_flags;
8292   else if (arches != NULL)
8293     elf_flags = gdbarch_tdep (arches->gdbarch)->elf_flags;
8294   else
8295     elf_flags = 0;
8296   if (gdbarch_debug)
8297     fprintf_unfiltered (gdb_stdlog,
8298                         "mips_gdbarch_init: elf_flags = 0x%08x\n", elf_flags);
8299
8300   /* Check ELF_FLAGS to see if it specifies the ABI being used.  */
8301   switch ((elf_flags & EF_MIPS_ABI))
8302     {
8303     case E_MIPS_ABI_O32:
8304       found_abi = MIPS_ABI_O32;
8305       break;
8306     case E_MIPS_ABI_O64:
8307       found_abi = MIPS_ABI_O64;
8308       break;
8309     case E_MIPS_ABI_EABI32:
8310       found_abi = MIPS_ABI_EABI32;
8311       break;
8312     case E_MIPS_ABI_EABI64:
8313       found_abi = MIPS_ABI_EABI64;
8314       break;
8315     default:
8316       if ((elf_flags & EF_MIPS_ABI2))
8317         found_abi = MIPS_ABI_N32;
8318       else
8319         found_abi = MIPS_ABI_UNKNOWN;
8320       break;
8321     }
8322
8323   /* GCC creates a pseudo-section whose name describes the ABI.  */
8324   if (found_abi == MIPS_ABI_UNKNOWN && info.abfd != NULL)
8325     bfd_map_over_sections (info.abfd, mips_find_abi_section, &found_abi);
8326
8327   /* If we have no useful BFD information, use the ABI from the last
8328      MIPS architecture (if there is one).  */
8329   if (found_abi == MIPS_ABI_UNKNOWN && info.abfd == NULL && arches != NULL)
8330     found_abi = gdbarch_tdep (arches->gdbarch)->found_abi;
8331
8332   /* Try the architecture for any hint of the correct ABI.  */
8333   if (found_abi == MIPS_ABI_UNKNOWN
8334       && info.bfd_arch_info != NULL
8335       && info.bfd_arch_info->arch == bfd_arch_mips)
8336     {
8337       switch (info.bfd_arch_info->mach)
8338         {
8339         case bfd_mach_mips3900:
8340           found_abi = MIPS_ABI_EABI32;
8341           break;
8342         case bfd_mach_mips4100:
8343         case bfd_mach_mips5000:
8344           found_abi = MIPS_ABI_EABI64;
8345           break;
8346         case bfd_mach_mips8000:
8347         case bfd_mach_mips10000:
8348           /* On Irix, ELF64 executables use the N64 ABI.  The
8349              pseudo-sections which describe the ABI aren't present
8350              on IRIX.  (Even for executables created by gcc.)  */
8351           if (info.abfd != NULL
8352               && bfd_get_flavour (info.abfd) == bfd_target_elf_flavour
8353               && elf_elfheader (info.abfd)->e_ident[EI_CLASS] == ELFCLASS64)
8354             found_abi = MIPS_ABI_N64;
8355           else
8356             found_abi = MIPS_ABI_N32;
8357           break;
8358         }
8359     }
8360
8361   /* Default 64-bit objects to N64 instead of O32.  */
8362   if (found_abi == MIPS_ABI_UNKNOWN
8363       && info.abfd != NULL
8364       && bfd_get_flavour (info.abfd) == bfd_target_elf_flavour
8365       && elf_elfheader (info.abfd)->e_ident[EI_CLASS] == ELFCLASS64)
8366     found_abi = MIPS_ABI_N64;
8367
8368   if (gdbarch_debug)
8369     fprintf_unfiltered (gdb_stdlog, "mips_gdbarch_init: found_abi = %d\n",
8370                         found_abi);
8371
8372   /* What has the user specified from the command line?  */
8373   wanted_abi = global_mips_abi ();
8374   if (gdbarch_debug)
8375     fprintf_unfiltered (gdb_stdlog, "mips_gdbarch_init: wanted_abi = %d\n",
8376                         wanted_abi);
8377
8378   /* Now that we have found what the ABI for this binary would be,
8379      check whether the user is overriding it.  */
8380   if (wanted_abi != MIPS_ABI_UNKNOWN)
8381     mips_abi = wanted_abi;
8382   else if (found_abi != MIPS_ABI_UNKNOWN)
8383     mips_abi = found_abi;
8384   else
8385     mips_abi = MIPS_ABI_O32;
8386   if (gdbarch_debug)
8387     fprintf_unfiltered (gdb_stdlog, "mips_gdbarch_init: mips_abi = %d\n",
8388                         mips_abi);
8389
8390   /* Determine the default compressed ISA.  */
8391   if ((elf_flags & EF_MIPS_ARCH_ASE_MICROMIPS) != 0
8392       && (elf_flags & EF_MIPS_ARCH_ASE_M16) == 0)
8393     mips_isa = ISA_MICROMIPS;
8394   else if ((elf_flags & EF_MIPS_ARCH_ASE_M16) != 0
8395            && (elf_flags & EF_MIPS_ARCH_ASE_MICROMIPS) == 0)
8396     mips_isa = ISA_MIPS16;
8397   else
8398     mips_isa = global_mips_compression ();
8399   mips_compression_string = mips_compression_strings[mips_isa];
8400
8401   /* Also used when doing an architecture lookup.  */
8402   if (gdbarch_debug)
8403     fprintf_unfiltered (gdb_stdlog,
8404                         "mips_gdbarch_init: "
8405                         "mips64_transfers_32bit_regs_p = %d\n",
8406                         mips64_transfers_32bit_regs_p);
8407
8408   /* Determine the MIPS FPU type.  */
8409 #ifdef HAVE_ELF
8410   if (info.abfd
8411       && bfd_get_flavour (info.abfd) == bfd_target_elf_flavour)
8412     elf_fpu_type = bfd_elf_get_obj_attr_int (info.abfd, OBJ_ATTR_GNU,
8413                                              Tag_GNU_MIPS_ABI_FP);
8414 #endif /* HAVE_ELF */
8415
8416   if (!mips_fpu_type_auto)
8417     fpu_type = mips_fpu_type;
8418   else if (elf_fpu_type != Val_GNU_MIPS_ABI_FP_ANY)
8419     {
8420       switch (elf_fpu_type)
8421         {
8422         case Val_GNU_MIPS_ABI_FP_DOUBLE:
8423           fpu_type = MIPS_FPU_DOUBLE;
8424           break;
8425         case Val_GNU_MIPS_ABI_FP_SINGLE:
8426           fpu_type = MIPS_FPU_SINGLE;
8427           break;
8428         case Val_GNU_MIPS_ABI_FP_SOFT:
8429         default:
8430           /* Soft float or unknown.  */
8431           fpu_type = MIPS_FPU_NONE;
8432           break;
8433         }
8434     }
8435   else if (info.bfd_arch_info != NULL
8436            && info.bfd_arch_info->arch == bfd_arch_mips)
8437     switch (info.bfd_arch_info->mach)
8438       {
8439       case bfd_mach_mips3900:
8440       case bfd_mach_mips4100:
8441       case bfd_mach_mips4111:
8442       case bfd_mach_mips4120:
8443         fpu_type = MIPS_FPU_NONE;
8444         break;
8445       case bfd_mach_mips4650:
8446         fpu_type = MIPS_FPU_SINGLE;
8447         break;
8448       default:
8449         fpu_type = MIPS_FPU_DOUBLE;
8450         break;
8451       }
8452   else if (arches != NULL)
8453     fpu_type = MIPS_FPU_TYPE (arches->gdbarch);
8454   else
8455     fpu_type = MIPS_FPU_DOUBLE;
8456   if (gdbarch_debug)
8457     fprintf_unfiltered (gdb_stdlog,
8458                         "mips_gdbarch_init: fpu_type = %d\n", fpu_type);
8459
8460   /* Check for blatant incompatibilities.  */
8461
8462   /* If we have only 32-bit registers, then we can't debug a 64-bit
8463      ABI.  */
8464   if (info.target_desc
8465       && tdesc_property (info.target_desc, PROPERTY_GP32) != NULL
8466       && mips_abi != MIPS_ABI_EABI32
8467       && mips_abi != MIPS_ABI_O32)
8468     {
8469       if (tdesc_data != NULL)
8470         tdesc_data_cleanup (tdesc_data);
8471       return NULL;
8472     }
8473
8474   /* Try to find a pre-existing architecture.  */
8475   for (arches = gdbarch_list_lookup_by_info (arches, &info);
8476        arches != NULL;
8477        arches = gdbarch_list_lookup_by_info (arches->next, &info))
8478     {
8479       /* MIPS needs to be pedantic about which ABI and the compressed
8480          ISA variation the object is using.  */
8481       if (gdbarch_tdep (arches->gdbarch)->elf_flags != elf_flags)
8482         continue;
8483       if (gdbarch_tdep (arches->gdbarch)->mips_abi != mips_abi)
8484         continue;
8485       if (gdbarch_tdep (arches->gdbarch)->mips_isa != mips_isa)
8486         continue;
8487       /* Need to be pedantic about which register virtual size is
8488          used.  */
8489       if (gdbarch_tdep (arches->gdbarch)->mips64_transfers_32bit_regs_p
8490           != mips64_transfers_32bit_regs_p)
8491         continue;
8492       /* Be pedantic about which FPU is selected.  */
8493       if (MIPS_FPU_TYPE (arches->gdbarch) != fpu_type)
8494         continue;
8495
8496       if (tdesc_data != NULL)
8497         tdesc_data_cleanup (tdesc_data);
8498       return arches->gdbarch;
8499     }
8500
8501   /* Need a new architecture.  Fill in a target specific vector.  */
8502   tdep = XCNEW (struct gdbarch_tdep);
8503   gdbarch = gdbarch_alloc (&info, tdep);
8504   tdep->elf_flags = elf_flags;
8505   tdep->mips64_transfers_32bit_regs_p = mips64_transfers_32bit_regs_p;
8506   tdep->found_abi = found_abi;
8507   tdep->mips_abi = mips_abi;
8508   tdep->mips_isa = mips_isa;
8509   tdep->mips_fpu_type = fpu_type;
8510   tdep->register_size_valid_p = 0;
8511   tdep->register_size = 0;
8512
8513   if (info.target_desc)
8514     {
8515       /* Some useful properties can be inferred from the target.  */
8516       if (tdesc_property (info.target_desc, PROPERTY_GP32) != NULL)
8517         {
8518           tdep->register_size_valid_p = 1;
8519           tdep->register_size = 4;
8520         }
8521       else if (tdesc_property (info.target_desc, PROPERTY_GP64) != NULL)
8522         {
8523           tdep->register_size_valid_p = 1;
8524           tdep->register_size = 8;
8525         }
8526     }
8527
8528   /* Initially set everything according to the default ABI/ISA.  */
8529   set_gdbarch_short_bit (gdbarch, 16);
8530   set_gdbarch_int_bit (gdbarch, 32);
8531   set_gdbarch_float_bit (gdbarch, 32);
8532   set_gdbarch_double_bit (gdbarch, 64);
8533   set_gdbarch_long_double_bit (gdbarch, 64);
8534   set_gdbarch_register_reggroup_p (gdbarch, mips_register_reggroup_p);
8535   set_gdbarch_pseudo_register_read (gdbarch, mips_pseudo_register_read);
8536   set_gdbarch_pseudo_register_write (gdbarch, mips_pseudo_register_write);
8537
8538   set_gdbarch_ax_pseudo_register_collect (gdbarch,
8539                                           mips_ax_pseudo_register_collect);
8540   set_gdbarch_ax_pseudo_register_push_stack
8541       (gdbarch, mips_ax_pseudo_register_push_stack);
8542
8543   set_gdbarch_elf_make_msymbol_special (gdbarch,
8544                                         mips_elf_make_msymbol_special);
8545   set_gdbarch_make_symbol_special (gdbarch, mips_make_symbol_special);
8546   set_gdbarch_adjust_dwarf2_addr (gdbarch, mips_adjust_dwarf2_addr);
8547   set_gdbarch_adjust_dwarf2_line (gdbarch, mips_adjust_dwarf2_line);
8548
8549   regnum = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct mips_regnum);
8550   *regnum = mips_regnum;
8551   set_gdbarch_fp0_regnum (gdbarch, regnum->fp0);
8552   set_gdbarch_num_regs (gdbarch, num_regs);
8553   set_gdbarch_num_pseudo_regs (gdbarch, num_regs);
8554   set_gdbarch_register_name (gdbarch, mips_register_name);
8555   set_gdbarch_virtual_frame_pointer (gdbarch, mips_virtual_frame_pointer);
8556   tdep->mips_processor_reg_names = reg_names;
8557   tdep->regnum = regnum;
8558
8559   switch (mips_abi)
8560     {
8561     case MIPS_ABI_O32:
8562       set_gdbarch_push_dummy_call (gdbarch, mips_o32_push_dummy_call);
8563       set_gdbarch_return_value (gdbarch, mips_o32_return_value);
8564       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 4 - 1;
8565       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 4 - 1;
8566       tdep->default_mask_address_p = 0;
8567       set_gdbarch_long_bit (gdbarch, 32);
8568       set_gdbarch_ptr_bit (gdbarch, 32);
8569       set_gdbarch_long_long_bit (gdbarch, 64);
8570       break;
8571     case MIPS_ABI_O64:
8572       set_gdbarch_push_dummy_call (gdbarch, mips_o64_push_dummy_call);
8573       set_gdbarch_return_value (gdbarch, mips_o64_return_value);
8574       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 4 - 1;
8575       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 4 - 1;
8576       tdep->default_mask_address_p = 0;
8577       set_gdbarch_long_bit (gdbarch, 32);
8578       set_gdbarch_ptr_bit (gdbarch, 32);
8579       set_gdbarch_long_long_bit (gdbarch, 64);
8580       break;
8581     case MIPS_ABI_EABI32:
8582       set_gdbarch_push_dummy_call (gdbarch, mips_eabi_push_dummy_call);
8583       set_gdbarch_return_value (gdbarch, mips_eabi_return_value);
8584       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 8 - 1;
8585       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 8 - 1;
8586       tdep->default_mask_address_p = 0;
8587       set_gdbarch_long_bit (gdbarch, 32);
8588       set_gdbarch_ptr_bit (gdbarch, 32);
8589       set_gdbarch_long_long_bit (gdbarch, 64);
8590       break;
8591     case MIPS_ABI_EABI64:
8592       set_gdbarch_push_dummy_call (gdbarch, mips_eabi_push_dummy_call);
8593       set_gdbarch_return_value (gdbarch, mips_eabi_return_value);
8594       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 8 - 1;
8595       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 8 - 1;
8596       tdep->default_mask_address_p = 0;
8597       set_gdbarch_long_bit (gdbarch, 64);
8598       set_gdbarch_ptr_bit (gdbarch, 64);
8599       set_gdbarch_long_long_bit (gdbarch, 64);
8600       break;
8601     case MIPS_ABI_N32:
8602       set_gdbarch_push_dummy_call (gdbarch, mips_n32n64_push_dummy_call);
8603       set_gdbarch_return_value (gdbarch, mips_n32n64_return_value);
8604       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 8 - 1;
8605       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 8 - 1;
8606       tdep->default_mask_address_p = 0;
8607       set_gdbarch_long_bit (gdbarch, 32);
8608       set_gdbarch_ptr_bit (gdbarch, 32);
8609       set_gdbarch_long_long_bit (gdbarch, 64);
8610       set_gdbarch_long_double_bit (gdbarch, 128);
8611       set_gdbarch_long_double_format (gdbarch, floatformats_ibm_long_double);
8612       break;
8613     case MIPS_ABI_N64:
8614       set_gdbarch_push_dummy_call (gdbarch, mips_n32n64_push_dummy_call);
8615       set_gdbarch_return_value (gdbarch, mips_n32n64_return_value);
8616       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 8 - 1;
8617       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 8 - 1;
8618       tdep->default_mask_address_p = 0;
8619       set_gdbarch_long_bit (gdbarch, 64);
8620       set_gdbarch_ptr_bit (gdbarch, 64);
8621       set_gdbarch_long_long_bit (gdbarch, 64);
8622       set_gdbarch_long_double_bit (gdbarch, 128);
8623       set_gdbarch_long_double_format (gdbarch, floatformats_ibm_long_double);
8624       break;
8625     default:
8626       internal_error (__FILE__, __LINE__, _("unknown ABI in switch"));
8627     }
8628
8629   /* GCC creates a pseudo-section whose name specifies the size of
8630      longs, since -mlong32 or -mlong64 may be used independent of
8631      other options.  How those options affect pointer sizes is ABI and
8632      architecture dependent, so use them to override the default sizes
8633      set by the ABI.  This table shows the relationship between ABI,
8634      -mlongXX, and size of pointers:
8635
8636      ABI                -mlongXX        ptr bits
8637      ---                --------        --------
8638      o32                32              32
8639      o32                64              32
8640      n32                32              32
8641      n32                64              64
8642      o64                32              32
8643      o64                64              64
8644      n64                32              32
8645      n64                64              64
8646      eabi32             32              32
8647      eabi32             64              32
8648      eabi64             32              32
8649      eabi64             64              64
8650
8651     Note that for o32 and eabi32, pointers are always 32 bits
8652     regardless of any -mlongXX option.  For all others, pointers and
8653     longs are the same, as set by -mlongXX or set by defaults.  */
8654
8655   if (info.abfd != NULL)
8656     {
8657       int long_bit = 0;
8658
8659       bfd_map_over_sections (info.abfd, mips_find_long_section, &long_bit);
8660       if (long_bit)
8661         {
8662           set_gdbarch_long_bit (gdbarch, long_bit);
8663           switch (mips_abi)
8664             {
8665             case MIPS_ABI_O32:
8666             case MIPS_ABI_EABI32:
8667               break;
8668             case MIPS_ABI_N32:
8669             case MIPS_ABI_O64:
8670             case MIPS_ABI_N64:
8671             case MIPS_ABI_EABI64:
8672               set_gdbarch_ptr_bit (gdbarch, long_bit);
8673               break;
8674             default:
8675               internal_error (__FILE__, __LINE__, _("unknown ABI in switch"));
8676             }
8677         }
8678     }
8679
8680   /* FIXME: jlarmour/2000-04-07: There *is* a flag EF_MIPS_32BIT_MODE
8681      that could indicate -gp32 BUT gas/config/tc-mips.c contains the
8682      comment:
8683
8684      ``We deliberately don't allow "-gp32" to set the MIPS_32BITMODE
8685      flag in object files because to do so would make it impossible to
8686      link with libraries compiled without "-gp32".  This is
8687      unnecessarily restrictive.
8688
8689      We could solve this problem by adding "-gp32" multilibs to gcc,
8690      but to set this flag before gcc is built with such multilibs will
8691      break too many systems.''
8692
8693      But even more unhelpfully, the default linker output target for
8694      mips64-elf is elf32-bigmips, and has EF_MIPS_32BIT_MODE set, even
8695      for 64-bit programs - you need to change the ABI to change this,
8696      and not all gcc targets support that currently.  Therefore using
8697      this flag to detect 32-bit mode would do the wrong thing given
8698      the current gcc - it would make GDB treat these 64-bit programs
8699      as 32-bit programs by default.  */
8700
8701   set_gdbarch_read_pc (gdbarch, mips_read_pc);
8702   set_gdbarch_write_pc (gdbarch, mips_write_pc);
8703
8704   /* Add/remove bits from an address.  The MIPS needs be careful to
8705      ensure that all 32 bit addresses are sign extended to 64 bits.  */
8706   set_gdbarch_addr_bits_remove (gdbarch, mips_addr_bits_remove);
8707
8708   /* Unwind the frame.  */
8709   set_gdbarch_unwind_pc (gdbarch, mips_unwind_pc);
8710   set_gdbarch_unwind_sp (gdbarch, mips_unwind_sp);
8711   set_gdbarch_dummy_id (gdbarch, mips_dummy_id);
8712
8713   /* Map debug register numbers onto internal register numbers.  */
8714   set_gdbarch_stab_reg_to_regnum (gdbarch, mips_stab_reg_to_regnum);
8715   set_gdbarch_ecoff_reg_to_regnum (gdbarch,
8716                                    mips_dwarf_dwarf2_ecoff_reg_to_regnum);
8717   set_gdbarch_dwarf2_reg_to_regnum (gdbarch,
8718                                     mips_dwarf_dwarf2_ecoff_reg_to_regnum);
8719   set_gdbarch_register_sim_regno (gdbarch, mips_register_sim_regno);
8720
8721   /* MIPS version of CALL_DUMMY.  */
8722
8723   set_gdbarch_call_dummy_location (gdbarch, ON_STACK);
8724   set_gdbarch_push_dummy_code (gdbarch, mips_push_dummy_code);
8725   set_gdbarch_frame_align (gdbarch, mips_frame_align);
8726
8727   set_gdbarch_print_float_info (gdbarch, mips_print_float_info);
8728
8729   set_gdbarch_convert_register_p (gdbarch, mips_convert_register_p);
8730   set_gdbarch_register_to_value (gdbarch, mips_register_to_value);
8731   set_gdbarch_value_to_register (gdbarch, mips_value_to_register);
8732
8733   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
8734   set_gdbarch_breakpoint_kind_from_pc (gdbarch, mips_breakpoint_kind_from_pc);
8735   set_gdbarch_sw_breakpoint_from_kind (gdbarch, mips_sw_breakpoint_from_kind);
8736   set_gdbarch_adjust_breakpoint_address (gdbarch,
8737                                          mips_adjust_breakpoint_address);
8738
8739   set_gdbarch_skip_prologue (gdbarch, mips_skip_prologue);
8740
8741   set_gdbarch_stack_frame_destroyed_p (gdbarch, mips_stack_frame_destroyed_p);
8742
8743   set_gdbarch_pointer_to_address (gdbarch, signed_pointer_to_address);
8744   set_gdbarch_address_to_pointer (gdbarch, address_to_signed_pointer);
8745   set_gdbarch_integer_to_address (gdbarch, mips_integer_to_address);
8746
8747   set_gdbarch_register_type (gdbarch, mips_register_type);
8748
8749   set_gdbarch_print_registers_info (gdbarch, mips_print_registers_info);
8750
8751   if (mips_abi == MIPS_ABI_N32)
8752     set_gdbarch_print_insn (gdbarch, gdb_print_insn_mips_n32);
8753   else if (mips_abi == MIPS_ABI_N64)
8754     set_gdbarch_print_insn (gdbarch, gdb_print_insn_mips_n64);
8755   else
8756     set_gdbarch_print_insn (gdbarch, gdb_print_insn_mips);
8757
8758   /* FIXME: cagney/2003-08-29: The macros target_have_steppable_watchpoint,
8759      HAVE_NONSTEPPABLE_WATCHPOINT, and target_have_continuable_watchpoint
8760      need to all be folded into the target vector.  Since they are
8761      being used as guards for target_stopped_by_watchpoint, why not have
8762      target_stopped_by_watchpoint return the type of watchpoint that the code
8763      is sitting on?  */
8764   set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
8765
8766   set_gdbarch_skip_trampoline_code (gdbarch, mips_skip_trampoline_code);
8767
8768   /* NOTE drow/2012-04-25: We overload the core solib trampoline code
8769      to support MIPS16.  This is a bad thing.  Make sure not to do it
8770      if we have an OS ABI that actually supports shared libraries, since
8771      shared library support is more important.  If we have an OS someday
8772      that supports both shared libraries and MIPS16, we'll have to find
8773      a better place for these.
8774      macro/2012-04-25: But that applies to return trampolines only and
8775      currently no MIPS OS ABI uses shared libraries that have them.  */
8776   set_gdbarch_in_solib_return_trampoline (gdbarch, mips_in_return_stub);
8777
8778   set_gdbarch_single_step_through_delay (gdbarch,
8779                                          mips_single_step_through_delay);
8780
8781   /* Virtual tables.  */
8782   set_gdbarch_vbit_in_delta (gdbarch, 1);
8783
8784   mips_register_g_packet_guesses (gdbarch);
8785
8786   /* Hook in OS ABI-specific overrides, if they have been registered.  */
8787   info.tdesc_data = tdesc_data;
8788   gdbarch_init_osabi (info, gdbarch);
8789
8790   /* The hook may have adjusted num_regs, fetch the final value and
8791      set pc_regnum and sp_regnum now that it has been fixed.  */
8792   num_regs = gdbarch_num_regs (gdbarch);
8793   set_gdbarch_pc_regnum (gdbarch, regnum->pc + num_regs);
8794   set_gdbarch_sp_regnum (gdbarch, MIPS_SP_REGNUM + num_regs);
8795
8796   /* Unwind the frame.  */
8797   dwarf2_append_unwinders (gdbarch);
8798   frame_unwind_append_unwinder (gdbarch, &mips_stub_frame_unwind);
8799   frame_unwind_append_unwinder (gdbarch, &mips_insn16_frame_unwind);
8800   frame_unwind_append_unwinder (gdbarch, &mips_micro_frame_unwind);
8801   frame_unwind_append_unwinder (gdbarch, &mips_insn32_frame_unwind);
8802   frame_base_append_sniffer (gdbarch, dwarf2_frame_base_sniffer);
8803   frame_base_append_sniffer (gdbarch, mips_stub_frame_base_sniffer);
8804   frame_base_append_sniffer (gdbarch, mips_insn16_frame_base_sniffer);
8805   frame_base_append_sniffer (gdbarch, mips_micro_frame_base_sniffer);
8806   frame_base_append_sniffer (gdbarch, mips_insn32_frame_base_sniffer);
8807
8808   if (tdesc_data)
8809     {
8810       set_tdesc_pseudo_register_type (gdbarch, mips_pseudo_register_type);
8811       tdesc_use_registers (gdbarch, info.target_desc, tdesc_data);
8812
8813       /* Override the normal target description methods to handle our
8814          dual real and pseudo registers.  */
8815       set_gdbarch_register_name (gdbarch, mips_register_name);
8816       set_gdbarch_register_reggroup_p (gdbarch,
8817                                        mips_tdesc_register_reggroup_p);
8818
8819       num_regs = gdbarch_num_regs (gdbarch);
8820       set_gdbarch_num_pseudo_regs (gdbarch, num_regs);
8821       set_gdbarch_pc_regnum (gdbarch, tdep->regnum->pc + num_regs);
8822       set_gdbarch_sp_regnum (gdbarch, MIPS_SP_REGNUM + num_regs);
8823     }
8824
8825   /* Add ABI-specific aliases for the registers.  */
8826   if (mips_abi == MIPS_ABI_N32 || mips_abi == MIPS_ABI_N64)
8827     for (i = 0; i < ARRAY_SIZE (mips_n32_n64_aliases); i++)
8828       user_reg_add (gdbarch, mips_n32_n64_aliases[i].name,
8829                     value_of_mips_user_reg, &mips_n32_n64_aliases[i].regnum);
8830   else
8831     for (i = 0; i < ARRAY_SIZE (mips_o32_aliases); i++)
8832       user_reg_add (gdbarch, mips_o32_aliases[i].name,
8833                     value_of_mips_user_reg, &mips_o32_aliases[i].regnum);
8834
8835   /* Add some other standard aliases.  */
8836   for (i = 0; i < ARRAY_SIZE (mips_register_aliases); i++)
8837     user_reg_add (gdbarch, mips_register_aliases[i].name,
8838                   value_of_mips_user_reg, &mips_register_aliases[i].regnum);
8839
8840   for (i = 0; i < ARRAY_SIZE (mips_numeric_register_aliases); i++)
8841     user_reg_add (gdbarch, mips_numeric_register_aliases[i].name,
8842                   value_of_mips_user_reg, 
8843                   &mips_numeric_register_aliases[i].regnum);
8844
8845   return gdbarch;
8846 }
8847
8848 static void
8849 mips_abi_update (char *ignore_args, int from_tty, struct cmd_list_element *c)
8850 {
8851   struct gdbarch_info info;
8852
8853   /* Force the architecture to update, and (if it's a MIPS architecture)
8854      mips_gdbarch_init will take care of the rest.  */
8855   gdbarch_info_init (&info);
8856   gdbarch_update_p (info);
8857 }
8858
8859 /* Print out which MIPS ABI is in use.  */
8860
8861 static void
8862 show_mips_abi (struct ui_file *file,
8863                int from_tty,
8864                struct cmd_list_element *ignored_cmd,
8865                const char *ignored_value)
8866 {
8867   if (gdbarch_bfd_arch_info (target_gdbarch ())->arch != bfd_arch_mips)
8868     fprintf_filtered
8869       (file, 
8870        "The MIPS ABI is unknown because the current architecture "
8871        "is not MIPS.\n");
8872   else
8873     {
8874       enum mips_abi global_abi = global_mips_abi ();
8875       enum mips_abi actual_abi = mips_abi (target_gdbarch ());
8876       const char *actual_abi_str = mips_abi_strings[actual_abi];
8877
8878       if (global_abi == MIPS_ABI_UNKNOWN)
8879         fprintf_filtered
8880           (file, 
8881            "The MIPS ABI is set automatically (currently \"%s\").\n",
8882            actual_abi_str);
8883       else if (global_abi == actual_abi)
8884         fprintf_filtered
8885           (file,
8886            "The MIPS ABI is assumed to be \"%s\" (due to user setting).\n",
8887            actual_abi_str);
8888       else
8889         {
8890           /* Probably shouldn't happen...  */
8891           fprintf_filtered (file,
8892                             "The (auto detected) MIPS ABI \"%s\" is in use "
8893                             "even though the user setting was \"%s\".\n",
8894              actual_abi_str, mips_abi_strings[global_abi]);
8895         }
8896     }
8897 }
8898
8899 /* Print out which MIPS compressed ISA encoding is used.  */
8900
8901 static void
8902 show_mips_compression (struct ui_file *file, int from_tty,
8903                        struct cmd_list_element *c, const char *value)
8904 {
8905   fprintf_filtered (file, _("The compressed ISA encoding used is %s.\n"),
8906                     value);
8907 }
8908
8909 /* Return a textual name for MIPS FPU type FPU_TYPE.  */
8910
8911 static const char *
8912 mips_fpu_type_str (enum mips_fpu_type fpu_type)
8913 {
8914   switch (fpu_type)
8915     {
8916     case MIPS_FPU_NONE:
8917       return "none";
8918     case MIPS_FPU_SINGLE:
8919       return "single";
8920     case MIPS_FPU_DOUBLE:
8921       return "double";
8922     default:
8923       return "???";
8924     }
8925 }
8926
8927 static void
8928 mips_dump_tdep (struct gdbarch *gdbarch, struct ui_file *file)
8929 {
8930   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
8931   if (tdep != NULL)
8932     {
8933       int ef_mips_arch;
8934       int ef_mips_32bitmode;
8935       /* Determine the ISA.  */
8936       switch (tdep->elf_flags & EF_MIPS_ARCH)
8937         {
8938         case E_MIPS_ARCH_1:
8939           ef_mips_arch = 1;
8940           break;
8941         case E_MIPS_ARCH_2:
8942           ef_mips_arch = 2;
8943           break;
8944         case E_MIPS_ARCH_3:
8945           ef_mips_arch = 3;
8946           break;
8947         case E_MIPS_ARCH_4:
8948           ef_mips_arch = 4;
8949           break;
8950         default:
8951           ef_mips_arch = 0;
8952           break;
8953         }
8954       /* Determine the size of a pointer.  */
8955       ef_mips_32bitmode = (tdep->elf_flags & EF_MIPS_32BITMODE);
8956       fprintf_unfiltered (file,
8957                           "mips_dump_tdep: tdep->elf_flags = 0x%x\n",
8958                           tdep->elf_flags);
8959       fprintf_unfiltered (file,
8960                           "mips_dump_tdep: ef_mips_32bitmode = %d\n",
8961                           ef_mips_32bitmode);
8962       fprintf_unfiltered (file,
8963                           "mips_dump_tdep: ef_mips_arch = %d\n",
8964                           ef_mips_arch);
8965       fprintf_unfiltered (file,
8966                           "mips_dump_tdep: tdep->mips_abi = %d (%s)\n",
8967                           tdep->mips_abi, mips_abi_strings[tdep->mips_abi]);
8968       fprintf_unfiltered (file,
8969                           "mips_dump_tdep: "
8970                           "mips_mask_address_p() %d (default %d)\n",
8971                           mips_mask_address_p (tdep),
8972                           tdep->default_mask_address_p);
8973     }
8974   fprintf_unfiltered (file,
8975                       "mips_dump_tdep: MIPS_DEFAULT_FPU_TYPE = %d (%s)\n",
8976                       MIPS_DEFAULT_FPU_TYPE,
8977                       mips_fpu_type_str (MIPS_DEFAULT_FPU_TYPE));
8978   fprintf_unfiltered (file, "mips_dump_tdep: MIPS_EABI = %d\n",
8979                       MIPS_EABI (gdbarch));
8980   fprintf_unfiltered (file,
8981                       "mips_dump_tdep: MIPS_FPU_TYPE = %d (%s)\n",
8982                       MIPS_FPU_TYPE (gdbarch),
8983                       mips_fpu_type_str (MIPS_FPU_TYPE (gdbarch)));
8984 }
8985
8986 void
8987 _initialize_mips_tdep (void)
8988 {
8989   static struct cmd_list_element *mipsfpulist = NULL;
8990   struct cmd_list_element *c;
8991
8992   mips_abi_string = mips_abi_strings[MIPS_ABI_UNKNOWN];
8993   if (MIPS_ABI_LAST + 1
8994       != sizeof (mips_abi_strings) / sizeof (mips_abi_strings[0]))
8995     internal_error (__FILE__, __LINE__, _("mips_abi_strings out of sync"));
8996
8997   gdbarch_register (bfd_arch_mips, mips_gdbarch_init, mips_dump_tdep);
8998
8999   mips_pdr_data = register_objfile_data ();
9000
9001   /* Create feature sets with the appropriate properties.  The values
9002      are not important.  */
9003   mips_tdesc_gp32 = allocate_target_description ();
9004   set_tdesc_property (mips_tdesc_gp32, PROPERTY_GP32, "");
9005
9006   mips_tdesc_gp64 = allocate_target_description ();
9007   set_tdesc_property (mips_tdesc_gp64, PROPERTY_GP64, "");
9008
9009   /* Add root prefix command for all "set mips"/"show mips" commands.  */
9010   add_prefix_cmd ("mips", no_class, set_mips_command,
9011                   _("Various MIPS specific commands."),
9012                   &setmipscmdlist, "set mips ", 0, &setlist);
9013
9014   add_prefix_cmd ("mips", no_class, show_mips_command,
9015                   _("Various MIPS specific commands."),
9016                   &showmipscmdlist, "show mips ", 0, &showlist);
9017
9018   /* Allow the user to override the ABI.  */
9019   add_setshow_enum_cmd ("abi", class_obscure, mips_abi_strings,
9020                         &mips_abi_string, _("\
9021 Set the MIPS ABI used by this program."), _("\
9022 Show the MIPS ABI used by this program."), _("\
9023 This option can be set to one of:\n\
9024   auto  - the default ABI associated with the current binary\n\
9025   o32\n\
9026   o64\n\
9027   n32\n\
9028   n64\n\
9029   eabi32\n\
9030   eabi64"),
9031                         mips_abi_update,
9032                         show_mips_abi,
9033                         &setmipscmdlist, &showmipscmdlist);
9034
9035   /* Allow the user to set the ISA to assume for compressed code if ELF
9036      file flags don't tell or there is no program file selected.  This
9037      setting is updated whenever unambiguous ELF file flags are interpreted,
9038      and carried over to subsequent sessions.  */
9039   add_setshow_enum_cmd ("compression", class_obscure, mips_compression_strings,
9040                         &mips_compression_string, _("\
9041 Set the compressed ISA encoding used by MIPS code."), _("\
9042 Show the compressed ISA encoding used by MIPS code."), _("\
9043 Select the compressed ISA encoding used in functions that have no symbol\n\
9044 information available.  The encoding can be set to either of:\n\
9045   mips16\n\
9046   micromips\n\
9047 and is updated automatically from ELF file flags if available."),
9048                         mips_abi_update,
9049                         show_mips_compression,
9050                         &setmipscmdlist, &showmipscmdlist);
9051
9052   /* Let the user turn off floating point and set the fence post for
9053      heuristic_proc_start.  */
9054
9055   add_prefix_cmd ("mipsfpu", class_support, set_mipsfpu_command,
9056                   _("Set use of MIPS floating-point coprocessor."),
9057                   &mipsfpulist, "set mipsfpu ", 0, &setlist);
9058   add_cmd ("single", class_support, set_mipsfpu_single_command,
9059            _("Select single-precision MIPS floating-point coprocessor."),
9060            &mipsfpulist);
9061   add_cmd ("double", class_support, set_mipsfpu_double_command,
9062            _("Select double-precision MIPS floating-point coprocessor."),
9063            &mipsfpulist);
9064   add_alias_cmd ("on", "double", class_support, 1, &mipsfpulist);
9065   add_alias_cmd ("yes", "double", class_support, 1, &mipsfpulist);
9066   add_alias_cmd ("1", "double", class_support, 1, &mipsfpulist);
9067   add_cmd ("none", class_support, set_mipsfpu_none_command,
9068            _("Select no MIPS floating-point coprocessor."), &mipsfpulist);
9069   add_alias_cmd ("off", "none", class_support, 1, &mipsfpulist);
9070   add_alias_cmd ("no", "none", class_support, 1, &mipsfpulist);
9071   add_alias_cmd ("0", "none", class_support, 1, &mipsfpulist);
9072   add_cmd ("auto", class_support, set_mipsfpu_auto_command,
9073            _("Select MIPS floating-point coprocessor automatically."),
9074            &mipsfpulist);
9075   add_cmd ("mipsfpu", class_support, show_mipsfpu_command,
9076            _("Show current use of MIPS floating-point coprocessor target."),
9077            &showlist);
9078
9079   /* We really would like to have both "0" and "unlimited" work, but
9080      command.c doesn't deal with that.  So make it a var_zinteger
9081      because the user can always use "999999" or some such for unlimited.  */
9082   add_setshow_zinteger_cmd ("heuristic-fence-post", class_support,
9083                             &heuristic_fence_post, _("\
9084 Set the distance searched for the start of a function."), _("\
9085 Show the distance searched for the start of a function."), _("\
9086 If you are debugging a stripped executable, GDB needs to search through the\n\
9087 program for the start of a function.  This command sets the distance of the\n\
9088 search.  The only need to set it is when debugging a stripped executable."),
9089                             reinit_frame_cache_sfunc,
9090                             NULL, /* FIXME: i18n: The distance searched for
9091                                      the start of a function is %s.  */
9092                             &setlist, &showlist);
9093
9094   /* Allow the user to control whether the upper bits of 64-bit
9095      addresses should be zeroed.  */
9096   add_setshow_auto_boolean_cmd ("mask-address", no_class,
9097                                 &mask_address_var, _("\
9098 Set zeroing of upper 32 bits of 64-bit addresses."), _("\
9099 Show zeroing of upper 32 bits of 64-bit addresses."), _("\
9100 Use \"on\" to enable the masking, \"off\" to disable it and \"auto\" to\n\
9101 allow GDB to determine the correct value."),
9102                                 NULL, show_mask_address,
9103                                 &setmipscmdlist, &showmipscmdlist);
9104
9105   /* Allow the user to control the size of 32 bit registers within the
9106      raw remote packet.  */
9107   add_setshow_boolean_cmd ("remote-mips64-transfers-32bit-regs", class_obscure,
9108                            &mips64_transfers_32bit_regs_p, _("\
9109 Set compatibility with 64-bit MIPS target that transfers 32-bit quantities."),
9110                            _("\
9111 Show compatibility with 64-bit MIPS target that transfers 32-bit quantities."),
9112                            _("\
9113 Use \"on\" to enable backward compatibility with older MIPS 64 GDB+target\n\
9114 that would transfer 32 bits for some registers (e.g. SR, FSR) and\n\
9115 64 bits for others.  Use \"off\" to disable compatibility mode"),
9116                            set_mips64_transfers_32bit_regs,
9117                            NULL, /* FIXME: i18n: Compatibility with 64-bit
9118                                     MIPS target that transfers 32-bit
9119                                     quantities is %s.  */
9120                            &setlist, &showlist);
9121
9122   /* Debug this files internals.  */
9123   add_setshow_zuinteger_cmd ("mips", class_maintenance,
9124                              &mips_debug, _("\
9125 Set mips debugging."), _("\
9126 Show mips debugging."), _("\
9127 When non-zero, mips specific debugging is enabled."),
9128                              NULL,
9129                              NULL, /* FIXME: i18n: Mips debugging is
9130                                       currently %s.  */
9131                              &setdebuglist, &showdebuglist);
9132 }