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