OSDN Git Service

2008-04-03 Jan Hubicka <jh@suse.cz>
[pf3gnuchains/gcc-fork.git] / gcc / config / mips / mips.c
index 5e939d1..861a308 100644 (file)
@@ -1,6 +1,6 @@
 /* Subroutines used for MIPS code generation.
    Copyright (C) 1989, 1990, 1991, 1993, 1994, 1995, 1996, 1997, 1998,
-   1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 
+   1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
    Free Software Foundation, Inc.
    Contributed by A. Lichnewsky, lich@inria.inria.fr.
    Changes by Michael Meissner, meissner@osf.org.
@@ -59,7 +59,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "bitmap.h"
 #include "diagnostic.h"
 
-/* True if X is an unspec wrapper around a SYMBOL_REF or LABEL_REF.  */
+/* True if X is an UNSPEC wrapper around a SYMBOL_REF or LABEL_REF.  */
 #define UNSPEC_ADDRESS_P(X)                                    \
   (GET_CODE (X) == UNSPEC                                      \
    && XINT (X, 1) >= UNSPEC_ADDRESS_FIRST                      \
@@ -139,7 +139,7 @@ along with GCC; see the file COPYING3.  If not see
        A signed 16-bit constant address.
 
    ADDRESS_SYMBOLIC:
-       A constant symbolic address (equivalent to CONSTANT_SYMBOLIC).  */
+       A constant symbolic address.  */
 enum mips_address_type {
   ADDRESS_REG,
   ADDRESS_LO_SUM,
@@ -147,85 +147,39 @@ enum mips_address_type {
   ADDRESS_SYMBOLIC
 };
 
-/* Classifies the prototype of a builtin function.  */
-enum mips_function_type
-{
-  MIPS_V2SF_FTYPE_V2SF,
-  MIPS_V2SF_FTYPE_V2SF_V2SF,
-  MIPS_V2SF_FTYPE_V2SF_V2SF_INT,
-  MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF,
-  MIPS_V2SF_FTYPE_SF_SF,
-  MIPS_INT_FTYPE_V2SF_V2SF,
-  MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF,
-  MIPS_INT_FTYPE_SF_SF,
-  MIPS_INT_FTYPE_DF_DF,
-  MIPS_SF_FTYPE_V2SF,
-  MIPS_SF_FTYPE_SF,
-  MIPS_SF_FTYPE_SF_SF,
-  MIPS_DF_FTYPE_DF,
-  MIPS_DF_FTYPE_DF_DF,
-
-  /* For MIPS DSP ASE  */
-  MIPS_DI_FTYPE_DI_SI,
-  MIPS_DI_FTYPE_DI_SI_SI,
-  MIPS_DI_FTYPE_DI_V2HI_V2HI,
-  MIPS_DI_FTYPE_DI_V4QI_V4QI,
-  MIPS_SI_FTYPE_DI_SI,
-  MIPS_SI_FTYPE_PTR_SI,
-  MIPS_SI_FTYPE_SI,
-  MIPS_SI_FTYPE_SI_SI,
-  MIPS_SI_FTYPE_V2HI,
-  MIPS_SI_FTYPE_V2HI_V2HI,
-  MIPS_SI_FTYPE_V4QI,
-  MIPS_SI_FTYPE_V4QI_V4QI,
-  MIPS_SI_FTYPE_VOID,
-  MIPS_V2HI_FTYPE_SI,
-  MIPS_V2HI_FTYPE_SI_SI,
-  MIPS_V2HI_FTYPE_V2HI,
-  MIPS_V2HI_FTYPE_V2HI_SI,
-  MIPS_V2HI_FTYPE_V2HI_V2HI,
-  MIPS_V2HI_FTYPE_V4QI,
-  MIPS_V2HI_FTYPE_V4QI_V2HI,
-  MIPS_V4QI_FTYPE_SI,
-  MIPS_V4QI_FTYPE_V2HI_V2HI,
-  MIPS_V4QI_FTYPE_V4QI_SI,
-  MIPS_V4QI_FTYPE_V4QI_V4QI,
-  MIPS_VOID_FTYPE_SI_SI,
-  MIPS_VOID_FTYPE_V2HI_V2HI,
-  MIPS_VOID_FTYPE_V4QI_V4QI,
-
-  /* For MIPS DSP REV 2 ASE.  */
-  MIPS_V4QI_FTYPE_V4QI,
-  MIPS_SI_FTYPE_SI_SI_SI,
-  MIPS_DI_FTYPE_DI_USI_USI,
-  MIPS_DI_FTYPE_SI_SI,
-  MIPS_DI_FTYPE_USI_USI,
-  MIPS_V2HI_FTYPE_SI_SI_SI,
-
-  /* The last type.  */
+/* Macros to create an enumeration identifier for a function prototype.  */
+#define MIPS_FTYPE_NAME1(A, B) MIPS_##A##_FTYPE_##B
+#define MIPS_FTYPE_NAME2(A, B, C) MIPS_##A##_FTYPE_##B##_##C
+#define MIPS_FTYPE_NAME3(A, B, C, D) MIPS_##A##_FTYPE_##B##_##C##_##D
+#define MIPS_FTYPE_NAME4(A, B, C, D, E) MIPS_##A##_FTYPE_##B##_##C##_##D##_##E
+
+/* Classifies the prototype of a built-in function.  */
+enum mips_function_type {
+#define DEF_MIPS_FTYPE(NARGS, LIST) MIPS_FTYPE_NAME##NARGS LIST,
+#include "config/mips/mips-ftypes.def"
+#undef DEF_MIPS_FTYPE
   MIPS_MAX_FTYPE_MAX
 };
 
-/* Specifies how a builtin function should be converted into rtl.  */
-enum mips_builtin_type
-{
-  /* The builtin corresponds directly to an .md pattern.  The return
+/* Specifies how a built-in function should be converted into rtl.  */
+enum mips_builtin_type {
+  /* The function corresponds directly to an .md pattern.  The return
      value is mapped to operand 0 and the arguments are mapped to
      operands 1 and above.  */
   MIPS_BUILTIN_DIRECT,
 
-  /* The builtin corresponds directly to an .md pattern.  There is no return
+  /* The function corresponds directly to an .md pattern.  There is no return
      value and the arguments are mapped to operands 0 and above.  */
   MIPS_BUILTIN_DIRECT_NO_TARGET,
 
-  /* The builtin corresponds to a comparison instruction followed by
+  /* The function corresponds to a comparison instruction followed by
      a mips_cond_move_tf_ps pattern.  The first two arguments are the
      values to compare and the second two arguments are the vector
      operands for the movt.ps or movf.ps instruction (in assembly order).  */
   MIPS_BUILTIN_MOVF,
   MIPS_BUILTIN_MOVT,
 
-  /* The builtin corresponds to a V2SF comparison instruction.  Operand 0
+  /* The function corresponds to a V2SF comparison instruction.  Operand 0
      of this instruction is the result of the comparison, which has mode
      CCV2 or CCV4.  The function arguments are mapped to operands 1 and
      above.  The function's return value is an SImode boolean that is
@@ -247,7 +201,7 @@ enum mips_builtin_type
   MIPS_BUILTIN_BPOSGE32
 };
 
-/* Invokes MACRO (COND) for each c.cond.fmt condition.  */
+/* Invoke MACRO (COND) for each C.cond.fmt condition.  */
 #define MIPS_FP_CONDITIONS(MACRO) \
   MACRO (f),   \
   MACRO (un),  \
@@ -278,196 +232,59 @@ static const char *const mips_fp_conditions[] = {
   MIPS_FP_CONDITIONS (STRINGIFY)
 };
 
-/* A function to save or store a register.  The first argument is the
-   register and the second is the stack slot.  */
-typedef void (*mips_save_restore_fn) (rtx, rtx);
+/* Information about a function's frame layout.  */
+struct mips_frame_info GTY(()) {
+  /* The size of the frame in bytes.  */
+  HOST_WIDE_INT total_size;
 
-struct mips16_constant;
-struct mips_arg_info;
-struct mips_address_info;
-struct mips_integer_op;
-struct mips_sim;
-
-static bool mips_valid_base_register_p (rtx, enum machine_mode, int);
-static bool mips_classify_address (struct mips_address_info *, rtx,
-                                  enum machine_mode, int);
-static bool mips_cannot_force_const_mem (rtx);
-static bool mips_use_blocks_for_constant_p (enum machine_mode, const_rtx);
-static int mips_symbol_insns (enum mips_symbol_type, enum machine_mode);
-static bool mips16_unextended_reference_p (enum machine_mode mode, rtx, rtx);
-static rtx mips_force_temporary (rtx, rtx);
-static rtx mips_unspec_offset_high (rtx, rtx, rtx, enum mips_symbol_type);
-static rtx mips_add_offset (rtx, rtx, HOST_WIDE_INT);
-static unsigned int mips_build_shift (struct mips_integer_op *, HOST_WIDE_INT);
-static unsigned int mips_build_lower (struct mips_integer_op *,
-                                     unsigned HOST_WIDE_INT);
-static unsigned int mips_build_integer (struct mips_integer_op *,
-                                       unsigned HOST_WIDE_INT);
-static void mips_legitimize_const_move (enum machine_mode, rtx, rtx);
-static int m16_check_op (rtx, int, int, int);
-static bool mips_rtx_costs (rtx, int, int, int *);
-static int mips_address_cost (rtx);
-static void mips_emit_compare (enum rtx_code *, rtx *, rtx *, bool);
-static void mips_load_call_address (rtx, rtx, int);
-static bool mips_function_ok_for_sibcall (tree, tree);
-static void mips_block_move_straight (rtx, rtx, HOST_WIDE_INT);
-static void mips_adjust_block_mem (rtx, HOST_WIDE_INT, rtx *, rtx *);
-static void mips_block_move_loop (rtx, rtx, HOST_WIDE_INT);
-static void mips_arg_info (const CUMULATIVE_ARGS *, enum machine_mode,
-                          tree, int, struct mips_arg_info *);
-static bool mips_get_unaligned_mem (rtx *, unsigned int, int, rtx *, rtx *);
-static void mips_set_architecture (const struct mips_cpu_info *);
-static void mips_set_tune (const struct mips_cpu_info *);
-static bool mips_handle_option (size_t, const char *, int);
-static struct machine_function *mips_init_machine_status (void);
-static void print_operand_reloc (FILE *, rtx, enum mips_symbol_context,
-                                const char **);
-static void mips_file_start (void);
-static int mips_small_data_pattern_1 (rtx *, void *);
-static int mips_rewrite_small_data_1 (rtx *, void *);
-static bool mips_function_has_gp_insn (void);
-static unsigned int mips_global_pointer        (void);
-static bool mips_save_reg_p (unsigned int);
-static void mips_save_restore_reg (enum machine_mode, int, HOST_WIDE_INT,
-                                  mips_save_restore_fn);
-static void mips_for_each_saved_reg (HOST_WIDE_INT, mips_save_restore_fn);
-static void mips_output_cplocal (void);
-static void mips_emit_loadgp (void);
-static void mips_output_function_prologue (FILE *, HOST_WIDE_INT);
-static void mips_set_frame_expr (rtx);
-static rtx mips_frame_set (rtx, rtx);
-static void mips_save_reg (rtx, rtx);
-static void mips_output_function_epilogue (FILE *, HOST_WIDE_INT);
-static void mips_restore_reg (rtx, rtx);
-static void mips_output_mi_thunk (FILE *, tree, HOST_WIDE_INT,
-                                 HOST_WIDE_INT, tree);
-static section *mips_select_rtx_section (enum machine_mode, rtx,
-                                        unsigned HOST_WIDE_INT);
-static section *mips_function_rodata_section (tree);
-static bool mips_in_small_data_p (const_tree);
-static bool mips_use_anchors_for_symbol_p (const_rtx);
-static int mips_fpr_return_fields (const_tree, tree *);
-static bool mips_return_in_msb (const_tree);
-static rtx mips_return_fpr_pair (enum machine_mode mode,
-                                enum machine_mode mode1, HOST_WIDE_INT,
-                                enum machine_mode mode2, HOST_WIDE_INT);
-static rtx mips16_gp_pseudo_reg (void);
-static void mips16_fp_args (FILE *, int, int);
-static void build_mips16_function_stub (FILE *);
-static rtx dump_constants_1 (enum machine_mode, rtx, rtx);
-static void dump_constants (struct mips16_constant *, rtx);
-static int mips16_insn_length (rtx);
-static int mips16_rewrite_pool_refs (rtx *, void *);
-static void mips16_lay_out_constants (void);
-static void mips_sim_reset (struct mips_sim *);
-static void mips_sim_init (struct mips_sim *, state_t);
-static void mips_sim_next_cycle (struct mips_sim *);
-static void mips_sim_wait_reg (struct mips_sim *, rtx, rtx);
-static int mips_sim_wait_regs_2 (rtx *, void *);
-static void mips_sim_wait_regs_1 (rtx *, void *);
-static void mips_sim_wait_regs (struct mips_sim *, rtx);
-static void mips_sim_wait_units (struct mips_sim *, rtx);
-static void mips_sim_wait_insn (struct mips_sim *, rtx);
-static void mips_sim_record_set (rtx, const_rtx, void *);
-static void mips_sim_issue_insn (struct mips_sim *, rtx);
-static void mips_sim_issue_nop (struct mips_sim *);
-static void mips_sim_finish_insn (struct mips_sim *, rtx);
-static void vr4130_avoid_branch_rt_conflict (rtx);
-static void vr4130_align_insns (void);
-static void mips_avoid_hazard (rtx, rtx, int *, rtx *, rtx);
-static void mips_avoid_hazards (void);
-static void mips_reorg (void);
-static bool mips_strict_matching_cpu_name_p (const char *, const char *);
-static bool mips_matching_cpu_name_p (const char *, const char *);
-static const struct mips_cpu_info *mips_parse_cpu (const char *);
-static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
-static bool mips_return_in_memory (const_tree, const_tree);
-static bool mips_strict_argument_naming (CUMULATIVE_ARGS *);
-static void mips_macc_chains_record (rtx);
-static void mips_macc_chains_reorder (rtx *, int);
-static void vr4130_true_reg_dependence_p_1 (rtx, const_rtx, void *);
-static bool vr4130_true_reg_dependence_p (rtx);
-static bool vr4130_swap_insns_p (rtx, rtx);
-static void vr4130_reorder (rtx *, int);
-static void mips_promote_ready (rtx *, int, int);
-static void mips_sched_init (FILE *, int, int);
-static int mips_sched_reorder (FILE *, int, rtx *, int *, int);
-static int mips_variable_issue (FILE *, int, rtx, int);
-static int mips_adjust_cost (rtx, rtx, rtx, int);
-static int mips_issue_rate (void);
-static int mips_multipass_dfa_lookahead (void);
-static void mips_init_libfuncs (void);
-static void mips_setup_incoming_varargs (CUMULATIVE_ARGS *, enum machine_mode,
-                                        tree, int *, int);
-static tree mips_build_builtin_va_list (void);
-static tree mips_gimplify_va_arg_expr (tree, tree, tree *, tree *);
-static bool mips_pass_by_reference (CUMULATIVE_ARGS *, enum machine_mode mode,
-                                   const_tree, bool);
-static bool mips_callee_copies (CUMULATIVE_ARGS *, enum machine_mode mode,
-                               const_tree, bool);
-static int mips_arg_partial_bytes (CUMULATIVE_ARGS *, enum machine_mode mode,
-                                  tree, bool);
-static bool mips_valid_pointer_mode (enum machine_mode);
-static bool mips_scalar_mode_supported_p (enum machine_mode);
-static bool mips_vector_mode_supported_p (enum machine_mode);
-static rtx mips_prepare_builtin_arg (enum insn_code, unsigned int, tree, unsigned int);
-static rtx mips_prepare_builtin_target (enum insn_code, unsigned int, rtx);
-static rtx mips_expand_builtin (tree, rtx, rtx, enum machine_mode, int);
-static void mips_init_builtins (void);
-static rtx mips_expand_builtin_direct (enum insn_code, rtx, tree, bool);
-static rtx mips_expand_builtin_movtf (enum mips_builtin_type,
-                                     enum insn_code, enum mips_fp_condition,
-                                     rtx, tree);
-static rtx mips_expand_builtin_compare (enum mips_builtin_type,
-                                       enum insn_code, enum mips_fp_condition,
-                                       rtx, tree);
-static rtx mips_expand_builtin_bposge (enum mips_builtin_type, rtx);
-static void mips_encode_section_info (tree, rtx, int);
-static void mips_extra_live_on_entry (bitmap);
-static int mips_comp_type_attributes (const_tree, const_tree);
-static void mips_set_mips16_mode (int);
-static void mips_insert_attributes (tree, tree *);
-static tree mips_merge_decl_attributes (tree, tree);
-static void mips_set_current_function (tree);
-static int mips_mode_rep_extended (enum machine_mode, enum machine_mode);
-static bool mips_offset_within_alignment_p (rtx, HOST_WIDE_INT);
-static void mips_output_dwarf_dtprel (FILE *, int, rtx) ATTRIBUTE_UNUSED;
-
-/* Structure to be filled in by compute_frame_size with register
-   save masks, and offsets for the current function.  */
-
-struct mips_frame_info GTY(())
-{
-  HOST_WIDE_INT total_size;    /* # bytes that the entire frame takes up */
-  HOST_WIDE_INT var_size;      /* # bytes that variables take up */
-  HOST_WIDE_INT args_size;     /* # bytes that outgoing arguments take up */
-  HOST_WIDE_INT cprestore_size;        /* # bytes that the .cprestore slot takes up */
-  HOST_WIDE_INT gp_reg_size;   /* # bytes needed to store gp regs */
-  HOST_WIDE_INT fp_reg_size;   /* # bytes needed to store fp regs */
-  unsigned int mask;           /* mask of saved gp registers */
-  unsigned int fmask;          /* mask of saved fp registers */
-  HOST_WIDE_INT gp_save_offset;        /* offset from vfp to store gp registers */
-  HOST_WIDE_INT fp_save_offset;        /* offset from vfp to store fp registers */
-  HOST_WIDE_INT gp_sp_offset;  /* offset from new sp to store gp registers */
-  HOST_WIDE_INT fp_sp_offset;  /* offset from new sp to store fp registers */
-  bool initialized;            /* true if frame size already calculated */
-  int num_gp;                  /* number of gp registers saved */
-  int num_fp;                  /* number of fp registers saved */
+  /* The number of bytes allocated to variables.  */
+  HOST_WIDE_INT var_size;
+
+  /* The number of bytes allocated to outgoing function arguments.  */
+  HOST_WIDE_INT args_size;
+
+  /* The number of bytes allocated to the .cprestore slot, or 0 if there
+     is no such slot.  */
+  HOST_WIDE_INT cprestore_size;
+
+  /* Bit X is set if the function saves or restores GPR X.  */
+  unsigned int mask;
+
+  /* Likewise FPR X.  */
+  unsigned int fmask;
+
+  /* The number of GPRs and FPRs saved.  */
+  unsigned int num_gp;
+  unsigned int num_fp;
+
+  /* The offset of the topmost GPR and FPR save slots from the top of
+     the frame, or zero if no such slots are needed.  */
+  HOST_WIDE_INT gp_save_offset;
+  HOST_WIDE_INT fp_save_offset;
+
+  /* Likewise, but giving offsets from the bottom of the frame.  */
+  HOST_WIDE_INT gp_sp_offset;
+  HOST_WIDE_INT fp_sp_offset;
+
+  /* The offset of arg_pointer_rtx from frame_pointer_rtx.  */
+  HOST_WIDE_INT arg_pointer_offset;
+
+  /* The offset of hard_frame_pointer_rtx from frame_pointer_rtx.  */
+  HOST_WIDE_INT hard_frame_pointer_offset;
 };
 
 struct machine_function GTY(()) {
-  /* Pseudo-reg holding the value of $28 in a mips16 function which
-     refers to GP relative global variables.  */
+  /* The register returned by mips16_gp_pseudo_reg; see there for details.  */
   rtx mips16_gp_pseudo_rtx;
 
   /* The number of extra stack bytes taken up by register varargs.
      This area is allocated by the callee at the very top of the frame.  */
   int varargs_size;
 
-  /* Current frame information, calculated by compute_frame_size.  */
+  /* The current frame information, calculated by mips_compute_frame_info.  */
   struct mips_frame_info frame;
 
-  /* The register to use as the global pointer within this function.  */
+  /* The register to use as the function's global pointer.  */
   unsigned int global_pointer;
 
   /* True if mips_adjust_insn_length should ignore an instruction's
@@ -487,8 +304,7 @@ struct machine_function GTY(()) {
 };
 
 /* Information about a single argument.  */
-struct mips_arg_info
-{
+struct mips_arg_info {
   /* True if the argument is passed in a floating-point register, or
      would have been if we hadn't run out of registers.  */
   bool fpr_p;
@@ -513,7 +329,6 @@ struct mips_arg_info
   unsigned int stack_offset;
 };
 
-
 /* Information about an address described by mips_address_type.
 
    ADDRESS_CONST_INT
@@ -523,22 +338,18 @@ struct mips_arg_info
        REG is the base register and OFFSET is the constant offset.
 
    ADDRESS_LO_SUM
-       REG is the register that contains the high part of the address,
-       OFFSET is the symbolic address being referenced and SYMBOL_TYPE
-       is the type of OFFSET's symbol.
+       REG and OFFSET are the operands to the LO_SUM and SYMBOL_TYPE
+       is the type of symbol it references.
 
    ADDRESS_SYMBOLIC
-       SYMBOL_TYPE is the type of symbol being referenced.  */
-
-struct mips_address_info
-{
+       SYMBOL_TYPE is the type of symbol that the address references.  */
+struct mips_address_info {
   enum mips_address_type type;
   rtx reg;
   rtx offset;
   enum mips_symbol_type symbol_type;
 };
 
-
 /* One stage in a constant building sequence.  These sequences have
    the form:
 
@@ -548,13 +359,12 @@ struct mips_address_info
        ...
 
    where A is an accumulator, each CODE[i] is a binary rtl operation
-   and each VALUE[i] is a constant integer.  */
+   and each VALUE[i] is a constant integer.  CODE[0] is undefined.  */
 struct mips_integer_op {
   enum rtx_code code;
   unsigned HOST_WIDE_INT value;
 };
 
-
 /* The largest number of operations needed to load an integer constant.
    The worst accepted case for 64-bit constants is LUI,ORI,SLL,ORI,SLL,ORI.
    When the lowest bit is clear, we can try, but reject a sequence with
@@ -576,98 +386,86 @@ struct mips16e_save_restore_info {
 
 /* Global variables for machine-dependent things.  */
 
-/* Threshold for data being put into the small data/bss area, instead
-   of the normal data area.  */
-int mips_section_threshold = -1;
+/* The -G setting, or the configuration's default small-data limit if
+   no -G option is given.  */
+static unsigned int mips_small_data_threshold;
 
-/* Count the number of .file directives, so that .loc is up to date.  */
-int num_source_filenames = 0;
+/* The number of file directives written by mips_output_filename.  */
+int num_source_filenames;
 
-/* Count the number of sdb related labels are generated (to find block
-   start and end boundaries).  */
-int sdb_label_count = 0;
+/* The name that appeared in the last .file directive written by
+   mips_output_filename, or "" if mips_output_filename hasn't
+   written anything yet.  */
+const char *current_function_file = "";
 
-/* Next label # for each statement for Silicon Graphics IRIS systems.  */
-int sym_lineno = 0;
+/* A label counter used by PUT_SDB_BLOCK_START and PUT_SDB_BLOCK_END.  */
+int sdb_label_count;
 
-/* Name of the file containing the current function.  */
-const char *current_function_file = "";
+/* Arrays that map GCC register numbers to debugger register numbers.  */
+int mips_dbx_regno[FIRST_PSEUDO_REGISTER];
+int mips_dwarf_regno[FIRST_PSEUDO_REGISTER];
 
-/* Number of nested .set noreorder, noat, nomacro, and volatile requests.  */
+/* The nesting depth of the PRINT_OPERAND '%(', '%<' and '%[' constructs.  */
 int set_noreorder;
-int set_noat;
 int set_nomacro;
-int set_volatile;
+static int set_noat;
 
-/* The next branch instruction is a branch likely, not branch normal.  */
-int mips_branch_likely;
+/* True if we're writing out a branch-likely instruction rather than a
+   normal branch.  */
+static bool mips_branch_likely;
 
 /* The operands passed to the last cmpMM expander.  */
 rtx cmp_operands[2];
 
-/* The target cpu for code generation.  */
+/* The current instruction-set architecture.  */
 enum processor_type mips_arch;
 const struct mips_cpu_info *mips_arch_info;
 
-/* The target cpu for optimization and scheduling.  */
+/* The processor that we should tune the code for.  */
 enum processor_type mips_tune;
 const struct mips_cpu_info *mips_tune_info;
 
-/* Which instruction set architecture to use.  */
+/* The ISA level associated with mips_arch.  */
 int mips_isa;
 
+/* The architecture selected by -mipsN, or null if -mipsN wasn't used.  */
+static const struct mips_cpu_info *mips_isa_option_info;
+
 /* Which ABI to use.  */
 int mips_abi = MIPS_ABI_DEFAULT;
 
-/* Cost information to use.  */
+/* Which cost information to use.  */
 const struct mips_rtx_cost_data *mips_cost;
 
-/* Remember the ambient target flags, excluding mips16.  */
+/* The ambient target flags, excluding MASK_MIPS16.  */
 static int mips_base_target_flags;
-/* The mips16 command-line target flags only.  */
+
+/* True if MIPS16 is the default mode.  */
 static bool mips_base_mips16;
-/* Similar copies of option settings.  */
+
+/* The ambient values of other global variables.  */
+static int mips_base_delayed_branch; /* flag_delayed_branch */
 static int mips_base_schedule_insns; /* flag_schedule_insns */
 static int mips_base_reorder_blocks_and_partition; /* flag_reorder... */
 static int mips_base_move_loop_invariants; /* flag_move_loop_invariants */
 static int mips_base_align_loops; /* align_loops */
 static int mips_base_align_jumps; /* align_jumps */
 static int mips_base_align_functions; /* align_functions */
-static GTY(()) int mips16_flipper;
 
-/* The -mtext-loads setting.  */
+/* The -mcode-readable setting.  */
 enum mips_code_readable_setting mips_code_readable = CODE_READABLE_YES;
 
-/* The -mllsc setting.  */
-enum mips_llsc_setting mips_llsc = LLSC_DEFAULT;
-
-/* The architecture selected by -mipsN.  */
-static const struct mips_cpu_info *mips_isa_info;
-
-/* If TRUE, we split addresses into their high and low parts in the RTL.  */
-int mips_split_addresses;
-
-/* Mode used for saving/restoring general purpose registers.  */
-static enum machine_mode gpr_mode;
+/* Index [M][R] is true if register R is allowed to hold a value of mode M.  */
+bool mips_hard_regno_mode_ok[(int) MAX_MACHINE_MODE][FIRST_PSEUDO_REGISTER];
 
-/* Array giving truth value on whether or not a given hard register
-   can support a given mode.  */
-char mips_hard_regno_mode_ok[(int)MAX_MACHINE_MODE][FIRST_PSEUDO_REGISTER];
-
-/* List of all MIPS punctuation characters used by print_operand.  */
-char mips_print_operand_punct[256];
-
-/* Map GCC register number to debugger register number.  */
-int mips_dbx_regno[FIRST_PSEUDO_REGISTER];
-int mips_dwarf_regno[FIRST_PSEUDO_REGISTER];
-
-/* A copy of the original flag_delayed_branch: see override_options.  */
-static int mips_flag_delayed_branch;
+/* Index C is true if character C is a valid PRINT_OPERAND punctation
+   character.  */
+bool mips_print_operand_punct[256];
 
 static GTY (()) int mips_output_filename_first_time = 1;
 
 /* mips_split_p[X] is true if symbols of type X can be split by
-   mips_split_symbol().  */
+   mips_split_symbol.  */
 bool mips_split_p[NUM_SYMBOL_TYPES];
 
 /* mips_lo_relocs[X] is the relocation to use when a symbol of type X
@@ -678,9 +476,8 @@ static const char *mips_lo_relocs[NUM_SYMBOL_TYPES];
 /* Likewise for HIGHs.  */
 static const char *mips_hi_relocs[NUM_SYMBOL_TYPES];
 
-/* Map hard register number to register class */
-const enum reg_class mips_regno_to_class[] =
-{
+/* Index R is the smallest register class that contains register R.  */
+const enum reg_class mips_regno_to_class[FIRST_PSEUDO_REGISTER] = {
   LEA_REGS,    LEA_REGS,       M16_NA_REGS,    V1_REG,
   M16_REGS,    M16_REGS,       M16_REGS,       M16_REGS,
   LEA_REGS,    LEA_REGS,       LEA_REGS,       LEA_REGS,
@@ -730,123 +527,124 @@ const enum reg_class mips_regno_to_class[] =
   ALL_REGS,    ALL_REGS,       ALL_REGS,       ALL_REGS
 };
 
-/* Table of machine dependent attributes.  */
-const struct attribute_spec mips_attribute_table[] =
-{
+/* The value of TARGET_ATTRIBUTE_TABLE.  */
+const struct attribute_spec mips_attribute_table[] = {
+  /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
   { "long_call",   0, 0, false, true,  true,  NULL },
   { "far",                0, 0, false, true,  true,  NULL },
   { "near",        0, 0, false, true,  true,  NULL },
-  /* Switch MIPS16 ASE on and off per-function.  We would really like
-     to make these type attributes, but GCC doesn't provide the hooks
-     we need to support the right conversion rules.  As declaration
-     attributes, they affect code generation but don't carry other
-     semantics.  */
+  /* We would really like to treat "mips16" and "nomips16" as type
+     attributes, but GCC doesn't provide the hooks we need to support
+     the right conversion rules.  As declaration attributes, they affect
+     code generation but don't carry other semantics.  */
   { "mips16",     0, 0, true,  false, false, NULL },
   { "nomips16",    0, 0, true,  false, false, NULL },
   { NULL,         0, 0, false, false, false, NULL }
 };
 \f
-/* A table describing all the processors gcc knows about.  Names are
+/* A table describing all the processors GCC knows about.  Names are
    matched in the order listed.  The first mention of an ISA level is
    taken as the canonical name for that ISA.
 
    To ease comparison, please keep this table in the same order
-   as gas's mips_cpu_info_table[].  Please also make sure that
+   as GAS's mips_cpu_info_table.  Please also make sure that
    MIPS_ISA_LEVEL_SPEC and MIPS_ARCH_FLOAT_SPEC handle all -march
    options correctly.  */
-const struct mips_cpu_info mips_cpu_info_table[] = {
-  /* Entries for generic ISAs */
-  { "mips1", PROCESSOR_R3000, 1 },
-  { "mips2", PROCESSOR_R6000, 2 },
-  { "mips3", PROCESSOR_R4000, 3 },
-  { "mips4", PROCESSOR_R8000, 4 },
-  { "mips32", PROCESSOR_4KC, 32 },
-  { "mips32r2", PROCESSOR_M4K, 33 },
-  { "mips64", PROCESSOR_5KC, 64 },
-
-  /* MIPS I */
-  { "r3000", PROCESSOR_R3000, 1 },
-  { "r2000", PROCESSOR_R3000, 1 }, /* = r3000 */
-  { "r3900", PROCESSOR_R3900, 1 },
-
-  /* MIPS II */
-  { "r6000", PROCESSOR_R6000, 2 },
-
-  /* MIPS III */
-  { "r4000", PROCESSOR_R4000, 3 },
-  { "vr4100", PROCESSOR_R4100, 3 },
-  { "vr4111", PROCESSOR_R4111, 3 },
-  { "vr4120", PROCESSOR_R4120, 3 },
-  { "vr4130", PROCESSOR_R4130, 3 },
-  { "vr4300", PROCESSOR_R4300, 3 },
-  { "r4400", PROCESSOR_R4000, 3 }, /* = r4000 */
-  { "r4600", PROCESSOR_R4600, 3 },
-  { "orion", PROCESSOR_R4600, 3 }, /* = r4600 */
-  { "r4650", PROCESSOR_R4650, 3 },
-
-  /* MIPS IV */
-  { "r8000", PROCESSOR_R8000, 4 },
-  { "vr5000", PROCESSOR_R5000, 4 },
-  { "vr5400", PROCESSOR_R5400, 4 },
-  { "vr5500", PROCESSOR_R5500, 4 },
-  { "rm7000", PROCESSOR_R7000, 4 },
-  { "rm9000", PROCESSOR_R9000, 4 },
-
-  /* MIPS32 */
-  { "4kc", PROCESSOR_4KC, 32 },
-  { "4km", PROCESSOR_4KC, 32 }, /* = 4kc */
-  { "4kp", PROCESSOR_4KP, 32 },
-  { "4ksc", PROCESSOR_4KC, 32 },
-
-  /* MIPS32 Release 2 */
-  { "m4k", PROCESSOR_M4K, 33 },
-  { "4kec", PROCESSOR_4KC, 33 },
-  { "4kem", PROCESSOR_4KC, 33 },
-  { "4kep", PROCESSOR_4KP, 33 },
-  { "4ksd", PROCESSOR_4KC, 33 },
-
-  { "24kc", PROCESSOR_24KC, 33 },
-  { "24kf2_1", PROCESSOR_24KF2_1, 33 },
-  { "24kf", PROCESSOR_24KF2_1, 33 },
-  { "24kf1_1", PROCESSOR_24KF1_1, 33 },
-  { "24kfx", PROCESSOR_24KF1_1, 33 },
-  { "24kx", PROCESSOR_24KF1_1, 33 },
-
-  { "24kec", PROCESSOR_24KC, 33 }, /* 24K with DSP */
-  { "24kef2_1", PROCESSOR_24KF2_1, 33 },
-  { "24kef", PROCESSOR_24KF2_1, 33 },
-  { "24kef1_1", PROCESSOR_24KF1_1, 33 },
-  { "24kefx", PROCESSOR_24KF1_1, 33 },
-  { "24kex", PROCESSOR_24KF1_1, 33 },
-
-  { "34kc", PROCESSOR_24KC, 33 }, /* 34K with MT/DSP */
-  { "34kf2_1", PROCESSOR_24KF2_1, 33 },
-  { "34kf", PROCESSOR_24KF2_1, 33 },
-  { "34kf1_1", PROCESSOR_24KF1_1, 33 },
-  { "34kfx", PROCESSOR_24KF1_1, 33 },
-  { "34kx", PROCESSOR_24KF1_1, 33 },
-
-  { "74kc", PROCESSOR_74KC, 33 }, /* 74K with DSPr2 */
-  { "74kf2_1", PROCESSOR_74KF2_1, 33 },
-  { "74kf", PROCESSOR_74KF2_1, 33 },
-  { "74kf1_1", PROCESSOR_74KF1_1, 33 },
-  { "74kfx", PROCESSOR_74KF1_1, 33 },
-  { "74kx", PROCESSOR_74KF1_1, 33 },
-  { "74kf3_2", PROCESSOR_74KF3_2, 33 },
-
-  /* MIPS64 */
-  { "5kc", PROCESSOR_5KC, 64 },
-  { "5kf", PROCESSOR_5KF, 64 },
-  { "20kc", PROCESSOR_20KC, 64 },
-  { "sb1", PROCESSOR_SB1, 64 },
-  { "sb1a", PROCESSOR_SB1A, 64 },
-  { "sr71000", PROCESSOR_SR71000, 64 },
-
-  /* End marker */
-  { 0, 0, 0 }
+static const struct mips_cpu_info mips_cpu_info_table[] = {
+  /* Entries for generic ISAs.  */
+  { "mips1", PROCESSOR_R3000, 1, 0 },
+  { "mips2", PROCESSOR_R6000, 2, 0 },
+  { "mips3", PROCESSOR_R4000, 3, 0 },
+  { "mips4", PROCESSOR_R8000, 4, 0 },
+  /* Prefer not to use branch-likely instructions for generic MIPS32rX
+     and MIPS64rX code.  The instructions were officially deprecated
+     in revisions 2 and earlier, but revision 3 is likely to downgrade
+     that to a recommendation to avoid the instructions in code that
+     isn't tuned to a specific processor.  */
+  { "mips32", PROCESSOR_4KC, 32, PTF_AVOID_BRANCHLIKELY },
+  { "mips32r2", PROCESSOR_M4K, 33, PTF_AVOID_BRANCHLIKELY },
+  { "mips64", PROCESSOR_5KC, 64, PTF_AVOID_BRANCHLIKELY },
+
+  /* MIPS I processors.  */
+  { "r3000", PROCESSOR_R3000, 1, 0 },
+  { "r2000", PROCESSOR_R3000, 1, 0 },
+  { "r3900", PROCESSOR_R3900, 1, 0 },
+
+  /* MIPS II processors.  */
+  { "r6000", PROCESSOR_R6000, 2, 0 },
+
+  /* MIPS III processors.  */
+  { "r4000", PROCESSOR_R4000, 3, 0 },
+  { "vr4100", PROCESSOR_R4100, 3, 0 },
+  { "vr4111", PROCESSOR_R4111, 3, 0 },
+  { "vr4120", PROCESSOR_R4120, 3, 0 },
+  { "vr4130", PROCESSOR_R4130, 3, 0 },
+  { "vr4300", PROCESSOR_R4300, 3, 0 },
+  { "r4400", PROCESSOR_R4000, 3, 0 },
+  { "r4600", PROCESSOR_R4600, 3, 0 },
+  { "orion", PROCESSOR_R4600, 3, 0 },
+  { "r4650", PROCESSOR_R4650, 3, 0 },
+
+  /* MIPS IV processors. */
+  { "r8000", PROCESSOR_R8000, 4, 0 },
+  { "vr5000", PROCESSOR_R5000, 4, 0 },
+  { "vr5400", PROCESSOR_R5400, 4, 0 },
+  { "vr5500", PROCESSOR_R5500, 4, PTF_AVOID_BRANCHLIKELY },
+  { "rm7000", PROCESSOR_R7000, 4, 0 },
+  { "rm9000", PROCESSOR_R9000, 4, 0 },
+
+  /* MIPS32 processors.  */
+  { "4kc", PROCESSOR_4KC, 32, 0 },
+  { "4km", PROCESSOR_4KC, 32, 0 },
+  { "4kp", PROCESSOR_4KP, 32, 0 },
+  { "4ksc", PROCESSOR_4KC, 32, 0 },
+
+  /* MIPS32 Release 2 processors.  */
+  { "m4k", PROCESSOR_M4K, 33, 0 },
+  { "4kec", PROCESSOR_4KC, 33, 0 },
+  { "4kem", PROCESSOR_4KC, 33, 0 },
+  { "4kep", PROCESSOR_4KP, 33, 0 },
+  { "4ksd", PROCESSOR_4KC, 33, 0 },
+
+  { "24kc", PROCESSOR_24KC, 33, 0 },
+  { "24kf2_1", PROCESSOR_24KF2_1, 33, 0 },
+  { "24kf", PROCESSOR_24KF2_1, 33, 0 },
+  { "24kf1_1", PROCESSOR_24KF1_1, 33, 0 },
+  { "24kfx", PROCESSOR_24KF1_1, 33, 0 },
+  { "24kx", PROCESSOR_24KF1_1, 33, 0 },
+
+  { "24kec", PROCESSOR_24KC, 33, 0 }, /* 24K with DSP.  */
+  { "24kef2_1", PROCESSOR_24KF2_1, 33, 0 },
+  { "24kef", PROCESSOR_24KF2_1, 33, 0 },
+  { "24kef1_1", PROCESSOR_24KF1_1, 33, 0 },
+  { "24kefx", PROCESSOR_24KF1_1, 33, 0 },
+  { "24kex", PROCESSOR_24KF1_1, 33, 0 },
+
+  { "34kc", PROCESSOR_24KC, 33, 0 }, /* 34K with MT/DSP.  */
+  { "34kf2_1", PROCESSOR_24KF2_1, 33, 0 },
+  { "34kf", PROCESSOR_24KF2_1, 33, 0 },
+  { "34kf1_1", PROCESSOR_24KF1_1, 33, 0 },
+  { "34kfx", PROCESSOR_24KF1_1, 33, 0 },
+  { "34kx", PROCESSOR_24KF1_1, 33, 0 },
+
+  { "74kc", PROCESSOR_74KC, 33, 0 }, /* 74K with DSPr2.  */
+  { "74kf2_1", PROCESSOR_74KF2_1, 33, 0 },
+  { "74kf", PROCESSOR_74KF2_1, 33, 0 },
+  { "74kf1_1", PROCESSOR_74KF1_1, 33, 0 },
+  { "74kfx", PROCESSOR_74KF1_1, 33, 0 },
+  { "74kx", PROCESSOR_74KF1_1, 33, 0 },
+  { "74kf3_2", PROCESSOR_74KF3_2, 33, 0 },
+
+  /* MIPS64 processors.  */
+  { "5kc", PROCESSOR_5KC, 64, 0 },
+  { "5kf", PROCESSOR_5KF, 64, 0 },
+  { "20kc", PROCESSOR_20KC, 64, PTF_AVOID_BRANCHLIKELY },
+  { "sb1", PROCESSOR_SB1, 64, PTF_AVOID_BRANCHLIKELY },
+  { "sb1a", PROCESSOR_SB1A, 64, PTF_AVOID_BRANCHLIKELY },
+  { "sr71000", PROCESSOR_SR71000, 64, PTF_AVOID_BRANCHLIKELY },
 };
 
-/* Default costs. If these are used for a processor we should look
+/* Default costs.  If these are used for a processor we should look
    up the actual costs.  */
 #define DEFAULT_COSTS COSTS_N_INSNS (6),  /* fp_add */       \
                       COSTS_N_INSNS (7),  /* fp_mult_sf */   \
@@ -860,536 +658,418 @@ const struct mips_cpu_info mips_cpu_info_table[] = {
                                        2, /* branch_cost */  \
                                        4  /* memory_latency */
 
-/* Need to replace these with the costs of calling the appropriate
-   libgcc routine.  */
+/* Floating-point costs for processors without an FPU.  Just assume that
+   all floating-point libcalls are very expensive.  */
 #define SOFT_FP_COSTS COSTS_N_INSNS (256), /* fp_add */       \
                       COSTS_N_INSNS (256), /* fp_mult_sf */   \
                       COSTS_N_INSNS (256), /* fp_mult_df */   \
                       COSTS_N_INSNS (256), /* fp_div_sf */    \
                       COSTS_N_INSNS (256)  /* fp_div_df */
 
-static struct mips_rtx_cost_data const mips_rtx_cost_optimize_size =
-  {
-      COSTS_N_INSNS (1),            /* fp_add */
-      COSTS_N_INSNS (1),            /* fp_mult_sf */
-      COSTS_N_INSNS (1),            /* fp_mult_df */
-      COSTS_N_INSNS (1),            /* fp_div_sf */
-      COSTS_N_INSNS (1),            /* fp_div_df */
-      COSTS_N_INSNS (1),            /* int_mult_si */
-      COSTS_N_INSNS (1),            /* int_mult_di */
-      COSTS_N_INSNS (1),            /* int_div_si */
-      COSTS_N_INSNS (1),            /* int_div_di */
-                       2,           /* branch_cost */
-                       4            /* memory_latency */
-  };
-
-static struct mips_rtx_cost_data const mips_rtx_cost_data[PROCESSOR_MAX] =
-  {
-    { /* R3000 */
-      COSTS_N_INSNS (2),            /* fp_add */
-      COSTS_N_INSNS (4),            /* fp_mult_sf */
-      COSTS_N_INSNS (5),            /* fp_mult_df */
-      COSTS_N_INSNS (12),           /* fp_div_sf */
-      COSTS_N_INSNS (19),           /* fp_div_df */
-      COSTS_N_INSNS (12),           /* int_mult_si */
-      COSTS_N_INSNS (12),           /* int_mult_di */
-      COSTS_N_INSNS (35),           /* int_div_si */
-      COSTS_N_INSNS (35),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-
-    },
-    { /* 4KC */
-      SOFT_FP_COSTS,
-      COSTS_N_INSNS (6),            /* int_mult_si */
-      COSTS_N_INSNS (6),            /* int_mult_di */
-      COSTS_N_INSNS (36),           /* int_div_si */
-      COSTS_N_INSNS (36),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 4KP */
-      SOFT_FP_COSTS,
-      COSTS_N_INSNS (36),           /* int_mult_si */
-      COSTS_N_INSNS (36),           /* int_mult_di */
-      COSTS_N_INSNS (37),           /* int_div_si */
-      COSTS_N_INSNS (37),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 5KC */
-      SOFT_FP_COSTS,
-      COSTS_N_INSNS (4),            /* int_mult_si */
-      COSTS_N_INSNS (11),           /* int_mult_di */
-      COSTS_N_INSNS (36),           /* int_div_si */
-      COSTS_N_INSNS (68),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 5KF */
-      COSTS_N_INSNS (4),            /* fp_add */
-      COSTS_N_INSNS (4),            /* fp_mult_sf */
-      COSTS_N_INSNS (5),            /* fp_mult_df */
-      COSTS_N_INSNS (17),           /* fp_div_sf */
-      COSTS_N_INSNS (32),           /* fp_div_df */
-      COSTS_N_INSNS (4),            /* int_mult_si */
-      COSTS_N_INSNS (11),           /* int_mult_di */
-      COSTS_N_INSNS (36),           /* int_div_si */
-      COSTS_N_INSNS (68),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 20KC */
-      COSTS_N_INSNS (4),            /* fp_add */
-      COSTS_N_INSNS (4),            /* fp_mult_sf */
-      COSTS_N_INSNS (5),            /* fp_mult_df */
-      COSTS_N_INSNS (17),           /* fp_div_sf */
-      COSTS_N_INSNS (32),           /* fp_div_df */
-      COSTS_N_INSNS (4),            /* int_mult_si */
-      COSTS_N_INSNS (7),            /* int_mult_di */
-      COSTS_N_INSNS (42),           /* int_div_si */
-      COSTS_N_INSNS (72),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 24KC */
-      SOFT_FP_COSTS,
-      COSTS_N_INSNS (5),            /* int_mult_si */
-      COSTS_N_INSNS (5),            /* int_mult_di */
-      COSTS_N_INSNS (41),           /* int_div_si */
-      COSTS_N_INSNS (41),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 24KF2_1 */
-      COSTS_N_INSNS (8),            /* fp_add */
-      COSTS_N_INSNS (8),            /* fp_mult_sf */
-      COSTS_N_INSNS (10),           /* fp_mult_df */
-      COSTS_N_INSNS (34),           /* fp_div_sf */
-      COSTS_N_INSNS (64),           /* fp_div_df */
-      COSTS_N_INSNS (5),            /* int_mult_si */
-      COSTS_N_INSNS (5),            /* int_mult_di */
-      COSTS_N_INSNS (41),           /* int_div_si */
-      COSTS_N_INSNS (41),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 24KF1_1 */
-      COSTS_N_INSNS (4),            /* fp_add */
-      COSTS_N_INSNS (4),            /* fp_mult_sf */
-      COSTS_N_INSNS (5),            /* fp_mult_df */
-      COSTS_N_INSNS (17),           /* fp_div_sf */
-      COSTS_N_INSNS (32),           /* fp_div_df */
-      COSTS_N_INSNS (5),            /* int_mult_si */
-      COSTS_N_INSNS (5),            /* int_mult_di */
-      COSTS_N_INSNS (41),           /* int_div_si */
-      COSTS_N_INSNS (41),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 74KC */
-      SOFT_FP_COSTS,
-      COSTS_N_INSNS (5),            /* int_mult_si */
-      COSTS_N_INSNS (5),            /* int_mult_di */
-      COSTS_N_INSNS (41),           /* int_div_si */
-      COSTS_N_INSNS (41),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 74KF2_1 */
-      COSTS_N_INSNS (8),            /* fp_add */
-      COSTS_N_INSNS (8),            /* fp_mult_sf */
-      COSTS_N_INSNS (10),           /* fp_mult_df */
-      COSTS_N_INSNS (34),           /* fp_div_sf */
-      COSTS_N_INSNS (64),           /* fp_div_df */
-      COSTS_N_INSNS (5),            /* int_mult_si */
-      COSTS_N_INSNS (5),            /* int_mult_di */
-      COSTS_N_INSNS (41),           /* int_div_si */
-      COSTS_N_INSNS (41),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 74KF1_1 */
-      COSTS_N_INSNS (4),            /* fp_add */
-      COSTS_N_INSNS (4),            /* fp_mult_sf */
-      COSTS_N_INSNS (5),            /* fp_mult_df */
-      COSTS_N_INSNS (17),           /* fp_div_sf */
-      COSTS_N_INSNS (32),           /* fp_div_df */
-      COSTS_N_INSNS (5),            /* int_mult_si */
-      COSTS_N_INSNS (5),            /* int_mult_di */
-      COSTS_N_INSNS (41),           /* int_div_si */
-      COSTS_N_INSNS (41),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* 74KF3_2 */
-      COSTS_N_INSNS (6),            /* fp_add */
-      COSTS_N_INSNS (6),            /* fp_mult_sf */
-      COSTS_N_INSNS (7),            /* fp_mult_df */
-      COSTS_N_INSNS (25),           /* fp_div_sf */
-      COSTS_N_INSNS (48),           /* fp_div_df */
-      COSTS_N_INSNS (5),            /* int_mult_si */
-      COSTS_N_INSNS (5),            /* int_mult_di */
-      COSTS_N_INSNS (41),           /* int_div_si */
-      COSTS_N_INSNS (41),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* M4k */
-      DEFAULT_COSTS
-    },
-    { /* R3900 */
-      COSTS_N_INSNS (2),            /* fp_add */
-      COSTS_N_INSNS (4),            /* fp_mult_sf */
-      COSTS_N_INSNS (5),            /* fp_mult_df */
-      COSTS_N_INSNS (12),           /* fp_div_sf */
-      COSTS_N_INSNS (19),           /* fp_div_df */
-      COSTS_N_INSNS (2),            /* int_mult_si */
-      COSTS_N_INSNS (2),            /* int_mult_di */
-      COSTS_N_INSNS (35),           /* int_div_si */
-      COSTS_N_INSNS (35),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* R6000 */
-      COSTS_N_INSNS (3),            /* fp_add */
-      COSTS_N_INSNS (5),            /* fp_mult_sf */
-      COSTS_N_INSNS (6),            /* fp_mult_df */
-      COSTS_N_INSNS (15),           /* fp_div_sf */
-      COSTS_N_INSNS (16),           /* fp_div_df */
-      COSTS_N_INSNS (17),           /* int_mult_si */
-      COSTS_N_INSNS (17),           /* int_mult_di */
-      COSTS_N_INSNS (38),           /* int_div_si */
-      COSTS_N_INSNS (38),           /* int_div_di */
-                       2,           /* branch_cost */
-                       6            /* memory_latency */
-    },
-    { /* R4000 */
-       COSTS_N_INSNS (6),           /* fp_add */
-       COSTS_N_INSNS (7),           /* fp_mult_sf */
-       COSTS_N_INSNS (8),           /* fp_mult_df */
-       COSTS_N_INSNS (23),          /* fp_div_sf */
-       COSTS_N_INSNS (36),          /* fp_div_df */
-       COSTS_N_INSNS (10),          /* int_mult_si */
-       COSTS_N_INSNS (10),          /* int_mult_di */
-       COSTS_N_INSNS (69),          /* int_div_si */
-       COSTS_N_INSNS (69),          /* int_div_di */
-                        2,          /* branch_cost */
-                        6           /* memory_latency */
-    },
-    { /* R4100 */
-      DEFAULT_COSTS
-    },
-    { /* R4111 */
-      DEFAULT_COSTS
-    },
-    { /* R4120 */
-      DEFAULT_COSTS
-    },
-    { /* R4130 */
-      /* The only costs that appear to be updated here are
-        integer multiplication.  */
-      SOFT_FP_COSTS,
-      COSTS_N_INSNS (4),            /* int_mult_si */
-      COSTS_N_INSNS (6),            /* int_mult_di */
-      COSTS_N_INSNS (69),           /* int_div_si */
-      COSTS_N_INSNS (69),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* R4300 */
-      DEFAULT_COSTS
-    },
-    { /* R4600 */
-      DEFAULT_COSTS
-    },
-    { /* R4650 */
-      DEFAULT_COSTS
-    },
-    { /* R5000 */
-      COSTS_N_INSNS (6),            /* fp_add */
-      COSTS_N_INSNS (4),            /* fp_mult_sf */
-      COSTS_N_INSNS (5),            /* fp_mult_df */
-      COSTS_N_INSNS (23),           /* fp_div_sf */
-      COSTS_N_INSNS (36),           /* fp_div_df */
-      COSTS_N_INSNS (5),            /* int_mult_si */
-      COSTS_N_INSNS (5),            /* int_mult_di */
-      COSTS_N_INSNS (36),           /* int_div_si */
-      COSTS_N_INSNS (36),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* R5400 */
-      COSTS_N_INSNS (6),            /* fp_add */
-      COSTS_N_INSNS (5),            /* fp_mult_sf */
-      COSTS_N_INSNS (6),            /* fp_mult_df */
-      COSTS_N_INSNS (30),           /* fp_div_sf */
-      COSTS_N_INSNS (59),           /* fp_div_df */
-      COSTS_N_INSNS (3),            /* int_mult_si */
-      COSTS_N_INSNS (4),            /* int_mult_di */
-      COSTS_N_INSNS (42),           /* int_div_si */
-      COSTS_N_INSNS (74),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* R5500 */
-      COSTS_N_INSNS (6),            /* fp_add */
-      COSTS_N_INSNS (5),            /* fp_mult_sf */
-      COSTS_N_INSNS (6),            /* fp_mult_df */
-      COSTS_N_INSNS (30),           /* fp_div_sf */
-      COSTS_N_INSNS (59),           /* fp_div_df */
-      COSTS_N_INSNS (5),            /* int_mult_si */
-      COSTS_N_INSNS (9),            /* int_mult_di */
-      COSTS_N_INSNS (42),           /* int_div_si */
-      COSTS_N_INSNS (74),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* R7000 */
-      /* The only costs that are changed here are
-        integer multiplication.  */
-      COSTS_N_INSNS (6),            /* fp_add */
-      COSTS_N_INSNS (7),            /* fp_mult_sf */
-      COSTS_N_INSNS (8),            /* fp_mult_df */
-      COSTS_N_INSNS (23),           /* fp_div_sf */
-      COSTS_N_INSNS (36),           /* fp_div_df */
-      COSTS_N_INSNS (5),            /* int_mult_si */
-      COSTS_N_INSNS (9),            /* int_mult_di */
-      COSTS_N_INSNS (69),           /* int_div_si */
-      COSTS_N_INSNS (69),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* R8000 */
-      DEFAULT_COSTS
-    },
-    { /* R9000 */
-      /* The only costs that are changed here are
-        integer multiplication.  */
-      COSTS_N_INSNS (6),            /* fp_add */
-      COSTS_N_INSNS (7),            /* fp_mult_sf */
-      COSTS_N_INSNS (8),            /* fp_mult_df */
-      COSTS_N_INSNS (23),           /* fp_div_sf */
-      COSTS_N_INSNS (36),           /* fp_div_df */
-      COSTS_N_INSNS (3),            /* int_mult_si */
-      COSTS_N_INSNS (8),            /* int_mult_di */
-      COSTS_N_INSNS (69),           /* int_div_si */
-      COSTS_N_INSNS (69),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* SB1 */
-      /* These costs are the same as the SB-1A below.  */
-      COSTS_N_INSNS (4),            /* fp_add */
-      COSTS_N_INSNS (4),            /* fp_mult_sf */
-      COSTS_N_INSNS (4),            /* fp_mult_df */
-      COSTS_N_INSNS (24),           /* fp_div_sf */
-      COSTS_N_INSNS (32),           /* fp_div_df */
-      COSTS_N_INSNS (3),            /* int_mult_si */
-      COSTS_N_INSNS (4),            /* int_mult_di */
-      COSTS_N_INSNS (36),           /* int_div_si */
-      COSTS_N_INSNS (68),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* SB1-A */
-      /* These costs are the same as the SB-1 above.  */
-      COSTS_N_INSNS (4),            /* fp_add */
-      COSTS_N_INSNS (4),            /* fp_mult_sf */
-      COSTS_N_INSNS (4),            /* fp_mult_df */
-      COSTS_N_INSNS (24),           /* fp_div_sf */
-      COSTS_N_INSNS (32),           /* fp_div_df */
-      COSTS_N_INSNS (3),            /* int_mult_si */
-      COSTS_N_INSNS (4),            /* int_mult_di */
-      COSTS_N_INSNS (36),           /* int_div_si */
-      COSTS_N_INSNS (68),           /* int_div_di */
-                       1,           /* branch_cost */
-                       4            /* memory_latency */
-    },
-    { /* SR71000 */
-      DEFAULT_COSTS
-    },
-  };
-
-/* If a MIPS16e SAVE or RESTORE instruction saves or restores register
-   mips16e_s2_s8_regs[X], it must also save the registers in indexes
-   X + 1 onwards.  Likewise mips16e_a0_a3_regs.  */
-static const unsigned char mips16e_s2_s8_regs[] = {
-  30, 23, 22, 21, 20, 19, 18
-};
-static const unsigned char mips16e_a0_a3_regs[] = {
-  4, 5, 6, 7
+/* Costs to use when optimizing for size.  */
+static const struct mips_rtx_cost_data mips_rtx_cost_optimize_size = {
+  COSTS_N_INSNS (1),            /* fp_add */
+  COSTS_N_INSNS (1),            /* fp_mult_sf */
+  COSTS_N_INSNS (1),            /* fp_mult_df */
+  COSTS_N_INSNS (1),            /* fp_div_sf */
+  COSTS_N_INSNS (1),            /* fp_div_df */
+  COSTS_N_INSNS (1),            /* int_mult_si */
+  COSTS_N_INSNS (1),            /* int_mult_di */
+  COSTS_N_INSNS (1),            /* int_div_si */
+  COSTS_N_INSNS (1),            /* int_div_di */
+                  2,           /* branch_cost */
+                  4            /* memory_latency */
 };
 
-/* A list of the registers that can be saved by the MIPS16e SAVE instruction,
-   ordered from the uppermost in memory to the lowest in memory.  */
-static const unsigned char mips16e_save_restore_regs[] = {
-  31, 30, 23, 22, 21, 20, 19, 18, 17, 16, 7, 6, 5, 4
+/* Costs to use when optimizing for speed, indexed by processor.  */
+static const struct mips_rtx_cost_data mips_rtx_cost_data[PROCESSOR_MAX] = {
+  { /* R3000 */
+    COSTS_N_INSNS (2),            /* fp_add */
+    COSTS_N_INSNS (4),            /* fp_mult_sf */
+    COSTS_N_INSNS (5),            /* fp_mult_df */
+    COSTS_N_INSNS (12),           /* fp_div_sf */
+    COSTS_N_INSNS (19),           /* fp_div_df */
+    COSTS_N_INSNS (12),           /* int_mult_si */
+    COSTS_N_INSNS (12),           /* int_mult_di */
+    COSTS_N_INSNS (35),           /* int_div_si */
+    COSTS_N_INSNS (35),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 4KC */
+    SOFT_FP_COSTS,
+    COSTS_N_INSNS (6),            /* int_mult_si */
+    COSTS_N_INSNS (6),            /* int_mult_di */
+    COSTS_N_INSNS (36),           /* int_div_si */
+    COSTS_N_INSNS (36),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 4KP */
+    SOFT_FP_COSTS,
+    COSTS_N_INSNS (36),           /* int_mult_si */
+    COSTS_N_INSNS (36),           /* int_mult_di */
+    COSTS_N_INSNS (37),           /* int_div_si */
+    COSTS_N_INSNS (37),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 5KC */
+    SOFT_FP_COSTS,
+    COSTS_N_INSNS (4),            /* int_mult_si */
+    COSTS_N_INSNS (11),           /* int_mult_di */
+    COSTS_N_INSNS (36),           /* int_div_si */
+    COSTS_N_INSNS (68),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 5KF */
+    COSTS_N_INSNS (4),            /* fp_add */
+    COSTS_N_INSNS (4),            /* fp_mult_sf */
+    COSTS_N_INSNS (5),            /* fp_mult_df */
+    COSTS_N_INSNS (17),           /* fp_div_sf */
+    COSTS_N_INSNS (32),           /* fp_div_df */
+    COSTS_N_INSNS (4),            /* int_mult_si */
+    COSTS_N_INSNS (11),           /* int_mult_di */
+    COSTS_N_INSNS (36),           /* int_div_si */
+    COSTS_N_INSNS (68),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 20KC */
+    COSTS_N_INSNS (4),            /* fp_add */
+    COSTS_N_INSNS (4),            /* fp_mult_sf */
+    COSTS_N_INSNS (5),            /* fp_mult_df */
+    COSTS_N_INSNS (17),           /* fp_div_sf */
+    COSTS_N_INSNS (32),           /* fp_div_df */
+    COSTS_N_INSNS (4),            /* int_mult_si */
+    COSTS_N_INSNS (7),            /* int_mult_di */
+    COSTS_N_INSNS (42),           /* int_div_si */
+    COSTS_N_INSNS (72),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 24KC */
+    SOFT_FP_COSTS,
+    COSTS_N_INSNS (5),            /* int_mult_si */
+    COSTS_N_INSNS (5),            /* int_mult_di */
+    COSTS_N_INSNS (41),           /* int_div_si */
+    COSTS_N_INSNS (41),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 24KF2_1 */
+    COSTS_N_INSNS (8),            /* fp_add */
+    COSTS_N_INSNS (8),            /* fp_mult_sf */
+    COSTS_N_INSNS (10),           /* fp_mult_df */
+    COSTS_N_INSNS (34),           /* fp_div_sf */
+    COSTS_N_INSNS (64),           /* fp_div_df */
+    COSTS_N_INSNS (5),            /* int_mult_si */
+    COSTS_N_INSNS (5),            /* int_mult_di */
+    COSTS_N_INSNS (41),           /* int_div_si */
+    COSTS_N_INSNS (41),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 24KF1_1 */
+    COSTS_N_INSNS (4),            /* fp_add */
+    COSTS_N_INSNS (4),            /* fp_mult_sf */
+    COSTS_N_INSNS (5),            /* fp_mult_df */
+    COSTS_N_INSNS (17),           /* fp_div_sf */
+    COSTS_N_INSNS (32),           /* fp_div_df */
+    COSTS_N_INSNS (5),            /* int_mult_si */
+    COSTS_N_INSNS (5),            /* int_mult_di */
+    COSTS_N_INSNS (41),           /* int_div_si */
+    COSTS_N_INSNS (41),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 74KC */
+    SOFT_FP_COSTS,
+    COSTS_N_INSNS (5),            /* int_mult_si */
+    COSTS_N_INSNS (5),            /* int_mult_di */
+    COSTS_N_INSNS (41),           /* int_div_si */
+    COSTS_N_INSNS (41),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 74KF2_1 */
+    COSTS_N_INSNS (8),            /* fp_add */
+    COSTS_N_INSNS (8),            /* fp_mult_sf */
+    COSTS_N_INSNS (10),           /* fp_mult_df */
+    COSTS_N_INSNS (34),           /* fp_div_sf */
+    COSTS_N_INSNS (64),           /* fp_div_df */
+    COSTS_N_INSNS (5),            /* int_mult_si */
+    COSTS_N_INSNS (5),            /* int_mult_di */
+    COSTS_N_INSNS (41),           /* int_div_si */
+    COSTS_N_INSNS (41),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 74KF1_1 */
+    COSTS_N_INSNS (4),            /* fp_add */
+    COSTS_N_INSNS (4),            /* fp_mult_sf */
+    COSTS_N_INSNS (5),            /* fp_mult_df */
+    COSTS_N_INSNS (17),           /* fp_div_sf */
+    COSTS_N_INSNS (32),           /* fp_div_df */
+    COSTS_N_INSNS (5),            /* int_mult_si */
+    COSTS_N_INSNS (5),            /* int_mult_di */
+    COSTS_N_INSNS (41),           /* int_div_si */
+    COSTS_N_INSNS (41),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* 74KF3_2 */
+    COSTS_N_INSNS (6),            /* fp_add */
+    COSTS_N_INSNS (6),            /* fp_mult_sf */
+    COSTS_N_INSNS (7),            /* fp_mult_df */
+    COSTS_N_INSNS (25),           /* fp_div_sf */
+    COSTS_N_INSNS (48),           /* fp_div_df */
+    COSTS_N_INSNS (5),            /* int_mult_si */
+    COSTS_N_INSNS (5),            /* int_mult_di */
+    COSTS_N_INSNS (41),           /* int_div_si */
+    COSTS_N_INSNS (41),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* M4k */
+    DEFAULT_COSTS
+  },
+  { /* R3900 */
+    COSTS_N_INSNS (2),            /* fp_add */
+    COSTS_N_INSNS (4),            /* fp_mult_sf */
+    COSTS_N_INSNS (5),            /* fp_mult_df */
+    COSTS_N_INSNS (12),           /* fp_div_sf */
+    COSTS_N_INSNS (19),           /* fp_div_df */
+    COSTS_N_INSNS (2),            /* int_mult_si */
+    COSTS_N_INSNS (2),            /* int_mult_di */
+    COSTS_N_INSNS (35),           /* int_div_si */
+    COSTS_N_INSNS (35),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* R6000 */
+    COSTS_N_INSNS (3),            /* fp_add */
+    COSTS_N_INSNS (5),            /* fp_mult_sf */
+    COSTS_N_INSNS (6),            /* fp_mult_df */
+    COSTS_N_INSNS (15),           /* fp_div_sf */
+    COSTS_N_INSNS (16),           /* fp_div_df */
+    COSTS_N_INSNS (17),           /* int_mult_si */
+    COSTS_N_INSNS (17),           /* int_mult_di */
+    COSTS_N_INSNS (38),           /* int_div_si */
+    COSTS_N_INSNS (38),           /* int_div_di */
+                    2,           /* branch_cost */
+                    6            /* memory_latency */
+  },
+  { /* R4000 */
+     COSTS_N_INSNS (6),           /* fp_add */
+     COSTS_N_INSNS (7),           /* fp_mult_sf */
+     COSTS_N_INSNS (8),           /* fp_mult_df */
+     COSTS_N_INSNS (23),          /* fp_div_sf */
+     COSTS_N_INSNS (36),          /* fp_div_df */
+     COSTS_N_INSNS (10),          /* int_mult_si */
+     COSTS_N_INSNS (10),          /* int_mult_di */
+     COSTS_N_INSNS (69),          /* int_div_si */
+     COSTS_N_INSNS (69),          /* int_div_di */
+                     2,          /* branch_cost */
+                     6           /* memory_latency */
+  },
+  { /* R4100 */
+    DEFAULT_COSTS
+  },
+  { /* R4111 */
+    DEFAULT_COSTS
+  },
+  { /* R4120 */
+    DEFAULT_COSTS
+  },
+  { /* R4130 */
+    /* The only costs that appear to be updated here are
+       integer multiplication.  */
+    SOFT_FP_COSTS,
+    COSTS_N_INSNS (4),            /* int_mult_si */
+    COSTS_N_INSNS (6),            /* int_mult_di */
+    COSTS_N_INSNS (69),           /* int_div_si */
+    COSTS_N_INSNS (69),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* R4300 */
+    DEFAULT_COSTS
+  },
+  { /* R4600 */
+    DEFAULT_COSTS
+  },
+  { /* R4650 */
+    DEFAULT_COSTS
+  },
+  { /* R5000 */
+    COSTS_N_INSNS (6),            /* fp_add */
+    COSTS_N_INSNS (4),            /* fp_mult_sf */
+    COSTS_N_INSNS (5),            /* fp_mult_df */
+    COSTS_N_INSNS (23),           /* fp_div_sf */
+    COSTS_N_INSNS (36),           /* fp_div_df */
+    COSTS_N_INSNS (5),            /* int_mult_si */
+    COSTS_N_INSNS (5),            /* int_mult_di */
+    COSTS_N_INSNS (36),           /* int_div_si */
+    COSTS_N_INSNS (36),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* R5400 */
+    COSTS_N_INSNS (6),            /* fp_add */
+    COSTS_N_INSNS (5),            /* fp_mult_sf */
+    COSTS_N_INSNS (6),            /* fp_mult_df */
+    COSTS_N_INSNS (30),           /* fp_div_sf */
+    COSTS_N_INSNS (59),           /* fp_div_df */
+    COSTS_N_INSNS (3),            /* int_mult_si */
+    COSTS_N_INSNS (4),            /* int_mult_di */
+    COSTS_N_INSNS (42),           /* int_div_si */
+    COSTS_N_INSNS (74),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* R5500 */
+    COSTS_N_INSNS (6),            /* fp_add */
+    COSTS_N_INSNS (5),            /* fp_mult_sf */
+    COSTS_N_INSNS (6),            /* fp_mult_df */
+    COSTS_N_INSNS (30),           /* fp_div_sf */
+    COSTS_N_INSNS (59),           /* fp_div_df */
+    COSTS_N_INSNS (5),            /* int_mult_si */
+    COSTS_N_INSNS (9),            /* int_mult_di */
+    COSTS_N_INSNS (42),           /* int_div_si */
+    COSTS_N_INSNS (74),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* R7000 */
+    /* The only costs that are changed here are
+       integer multiplication.  */
+    COSTS_N_INSNS (6),            /* fp_add */
+    COSTS_N_INSNS (7),            /* fp_mult_sf */
+    COSTS_N_INSNS (8),            /* fp_mult_df */
+    COSTS_N_INSNS (23),           /* fp_div_sf */
+    COSTS_N_INSNS (36),           /* fp_div_df */
+    COSTS_N_INSNS (5),            /* int_mult_si */
+    COSTS_N_INSNS (9),            /* int_mult_di */
+    COSTS_N_INSNS (69),           /* int_div_si */
+    COSTS_N_INSNS (69),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* R8000 */
+    DEFAULT_COSTS
+  },
+  { /* R9000 */
+    /* The only costs that are changed here are
+       integer multiplication.  */
+    COSTS_N_INSNS (6),            /* fp_add */
+    COSTS_N_INSNS (7),            /* fp_mult_sf */
+    COSTS_N_INSNS (8),            /* fp_mult_df */
+    COSTS_N_INSNS (23),           /* fp_div_sf */
+    COSTS_N_INSNS (36),           /* fp_div_df */
+    COSTS_N_INSNS (3),            /* int_mult_si */
+    COSTS_N_INSNS (8),            /* int_mult_di */
+    COSTS_N_INSNS (69),           /* int_div_si */
+    COSTS_N_INSNS (69),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* SB1 */
+    /* These costs are the same as the SB-1A below.  */
+    COSTS_N_INSNS (4),            /* fp_add */
+    COSTS_N_INSNS (4),            /* fp_mult_sf */
+    COSTS_N_INSNS (4),            /* fp_mult_df */
+    COSTS_N_INSNS (24),           /* fp_div_sf */
+    COSTS_N_INSNS (32),           /* fp_div_df */
+    COSTS_N_INSNS (3),            /* int_mult_si */
+    COSTS_N_INSNS (4),            /* int_mult_di */
+    COSTS_N_INSNS (36),           /* int_div_si */
+    COSTS_N_INSNS (68),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* SB1-A */
+    /* These costs are the same as the SB-1 above.  */
+    COSTS_N_INSNS (4),            /* fp_add */
+    COSTS_N_INSNS (4),            /* fp_mult_sf */
+    COSTS_N_INSNS (4),            /* fp_mult_df */
+    COSTS_N_INSNS (24),           /* fp_div_sf */
+    COSTS_N_INSNS (32),           /* fp_div_df */
+    COSTS_N_INSNS (3),            /* int_mult_si */
+    COSTS_N_INSNS (4),            /* int_mult_di */
+    COSTS_N_INSNS (36),           /* int_div_si */
+    COSTS_N_INSNS (68),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  },
+  { /* SR71000 */
+    DEFAULT_COSTS
+  },
 };
 \f
-/* Initialize the GCC target structure.  */
-#undef TARGET_ASM_ALIGNED_HI_OP
-#define TARGET_ASM_ALIGNED_HI_OP "\t.half\t"
-#undef TARGET_ASM_ALIGNED_SI_OP
-#define TARGET_ASM_ALIGNED_SI_OP "\t.word\t"
-#undef TARGET_ASM_ALIGNED_DI_OP
-#define TARGET_ASM_ALIGNED_DI_OP "\t.dword\t"
-
-#undef TARGET_ASM_FUNCTION_PROLOGUE
-#define TARGET_ASM_FUNCTION_PROLOGUE mips_output_function_prologue
-#undef TARGET_ASM_FUNCTION_EPILOGUE
-#define TARGET_ASM_FUNCTION_EPILOGUE mips_output_function_epilogue
-#undef TARGET_ASM_SELECT_RTX_SECTION
-#define TARGET_ASM_SELECT_RTX_SECTION mips_select_rtx_section
-#undef TARGET_ASM_FUNCTION_RODATA_SECTION
-#define TARGET_ASM_FUNCTION_RODATA_SECTION mips_function_rodata_section
-
-#undef TARGET_SCHED_INIT
-#define TARGET_SCHED_INIT mips_sched_init
-#undef TARGET_SCHED_REORDER
-#define TARGET_SCHED_REORDER mips_sched_reorder
-#undef TARGET_SCHED_REORDER2
-#define TARGET_SCHED_REORDER2 mips_sched_reorder
-#undef TARGET_SCHED_VARIABLE_ISSUE
-#define TARGET_SCHED_VARIABLE_ISSUE mips_variable_issue
-#undef TARGET_SCHED_ADJUST_COST
-#define TARGET_SCHED_ADJUST_COST mips_adjust_cost
-#undef TARGET_SCHED_ISSUE_RATE
-#define TARGET_SCHED_ISSUE_RATE mips_issue_rate
-#undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
-#define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD \
-  mips_multipass_dfa_lookahead
-
-#undef TARGET_DEFAULT_TARGET_FLAGS
-#define TARGET_DEFAULT_TARGET_FLAGS            \
-  (TARGET_DEFAULT                              \
-   | TARGET_CPU_DEFAULT                                \
-   | TARGET_ENDIAN_DEFAULT                     \
-   | TARGET_FP_EXCEPTIONS_DEFAULT              \
-   | MASK_CHECK_ZERO_DIV                       \
-   | MASK_FUSED_MADD)
-#undef TARGET_HANDLE_OPTION
-#define TARGET_HANDLE_OPTION mips_handle_option
-
-#undef TARGET_FUNCTION_OK_FOR_SIBCALL
-#define TARGET_FUNCTION_OK_FOR_SIBCALL mips_function_ok_for_sibcall
-
-#undef TARGET_INSERT_ATTRIBUTES
-#define TARGET_INSERT_ATTRIBUTES mips_insert_attributes
-#undef TARGET_MERGE_DECL_ATTRIBUTES
-#define TARGET_MERGE_DECL_ATTRIBUTES mips_merge_decl_attributes
-#undef TARGET_SET_CURRENT_FUNCTION
-#define TARGET_SET_CURRENT_FUNCTION mips_set_current_function
-
-#undef TARGET_VALID_POINTER_MODE
-#define TARGET_VALID_POINTER_MODE mips_valid_pointer_mode
-#undef TARGET_RTX_COSTS
-#define TARGET_RTX_COSTS mips_rtx_costs
-#undef TARGET_ADDRESS_COST
-#define TARGET_ADDRESS_COST mips_address_cost
-
-#undef TARGET_IN_SMALL_DATA_P
-#define TARGET_IN_SMALL_DATA_P mips_in_small_data_p
-
-#undef TARGET_MACHINE_DEPENDENT_REORG
-#define TARGET_MACHINE_DEPENDENT_REORG mips_reorg
-
-#undef TARGET_ASM_FILE_START
-#define TARGET_ASM_FILE_START mips_file_start
-#undef TARGET_ASM_FILE_START_FILE_DIRECTIVE
-#define TARGET_ASM_FILE_START_FILE_DIRECTIVE true
-
-#undef TARGET_INIT_LIBFUNCS
-#define TARGET_INIT_LIBFUNCS mips_init_libfuncs
-
-#undef TARGET_BUILD_BUILTIN_VA_LIST
-#define TARGET_BUILD_BUILTIN_VA_LIST mips_build_builtin_va_list
-#undef TARGET_GIMPLIFY_VA_ARG_EXPR
-#define TARGET_GIMPLIFY_VA_ARG_EXPR mips_gimplify_va_arg_expr
-
-#undef TARGET_PROMOTE_FUNCTION_ARGS
-#define TARGET_PROMOTE_FUNCTION_ARGS hook_bool_const_tree_true
-#undef TARGET_PROMOTE_FUNCTION_RETURN
-#define TARGET_PROMOTE_FUNCTION_RETURN hook_bool_const_tree_true
-#undef TARGET_PROMOTE_PROTOTYPES
-#define TARGET_PROMOTE_PROTOTYPES hook_bool_const_tree_true
-
-#undef TARGET_RETURN_IN_MEMORY
-#define TARGET_RETURN_IN_MEMORY mips_return_in_memory
-#undef TARGET_RETURN_IN_MSB
-#define TARGET_RETURN_IN_MSB mips_return_in_msb
-
-#undef TARGET_ASM_OUTPUT_MI_THUNK
-#define TARGET_ASM_OUTPUT_MI_THUNK mips_output_mi_thunk
-#undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
-#define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
-
-#undef TARGET_SETUP_INCOMING_VARARGS
-#define TARGET_SETUP_INCOMING_VARARGS mips_setup_incoming_varargs
-#undef TARGET_STRICT_ARGUMENT_NAMING
-#define TARGET_STRICT_ARGUMENT_NAMING mips_strict_argument_naming
-#undef TARGET_MUST_PASS_IN_STACK
-#define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
-#undef TARGET_PASS_BY_REFERENCE
-#define TARGET_PASS_BY_REFERENCE mips_pass_by_reference
-#undef TARGET_CALLEE_COPIES
-#define TARGET_CALLEE_COPIES mips_callee_copies
-#undef TARGET_ARG_PARTIAL_BYTES
-#define TARGET_ARG_PARTIAL_BYTES mips_arg_partial_bytes
-
-#undef TARGET_MODE_REP_EXTENDED
-#define TARGET_MODE_REP_EXTENDED mips_mode_rep_extended
-
-#undef TARGET_VECTOR_MODE_SUPPORTED_P
-#define TARGET_VECTOR_MODE_SUPPORTED_P mips_vector_mode_supported_p
-
-#undef TARGET_SCALAR_MODE_SUPPORTED_P
-#define TARGET_SCALAR_MODE_SUPPORTED_P mips_scalar_mode_supported_p
-
-#undef TARGET_INIT_BUILTINS
-#define TARGET_INIT_BUILTINS mips_init_builtins
-#undef TARGET_EXPAND_BUILTIN
-#define TARGET_EXPAND_BUILTIN mips_expand_builtin
-
-#undef TARGET_HAVE_TLS
-#define TARGET_HAVE_TLS HAVE_AS_TLS
-
-#undef TARGET_CANNOT_FORCE_CONST_MEM
-#define TARGET_CANNOT_FORCE_CONST_MEM mips_cannot_force_const_mem
+/* This hash table keeps track of implicit "mips16" and "nomips16" attributes
+   for -mflip_mips16.  It maps decl names onto a boolean mode setting.  */
+struct mflip_mips16_entry GTY (()) {
+  const char *name;
+  bool mips16_p;
+};
+static GTY ((param_is (struct mflip_mips16_entry))) htab_t mflip_mips16_htab;
 
-#undef TARGET_ENCODE_SECTION_INFO
-#define TARGET_ENCODE_SECTION_INFO mips_encode_section_info
+/* Hash table callbacks for mflip_mips16_htab.  */
 
-#undef TARGET_ATTRIBUTE_TABLE
-#define TARGET_ATTRIBUTE_TABLE mips_attribute_table
-/* All our function attributes are related to how out-of-line copies should
-   be compiled or called.  They don't in themselves prevent inlining.  */
-#undef TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P
-#define TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P hook_bool_const_tree_true
+static hashval_t
+mflip_mips16_htab_hash (const void *entry)
+{
+  return htab_hash_string (((const struct mflip_mips16_entry *) entry)->name);
+}
 
-#undef TARGET_EXTRA_LIVE_ON_ENTRY
-#define TARGET_EXTRA_LIVE_ON_ENTRY mips_extra_live_on_entry
+static int
+mflip_mips16_htab_eq (const void *entry, const void *name)
+{
+  return strcmp (((const struct mflip_mips16_entry *) entry)->name,
+                (const char *) name) == 0;
+}
 
-#undef TARGET_MIN_ANCHOR_OFFSET
-#define TARGET_MIN_ANCHOR_OFFSET -32768
-#undef TARGET_MAX_ANCHOR_OFFSET
-#define TARGET_MAX_ANCHOR_OFFSET 32767
-#undef TARGET_USE_BLOCKS_FOR_CONSTANT_P
-#define TARGET_USE_BLOCKS_FOR_CONSTANT_P mips_use_blocks_for_constant_p
-#undef TARGET_USE_ANCHORS_FOR_SYMBOL_P
-#define TARGET_USE_ANCHORS_FOR_SYMBOL_P mips_use_anchors_for_symbol_p
+/* True if -mflip-mips16 should next add an attribute for the default MIPS16
+   mode, false if it should next add an attribute for the opposite mode.  */
+static GTY(()) bool mips16_flipper;
 
-#undef  TARGET_COMP_TYPE_ATTRIBUTES
-#define TARGET_COMP_TYPE_ATTRIBUTES mips_comp_type_attributes
+/* DECL is a function that needs a default "mips16" or "nomips16" attribute
+   for -mflip-mips16.  Return true if it should use "mips16" and false if
+   it should use "nomips16".  */
 
-#ifdef HAVE_AS_DTPRELWORD
-#undef TARGET_ASM_OUTPUT_DWARF_DTPREL
-#define TARGET_ASM_OUTPUT_DWARF_DTPREL mips_output_dwarf_dtprel
-#endif
+static bool
+mflip_mips16_use_mips16_p (tree decl)
+{
+  struct mflip_mips16_entry *entry;
+  const char *name;
+  hashval_t hash;
+  void **slot;
 
-struct gcc_target targetm = TARGET_INITIALIZER;
+  /* Use the opposite of the command-line setting for anonymous decls.  */
+  if (!DECL_NAME (decl))
+    return !mips_base_mips16;
 
+  if (!mflip_mips16_htab)
+    mflip_mips16_htab = htab_create_ggc (37, mflip_mips16_htab_hash,
+                                        mflip_mips16_htab_eq, NULL);
 
+  name = IDENTIFIER_POINTER (DECL_NAME (decl));
+  hash = htab_hash_string (name);
+  slot = htab_find_slot_with_hash (mflip_mips16_htab, name, hash, INSERT);
+  entry = (struct mflip_mips16_entry *) *slot;
+  if (!entry)
+    {
+      mips16_flipper = !mips16_flipper;
+      entry = GGC_NEW (struct mflip_mips16_entry);
+      entry->name = name;
+      entry->mips16_p = mips16_flipper ? !mips_base_mips16 : mips_base_mips16;
+      *slot = entry;
+    }
+  return entry->mips16_p;
+}
+\f
 /* Predicates to test for presence of "near" and "far"/"long_call"
    attributes on the given TYPE.  */
 
@@ -1406,7 +1086,7 @@ mips_far_type_p (const_tree type)
          || lookup_attribute ("far", TYPE_ATTRIBUTES (type)) != NULL);
 }
 
-/* Similar predicates for "mips16"/"nomips16" attributes.  */
+/* Similar predicates for "mips16"/"nomips16" function attributes.  */
 
 static bool
 mips_mips16_decl_p (const_tree decl)
@@ -1420,25 +1100,97 @@ mips_nomips16_decl_p (const_tree decl)
   return lookup_attribute ("nomips16", DECL_ATTRIBUTES (decl)) != NULL;
 }
 
-/* Return 0 if the attributes for two types are incompatible, 1 if they
-   are compatible, and 2 if they are nearly compatible (which causes a
-   warning to be generated).  */
+/* Return true if function DECL is a MIPS16 function.  Return the ambient
+   setting if DECL is null.  */
 
-static int
-mips_comp_type_attributes (const_tree type1, const_tree type2)
-{
-  /* Check for mismatch of non-default calling convention.  */
-  if (TREE_CODE (type1) != FUNCTION_TYPE)
-    return 1;
+static bool
+mips_use_mips16_mode_p (tree decl)
+{
+  if (decl)
+    {
+      /* Nested functions must use the same frame pointer as their
+        parent and must therefore use the same ISA mode.  */
+      tree parent = decl_function_context (decl);
+      if (parent)
+       decl = parent;
+      if (mips_mips16_decl_p (decl))
+       return true;
+      if (mips_nomips16_decl_p (decl))
+       return false;
+    }
+  return mips_base_mips16;
+}
+
+/* Implement TARGET_COMP_TYPE_ATTRIBUTES.  */
 
+static int
+mips_comp_type_attributes (const_tree type1, const_tree type2)
+{
   /* Disallow mixed near/far attributes.  */
   if (mips_far_type_p (type1) && mips_near_type_p (type2))
     return 0;
   if (mips_near_type_p (type1) && mips_far_type_p (type2))
     return 0;
-
   return 1;
 }
+
+/* Implement TARGET_INSERT_ATTRIBUTES.  */
+
+static void
+mips_insert_attributes (tree decl, tree *attributes)
+{
+  const char *name;
+  bool mips16_p, nomips16_p;
+
+  /* Check for "mips16" and "nomips16" attributes.  */
+  mips16_p = lookup_attribute ("mips16", *attributes) != NULL;
+  nomips16_p = lookup_attribute ("nomips16", *attributes) != NULL;
+  if (TREE_CODE (decl) != FUNCTION_DECL)
+    {
+      if (mips16_p)
+       error ("%qs attribute only applies to functions", "mips16");
+      if (nomips16_p)
+       error ("%qs attribute only applies to functions", "nomips16");
+    }
+  else
+    {
+      mips16_p |= mips_mips16_decl_p (decl);
+      nomips16_p |= mips_nomips16_decl_p (decl);
+      if (mips16_p || nomips16_p)
+       {
+         /* DECL cannot be simultaneously "mips16" and "nomips16".  */
+         if (mips16_p && nomips16_p)
+           error ("%qs cannot have both %<mips16%> and "
+                  "%<nomips16%> attributes",
+                  IDENTIFIER_POINTER (DECL_NAME (decl)));
+       }
+      else if (TARGET_FLIP_MIPS16 && !DECL_ARTIFICIAL (decl))
+       {
+         /* Implement -mflip-mips16.  If DECL has neither a "nomips16" nor a
+            "mips16" attribute, arbitrarily pick one.  We must pick the same
+            setting for duplicate declarations of a function.  */
+         name = mflip_mips16_use_mips16_p (decl) ? "mips16" : "nomips16";
+         *attributes = tree_cons (get_identifier (name), NULL, *attributes);
+       }
+    }
+}
+
+/* Implement TARGET_MERGE_DECL_ATTRIBUTES.  */
+
+static tree
+mips_merge_decl_attributes (tree olddecl, tree newdecl)
+{
+  /* The decls' "mips16" and "nomips16" attributes must match exactly.  */
+  if (mips_mips16_decl_p (olddecl) != mips_mips16_decl_p (newdecl))
+    error ("%qs redeclared with conflicting %qs attributes",
+          IDENTIFIER_POINTER (DECL_NAME (newdecl)), "mips16");
+  if (mips_nomips16_decl_p (olddecl) != mips_nomips16_decl_p (newdecl))
+    error ("%qs redeclared with conflicting %qs attributes",
+          IDENTIFIER_POINTER (DECL_NAME (newdecl)), "nomips16");
+
+  return merge_attributes (DECL_ATTRIBUTES (olddecl),
+                          DECL_ATTRIBUTES (newdecl));
+}
 \f
 /* If X is a PLUS of a CONST_INT, return the two terms in *BASE_PTR
    and *OFFSET_PTR.  Return X in *BASE_PTR and 0 in *OFFSET_PTR otherwise.  */
@@ -1458,13 +1210,125 @@ mips_split_plus (rtx x, rtx *base_ptr, HOST_WIDE_INT *offset_ptr)
     }
 }
 \f
+static unsigned int mips_build_integer (struct mips_integer_op *,
+                                       unsigned HOST_WIDE_INT);
+
+/* A subroutine of mips_build_integer, with the same interface.
+   Assume that the final action in the sequence should be a left shift.  */
+
+static unsigned int
+mips_build_shift (struct mips_integer_op *codes, HOST_WIDE_INT value)
+{
+  unsigned int i, shift;
+
+  /* Shift VALUE right until its lowest bit is set.  Shift arithmetically
+     since signed numbers are easier to load than unsigned ones.  */
+  shift = 0;
+  while ((value & 1) == 0)
+    value /= 2, shift++;
+
+  i = mips_build_integer (codes, value);
+  codes[i].code = ASHIFT;
+  codes[i].value = shift;
+  return i + 1;
+}
+
+/* As for mips_build_shift, but assume that the final action will be
+   an IOR or PLUS operation.  */
+
+static unsigned int
+mips_build_lower (struct mips_integer_op *codes, unsigned HOST_WIDE_INT value)
+{
+  unsigned HOST_WIDE_INT high;
+  unsigned int i;
+
+  high = value & ~(unsigned HOST_WIDE_INT) 0xffff;
+  if (!LUI_OPERAND (high) && (value & 0x18000) == 0x18000)
+    {
+      /* The constant is too complex to load with a simple LUI/ORI pair,
+        so we want to give the recursive call as many trailing zeros as
+        possible.  In this case, we know bit 16 is set and that the
+        low 16 bits form a negative number.  If we subtract that number
+        from VALUE, we will clear at least the lowest 17 bits, maybe more.  */
+      i = mips_build_integer (codes, CONST_HIGH_PART (value));
+      codes[i].code = PLUS;
+      codes[i].value = CONST_LOW_PART (value);
+    }
+  else
+    {
+      /* Either this is a simple LUI/ORI pair, or clearing the lowest 16
+        bits gives a value with at least 17 trailing zeros.  */
+      i = mips_build_integer (codes, high);
+      codes[i].code = IOR;
+      codes[i].value = value & 0xffff;
+    }
+  return i + 1;
+}
+
+/* Fill CODES with a sequence of rtl operations to load VALUE.
+   Return the number of operations needed.  */
+
+static unsigned int
+mips_build_integer (struct mips_integer_op *codes,
+                   unsigned HOST_WIDE_INT value)
+{
+  if (SMALL_OPERAND (value)
+      || SMALL_OPERAND_UNSIGNED (value)
+      || LUI_OPERAND (value))
+    {
+      /* The value can be loaded with a single instruction.  */
+      codes[0].code = UNKNOWN;
+      codes[0].value = value;
+      return 1;
+    }
+  else if ((value & 1) != 0 || LUI_OPERAND (CONST_HIGH_PART (value)))
+    {
+      /* Either the constant is a simple LUI/ORI combination or its
+        lowest bit is set.  We don't want to shift in this case.  */
+      return mips_build_lower (codes, value);
+    }
+  else if ((value & 0xffff) == 0)
+    {
+      /* The constant will need at least three actions.  The lowest
+        16 bits are clear, so the final action will be a shift.  */
+      return mips_build_shift (codes, value);
+    }
+  else
+    {
+      /* The final action could be a shift, add or inclusive OR.
+        Rather than use a complex condition to select the best
+        approach, try both mips_build_shift and mips_build_lower
+        and pick the one that gives the shortest sequence.
+        Note that this case is only used once per constant.  */
+      struct mips_integer_op alt_codes[MIPS_MAX_INTEGER_OPS];
+      unsigned int cost, alt_cost;
+
+      cost = mips_build_shift (codes, value);
+      alt_cost = mips_build_lower (alt_codes, value);
+      if (alt_cost < cost)
+       {
+         memcpy (codes, alt_codes, alt_cost * sizeof (codes[0]));
+         cost = alt_cost;
+       }
+      return cost;
+    }
+}
+\f
+/* Return true if X is a thread-local symbol.  */
+
+static bool
+mips_tls_symbol_p (rtx x)
+{
+  return GET_CODE (x) == SYMBOL_REF && SYMBOL_REF_TLS_MODEL (x) != 0;
+}
+
 /* Return true if SYMBOL_REF X is associated with a global symbol
    (in the STB_GLOBAL sense).  */
 
 static bool
 mips_global_symbol_p (const_rtx x)
 {
-  const_tree const decl = SYMBOL_REF_DECL (x);
+  const_tree decl = SYMBOL_REF_DECL (x);
 
   if (!decl)
     return !SYMBOL_REF_LOCAL_P (x);
@@ -1493,7 +1357,20 @@ mips_rtx_constant_in_small_data_p (enum machine_mode mode)
 {
   return (!TARGET_EMBEDDED_DATA
          && TARGET_LOCAL_SDATA
-         && GET_MODE_SIZE (mode) <= mips_section_threshold);
+         && GET_MODE_SIZE (mode) <= mips_small_data_threshold);
+}
+
+/* Return true if X should not be moved directly into register $25.
+   We need this because many versions of GAS will treat "la $25,foo" as
+   part of a call sequence and so allow a global "foo" to be lazily bound.  */
+
+bool
+mips_dangerous_for_la25_p (rtx x)
+{
+  return (!TARGET_EXPLICIT_RELOCS
+         && TARGET_USE_GOT
+         && GET_CODE (x) == SYMBOL_REF
+         && mips_global_symbol_p (x));
 }
 
 /* Return the method that should be used to access SYMBOL_REF or
@@ -1512,8 +1389,10 @@ mips_classify_symbol (const_rtx x, enum mips_symbol_context context)
         the text section.  */
       if (TARGET_MIPS16_SHORT_JUMP_TABLES)
        return SYMBOL_PC_RELATIVE;
+
       if (TARGET_ABICALLS && !TARGET_ABSOLUTE_ABICALLS)
        return SYMBOL_GOT_PAGE_OFST;
+
       return SYMBOL_ABSOLUTE;
     }
 
@@ -1536,9 +1415,7 @@ mips_classify_symbol (const_rtx x, enum mips_symbol_context context)
 
   /* Do not use small-data accesses for weak symbols; they may end up
      being zero.  */
-  if (TARGET_GPOPT
-      && SYMBOL_REF_SMALL_P (x)
-      && !SYMBOL_REF_WEAK (x))
+  if (TARGET_GPOPT && SYMBOL_REF_SMALL_P (x) && !SYMBOL_REF_WEAK (x))
     return SYMBOL_GP_RELATIVE;
 
   /* Don't use GOT accesses for locally-binding symbols when -mno-shared
@@ -1573,11 +1450,12 @@ mips_classify_symbol (const_rtx x, enum mips_symbol_context context)
 
   if (TARGET_MIPS16_PCREL_LOADS && context != SYMBOL_CONTEXT_CALL)
     return SYMBOL_FORCE_TO_MEM;
+
   return SYMBOL_ABSOLUTE;
 }
 
-/* Classify symbolic expression X, given that it appears in context
-   CONTEXT.  */
+/* Classify the base of symbolic expression X, given that X appears in
+   context CONTEXT.  */
 
 static enum mips_symbol_type
 mips_classify_symbolic_expression (rtx x, enum mips_symbol_context context)
@@ -1592,23 +1470,15 @@ mips_classify_symbolic_expression (rtx x, enum mips_symbol_context context)
 }
 
 /* Return true if OFFSET is within the range [0, ALIGN), where ALIGN
-   is the alignment (in bytes) of SYMBOL_REF X.  */
+   is the alignment in bytes of SYMBOL_REF X.  */
 
 static bool
 mips_offset_within_alignment_p (rtx x, HOST_WIDE_INT offset)
 {
-  /* If for some reason we can't get the alignment for the
-     symbol, initializing this to one means we will only accept
-     a zero offset.  */
-  HOST_WIDE_INT align = 1;
-  tree t;
+  HOST_WIDE_INT align;
 
-  /* Get the alignment of the symbol we're referring to.  */
-  t = SYMBOL_REF_DECL (x);
-  if (t)
-    align = DECL_ALIGN_UNIT (t);
-
-  return offset >= 0 && offset < align;
+  align = SYMBOL_REF_DECL (x) ? DECL_ALIGN_UNIT (SYMBOL_REF_DECL (x)) : 1;
+  return IN_RANGE (offset, 0, align - 1);
 }
 
 /* Return true if X is a symbolic constant that can be used in context
@@ -1701,223 +1571,47 @@ mips_symbolic_constant_p (rtx x, enum mips_symbol_context context,
     }
   gcc_unreachable ();
 }
+\f
+/* Like mips_symbol_insns, but treat extended MIPS16 instructions as a
+   single instruction.  We rely on the fact that, in the worst case,
+   all instructions involved in a MIPS16 address calculation are usually
+   extended ones.  */
 
-
-/* This function is used to implement REG_MODE_OK_FOR_BASE_P.  */
-
-int
-mips_regno_mode_ok_for_base_p (int regno, enum machine_mode mode, int strict)
+static int
+mips_symbol_insns_1 (enum mips_symbol_type type, enum machine_mode mode)
 {
-  if (!HARD_REGISTER_NUM_P (regno))
+  switch (type)
     {
-      if (!strict)
-       return true;
-      regno = reg_renumber[regno];
-    }
-
-  /* These fake registers will be eliminated to either the stack or
-     hard frame pointer, both of which are usually valid base registers.
-     Reload deals with the cases where the eliminated form isn't valid.  */
-  if (regno == ARG_POINTER_REGNUM || regno == FRAME_POINTER_REGNUM)
-    return true;
-
-  /* In mips16 mode, the stack pointer can only address word and doubleword
-     values, nothing smaller.  There are two problems here:
-
-       (a) Instantiating virtual registers can introduce new uses of the
-          stack pointer.  If these virtual registers are valid addresses,
-          the stack pointer should be too.
+    case SYMBOL_ABSOLUTE:
+      /* When using 64-bit symbols, we need 5 preparatory instructions,
+        such as:
 
-       (b) Most uses of the stack pointer are not made explicit until
-          FRAME_POINTER_REGNUM and ARG_POINTER_REGNUM have been eliminated.
-          We don't know until that stage whether we'll be eliminating to the
-          stack pointer (which needs the restriction) or the hard frame
-          pointer (which doesn't).
+            lui     $at,%highest(symbol)
+            daddiu  $at,$at,%higher(symbol)
+            dsll    $at,$at,16
+            daddiu  $at,$at,%hi(symbol)
+            dsll    $at,$at,16
 
-     All in all, it seems more consistent to only enforce this restriction
-     during and after reload.  */
-  if (TARGET_MIPS16 && regno == STACK_POINTER_REGNUM)
-    return !strict || GET_MODE_SIZE (mode) == 4 || GET_MODE_SIZE (mode) == 8;
+        The final address is then $at + %lo(symbol).  With 32-bit
+        symbols we just need a preparatory LUI for normal mode and
+        a preparatory LI and SLL for MIPS16.  */
+      return ABI_HAS_64BIT_SYMBOLS ? 6 : TARGET_MIPS16 ? 3 : 2;
 
-  return TARGET_MIPS16 ? M16_REG_P (regno) : GP_REG_P (regno);
-}
+    case SYMBOL_GP_RELATIVE:
+      /* Treat GP-relative accesses as taking a single instruction on
+        MIPS16 too; the copy of $gp can often be shared.  */
+      return 1;
 
+    case SYMBOL_PC_RELATIVE:
+      /* PC-relative constants can be only be used with ADDIUPC,
+        DADDIUPC, LWPC and LDPC.  */
+      if (mode == MAX_MACHINE_MODE
+         || GET_MODE_SIZE (mode) == 4
+         || GET_MODE_SIZE (mode) == 8)
+       return 1;
 
-/* Return true if X is a valid base register for the given mode.
-   Allow only hard registers if STRICT.  */
-
-static bool
-mips_valid_base_register_p (rtx x, enum machine_mode mode, int strict)
-{
-  if (!strict && GET_CODE (x) == SUBREG)
-    x = SUBREG_REG (x);
-
-  return (REG_P (x)
-         && mips_regno_mode_ok_for_base_p (REGNO (x), mode, strict));
-}
-
-
-/* Return true if X is a valid address for machine mode MODE.  If it is,
-   fill in INFO appropriately.  STRICT is true if we should only accept
-   hard base registers.  */
-
-static bool
-mips_classify_address (struct mips_address_info *info, rtx x,
-                      enum machine_mode mode, int strict)
-{
-  switch (GET_CODE (x))
-    {
-    case REG:
-    case SUBREG:
-      info->type = ADDRESS_REG;
-      info->reg = x;
-      info->offset = const0_rtx;
-      return mips_valid_base_register_p (info->reg, mode, strict);
-
-    case PLUS:
-      info->type = ADDRESS_REG;
-      info->reg = XEXP (x, 0);
-      info->offset = XEXP (x, 1);
-      return (mips_valid_base_register_p (info->reg, mode, strict)
-             && const_arith_operand (info->offset, VOIDmode));
-
-    case LO_SUM:
-      info->type = ADDRESS_LO_SUM;
-      info->reg = XEXP (x, 0);
-      info->offset = XEXP (x, 1);
-      /* We have to trust the creator of the LO_SUM to do something vaguely
-        sane.  Target-independent code that creates a LO_SUM should also
-        create and verify the matching HIGH.  Target-independent code that
-        adds an offset to a LO_SUM must prove that the offset will not
-        induce a carry.  Failure to do either of these things would be
-        a bug, and we are not required to check for it here.  The MIPS
-        backend itself should only create LO_SUMs for valid symbolic
-        constants, with the high part being either a HIGH or a copy
-        of _gp. */
-      info->symbol_type
-       = mips_classify_symbolic_expression (info->offset, SYMBOL_CONTEXT_MEM);
-      return (mips_valid_base_register_p (info->reg, mode, strict)
-             && mips_symbol_insns (info->symbol_type, mode) > 0
-             && mips_lo_relocs[info->symbol_type] != 0);
-
-    case CONST_INT:
-      /* Small-integer addresses don't occur very often, but they
-        are legitimate if $0 is a valid base register.  */
-      info->type = ADDRESS_CONST_INT;
-      return !TARGET_MIPS16 && SMALL_INT (x);
-
-    case CONST:
-    case LABEL_REF:
-    case SYMBOL_REF:
-      info->type = ADDRESS_SYMBOLIC;
-      return (mips_symbolic_constant_p (x, SYMBOL_CONTEXT_MEM,
-                                       &info->symbol_type)
-             && mips_symbol_insns (info->symbol_type, mode) > 0
-             && !mips_split_p[info->symbol_type]);
-
-    default:
-      return false;
-    }
-}
-
-/* Return true if X is a thread-local symbol.  */
-
-static bool
-mips_tls_operand_p (rtx x)
-{
-  return GET_CODE (x) == SYMBOL_REF && SYMBOL_REF_TLS_MODEL (x) != 0;
-}
-
-/* Return true if X can not be forced into a constant pool.  */
-
-static int
-mips_tls_symbol_ref_1 (rtx *x, void *data ATTRIBUTE_UNUSED)
-{
-  return mips_tls_operand_p (*x);
-}
-
-/* Return true if X can not be forced into a constant pool.  */
-
-static bool
-mips_cannot_force_const_mem (rtx x)
-{
-  rtx base, offset;
-
-  if (!TARGET_MIPS16)
-    {
-      /* As an optimization, reject constants that mips_legitimize_move
-        can expand inline.
-
-        Suppose we have a multi-instruction sequence that loads constant C
-        into register R.  If R does not get allocated a hard register, and
-        R is used in an operand that allows both registers and memory
-        references, reload will consider forcing C into memory and using
-        one of the instruction's memory alternatives.  Returning false
-        here will force it to use an input reload instead.  */
-      if (GET_CODE (x) == CONST_INT)
-       return true;
-
-      split_const (x, &base, &offset);
-      if (symbolic_operand (base, VOIDmode) && SMALL_INT (offset))
-       return true;
-    }
-
-  if (TARGET_HAVE_TLS && for_each_rtx (&x, &mips_tls_symbol_ref_1, 0))
-    return true;
-
-  return false;
-}
-
-/* Implement TARGET_USE_BLOCKS_FOR_CONSTANT_P.  We can't use blocks for
-   constants when we're using a per-function constant pool.  */
-
-static bool
-mips_use_blocks_for_constant_p (enum machine_mode mode ATTRIBUTE_UNUSED,
-                               const_rtx x ATTRIBUTE_UNUSED)
-{
-  return !TARGET_MIPS16_PCREL_LOADS;
-}
-\f
-/* Like mips_symbol_insns, but treat extended MIPS16 instructions as a
-   single instruction.  We rely on the fact that, in the worst case,
-   all instructions involved in a MIPS16 address calculation are usually
-   extended ones.  */
-
-static int
-mips_symbol_insns_1 (enum mips_symbol_type type, enum machine_mode mode)
-{
-  switch (type)
-    {
-    case SYMBOL_ABSOLUTE:
-      /* When using 64-bit symbols, we need 5 preparatory instructions,
-        such as:
-
-            lui     $at,%highest(symbol)
-            daddiu  $at,$at,%higher(symbol)
-            dsll    $at,$at,16
-            daddiu  $at,$at,%hi(symbol)
-            dsll    $at,$at,16
-
-        The final address is then $at + %lo(symbol).  With 32-bit
-        symbols we just need a preparatory lui for normal mode and
-        a preparatory "li; sll" for MIPS16.  */
-      return ABI_HAS_64BIT_SYMBOLS ? 6 : TARGET_MIPS16 ? 3 : 2;
-
-    case SYMBOL_GP_RELATIVE:
-      /* Treat GP-relative accesses as taking a single instruction on
-        MIPS16 too; the copy of $gp can often be shared.  */
-      return 1;
-
-    case SYMBOL_PC_RELATIVE:
-      /* PC-relative constants can be only be used with addiupc,
-        lwpc and ldpc.  */
-      if (mode == MAX_MACHINE_MODE
-         || GET_MODE_SIZE (mode) == 4
-         || GET_MODE_SIZE (mode) == 8)
-       return 1;
-
-      /* The constant must be loaded using addiupc first.  */
-      return 0;
+      /* The constant must be loaded using ADDIUPC or DADDIUPC first.  */
+      return 0;
 
     case SYMBOL_FORCE_TO_MEM:
       /* LEAs will be converted into constant-pool references by
@@ -1925,7 +1619,7 @@ mips_symbol_insns_1 (enum mips_symbol_type type, enum machine_mode mode)
       if (mode == MAX_MACHINE_MODE)
        return 1;
 
-      /* The constant must be loaded from the constant pool.  */
+      /* The constant must be loaded and then dereferenced.  */
       return 0;
 
     case SYMBOL_GOT_DISP:
@@ -1937,11 +1631,8 @@ mips_symbol_insns_1 (enum mips_symbol_type type, enum machine_mode mode)
       /* Fall through.  */
 
     case SYMBOL_GOT_PAGE_OFST:
-      /* Unless -funit-at-a-time is in effect, we can't be sure whether
-        the local/global classification is accurate.  See override_options
-        for details.
-
-        The worst cases are:
+      /* Unless -funit-at-a-time is in effect, we can't be sure whether the
+        local/global classification is accurate.  The worst cases are:
 
         (1) For local symbols when generating o32 or o64 code.  The assembler
             will use:
@@ -1975,7 +1666,9 @@ mips_symbol_insns_1 (enum mips_symbol_type type, enum machine_mode mode)
     case SYMBOL_HALF:
       /* A 16-bit constant formed by a single relocation, or a 32-bit
         constant formed from a high 16-bit relocation and a low 16-bit
-        relocation.  Use mips_split_p to determine which.  */
+        relocation.  Use mips_split_p to determine which.  32-bit
+        constants need an "lui; addiu" sequence for normal mode and
+        an "li; sll; addiu" sequence for MIPS16 mode.  */
       return !mips_split_p[type] ? 1 : TARGET_MIPS16 ? 3 : 2;
 
     case SYMBOL_TLS:
@@ -2000,89 +1693,290 @@ mips_symbol_insns (enum mips_symbol_type type, enum machine_mode mode)
 {
   return mips_symbol_insns_1 (type, mode) * (TARGET_MIPS16 ? 2 : 1);
 }
+\f
+/* A for_each_rtx callback.  Stop the search if *X references a
+   thread-local symbol.  */
 
-/* Return true if X is a legitimate $sp-based address for mode MDOE.  */
-
-bool
-mips_stack_address_p (rtx x, enum machine_mode mode)
+static int
+mips_tls_symbol_ref_1 (rtx *x, void *data ATTRIBUTE_UNUSED)
 {
-  struct mips_address_info addr;
-
-  return (mips_classify_address (&addr, x, mode, false)
-         && addr.type == ADDRESS_REG
-         && addr.reg == stack_pointer_rtx);
+  return mips_tls_symbol_p (*x);
 }
 
-/* Return true if a value at OFFSET bytes from BASE can be accessed
-   using an unextended mips16 instruction.  MODE is the mode of the
-   value.
-
-   Usually the offset in an unextended instruction is a 5-bit field.
-   The offset is unsigned and shifted left once for HIs, twice
-   for SIs, and so on.  An exception is SImode accesses off the
-   stack pointer, which have an 8-bit immediate field.  */
+/* Implement TARGET_CANNOT_FORCE_CONST_MEM.  */
 
 static bool
-mips16_unextended_reference_p (enum machine_mode mode, rtx base, rtx offset)
+mips_cannot_force_const_mem (rtx x)
 {
-  if (TARGET_MIPS16
-      && GET_CODE (offset) == CONST_INT
-      && INTVAL (offset) >= 0
-      && (INTVAL (offset) & (GET_MODE_SIZE (mode) - 1)) == 0)
+  rtx base, offset;
+
+  if (!TARGET_MIPS16)
     {
-      if (GET_MODE_SIZE (mode) == 4 && base == stack_pointer_rtx)
-       return INTVAL (offset) < 256 * GET_MODE_SIZE (mode);
-      return INTVAL (offset) < 32 * GET_MODE_SIZE (mode);
+      /* As an optimization, reject constants that mips_legitimize_move
+        can expand inline.
+
+        Suppose we have a multi-instruction sequence that loads constant C
+        into register R.  If R does not get allocated a hard register, and
+        R is used in an operand that allows both registers and memory
+        references, reload will consider forcing C into memory and using
+        one of the instruction's memory alternatives.  Returning false
+        here will force it to use an input reload instead.  */
+      if (GET_CODE (x) == CONST_INT)
+       return true;
+
+      split_const (x, &base, &offset);
+      if (symbolic_operand (base, VOIDmode) && SMALL_INT (offset))
+       return true;
     }
+
+  /* TLS symbols must be computed by mips_legitimize_move.  */
+  if (for_each_rtx (&x, &mips_tls_symbol_ref_1, NULL))
+    return true;
+
   return false;
 }
 
+/* Implement TARGET_USE_BLOCKS_FOR_CONSTANT_P.  We can't use blocks for
+   constants when we're using a per-function constant pool.  */
 
-/* Return the number of instructions needed to load or store a value
-   of mode MODE at X.  Return 0 if X isn't valid for MODE.  Assume that
-   multiword moves may need to be split into word moves if MIGHT_SPLIT_P,
-   otherwise assume that a single load or store is enough.
-
-   For mips16 code, count extended instructions as two instructions.  */
+static bool
+mips_use_blocks_for_constant_p (enum machine_mode mode ATTRIBUTE_UNUSED,
+                               const_rtx x ATTRIBUTE_UNUSED)
+{
+  return !TARGET_MIPS16_PCREL_LOADS;
+}
+\f
+/* Return true if register REGNO is a valid base register for mode MODE.
+   STRICT_P is true if REG_OK_STRICT is in effect.  */
 
 int
-mips_address_insns (rtx x, enum machine_mode mode, bool might_split_p)
+mips_regno_mode_ok_for_base_p (int regno, enum machine_mode mode,
+                              bool strict_p)
 {
-  struct mips_address_info addr;
-  int factor;
+  if (!HARD_REGISTER_NUM_P (regno))
+    {
+      if (!strict_p)
+       return true;
+      regno = reg_renumber[regno];
+    }
 
-  /* BLKmode is used for single unaligned loads and stores and should
-     not count as a multiword mode.  (GET_MODE_SIZE (BLKmode) is pretty
-     meaningless, so we have to single it out as a special case one way
-     or the other.)  */
-  if (mode != BLKmode && might_split_p)
-    factor = (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
-  else
-    factor = 1;
+  /* These fake registers will be eliminated to either the stack or
+     hard frame pointer, both of which are usually valid base registers.
+     Reload deals with the cases where the eliminated form isn't valid.  */
+  if (regno == ARG_POINTER_REGNUM || regno == FRAME_POINTER_REGNUM)
+    return true;
 
-  if (mips_classify_address (&addr, x, mode, false))
-    switch (addr.type)
-      {
-      case ADDRESS_REG:
-       if (TARGET_MIPS16
-           && !mips16_unextended_reference_p (mode, addr.reg, addr.offset))
-         return factor * 2;
-       return factor;
+  /* In MIPS16 mode, the stack pointer can only address word and doubleword
+     values, nothing smaller.  There are two problems here:
 
-      case ADDRESS_LO_SUM:
-       return (TARGET_MIPS16 ? factor * 2 : factor);
+       (a) Instantiating virtual registers can introduce new uses of the
+          stack pointer.  If these virtual registers are valid addresses,
+          the stack pointer should be too.
 
-      case ADDRESS_CONST_INT:
-       return factor;
+       (b) Most uses of the stack pointer are not made explicit until
+          FRAME_POINTER_REGNUM and ARG_POINTER_REGNUM have been eliminated.
+          We don't know until that stage whether we'll be eliminating to the
+          stack pointer (which needs the restriction) or the hard frame
+          pointer (which doesn't).
 
-      case ADDRESS_SYMBOLIC:
-       return factor * mips_symbol_insns (addr.symbol_type, mode);
-      }
-  return 0;
+     All in all, it seems more consistent to only enforce this restriction
+     during and after reload.  */
+  if (TARGET_MIPS16 && regno == STACK_POINTER_REGNUM)
+    return !strict_p || GET_MODE_SIZE (mode) == 4 || GET_MODE_SIZE (mode) == 8;
+
+  return TARGET_MIPS16 ? M16_REG_P (regno) : GP_REG_P (regno);
 }
 
+/* Return true if X is a valid base register for mode MODE.
+   STRICT_P is true if REG_OK_STRICT is in effect.  */
 
-/* Likewise for constant X.  */
+static bool
+mips_valid_base_register_p (rtx x, enum machine_mode mode, bool strict_p)
+{
+  if (!strict_p && GET_CODE (x) == SUBREG)
+    x = SUBREG_REG (x);
+
+  return (REG_P (x)
+         && mips_regno_mode_ok_for_base_p (REGNO (x), mode, strict_p));
+}
+
+/* Return true if X is a valid address for machine mode MODE.  If it is,
+   fill in INFO appropriately.  STRICT_P is true if REG_OK_STRICT is in
+   effect.  */
+
+static bool
+mips_classify_address (struct mips_address_info *info, rtx x,
+                      enum machine_mode mode, bool strict_p)
+{
+  switch (GET_CODE (x))
+    {
+    case REG:
+    case SUBREG:
+      info->type = ADDRESS_REG;
+      info->reg = x;
+      info->offset = const0_rtx;
+      return mips_valid_base_register_p (info->reg, mode, strict_p);
+
+    case PLUS:
+      info->type = ADDRESS_REG;
+      info->reg = XEXP (x, 0);
+      info->offset = XEXP (x, 1);
+      return (mips_valid_base_register_p (info->reg, mode, strict_p)
+             && const_arith_operand (info->offset, VOIDmode));
+
+    case LO_SUM:
+      info->type = ADDRESS_LO_SUM;
+      info->reg = XEXP (x, 0);
+      info->offset = XEXP (x, 1);
+      /* We have to trust the creator of the LO_SUM to do something vaguely
+        sane.  Target-independent code that creates a LO_SUM should also
+        create and verify the matching HIGH.  Target-independent code that
+        adds an offset to a LO_SUM must prove that the offset will not
+        induce a carry.  Failure to do either of these things would be
+        a bug, and we are not required to check for it here.  The MIPS
+        backend itself should only create LO_SUMs for valid symbolic
+        constants, with the high part being either a HIGH or a copy
+        of _gp. */
+      info->symbol_type
+       = mips_classify_symbolic_expression (info->offset, SYMBOL_CONTEXT_MEM);
+      return (mips_valid_base_register_p (info->reg, mode, strict_p)
+             && mips_symbol_insns (info->symbol_type, mode) > 0
+             && mips_lo_relocs[info->symbol_type] != 0);
+
+    case CONST_INT:
+      /* Small-integer addresses don't occur very often, but they
+        are legitimate if $0 is a valid base register.  */
+      info->type = ADDRESS_CONST_INT;
+      return !TARGET_MIPS16 && SMALL_INT (x);
+
+    case CONST:
+    case LABEL_REF:
+    case SYMBOL_REF:
+      info->type = ADDRESS_SYMBOLIC;
+      return (mips_symbolic_constant_p (x, SYMBOL_CONTEXT_MEM,
+                                       &info->symbol_type)
+             && mips_symbol_insns (info->symbol_type, mode) > 0
+             && !mips_split_p[info->symbol_type]);
+
+    default:
+      return false;
+    }
+}
+
+/* Return true if X is a legitimate address for a memory operand of mode
+   MODE.  STRICT_P is true if REG_OK_STRICT is in effect.  */
+
+bool
+mips_legitimate_address_p (enum machine_mode mode, rtx x, bool strict_p)
+{
+  struct mips_address_info addr;
+
+  return mips_classify_address (&addr, x, mode, strict_p);
+}
+
+/* Return true if X is a legitimate $sp-based address for mode MDOE.  */
+
+bool
+mips_stack_address_p (rtx x, enum machine_mode mode)
+{
+  struct mips_address_info addr;
+
+  return (mips_classify_address (&addr, x, mode, false)
+         && addr.type == ADDRESS_REG
+         && addr.reg == stack_pointer_rtx);
+}
+
+/* Return true if ADDR matches the pattern for the LWXS load scaled indexed
+   address instruction.  Note that such addresses are not considered
+   legitimate in the GO_IF_LEGITIMATE_ADDRESS sense, because their use
+   is so restricted.  */
+
+static bool
+mips_lwxs_address_p (rtx addr)
+{
+  if (ISA_HAS_LWXS
+      && GET_CODE (addr) == PLUS
+      && REG_P (XEXP (addr, 1)))
+    {
+      rtx offset = XEXP (addr, 0);
+      if (GET_CODE (offset) == MULT
+         && REG_P (XEXP (offset, 0))
+         && GET_CODE (XEXP (offset, 1)) == CONST_INT
+         && INTVAL (XEXP (offset, 1)) == 4)
+       return true;
+    }
+  return false;
+}
+\f
+/* Return true if a value at OFFSET bytes from base register BASE can be
+   accessed using an unextended MIPS16 instruction.  MODE is the mode of
+   the value.
+
+   Usually the offset in an unextended instruction is a 5-bit field.
+   The offset is unsigned and shifted left once for LH and SH, twice
+   for LW and SW, and so on.  An exception is LWSP and SWSP, which have
+   an 8-bit immediate field that's shifted left twice.  */
+
+static bool
+mips16_unextended_reference_p (enum machine_mode mode, rtx base,
+                              unsigned HOST_WIDE_INT offset)
+{
+  if (offset % GET_MODE_SIZE (mode) == 0)
+    {
+      if (GET_MODE_SIZE (mode) == 4 && base == stack_pointer_rtx)
+       return offset < 256U * GET_MODE_SIZE (mode);
+      return offset < 32U * GET_MODE_SIZE (mode);
+    }
+  return false;
+}
+
+/* Return the number of instructions needed to load or store a value
+   of mode MODE at address X.  Return 0 if X isn't valid for MODE.
+   Assume that multiword moves may need to be split into word moves
+   if MIGHT_SPLIT_P, otherwise assume that a single load or store is
+   enough.
+
+   For MIPS16 code, count extended instructions as two instructions.  */
+
+int
+mips_address_insns (rtx x, enum machine_mode mode, bool might_split_p)
+{
+  struct mips_address_info addr;
+  int factor;
+
+  /* BLKmode is used for single unaligned loads and stores and should
+     not count as a multiword mode.  (GET_MODE_SIZE (BLKmode) is pretty
+     meaningless, so we have to single it out as a special case one way
+     or the other.)  */
+  if (mode != BLKmode && might_split_p)
+    factor = (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
+  else
+    factor = 1;
+
+  if (mips_classify_address (&addr, x, mode, false))
+    switch (addr.type)
+      {
+      case ADDRESS_REG:
+       if (TARGET_MIPS16
+           && !mips16_unextended_reference_p (mode, addr.reg,
+                                              UINTVAL (addr.offset)))
+         return factor * 2;
+       return factor;
+
+      case ADDRESS_LO_SUM:
+       return TARGET_MIPS16 ? factor * 2 : factor;
+
+      case ADDRESS_CONST_INT:
+       return factor;
+
+      case ADDRESS_SYMBOLIC:
+       return factor * mips_symbol_insns (addr.symbol_type, mode);
+      }
+  return 0;
+}
+
+/* Return the number of instructions needed to load constant X.
+   Return 0 if X isn't a valid constant.  */
 
 int
 mips_const_insns (rtx x)
@@ -2099,8 +1993,8 @@ mips_const_insns (rtx x)
          || !mips_split_p[symbol_type])
        return 0;
 
-      /* This is simply an lui for normal mode.  It is an extended
-        "li" followed by an extended "sll" for MIPS16.  */
+      /* This is simply an LUI for normal mode.  It is an extended
+        LI followed by an extended SLL for MIPS16.  */
       return TARGET_MIPS16 ? 4 : 1;
 
     case CONST_INT:
@@ -2109,9 +2003,9 @@ mips_const_insns (rtx x)
           LI instruction.  Unsigned 16-bit constants can be loaded
           using an extended LI.  Negative constants must be loaded
           using LI and then negated.  */
-       return (INTVAL (x) >= 0 && INTVAL (x) < 256 ? 1
+       return (IN_RANGE (INTVAL (x), 0, 255) ? 1
                : SMALL_OPERAND_UNSIGNED (INTVAL (x)) ? 2
-               : INTVAL (x) > -256 && INTVAL (x) < 0 ? 2
+               : IN_RANGE (-INTVAL (x), 0, 255) ? 2
                : SMALL_OPERAND_UNSIGNED (-INTVAL (x)) ? 3
                : 0);
 
@@ -2119,7 +2013,8 @@ mips_const_insns (rtx x)
 
     case CONST_DOUBLE:
     case CONST_VECTOR:
-      return (!TARGET_MIPS16 && x == CONST0_RTX (GET_MODE (x)) ? 1 : 0);
+      /* Allow zeros for normal mode, where we can use $0.  */
+      return !TARGET_MIPS16 && x == CONST0_RTX (GET_MODE (x)) ? 1 : 0;
 
     case CONST:
       if (CONST_GP_P (x))
@@ -2130,7 +2025,7 @@ mips_const_insns (rtx x)
        return mips_symbol_insns (symbol_type, MAX_MACHINE_MODE);
 
       /* Otherwise try splitting the constant into a base and offset.
-        16-bit offsets can be added using an extra addiu.  Larger offsets
+        16-bit offsets can be added using an extra ADDIU.  Larger offsets
         must be calculated separately and then added to the base.  */
       split_const (x, &x, &offset);
       if (offset != 0)
@@ -2156,10 +2051,9 @@ mips_const_insns (rtx x)
     }
 }
 
-
 /* Return the number of instructions needed to implement INSN,
    given that it loads from or stores to MEM.  Count extended
-   mips16 instructions as two instructions.  */
+   MIPS16 instructions as two instructions.  */
 
 int
 mips_load_store_insns (rtx mem, rtx insn)
@@ -2183,7 +2077,6 @@ mips_load_store_insns (rtx mem, rtx insn)
   return mips_address_insns (XEXP (mem, 0), mode, might_split_p);
 }
 
-
 /* Return the number of instructions needed for an integer division.  */
 
 int
@@ -2205,19 +2098,6 @@ mips_idiv_insns (void)
   return count;
 }
 \f
-/* This function is used to implement GO_IF_LEGITIMATE_ADDRESS.  It
-   returns a nonzero value if X is a legitimate address for a memory
-   operand of the indicated MODE.  STRICT is nonzero if this function
-   is called during reload.  */
-
-bool
-mips_legitimate_address_p (enum machine_mode mode, rtx x, int strict)
-{
-  struct mips_address_info addr;
-
-  return mips_classify_address (&addr, x, mode, strict);
-}
-
 /* Emit a move from SRC to DEST.  Assume that the move expanders can
    handle all moves if !can_create_pseudo_p ().  The distinction is
    important because, unlike emit_move_insn, the move expanders know
@@ -2232,7 +2112,16 @@ mips_emit_move (rtx dest, rtx src)
          : emit_move_insn_1 (dest, src));
 }
 
-/* Copy VALUE to a register and return that register.  If new psuedos
+/* Emit an instruction of the form (set TARGET (CODE OP0 OP1)).  */
+
+static void
+mips_emit_binary (enum rtx_code code, rtx target, rtx op0, rtx op1)
+{
+  emit_insn (gen_rtx_SET (VOIDmode, target,
+                         gen_rtx_fmt_ee (code, GET_MODE (target), op0, op1)));
+}
+
+/* Copy VALUE to a register and return that register.  If new pseudos
    are allowed, copy it into a new register, otherwise use DEST.  */
 
 static rtx
@@ -2242,11 +2131,86 @@ mips_force_temporary (rtx dest, rtx value)
     return force_reg (Pmode, value);
   else
     {
-      mips_emit_move (copy_rtx (dest), value);
+      mips_emit_move (dest, value);
       return dest;
     }
 }
 
+/* Emit a call sequence with call pattern PATTERN and return the call
+   instruction itself (which is not necessarily the last instruction
+   emitted).  LAZY_P is true if the call address is lazily-bound.  */
+
+static rtx
+mips_emit_call_insn (rtx pattern, bool lazy_p)
+{
+  rtx insn;
+
+  insn = emit_call_insn (pattern);
+
+  /* Lazy-binding stubs require $gp to be valid on entry.  */
+  if (lazy_p)
+    use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
+
+  if (TARGET_USE_GOT)
+    {
+      /* See the comment above load_call<mode> for details.  */
+      use_reg (&CALL_INSN_FUNCTION_USAGE (insn),
+              gen_rtx_REG (Pmode, GOT_VERSION_REGNUM));
+      emit_insn (gen_update_got_version ());
+    }
+  return insn;
+}
+\f
+/* Return an instruction that copies $gp into register REG.  We want
+   GCC to treat the register's value as constant, so that its value
+   can be rematerialized on demand.  */
+
+static rtx
+gen_load_const_gp (rtx reg)
+{
+  return (Pmode == SImode
+         ? gen_load_const_gp_si (reg)
+         : gen_load_const_gp_di (reg));
+}
+
+/* Return a pseudo register that contains the value of $gp throughout
+   the current function.  Such registers are needed by MIPS16 functions,
+   for which $gp itself is not a valid base register or addition operand.  */
+
+static rtx
+mips16_gp_pseudo_reg (void)
+{
+  if (cfun->machine->mips16_gp_pseudo_rtx == NULL_RTX)
+    cfun->machine->mips16_gp_pseudo_rtx = gen_reg_rtx (Pmode);
+
+  /* Don't emit an instruction to initialize the pseudo register if
+     we are being called from the tree optimizers' cost-calculation
+     routines.  */
+  if (!cfun->machine->initialized_mips16_gp_pseudo_p
+      && (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl))
+    {
+      rtx insn, scan, after;
+
+      insn = gen_load_const_gp (cfun->machine->mips16_gp_pseudo_rtx);
+
+      push_topmost_sequence ();
+      /* We need to emit the initialization after the FUNCTION_BEG
+         note, so that it will be integrated.  */
+      after = get_insns ();
+      for (scan = after; scan != NULL_RTX; scan = NEXT_INSN (scan))
+       if (NOTE_P (scan) && NOTE_KIND (scan) == NOTE_INSN_FUNCTION_BEG)
+         {
+           after = scan;
+           break;
+         }
+      insn = emit_insn_after (insn, after);
+      pop_topmost_sequence ();
+
+      cfun->machine->initialized_mips16_gp_pseudo_p = true;
+    }
+
+  return cfun->machine->mips16_gp_pseudo_rtx;
+}
 
 /* If MODE is MAX_MACHINE_MODE, ADDR appears as a move operand, otherwise
    it appears in a MEM of that mode.  Return true if ADDR is a legitimate
@@ -2278,7 +2242,7 @@ mips_split_symbol (rtx temp, rtx addr, enum machine_mode mode, rtx *lo_sum_out)
        {
          if (!can_create_pseudo_p ())
            {
-             emit_insn (gen_load_const_gp (copy_rtx (temp)));
+             emit_insn (gen_load_const_gp (temp));
              high = temp;
            }
          else
@@ -2294,9 +2258,8 @@ mips_split_symbol (rtx temp, rtx addr, enum machine_mode mode, rtx *lo_sum_out)
   return true;
 }
 
-
-/* Wrap symbol or label BASE in an unspec address of type SYMBOL_TYPE
-   and add CONST_INT OFFSET to the result.  */
+/* Wrap symbol or label BASE in an UNSPEC address of type SYMBOL_TYPE,
+   then add CONST_INT OFFSET to the result.  */
 
 static rtx
 mips_unspec_address_offset (rtx base, rtx offset,
@@ -2321,10 +2284,9 @@ mips_unspec_address (rtx address, enum mips_symbol_type symbol_type)
   return mips_unspec_address_offset (base, offset, symbol_type);
 }
 
-
 /* If mips_unspec_address (ADDR, SYMBOL_TYPE) is a 32-bit value, add the
    high part to BASE and return the result.  Just return BASE otherwise.
-   TEMP is available as a temporary register if needed.
+   TEMP is as for mips_force_temporary.
 
    The returned expression can be used as the first operand to a LO_SUM.  */
 
@@ -2336,12 +2298,11 @@ mips_unspec_offset_high (rtx temp, rtx base, rtx addr,
     {
       addr = gen_rtx_HIGH (Pmode, mips_unspec_address (addr, symbol_type));
       addr = mips_force_temporary (temp, addr);
-      return mips_force_temporary (temp, gen_rtx_PLUS (Pmode, addr, base));
+      base = mips_force_temporary (temp, gen_rtx_PLUS (Pmode, addr, base));
     }
   return base;
 }
 
-
 /* Return a legitimate address for REG + OFFSET.  TEMP is as for
    mips_force_temporary; it is only needed when OFFSET is not a
    SMALL_OPERAND.  */
@@ -2352,6 +2313,7 @@ mips_add_offset (rtx temp, rtx reg, HOST_WIDE_INT offset)
   if (!SMALL_OPERAND (offset))
     {
       rtx high;
+
       if (TARGET_MIPS16)
        {
          /* Load the full offset into a register so that we can use
@@ -2370,18 +2332,19 @@ mips_add_offset (rtx temp, rtx reg, HOST_WIDE_INT offset)
     }
   return plus_constant (reg, offset);
 }
-
-/* Emit a call to __tls_get_addr.  SYM is the TLS symbol we are
-   referencing, and TYPE is the symbol type to use (either global
-   dynamic or local dynamic).  V0 is an RTX for the return value
-   location.  The entire insn sequence is returned.  */
-
+\f
+/* The __tls_get_attr symbol.  */
 static GTY(()) rtx mips_tls_symbol;
 
+/* Return an instruction sequence that calls __tls_get_addr.  SYM is
+   the TLS symbol we are referencing and TYPE is the symbol type to use
+   (either global dynamic or local dynamic).  V0 is an RTX for the
+   return value location.  */
+
 static rtx
 mips_call_tls_get_addr (rtx sym, enum mips_symbol_type type, rtx v0)
 {
-  rtx insn, loc, tga, a0;
+  rtx insn, loc, a0;
 
   a0 = gen_rtx_REG (Pmode, GP_ARG_FIRST);
 
@@ -2394,10 +2357,8 @@ mips_call_tls_get_addr (rtx sym, enum mips_symbol_type type, rtx v0)
 
   emit_insn (gen_rtx_SET (Pmode, a0,
                          gen_rtx_LO_SUM (Pmode, pic_offset_table_rtx, loc)));
-  tga = gen_rtx_MEM (Pmode, mips_tls_symbol);
-  insn = emit_call_insn (gen_call_value (v0, tga, const0_rtx, const0_rtx));
+  insn = mips_expand_call (v0, mips_tls_symbol, const0_rtx, const0_rtx, false);
   CONST_OR_PURE_CALL_P (insn) = 1;
-  use_reg (&CALL_INSN_FUNCTION_USAGE (insn), v0);
   use_reg (&CALL_INSN_FUNCTION_USAGE (insn), a0);
   insn = get_insns ();
 
@@ -2406,9 +2367,9 @@ mips_call_tls_get_addr (rtx sym, enum mips_symbol_type type, rtx v0)
   return insn;
 }
 
-/* Generate the code to access LOC, a thread local SYMBOL_REF.  The
-   return value will be a valid address and move_operand (either a REG
-   or a LO_SUM).  */
+/* Generate the code to access LOC, a thread-local SYMBOL_REF, and return
+   its address.  The return value will be both a valid address and a valid
+   SET_SRC (either a REG or a LO_SUM).  */
 
 static rtx
 mips_legitimize_tls_address (rtx loc)
@@ -2422,9 +2383,6 @@ mips_legitimize_tls_address (rtx loc)
       return gen_reg_rtx (Pmode);
     }
 
-  v0 = gen_rtx_REG (Pmode, GP_RETURN);
-  v1 = gen_rtx_REG (Pmode, GP_RETURN + 1);
-
   model = SYMBOL_REF_TLS_MODEL (loc);
   /* Only TARGET_ABICALLS code can have more than one module; other
      code must be be static and should not use a GOT.  All TLS models
@@ -2435,12 +2393,14 @@ mips_legitimize_tls_address (rtx loc)
   switch (model)
     {
     case TLS_MODEL_GLOBAL_DYNAMIC:
+      v0 = gen_rtx_REG (Pmode, GP_RETURN);
       insn = mips_call_tls_get_addr (loc, SYMBOL_TLSGD, v0);
       dest = gen_reg_rtx (Pmode);
       emit_libcall_block (insn, dest, v0, loc);
       break;
 
     case TLS_MODEL_LOCAL_DYNAMIC:
+      v0 = gen_rtx_REG (Pmode, GP_RETURN);
       insn = mips_call_tls_get_addr (loc, SYMBOL_TLSLDM, v0);
       tmp1 = gen_reg_rtx (Pmode);
 
@@ -2456,6 +2416,7 @@ mips_legitimize_tls_address (rtx loc)
       break;
 
     case TLS_MODEL_INITIAL_EXEC:
+      v1 = gen_rtx_REG (Pmode, GP_RETURN + 1);
       tmp1 = gen_reg_rtx (Pmode);
       tmp2 = mips_unspec_address (loc, SYMBOL_GOTTPREL);
       if (Pmode == DImode)
@@ -2473,6 +2434,7 @@ mips_legitimize_tls_address (rtx loc)
       break;
 
     case TLS_MODEL_LOCAL_EXEC:
+      v1 = gen_rtx_REG (Pmode, GP_RETURN + 1);
       if (Pmode == DImode)
        emit_insn (gen_tls_get_tp_di (v1));
       else
@@ -2486,10 +2448,9 @@ mips_legitimize_tls_address (rtx loc)
     default:
       gcc_unreachable ();
     }
-
   return dest;
 }
-
+\f
 /* This function is used to implement LEGITIMIZE_ADDRESS.  If *XLOC can
    be legitimized in a way that the generic machinery might not expect,
    put the new address in *XLOC and return true.  MODE is the mode of
@@ -2498,7 +2459,10 @@ mips_legitimize_tls_address (rtx loc)
 bool
 mips_legitimize_address (rtx *xloc, enum machine_mode mode)
 {
-  if (mips_tls_operand_p (*xloc))
+  rtx base;
+  HOST_WIDE_INT offset;
+
+  if (mips_tls_symbol_p (*xloc))
     {
       *xloc = mips_legitimize_tls_address (*xloc);
       return true;
@@ -2508,141 +2472,35 @@ mips_legitimize_address (rtx *xloc, enum machine_mode mode)
   if (mips_split_symbol (NULL, *xloc, mode, xloc))
     return true;
 
-  if (GET_CODE (*xloc) == PLUS && GET_CODE (XEXP (*xloc, 1)) == CONST_INT)
+  /* Handle BASE + OFFSET using mips_add_offset.  */
+  mips_split_plus (*xloc, &base, &offset);
+  if (offset != 0)
     {
-      /* Handle REG + CONSTANT using mips_add_offset.  */
-      rtx reg;
-
-      reg = XEXP (*xloc, 0);
-      if (!mips_valid_base_register_p (reg, mode, 0))
-       reg = copy_to_mode_reg (Pmode, reg);
-      *xloc = mips_add_offset (0, reg, INTVAL (XEXP (*xloc, 1)));
+      if (!mips_valid_base_register_p (base, mode, false))
+       base = copy_to_mode_reg (Pmode, base);
+      *xloc = mips_add_offset (NULL, base, offset);
       return true;
     }
-
   return false;
 }
 
+/* Load VALUE into DEST.  TEMP is as for mips_force_temporary.  */
 
-/* Subroutine of mips_build_integer (with the same interface).
-   Assume that the final action in the sequence should be a left shift.  */
-
-static unsigned int
-mips_build_shift (struct mips_integer_op *codes, HOST_WIDE_INT value)
+void
+mips_move_integer (rtx temp, rtx dest, unsigned HOST_WIDE_INT value)
 {
-  unsigned int i, shift;
-
-  /* Shift VALUE right until its lowest bit is set.  Shift arithmetically
-     since signed numbers are easier to load than unsigned ones.  */
-  shift = 0;
-  while ((value & 1) == 0)
-    value /= 2, shift++;
-
-  i = mips_build_integer (codes, value);
-  codes[i].code = ASHIFT;
-  codes[i].value = shift;
-  return i + 1;
-}
-
+  struct mips_integer_op codes[MIPS_MAX_INTEGER_OPS];
+  enum machine_mode mode;
+  unsigned int i, num_ops;
+  rtx x;
 
-/* As for mips_build_shift, but assume that the final action will be
-   an IOR or PLUS operation.  */
-
-static unsigned int
-mips_build_lower (struct mips_integer_op *codes, unsigned HOST_WIDE_INT value)
-{
-  unsigned HOST_WIDE_INT high;
-  unsigned int i;
-
-  high = value & ~(unsigned HOST_WIDE_INT) 0xffff;
-  if (!LUI_OPERAND (high) && (value & 0x18000) == 0x18000)
-    {
-      /* The constant is too complex to load with a simple lui/ori pair
-        so our goal is to clear as many trailing zeros as possible.
-        In this case, we know bit 16 is set and that the low 16 bits
-        form a negative number.  If we subtract that number from VALUE,
-        we will clear at least the lowest 17 bits, maybe more.  */
-      i = mips_build_integer (codes, CONST_HIGH_PART (value));
-      codes[i].code = PLUS;
-      codes[i].value = CONST_LOW_PART (value);
-    }
-  else
-    {
-      i = mips_build_integer (codes, high);
-      codes[i].code = IOR;
-      codes[i].value = value & 0xffff;
-    }
-  return i + 1;
-}
-
-
-/* Fill CODES with a sequence of rtl operations to load VALUE.
-   Return the number of operations needed.  */
-
-static unsigned int
-mips_build_integer (struct mips_integer_op *codes,
-                   unsigned HOST_WIDE_INT value)
-{
-  if (SMALL_OPERAND (value)
-      || SMALL_OPERAND_UNSIGNED (value)
-      || LUI_OPERAND (value))
-    {
-      /* The value can be loaded with a single instruction.  */
-      codes[0].code = UNKNOWN;
-      codes[0].value = value;
-      return 1;
-    }
-  else if ((value & 1) != 0 || LUI_OPERAND (CONST_HIGH_PART (value)))
-    {
-      /* Either the constant is a simple LUI/ORI combination or its
-        lowest bit is set.  We don't want to shift in this case.  */
-      return mips_build_lower (codes, value);
-    }
-  else if ((value & 0xffff) == 0)
-    {
-      /* The constant will need at least three actions.  The lowest
-        16 bits are clear, so the final action will be a shift.  */
-      return mips_build_shift (codes, value);
-    }
-  else
-    {
-      /* The final action could be a shift, add or inclusive OR.
-        Rather than use a complex condition to select the best
-        approach, try both mips_build_shift and mips_build_lower
-        and pick the one that gives the shortest sequence.
-        Note that this case is only used once per constant.  */
-      struct mips_integer_op alt_codes[MIPS_MAX_INTEGER_OPS];
-      unsigned int cost, alt_cost;
-
-      cost = mips_build_shift (codes, value);
-      alt_cost = mips_build_lower (alt_codes, value);
-      if (alt_cost < cost)
-       {
-         memcpy (codes, alt_codes, alt_cost * sizeof (codes[0]));
-         cost = alt_cost;
-       }
-      return cost;
-    }
-}
-
-
-/* Load VALUE into DEST, using TEMP as a temporary register if need be.  */
-
-void
-mips_move_integer (rtx dest, rtx temp, unsigned HOST_WIDE_INT value)
-{
-  struct mips_integer_op codes[MIPS_MAX_INTEGER_OPS];
-  enum machine_mode mode;
-  unsigned int i, cost;
-  rtx x;
-
-  mode = GET_MODE (dest);
-  cost = mips_build_integer (codes, value);
+  mode = GET_MODE (dest);
+  num_ops = mips_build_integer (codes, value);
 
   /* Apply each binary operation to X.  Invariant: X is a legitimate
      source operand for a SET pattern.  */
   x = GEN_INT (codes[0].value);
-  for (i = 1; i < cost; i++)
+  for (i = 1; i < num_ops; i++)
     {
       if (!can_create_pseudo_p ())
        {
@@ -2657,7 +2515,6 @@ mips_move_integer (rtx dest, rtx temp, unsigned HOST_WIDE_INT value)
   emit_insn (gen_rtx_SET (VOIDmode, dest, x));
 }
 
-
 /* Subroutine of mips_legitimize_move.  Move constant SRC into register
    DEST given that SRC satisfies immediate_operand but doesn't satisfy
    move_operand.  */
@@ -2681,7 +2538,8 @@ mips_legitimize_const_move (enum machine_mode mode, rtx dest, rtx src)
       return;
     }
 
-  if (mips_tls_operand_p (src))
+  /* Generate the appropriate access sequences for TLS symbols.  */
+  if (mips_tls_symbol_p (src))
     {
       mips_emit_move (dest, mips_legitimize_tls_address (src));
       return;
@@ -2697,7 +2555,7 @@ mips_legitimize_const_move (enum machine_mode mode, rtx dest, rtx src)
          || (!TARGET_MIPS16 && can_create_pseudo_p ())))
     {
       base = mips_force_temporary (dest, base);
-      mips_emit_move (dest, mips_add_offset (0, base, INTVAL (offset)));
+      mips_emit_move (dest, mips_add_offset (NULL, base, INTVAL (offset)));
       return;
     }
 
@@ -2709,8 +2567,7 @@ mips_legitimize_const_move (enum machine_mode mode, rtx dest, rtx src)
   mips_emit_move (dest, src);
 }
 
-
-/* If (set DEST SRC) is not a valid instruction, emit an equivalent
+/* If (set DEST SRC) is not a valid move instruction, emit an equivalent
    sequence that is valid.  */
 
 bool
@@ -2729,18 +2586,18 @@ mips_legitimize_move (enum machine_mode mode, rtx dest, rtx src)
     {
       int other_regno = REGNO (src) == HI_REGNUM ? LO_REGNUM : HI_REGNUM;
       if (GET_MODE_SIZE (mode) <= 4)
-       emit_insn (gen_mfhilo_si (gen_rtx_REG (SImode, REGNO (dest)),
-                                 gen_rtx_REG (SImode, REGNO (src)),
+       emit_insn (gen_mfhilo_si (gen_lowpart (SImode, dest),
+                                 gen_lowpart (SImode, src),
                                  gen_rtx_REG (SImode, other_regno)));
       else
-       emit_insn (gen_mfhilo_di (gen_rtx_REG (DImode, REGNO (dest)),
-                                 gen_rtx_REG (DImode, REGNO (src)),
+       emit_insn (gen_mfhilo_di (gen_lowpart (DImode, dest),
+                                 gen_lowpart (DImode, src),
                                  gen_rtx_REG (DImode, other_regno)));
       return true;
     }
 
   /* We need to deal with constants that would be legitimate
-     immediate_operands but not legitimate move_operands.  */
+     immediate_operands but aren't legitimate move_operands.  */
   if (CONSTANT_P (src) && !move_operand (src, mode))
     {
       mips_legitimize_const_move (mode, dest, src);
@@ -2750,17 +2607,93 @@ mips_legitimize_move (enum machine_mode mode, rtx dest, rtx src)
   return false;
 }
 \f
-/* We need a lot of little routines to check constant values on the
-   mips16.  These are used to figure out how long the instruction will
-   be.  It would be much better to do this using constraints, but
-   there aren't nearly enough letters available.  */
+/* Return true if value X in context CONTEXT is a small-data address
+   that can be rewritten as a LO_SUM.  */
+
+static bool
+mips_rewrite_small_data_p (rtx x, enum mips_symbol_context context)
+{
+  enum mips_symbol_type symbol_type;
+
+  return (TARGET_EXPLICIT_RELOCS
+         && mips_symbolic_constant_p (x, context, &symbol_type)
+         && symbol_type == SYMBOL_GP_RELATIVE);
+}
+
+/* A for_each_rtx callback for mips_small_data_pattern_p.  DATA is the
+   containing MEM, or null if none.  */
+
+static int
+mips_small_data_pattern_1 (rtx *loc, void *data)
+{
+  enum mips_symbol_context context;
+
+  if (GET_CODE (*loc) == LO_SUM)
+    return -1;
+
+  if (MEM_P (*loc))
+    {
+      if (for_each_rtx (&XEXP (*loc, 0), mips_small_data_pattern_1, *loc))
+       return 1;
+      return -1;
+    }
+
+  context = data ? SYMBOL_CONTEXT_MEM : SYMBOL_CONTEXT_LEA;
+  return mips_rewrite_small_data_p (*loc, context);
+}
+
+/* Return true if OP refers to small data symbols directly, not through
+   a LO_SUM.  */
+
+bool
+mips_small_data_pattern_p (rtx op)
+{
+  return for_each_rtx (&op, mips_small_data_pattern_1, NULL);
+}
+
+/* A for_each_rtx callback, used by mips_rewrite_small_data.
+   DATA is the containing MEM, or null if none.  */
+
+static int
+mips_rewrite_small_data_1 (rtx *loc, void *data)
+{
+  enum mips_symbol_context context;
+
+  if (MEM_P (*loc))
+    {
+      for_each_rtx (&XEXP (*loc, 0), mips_rewrite_small_data_1, *loc);
+      return -1;
+    }
+
+  context = data ? SYMBOL_CONTEXT_MEM : SYMBOL_CONTEXT_LEA;
+  if (mips_rewrite_small_data_p (*loc, context))
+    *loc = gen_rtx_LO_SUM (Pmode, pic_offset_table_rtx, *loc);
+
+  if (GET_CODE (*loc) == LO_SUM)
+    return -1;
+
+  return 0;
+}
+
+/* Rewrite instruction pattern PATTERN so that it refers to small data
+   using explicit relocations.  */
+
+rtx
+mips_rewrite_small_data (rtx pattern)
+{
+  pattern = copy_insn (pattern);
+  for_each_rtx (&pattern, mips_rewrite_small_data_1, NULL);
+  return pattern;
+}
+\f
+/* We need a lot of little routines to check the range of MIPS16 immediate
+   operands.  */
 
 static int
 m16_check_op (rtx op, int low, int high, int mask)
 {
   return (GET_CODE (op) == CONST_INT
-         && INTVAL (op) >= low
-         && INTVAL (op) <= high
+         && IN_RANGE (INTVAL (op), low, high)
          && (INTVAL (op) & mask) == 0);
 }
 
@@ -2773,49 +2706,49 @@ m16_uimm3_b (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 int
 m16_simm4_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, - 0x8, 0x7, 0);
+  return m16_check_op (op, -0x8, 0x7, 0);
 }
 
 int
 m16_nsimm4_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, - 0x7, 0x8, 0);
+  return m16_check_op (op, -0x7, 0x8, 0);
 }
 
 int
 m16_simm5_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, - 0x10, 0xf, 0);
+  return m16_check_op (op, -0x10, 0xf, 0);
 }
 
 int
 m16_nsimm5_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, - 0xf, 0x10, 0);
+  return m16_check_op (op, -0xf, 0x10, 0);
 }
 
 int
 m16_uimm5_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, (- 0x10) << 2, 0xf << 2, 3);
+  return m16_check_op (op, -0x10 << 2, 0xf << 2, 3);
 }
 
 int
 m16_nuimm5_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, (- 0xf) << 2, 0x10 << 2, 3);
+  return m16_check_op (op, -0xf << 2, 0x10 << 2, 3);
 }
 
 int
 m16_simm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, - 0x80, 0x7f, 0);
+  return m16_check_op (op, -0x80, 0x7f, 0);
 }
 
 int
 m16_nsimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, - 0x7f, 0x80, 0);
+  return m16_check_op (op, -0x7f, 0x80, 0);
 }
 
 int
@@ -2827,13 +2760,13 @@ m16_uimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 int
 m16_nuimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, - 0xff, 0x0, 0);
+  return m16_check_op (op, -0xff, 0x0, 0);
 }
 
 int
 m16_uimm8_m1_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, - 0x1, 0xfe, 0);
+  return m16_check_op (op, -0x1, 0xfe, 0);
 }
 
 int
@@ -2845,44 +2778,23 @@ m16_uimm8_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 int
 m16_nuimm8_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, (- 0xff) << 2, 0x0, 3);
+  return m16_check_op (op, -0xff << 2, 0x0, 3);
 }
 
 int
 m16_simm8_8 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, (- 0x80) << 3, 0x7f << 3, 7);
+  return m16_check_op (op, -0x80 << 3, 0x7f << 3, 7);
 }
 
 int
 m16_nsimm8_8 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
 {
-  return m16_check_op (op, (- 0x7f) << 3, 0x80 << 3, 7);
+  return m16_check_op (op, -0x7f << 3, 0x80 << 3, 7);
 }
 \f
-/* Return true if ADDR matches the pattern for the lwxs load scaled indexed
-   address instruction.  */
-
-static bool
-mips_lwxs_address_p (rtx addr)
-{
-  if (ISA_HAS_LWXS
-      && GET_CODE (addr) == PLUS
-      && REG_P (XEXP (addr, 1)))
-    {
-      rtx offset = XEXP (addr, 0);
-      if (GET_CODE (offset) == MULT
-         && REG_P (XEXP (offset, 0))
-         && GET_CODE (XEXP (offset, 1)) == CONST_INT
-         && INTVAL (XEXP (offset, 1)) == 4)
-       return true;
-    }
-  return false;
-}
-
 /* The cost of loading values from the constant pool.  It should be
    larger than the cost of any constant we want to synthesize inline.  */
-
 #define CONSTANT_POOL_COST COSTS_N_INSNS (TARGET_MIPS16 ? 4 : 8)
 
 /* Return the cost of X when used as an operand to the MIPS16 instruction
@@ -3098,7 +3010,7 @@ mips_rtx_costs (rtx x, int code, int outer_code, int *total)
   /* The cost of a COMPARE is hard to define for MIPS.  COMPAREs don't
      appear in the instruction stream, and the cost of a comparison is
      really the cost of the branch or scc condition.  At the time of
-     writing, gcc only uses an explicit outer COMPARE code when optabs
+     writing, GCC only uses an explicit outer COMPARE code when optabs
      is testing whether a constant is expensive enough to force into a
      register.  We want optabs to pass such constants through the MIPS
      expanders instead, so make all constants very cheap here.  */
@@ -3295,7 +3207,7 @@ mips_rtx_costs (rtx x, int code, int outer_code, int *total)
 
     case MINUS:
       if (float_mode_p
-         && ISA_HAS_NMADD_NMSUB
+         && ISA_HAS_NMADD_NMSUB (mode)
          && TARGET_FUSED_MADD
          && !HONOR_NANS (mode)
          && !HONOR_SIGNED_ZEROS (mode))
@@ -3326,6 +3238,8 @@ mips_rtx_costs (rtx x, int code, int outer_code, int *total)
     case PLUS:
       if (float_mode_p)
        {
+         /* If this is part of a MADD or MSUB, treat the PLUS as
+            being free.  */
          if (ISA_HAS_FP4
              && TARGET_FUSED_MADD
              && GET_CODE (XEXP (x, 0)) == MULT)
@@ -3344,7 +3258,7 @@ mips_rtx_costs (rtx x, int code, int outer_code, int *total)
 
     case NEG:
       if (float_mode_p
-         && ISA_HAS_NMADD_NMSUB
+         && ISA_HAS_NMADD_NMSUB (mode)
          && TARGET_FUSED_MADD
          && !HONOR_NANS (mode)
          && HONOR_SIGNED_ZEROS (mode))
@@ -3388,22 +3302,18 @@ mips_rtx_costs (rtx x, int code, int outer_code, int *total)
 
     case DIV:
       /* Check for a reciprocal.  */
-      if (float_mode_p && XEXP (x, 0) == CONST1_RTX (mode))
-       {
-         if (ISA_HAS_FP4
-             && flag_unsafe_math_optimizations
-             && (outer_code == SQRT || GET_CODE (XEXP (x, 1)) == SQRT))
-           {
-             /* An rsqrt<mode>a or rsqrt<mode>b pattern.  Count the
-                division as being free.  */
-             *total = rtx_cost (XEXP (x, 1), 0);
-             return true;
-           }
-         if (!ISA_MIPS1)
-           {
-             *total = mips_fp_div_cost (mode) + rtx_cost (XEXP (x, 1), 0);
-             return true;
-           }
+      if (float_mode_p
+         && ISA_HAS_FP4
+         && flag_unsafe_math_optimizations
+         && XEXP (x, 0) == CONST1_RTX (mode))
+       {
+         if (outer_code == SQRT || GET_CODE (XEXP (x, 1)) == SQRT)
+           /* An rsqrt<mode>a or rsqrt<mode>b pattern.  Count the
+              division as being free.  */
+           *total = rtx_cost (XEXP (x, 1), 0);
+         else
+           *total = mips_fp_div_cost (mode) + rtx_cost (XEXP (x, 1), 0);
+         return true;
        }
       /* Fall through.  */
 
@@ -3462,8 +3372,7 @@ mips_rtx_costs (rtx x, int code, int outer_code, int *total)
     }
 }
 
-/* Provide the costs of an addressing mode that contains ADDR.
-   If ADDR is not a valid address, its cost is irrelevant.  */
+/* Implement TARGET_ADDRESS_COST.  */
 
 static int
 mips_address_cost (rtx addr)
@@ -3476,9 +3385,9 @@ mips_address_cost (rtx addr)
    false to select the low part.  */
 
 rtx
-mips_subword (rtx op, int high_p)
+mips_subword (rtx op, bool high_p)
 {
-  unsigned int byte;
+  unsigned int byte, offset;
   enum machine_mode mode;
 
   mode = GET_MODE (op);
@@ -3491,7 +3400,11 @@ mips_subword (rtx op, int high_p)
     byte = 0;
 
   if (FP_REG_RTX_P (op))
-    return gen_rtx_REG (word_mode, high_p ? REGNO (op) + 1 : REGNO (op));
+    {
+      /* Paired FPRs are always ordered little-endian.  */
+      offset = (UNITS_PER_WORD < UNITS_PER_HWFPVALUE ? high_p : byte != 0);
+      return gen_rtx_REG (word_mode, REGNO (op) + offset);
+    }
 
   if (MEM_P (op))
     return mips_rewrite_small_data (adjust_address (op, word_mode, byte));
@@ -3499,7 +3412,6 @@ mips_subword (rtx op, int high_p)
   return simplify_gen_subreg (word_mode, op, mode, byte);
 }
 
-
 /* Return true if a 64-bit move from SRC to DEST should be split into two.  */
 
 bool
@@ -3508,13 +3420,13 @@ mips_split_64bit_move_p (rtx dest, rtx src)
   if (TARGET_64BIT)
     return false;
 
-  /* FP->FP moves can be done in a single instruction.  */
+  /* FPR-to-FPR moves can be done in a single instruction, if they're
+     allowed at all.  */
   if (FP_REG_RTX_P (src) && FP_REG_RTX_P (dest))
     return false;
 
-  /* Check for floating-point loads and stores.  They can be done using
-     ldc1 and sdc1 on MIPS II and above.  */
-  if (mips_isa > 1)
+  /* Check for floating-point loads and stores.  */
+  if (ISA_HAS_LDC1_SDC1)
     {
       if (FP_REG_RTX_P (dest) && MEM_P (src))
        return false;
@@ -3524,57 +3436,25 @@ mips_split_64bit_move_p (rtx dest, rtx src)
   return true;
 }
 
-
-/* Split a 64-bit move from SRC to DEST assuming that
-   mips_split_64bit_move_p holds.
-
-   Moves into and out of FPRs cause some difficulty here.  Such moves
-   will always be DFmode, since paired FPRs are not allowed to store
-   DImode values.  The most natural representation would be two separate
-   32-bit moves, such as:
-
-       (set (reg:SI $f0) (mem:SI ...))
-       (set (reg:SI $f1) (mem:SI ...))
-
-   However, the second insn is invalid because odd-numbered FPRs are
-   not allowed to store independent values.  Use the patterns load_df_low,
-   load_df_high and store_df_high instead.  */
+/* Split a doubleword move from SRC to DEST.  On 32-bit targets,
+   this function handles 64-bit moves for which mips_split_64bit_move_p
+   holds.  For 64-bit targets, this function handles 128-bit moves.  */
 
 void
-mips_split_64bit_move (rtx dest, rtx src)
-{
-  if (FP_REG_RTX_P (dest))
-    {
-      /* Loading an FPR from memory or from GPRs.  */
-      if (ISA_HAS_MXHC1)
-       {
-         dest = gen_lowpart (DFmode, dest);
-         emit_insn (gen_load_df_low (dest, mips_subword (src, 0)));
-         emit_insn (gen_mthc1 (dest, mips_subword (src, 1),
-                               copy_rtx (dest)));
-       }
-      else
-       {
-         emit_insn (gen_load_df_low (copy_rtx (dest),
-                                     mips_subword (src, 0)));
-         emit_insn (gen_load_df_high (dest, mips_subword (src, 1),
-                                      copy_rtx (dest)));
-       }
-    }
-  else if (FP_REG_RTX_P (src))
-    {
-      /* Storing an FPR into memory or GPRs.  */
-      if (ISA_HAS_MXHC1)
-       {
-         src = gen_lowpart (DFmode, src);
-         mips_emit_move (mips_subword (dest, 0), mips_subword (src, 0));
-         emit_insn (gen_mfhc1 (mips_subword (dest, 1), src));
-       }
+mips_split_doubleword_move (rtx dest, rtx src)
+{
+  if (FP_REG_RTX_P (dest) || FP_REG_RTX_P (src))
+    {
+      if (!TARGET_64BIT && GET_MODE (dest) == DImode)
+       emit_insn (gen_move_doubleword_fprdi (dest, src));
+      else if (!TARGET_64BIT && GET_MODE (dest) == DFmode)
+       emit_insn (gen_move_doubleword_fprdf (dest, src));
+      else if (!TARGET_64BIT && GET_MODE (dest) == V2SFmode)
+       emit_insn (gen_move_doubleword_fprv2sf (dest, src));
+      else if (TARGET_64BIT && GET_MODE (dest) == TFmode)
+       emit_insn (gen_move_doubleword_fprtf (dest, src));
       else
-       {
-         mips_emit_move (mips_subword (dest, 0), mips_subword (src, 0));
-         emit_insn (gen_store_df_high (mips_subword (dest, 1), src));
-       }
+       gcc_unreachable ();
     }
   else
     {
@@ -3582,17 +3462,17 @@ mips_split_64bit_move (rtx dest, rtx src)
         which order to do them.  */
       rtx low_dest;
 
-      low_dest = mips_subword (dest, 0);
+      low_dest = mips_subword (dest, false);
       if (REG_P (low_dest)
          && reg_overlap_mentioned_p (low_dest, src))
        {
-         mips_emit_move (mips_subword (dest, 1), mips_subword (src, 1));
-         mips_emit_move (low_dest, mips_subword (src, 0));
+         mips_emit_move (mips_subword (dest, true), mips_subword (src, true));
+         mips_emit_move (low_dest, mips_subword (src, false));
        }
       else
        {
-         mips_emit_move (low_dest, mips_subword (src, 0));
-         mips_emit_move (mips_subword (dest, 1), mips_subword (src, 1));
+         mips_emit_move (low_dest, mips_subword (src, false));
+         mips_emit_move (mips_subword (dest, true), mips_subword (src, true));
        }
     }
 }
@@ -3604,18 +3484,20 @@ const char *
 mips_output_move (rtx dest, rtx src)
 {
   enum rtx_code dest_code, src_code;
+  enum machine_mode mode;
   enum mips_symbol_type symbol_type;
   bool dbl_p;
 
   dest_code = GET_CODE (dest);
   src_code = GET_CODE (src);
-  dbl_p = (GET_MODE_SIZE (GET_MODE (dest)) == 8);
+  mode = GET_MODE (dest);
+  dbl_p = (GET_MODE_SIZE (mode) == 8);
 
   if (dbl_p && mips_split_64bit_move_p (dest, src))
     return "#";
 
   if ((src_code == REG && GP_REG_P (REGNO (src)))
-      || (!TARGET_MIPS16 && src == CONST0_RTX (GET_MODE (dest))))
+      || (!TARGET_MIPS16 && src == CONST0_RTX (mode)))
     {
       if (dest_code == REG)
        {
@@ -3628,66 +3510,72 @@ mips_output_move (rtx dest, rtx src)
          if (DSP_ACC_REG_P (REGNO (dest)))
            {
              static char retval[] = "mt__\t%z1,%q0";
+
              retval[2] = reg_names[REGNO (dest)][4];
              retval[3] = reg_names[REGNO (dest)][5];
              return retval;
            }
 
          if (FP_REG_P (REGNO (dest)))
-           return (dbl_p ? "dmtc1\t%z1,%0" : "mtc1\t%z1,%0");
+           return dbl_p ? "dmtc1\t%z1,%0" : "mtc1\t%z1,%0";
 
          if (ALL_COP_REG_P (REGNO (dest)))
            {
              static char retval[] = "dmtc_\t%z1,%0";
 
              retval[4] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (dest));
-             return (dbl_p ? retval : retval + 1);
+             return dbl_p ? retval : retval + 1;
            }
        }
       if (dest_code == MEM)
-       return (dbl_p ? "sd\t%z1,%0" : "sw\t%z1,%0");
+       return dbl_p ? "sd\t%z1,%0" : "sw\t%z1,%0";
     }
   if (dest_code == REG && GP_REG_P (REGNO (dest)))
     {
       if (src_code == REG)
        {
+         /* Handled by separate patterns.  */
+         gcc_assert (!MD_REG_P (REGNO (src)));
+
          if (DSP_ACC_REG_P (REGNO (src)))
            {
              static char retval[] = "mf__\t%0,%q1";
+
              retval[2] = reg_names[REGNO (src)][4];
              retval[3] = reg_names[REGNO (src)][5];
              return retval;
            }
 
-         if (ST_REG_P (REGNO (src)) && ISA_HAS_8CC)
-           return "lui\t%0,0x3f80\n\tmovf\t%0,%.,%1";
-
          if (FP_REG_P (REGNO (src)))
-           return (dbl_p ? "dmfc1\t%0,%1" : "mfc1\t%0,%1");
+           return dbl_p ? "dmfc1\t%0,%1" : "mfc1\t%0,%1";
 
          if (ALL_COP_REG_P (REGNO (src)))
            {
              static char retval[] = "dmfc_\t%0,%1";
 
              retval[4] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (src));
-             return (dbl_p ? retval : retval + 1);
+             return dbl_p ? retval : retval + 1;
            }
+
+         if (ST_REG_P (REGNO (src)) && ISA_HAS_8CC)
+           return "lui\t%0,0x3f80\n\tmovf\t%0,%.,%1";
        }
 
       if (src_code == MEM)
-       return (dbl_p ? "ld\t%0,%1" : "lw\t%0,%1");
+       return dbl_p ? "ld\t%0,%1" : "lw\t%0,%1";
 
       if (src_code == CONST_INT)
        {
-         /* Don't use the X format, because that will give out of
-            range numbers for 64-bit hosts and 32-bit targets.  */
+         /* Don't use the X format for the operand itself, because that
+            will give out-of-range numbers for 64-bit hosts and 32-bit
+            targets.  */
          if (!TARGET_MIPS16)
            return "li\t%0,%1\t\t\t# %X1";
 
-         if (INTVAL (src) >= 0 && INTVAL (src) <= 0xffff)
+         if (SMALL_OPERAND_UNSIGNED (INTVAL (src)))
            return "li\t%0,%1";
 
-         if (INTVAL (src) < 0 && INTVAL (src) >= -0xffff)
+         if (SMALL_OPERAND_UNSIGNED (-INTVAL (src)))
            return "#";
        }
 
@@ -3711,7 +3599,7 @@ mips_output_move (rtx dest, rtx src)
          gcc_assert (TARGET_MIPS16
                      ? TARGET_MIPS16_TEXT_LOADS
                      : !TARGET_EXPLICIT_RELOCS);
-         return (dbl_p ? "dla\t%0,%1" : "la\t%0,%1");
+         return dbl_p ? "dla\t%0,%1" : "la\t%0,%1";
        }
     }
   if (src_code == REG && FP_REG_P (REGNO (src)))
@@ -3721,16 +3609,16 @@ mips_output_move (rtx dest, rtx src)
          if (GET_MODE (dest) == V2SFmode)
            return "mov.ps\t%0,%1";
          else
-           return (dbl_p ? "mov.d\t%0,%1" : "mov.s\t%0,%1");
+           return dbl_p ? "mov.d\t%0,%1" : "mov.s\t%0,%1";
        }
 
       if (dest_code == MEM)
-       return (dbl_p ? "sdc1\t%1,%0" : "swc1\t%1,%0");
+       return dbl_p ? "sdc1\t%1,%0" : "swc1\t%1,%0";
     }
   if (dest_code == REG && FP_REG_P (REGNO (dest)))
     {
       if (src_code == MEM)
-       return (dbl_p ? "ldc1\t%0,%1" : "lwc1\t%0,%1");
+       return dbl_p ? "ldc1\t%0,%1" : "lwc1\t%0,%1";
     }
   if (dest_code == REG && ALL_COP_REG_P (REGNO (dest)) && src_code == MEM)
     {
@@ -3751,42 +3639,11 @@ mips_output_move (rtx dest, rtx src)
   gcc_unreachable ();
 }
 \f
-/* Restore $gp from its save slot.  Valid only when using o32 or
-   o64 abicalls.  */
-
-void
-mips_restore_gp (void)
-{
-  rtx address, slot;
-
-  gcc_assert (TARGET_ABICALLS && TARGET_OLDABI);
-
-  address = mips_add_offset (pic_offset_table_rtx,
-                            frame_pointer_needed
-                            ? hard_frame_pointer_rtx
-                            : stack_pointer_rtx,
-                            current_function_outgoing_args_size);
-  slot = gen_rtx_MEM (Pmode, address);
-
-  mips_emit_move (pic_offset_table_rtx, slot);
-  if (!TARGET_EXPLICIT_RELOCS)
-    emit_insn (gen_blockage ());
-}
-\f
-/* Emit an instruction of the form (set TARGET (CODE OP0 OP1)).  */
-
-static void
-mips_emit_binary (enum rtx_code code, rtx target, rtx op0, rtx op1)
-{
-  emit_insn (gen_rtx_SET (VOIDmode, target,
-                         gen_rtx_fmt_ee (code, GET_MODE (target), op0, op1)));
-}
-
-/* Return true if CMP1 is a suitable second operand for relational
-   operator CODE.  See also the *sCC patterns in mips.md.  */
+/* Return true if CMP1 is a suitable second operand for integer ordering
+   test CODE.  See also the *sCC patterns in mips.md.  */
 
 static bool
-mips_relational_operand_ok_p (enum rtx_code code, rtx cmp1)
+mips_int_order_operand_ok_p (enum rtx_code code, rtx cmp1)
 {
   switch (code)
     {
@@ -3813,79 +3670,78 @@ mips_relational_operand_ok_p (enum rtx_code code, rtx cmp1)
     }
 }
 
-/* Canonicalize LE or LEU comparisons into LT comparisons when
-   possible to avoid extra instructions or inverting the
-   comparison.  */
+/* Return true if *CMP1 (of mode MODE) is a valid second operand for
+   integer ordering test *CODE, or if an equivalent combination can
+   be formed by adjusting *CODE and *CMP1.  When returning true, update
+   *CODE and *CMP1 with the chosen code and operand, otherwise leave
+   them alone.  */
 
 static bool
-mips_canonicalize_comparison (enum rtx_code *code, rtx *cmp1,
-                             enum machine_mode mode)
+mips_canonicalize_int_order_test (enum rtx_code *code, rtx *cmp1,
+                                 enum machine_mode mode)
 {
-  HOST_WIDE_INT original, plus_one;
+  HOST_WIDE_INT plus_one;
 
-  if (GET_CODE (*cmp1) != CONST_INT)
-    return false;
+  if (mips_int_order_operand_ok_p (*code, *cmp1))
+    return true;
 
-  original = INTVAL (*cmp1);
-  plus_one = trunc_int_for_mode ((unsigned HOST_WIDE_INT) original + 1, mode);
+  if (GET_CODE (*cmp1) == CONST_INT)
+    switch (*code)
+      {
+      case LE:
+       plus_one = trunc_int_for_mode (UINTVAL (*cmp1) + 1, mode);
+       if (INTVAL (*cmp1) < plus_one)
+         {
+           *code = LT;
+           *cmp1 = force_reg (mode, GEN_INT (plus_one));
+           return true;
+         }
+       break;
 
-  switch (*code)
-    {
-    case LE:
-      if (original < plus_one)
-       {
-         *code = LT;
-         *cmp1 = force_reg (mode, GEN_INT (plus_one));
-         return true;
-       }
-      break;
-
-    case LEU:
-      if (plus_one != 0)
-       {
-         *code = LTU;
-         *cmp1 = force_reg (mode, GEN_INT (plus_one));
-         return true;
-       }
-      break;
-
-    default:
-      return false;
-   }
+      case LEU:
+       plus_one = trunc_int_for_mode (UINTVAL (*cmp1) + 1, mode);
+       if (plus_one != 0)
+         {
+           *code = LTU;
+           *cmp1 = force_reg (mode, GEN_INT (plus_one));
+           return true;
+         }
+       break;
 
+      default:
+       break;
+      }
   return false;
-
 }
 
-/* Compare CMP0 and CMP1 using relational operator CODE and store the
-   result in TARGET.  CMP0 and TARGET are register_operands that have
-   the same integer mode.  If INVERT_PTR is nonnull, it's OK to set
-   TARGET to the inverse of the result and flip *INVERT_PTR instead.  */
+/* Compare CMP0 and CMP1 using ordering test CODE and store the result
+   in TARGET.  CMP0 and TARGET are register_operands that have the same
+   integer mode.  If INVERT_PTR is nonnull, it's OK to set TARGET to the
+   inverse of the result and flip *INVERT_PTR instead.  */
 
 static void
-mips_emit_int_relational (enum rtx_code code, bool *invert_ptr,
+mips_emit_int_order_test (enum rtx_code code, bool *invert_ptr,
                          rtx target, rtx cmp0, rtx cmp1)
 {
-  /* First see if there is a MIPS instruction that can do this operation
-     with CMP1 in its current form. If not, try to canonicalize the
-     comparison to LT. If that fails, try doing the same for the
-     inverse operation.  If that also fails, force CMP1 into a register
-     and try again.  */
-  if (mips_relational_operand_ok_p (code, cmp1))
-    mips_emit_binary (code, target, cmp0, cmp1);
-  else if (mips_canonicalize_comparison (&code, &cmp1, GET_MODE (target)))
+  enum machine_mode mode;
+
+  /* First see if there is a MIPS instruction that can do this operation.
+     If not, try doing the same for the inverse operation.  If that also
+     fails, force CMP1 into a register and try again.  */
+  mode = GET_MODE (target);
+  if (mips_canonicalize_int_order_test (&code, &cmp1, mode))
     mips_emit_binary (code, target, cmp0, cmp1);
   else
     {
       enum rtx_code inv_code = reverse_condition (code);
-      if (!mips_relational_operand_ok_p (inv_code, cmp1))
+      if (!mips_canonicalize_int_order_test (&inv_code, &cmp1, mode))
        {
-         cmp1 = force_reg (GET_MODE (cmp0), cmp1);
-         mips_emit_int_relational (code, invert_ptr, target, cmp0, cmp1);
+         cmp1 = force_reg (mode, cmp1);
+         mips_emit_int_order_test (code, invert_ptr, target, cmp0, cmp1);
        }
       else if (invert_ptr == 0)
        {
-         rtx inv_target = gen_reg_rtx (GET_MODE (target));
+         rtx inv_target = gen_reg_rtx (mode);
          mips_emit_binary (inv_code, inv_target, cmp0, cmp1);
          mips_emit_binary (XOR, target, inv_target, const1_rtx);
        }
@@ -3915,12 +3771,12 @@ mips_zero_if_equal (rtx cmp0, rtx cmp1)
 }
 
 /* Convert *CODE into a code that can be used in a floating-point
-   scc instruction (c.<cond>.<fmt>).  Return true if the values of
+   scc instruction (C.cond.fmt).  Return true if the values of
    the condition code registers will be inverted, with 0 indicating
    that the condition holds.  */
 
 static bool
-mips_reverse_fp_cond_p (enum rtx_code *code)
+mips_reversed_fp_cond (enum rtx_code *code)
 {
   switch (*code)
     {
@@ -3940,11 +3796,11 @@ mips_reverse_fp_cond_p (enum rtx_code *code)
    being compared and *CODE is the code used to compare them.
 
    Update *CODE, *OP0 and *OP1 so that they describe the final comparison.
-   If NEED_EQ_NE_P, then only EQ/NE comparisons against zero are possible,
+   If NEED_EQ_NE_P, then only EQ or NE comparisons against zero are possible,
    otherwise any standard branch condition can be used.  The standard branch
    conditions are:
 
-      - EQ/NE between two registers.
+      - EQ or NE between two registers.
       - any comparison between a register and zero.  */
 
 static void
@@ -3976,10 +3832,10 @@ mips_emit_compare (enum rtx_code *code, rtx *op0, rtx *op1, bool need_eq_ne_p)
             result of the scc in *OP0 and compare it against zero.  */
          bool invert = false;
          *op0 = gen_reg_rtx (GET_MODE (cmp_operands[0]));
-         *op1 = const0_rtx;
-         mips_emit_int_relational (*code, &invert, *op0,
+         mips_emit_int_order_test (*code, &invert, *op0,
                                    cmp_operands[0], cmp_operands[1]);
          *code = (invert ? EQ : NE);
+         *op1 = const0_rtx;
        }
     }
   else if (ALL_FIXED_POINT_MODE_P (GET_MODE (cmp_operands[0])))
@@ -3993,14 +3849,14 @@ mips_emit_compare (enum rtx_code *code, rtx *op0, rtx *op1, bool need_eq_ne_p)
     {
       enum rtx_code cmp_code;
 
-      /* Floating-point tests use a separate c.cond.fmt comparison to
+      /* Floating-point tests use a separate C.cond.fmt comparison to
         set a condition code register.  The branch or conditional move
         will then compare that register against zero.
 
         Set CMP_CODE to the code of the comparison instruction and
         *CODE to the code that the branch or move should use.  */
       cmp_code = *code;
-      *code = mips_reverse_fp_cond_p (&cmp_code) ? EQ : NE;
+      *code = mips_reversed_fp_cond (&cmp_code) ? EQ : NE;
       *op0 = (ISA_HAS_8CC
              ? gen_reg_rtx (CCmode)
              : gen_rtx_REG (CCmode, FPSW_REGNUM));
@@ -4015,7 +3871,7 @@ mips_emit_compare (enum rtx_code *code, rtx *op0, rtx *op1, bool need_eq_ne_p)
    On 64-bit targets, TARGET may be wider than cmp_operands[0].  */
 
 bool
-mips_emit_scc (enum rtx_code code, rtx target)
+mips_expand_scc (enum rtx_code code, rtx target)
 {
   if (GET_MODE_CLASS (GET_MODE (cmp_operands[0])) != MODE_INT)
     return false;
@@ -4027,17 +3883,16 @@ mips_emit_scc (enum rtx_code code, rtx target)
       mips_emit_binary (code, target, zie, const0_rtx);
     }
   else
-    mips_emit_int_relational (code, 0, target,
+    mips_emit_int_order_test (code, 0, target,
                              cmp_operands[0], cmp_operands[1]);
   return true;
 }
 
-/* Emit the common code for doing conditional branches.
-   operand[0] is the label to jump to.
-   The comparison operands are saved away by cmp{si,di,sf,df}.  */
+/* Compare cmp_operands[0] with cmp_operands[1] using comparison code
+   CODE and jump to OPERANDS[0] if the condition holds.  */
 
 void
-gen_conditional_branch (rtx *operands, enum rtx_code code)
+mips_expand_conditional_branch (rtx *operands, enum rtx_code code)
 {
   rtx op0, op1, condition;
 
@@ -4058,7 +3913,7 @@ mips_expand_vcondv2sf (rtx dest, rtx true_src, rtx false_src,
   rtx cmp_result;
   bool reversed_p;
 
-  reversed_p = mips_reverse_fp_cond_p (&cond);
+  reversed_p = mips_reversed_fp_cond (&cond);
   cmp_result = gen_reg_rtx (CCV2mode);
   emit_insn (gen_scc_ps (cmp_result,
                         gen_rtx_fmt_ee (cond, VOIDmode, cmp_op0, cmp_op1)));
@@ -4070,841 +3925,712 @@ mips_expand_vcondv2sf (rtx dest, rtx true_src, rtx false_src,
                                         cmp_result));
 }
 
-/* Emit the common code for conditional moves.  OPERANDS is the array
-   of operands passed to the conditional move define_expand.  */
+/* Compare cmp_operands[0] with cmp_operands[1] using the code of
+   OPERANDS[1].  Move OPERANDS[2] into OPERANDS[0] if the condition
+   holds, otherwise move OPERANDS[3] into OPERANDS[0].  */
 
 void
-gen_conditional_move (rtx *operands)
+mips_expand_conditional_move (rtx *operands)
 {
   enum rtx_code code;
-  rtx op0, op1;
+  rtx cond, op0, op1;
 
   code = GET_CODE (operands[1]);
   mips_emit_compare (&code, &op0, &op1, true);
+  cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1),
   emit_insn (gen_rtx_SET (VOIDmode, operands[0],
-                         gen_rtx_IF_THEN_ELSE (GET_MODE (operands[0]),
-                                               gen_rtx_fmt_ee (code,
-                                                               GET_MODE (op0),
-                                                               op0, op1),
+                         gen_rtx_IF_THEN_ELSE (GET_MODE (operands[0]), cond,
                                                operands[2], operands[3])));
 }
 
-/* Emit a conditional trap.  OPERANDS is the array of operands passed to
-   the conditional_trap expander.  */
+/* Compare cmp_operands[0] with cmp_operands[1] using rtl code CODE,
+   then trap if the condition holds.  */
 
 void
-mips_gen_conditional_trap (rtx *operands)
+mips_expand_conditional_trap (enum rtx_code code)
 {
   rtx op0, op1;
-  enum rtx_code cmp_code = GET_CODE (operands[0]);
-  enum machine_mode mode = GET_MODE (cmp_operands[0]);
+  enum machine_mode mode;
 
-  /* MIPS conditional trap machine instructions don't have GT or LE
-     flavors, so we must invert the comparison and convert to LT and
-     GE, respectively.  */
-  switch (cmp_code)
-    {
-    case GT: cmp_code = LT; break;
-    case LE: cmp_code = GE; break;
-    case GTU: cmp_code = LTU; break;
-    case LEU: cmp_code = GEU; break;
-    default: break;
-    }
-  if (cmp_code == GET_CODE (operands[0]))
-    {
-      op0 = cmp_operands[0];
-      op1 = cmp_operands[1];
-    }
-  else
+  /* MIPS conditional trap instructions don't have GT or LE flavors,
+     so we must swap the operands and convert to LT and GE respectively.  */
+  switch (code)
     {
+    case GT:
+    case LE:
+    case GTU:
+    case LEU:
+      code = swap_condition (code);
       op0 = cmp_operands[1];
       op1 = cmp_operands[0];
+      break;
+
+    default:
+      op0 = cmp_operands[0];
+      op1 = cmp_operands[1];
+      break;
     }
+
+  mode = GET_MODE (cmp_operands[0]);
   op0 = force_reg (mode, op0);
   if (!arith_operand (op1, mode))
     op1 = force_reg (mode, op1);
 
   emit_insn (gen_rtx_TRAP_IF (VOIDmode,
-                             gen_rtx_fmt_ee (cmp_code, mode, op0, op1),
-                             operands[1]));
+                             gen_rtx_fmt_ee (code, mode, op0, op1),
+                             const0_rtx));
 }
 \f
-/* Return true if function DECL is a MIPS16 function.  Return the ambient
-   setting if DECL is null.  */
+/* Initialize *CUM for a call to a function of type FNTYPE.  */
 
-static bool
-mips_use_mips16_mode_p (tree decl)
+void
+mips_init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype)
 {
-  if (decl)
-    {
-      /* Nested functions must use the same frame pointer as their
-        parent and must therefore use the same ISA mode.  */
-      tree parent = decl_function_context (decl);
-      if (parent)
-       decl = parent;
-      if (mips_mips16_decl_p (decl))
-       return true;
-      if (mips_nomips16_decl_p (decl))
-       return false;
-    }
-  return mips_base_mips16;
+  memset (cum, 0, sizeof (*cum));
+  cum->prototype = (fntype && prototype_p (fntype));
+  cum->gp_reg_found = (cum->prototype && stdarg_p (fntype));
 }
 
-/* Return true if calls to X can use R_MIPS_CALL* relocations.  */
+/* Fill INFO with information about a single argument.  CUM is the
+   cumulative state for earlier arguments.  MODE is the mode of this
+   argument and TYPE is its type (if known).  NAMED is true if this
+   is a named (fixed) argument rather than a variable one.  */
 
-static bool
-mips_ok_for_lazy_binding_p (rtx x)
+static void
+mips_get_arg_info (struct mips_arg_info *info, const CUMULATIVE_ARGS *cum,
+                  enum machine_mode mode, tree type, int named)
 {
-  return (TARGET_USE_GOT
-         && GET_CODE (x) == SYMBOL_REF
-         && !mips_symbol_binds_local_p (x));
-}
+  bool doubleword_aligned_p;
+  unsigned int num_bytes, num_words, max_regs;
 
-/* Load function address ADDR into register DEST.  SIBCALL_P is true
-   if the address is needed for a sibling call.  */
+  /* Work out the size of the argument.  */
+  num_bytes = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode);
+  num_words = (num_bytes + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
 
-static void
-mips_load_call_address (rtx dest, rtx addr, int sibcall_p)
-{
-  /* If we're generating PIC, and this call is to a global function,
-     try to allow its address to be resolved lazily.  This isn't
-     possible if TARGET_CALL_SAVED_GP since the value of $gp on entry
-     to the stub would be our caller's gp, not ours.  */
-  if (TARGET_EXPLICIT_RELOCS
-      && !(sibcall_p && TARGET_CALL_SAVED_GP)
-      && mips_ok_for_lazy_binding_p (addr))
+  /* Decide whether it should go in a floating-point register, assuming
+     one is free.  Later code checks for availability.
+
+     The checks against UNITS_PER_FPVALUE handle the soft-float and
+     single-float cases.  */
+  switch (mips_abi)
     {
-      rtx high, lo_sum_symbol;
+    case ABI_EABI:
+      /* The EABI conventions have traditionally been defined in terms
+        of TYPE_MODE, regardless of the actual type.  */
+      info->fpr_p = ((GET_MODE_CLASS (mode) == MODE_FLOAT
+                     || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
+                    && GET_MODE_SIZE (mode) <= UNITS_PER_FPVALUE);
+      break;
 
-      high = mips_unspec_offset_high (dest, pic_offset_table_rtx,
-                                     addr, SYMBOL_GOTOFF_CALL);
-      lo_sum_symbol = mips_unspec_address (addr, SYMBOL_GOTOFF_CALL);
-      if (Pmode == SImode)
-       emit_insn (gen_load_callsi (dest, high, lo_sum_symbol));
-      else
-       emit_insn (gen_load_calldi (dest, high, lo_sum_symbol));
-    }
-  else
-    mips_emit_move (dest, addr);
-}
+    case ABI_32:
+    case ABI_O64:
+      /* Only leading floating-point scalars are passed in
+        floating-point registers.  We also handle vector floats the same
+        say, which is OK because they are not covered by the standard ABI.  */
+      info->fpr_p = (!cum->gp_reg_found
+                    && cum->arg_number < 2
+                    && (type == 0
+                        || SCALAR_FLOAT_TYPE_P (type)
+                        || VECTOR_FLOAT_TYPE_P (type))
+                    && (GET_MODE_CLASS (mode) == MODE_FLOAT
+                        || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
+                    && GET_MODE_SIZE (mode) <= UNITS_PER_FPVALUE);
+      break;
+
+    case ABI_N32:
+    case ABI_64:
+      /* Scalar, complex and vector floating-point types are passed in
+        floating-point registers, as long as this is a named rather
+        than a variable argument.  */
+      info->fpr_p = (named
+                    && (type == 0 || FLOAT_TYPE_P (type))
+                    && (GET_MODE_CLASS (mode) == MODE_FLOAT
+                        || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT
+                        || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
+                    && GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_FPVALUE);
 
+      /* ??? According to the ABI documentation, the real and imaginary
+        parts of complex floats should be passed in individual registers.
+        The real and imaginary parts of stack arguments are supposed
+        to be contiguous and there should be an extra word of padding
+        at the end.
 
-/* Expand a call or call_value instruction.  RESULT is where the
-   result will go (null for calls), ADDR is the address of the
-   function, ARGS_SIZE is the size of the arguments and AUX is
-   the value passed to us by mips_function_arg.  SIBCALL_P is true
-   if we are expanding a sibling call, false if we're expanding
-   a normal call.  */
+        This has two problems.  First, it makes it impossible to use a
+        single "void *" va_list type, since register and stack arguments
+        are passed differently.  (At the time of writing, MIPSpro cannot
+        handle complex float varargs correctly.)  Second, it's unclear
+        what should happen when there is only one register free.
 
-void
-mips_expand_call (rtx result, rtx addr, rtx args_size, rtx aux, int sibcall_p)
-{
-  rtx orig_addr, pattern, insn;
+        For now, we assume that named complex floats should go into FPRs
+        if there are two FPRs free, otherwise they should be passed in the
+        same way as a struct containing two floats.  */
+      if (info->fpr_p
+         && GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT
+         && GET_MODE_UNIT_SIZE (mode) < UNITS_PER_FPVALUE)
+       {
+         if (cum->num_gprs >= MAX_ARGS_IN_REGISTERS - 1)
+           info->fpr_p = false;
+         else
+           num_words = 2;
+       }
+      break;
 
-  orig_addr = addr;
-  if (!call_insn_operand (addr, VOIDmode))
-    {
-      addr = gen_reg_rtx (Pmode);
-      mips_load_call_address (addr, orig_addr, sibcall_p);
+    default:
+      gcc_unreachable ();
     }
 
-  if (TARGET_MIPS16
-      && TARGET_HARD_FLOAT_ABI
-      && build_mips16_call_stub (result, addr, args_size,
-                                aux == 0 ? 0 : (int) GET_MODE (aux)))
-    return;
+  /* See whether the argument has doubleword alignment.  */
+  doubleword_aligned_p = FUNCTION_ARG_BOUNDARY (mode, type) > BITS_PER_WORD;
 
-  if (result == 0)
-    pattern = (sibcall_p
-              ? gen_sibcall_internal (addr, args_size)
-              : gen_call_internal (addr, args_size));
-  else if (GET_CODE (result) == PARALLEL && XVECLEN (result, 0) == 2)
-    {
-      rtx reg1, reg2;
+  /* Set REG_OFFSET to the register count we're interested in.
+     The EABI allocates the floating-point registers separately,
+     but the other ABIs allocate them like integer registers.  */
+  info->reg_offset = (mips_abi == ABI_EABI && info->fpr_p
+                     ? cum->num_fprs
+                     : cum->num_gprs);
 
-      reg1 = XEXP (XVECEXP (result, 0, 0), 0);
-      reg2 = XEXP (XVECEXP (result, 0, 1), 0);
-      pattern =
-       (sibcall_p
-        ? gen_sibcall_value_multiple_internal (reg1, addr, args_size, reg2)
-        : gen_call_value_multiple_internal (reg1, addr, args_size, reg2));
-    }
-  else
-    pattern = (sibcall_p
-              ? gen_sibcall_value_internal (result, addr, args_size)
-              : gen_call_value_internal (result, addr, args_size));
+  /* Advance to an even register if the argument is doubleword-aligned.  */
+  if (doubleword_aligned_p)
+    info->reg_offset += info->reg_offset & 1;
 
-  insn = emit_call_insn (pattern);
+  /* Work out the offset of a stack argument.  */
+  info->stack_offset = cum->stack_words;
+  if (doubleword_aligned_p)
+    info->stack_offset += info->stack_offset & 1;
 
-  /* Lazy-binding stubs require $gp to be valid on entry.  */
-  if (mips_ok_for_lazy_binding_p (orig_addr))
-    use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
+  max_regs = MAX_ARGS_IN_REGISTERS - info->reg_offset;
+
+  /* Partition the argument between registers and stack.  */
+  info->reg_words = MIN (num_words, max_regs);
+  info->stack_words = num_words - info->reg_words;
 }
 
+/* INFO describes a register argument that has the normal format for the
+   argument's mode.  Return the register it uses, assuming that FPRs are
+   available if HARD_FLOAT_P.  */
 
-/* Implement TARGET_FUNCTION_OK_FOR_SIBCALL.  */
+static unsigned int
+mips_arg_regno (const struct mips_arg_info *info, bool hard_float_p)
+{
+  if (!info->fpr_p || !hard_float_p)
+    return GP_ARG_FIRST + info->reg_offset;
+  else if (mips_abi == ABI_32 && TARGET_DOUBLE_FLOAT && info->reg_offset > 0)
+    /* In o32, the second argument is always passed in $f14
+       for TARGET_DOUBLE_FLOAT, regardless of whether the
+       first argument was a word or doubleword.  */
+    return FP_ARG_FIRST + 2;
+  else
+    return FP_ARG_FIRST + info->reg_offset;
+}
+
+/* Implement TARGET_STRICT_ARGUMENT_NAMING.  */
 
 static bool
-mips_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
+mips_strict_argument_naming (CUMULATIVE_ARGS *ca ATTRIBUTE_UNUSED)
 {
-  if (!TARGET_SIBCALLS)
-    return false;
-
-  /* We can't do a sibcall if the called function is a MIPS16 function
-     because there is no direct "jx" instruction equivalent to "jalx" to
-     switch the ISA mode.  */
-  if (mips_use_mips16_mode_p (decl))
-    return false;
+  return !TARGET_OLDABI;
+}
 
-  /* ...and when -minterlink-mips16 is in effect, assume that external
-     functions could be MIPS16 ones unless an attribute explicitly
-     tells us otherwise.  We only care about cases where the sibling
-     and normal calls would both be direct.  */
-  if (TARGET_INTERLINK_MIPS16
-      && decl
-      && DECL_EXTERNAL (decl)
-      && !mips_nomips16_decl_p (decl)
-      && const_call_insn_operand (XEXP (DECL_RTL (decl), 0), VOIDmode))
-    return false;
+/* Implement FUNCTION_ARG.  */
 
-  /* Otherwise OK.  */
-  return true;
-}
-\f
-/* Emit code to move general operand SRC into condition-code
-   register DEST.  SCRATCH is a scratch TFmode float register.
-   The sequence is:
+rtx
+mips_function_arg (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
+                  tree type, int named)
+{
+  struct mips_arg_info info;
 
-       FP1 = SRC
-       FP2 = 0.0f
-       DEST = FP2 < FP1
+  /* We will be called with a mode of VOIDmode after the last argument
+     has been seen.  Whatever we return will be passed to the call expander.
+     If we need a MIPS16 fp_code, return a REG with the code stored as
+     the mode.  */
+  if (mode == VOIDmode)
+    {
+      if (TARGET_MIPS16 && cum->fp_code != 0)
+       return gen_rtx_REG ((enum machine_mode) cum->fp_code, 0);
+      else
+       return NULL;
+    }
 
-   where FP1 and FP2 are single-precision float registers
-   taken from SCRATCH.  */
+  mips_get_arg_info (&info, cum, mode, type, named);
 
-void
-mips_emit_fcc_reload (rtx dest, rtx src, rtx scratch)
-{
-  rtx fp1, fp2;
+  /* Return straight away if the whole argument is passed on the stack.  */
+  if (info.reg_offset == MAX_ARGS_IN_REGISTERS)
+    return NULL;
 
-  /* Change the source to SFmode.  */
-  if (MEM_P (src))
-    src = adjust_address (src, SFmode, 0);
-  else if (REG_P (src) || GET_CODE (src) == SUBREG)
-    src = gen_rtx_REG (SFmode, true_regnum (src));
-
-  fp1 = gen_rtx_REG (SFmode, REGNO (scratch));
-  fp2 = gen_rtx_REG (SFmode, REGNO (scratch) + MAX_FPRS_PER_FMT);
+  /* The n32 and n64 ABIs say that if any 64-bit chunk of the structure
+     contains a double in its entirety, then that 64-bit chunk is passed
+     in a floating-point register.  */
+  if (TARGET_NEWABI
+      && TARGET_HARD_FLOAT
+      && named
+      && type != 0
+      && TREE_CODE (type) == RECORD_TYPE
+      && TYPE_SIZE_UNIT (type)
+      && host_integerp (TYPE_SIZE_UNIT (type), 1))
+    {
+      tree field;
 
-  mips_emit_move (copy_rtx (fp1), src);
-  mips_emit_move (copy_rtx (fp2), CONST0_RTX (SFmode));
-  emit_insn (gen_slt_sf (dest, fp2, fp1));
-}
-\f
-/* Emit code to change the current function's return address to
-   ADDRESS.  SCRATCH is available as a scratch register, if needed.
-   ADDRESS and SCRATCH are both word-mode GPRs.  */
+      /* First check to see if there is any such field.  */
+      for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
+       if (TREE_CODE (field) == FIELD_DECL
+           && SCALAR_FLOAT_TYPE_P (TREE_TYPE (field))
+           && TYPE_PRECISION (TREE_TYPE (field)) == BITS_PER_WORD
+           && host_integerp (bit_position (field), 0)
+           && int_bit_position (field) % BITS_PER_WORD == 0)
+         break;
 
-void
-mips_set_return_address (rtx address, rtx scratch)
-{
-  rtx slot_address;
+      if (field != 0)
+       {
+         /* Now handle the special case by returning a PARALLEL
+            indicating where each 64-bit chunk goes.  INFO.REG_WORDS
+            chunks are passed in registers.  */
+         unsigned int i;
+         HOST_WIDE_INT bitpos;
+         rtx ret;
 
-  compute_frame_size (get_frame_size ());
-  gcc_assert ((cfun->machine->frame.mask >> 31) & 1);
-  slot_address = mips_add_offset (scratch, stack_pointer_rtx,
-                                 cfun->machine->frame.gp_sp_offset);
+         /* assign_parms checks the mode of ENTRY_PARM, so we must
+            use the actual mode here.  */
+         ret = gen_rtx_PARALLEL (mode, rtvec_alloc (info.reg_words));
 
-  mips_emit_move (gen_rtx_MEM (GET_MODE (address), slot_address), address);
-}
-\f
-/* Emit straight-line code to move LENGTH bytes from SRC to DEST.
-   Assume that the areas do not overlap.  */
+         bitpos = 0;
+         field = TYPE_FIELDS (type);
+         for (i = 0; i < info.reg_words; i++)
+           {
+             rtx reg;
 
-static void
-mips_block_move_straight (rtx dest, rtx src, HOST_WIDE_INT length)
-{
-  HOST_WIDE_INT offset, delta;
-  unsigned HOST_WIDE_INT bits;
-  int i;
-  enum machine_mode mode;
-  rtx *regs;
+             for (; field; field = TREE_CHAIN (field))
+               if (TREE_CODE (field) == FIELD_DECL
+                   && int_bit_position (field) >= bitpos)
+                 break;
 
-  /* Work out how many bits to move at a time.  If both operands have
-     half-word alignment, it is usually better to move in half words.
-     For instance, lh/lh/sh/sh is usually better than lwl/lwr/swl/swr
-     and lw/lw/sw/sw is usually better than ldl/ldr/sdl/sdr.
-     Otherwise move word-sized chunks.  */
-  if (MEM_ALIGN (src) == BITS_PER_WORD / 2
-      && MEM_ALIGN (dest) == BITS_PER_WORD / 2)
-    bits = BITS_PER_WORD / 2;
-  else
-    bits = BITS_PER_WORD;
+             if (field
+                 && int_bit_position (field) == bitpos
+                 && SCALAR_FLOAT_TYPE_P (TREE_TYPE (field))
+                 && TYPE_PRECISION (TREE_TYPE (field)) == BITS_PER_WORD)
+               reg = gen_rtx_REG (DFmode, FP_ARG_FIRST + info.reg_offset + i);
+             else
+               reg = gen_rtx_REG (DImode, GP_ARG_FIRST + info.reg_offset + i);
 
-  mode = mode_for_size (bits, MODE_INT, 0);
-  delta = bits / BITS_PER_UNIT;
+             XVECEXP (ret, 0, i)
+               = gen_rtx_EXPR_LIST (VOIDmode, reg,
+                                    GEN_INT (bitpos / BITS_PER_UNIT));
 
-  /* Allocate a buffer for the temporary registers.  */
-  regs = alloca (sizeof (rtx) * length / delta);
+             bitpos += BITS_PER_WORD;
+           }
+         return ret;
+       }
+    }
 
-  /* Load as many BITS-sized chunks as possible.  Use a normal load if
-     the source has enough alignment, otherwise use left/right pairs.  */
-  for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
+  /* Handle the n32/n64 conventions for passing complex floating-point
+     arguments in FPR pairs.  The real part goes in the lower register
+     and the imaginary part goes in the upper register.  */
+  if (TARGET_NEWABI
+      && info.fpr_p
+      && GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
     {
-      regs[i] = gen_reg_rtx (mode);
-      if (MEM_ALIGN (src) >= bits)
-       mips_emit_move (regs[i], adjust_address (src, mode, offset));
+      rtx real, imag;
+      enum machine_mode inner;
+      unsigned int regno;
+
+      inner = GET_MODE_INNER (mode);
+      regno = FP_ARG_FIRST + info.reg_offset;
+      if (info.reg_words * UNITS_PER_WORD == GET_MODE_SIZE (inner))
+       {
+         /* Real part in registers, imaginary part on stack.  */
+         gcc_assert (info.stack_words == info.reg_words);
+         return gen_rtx_REG (inner, regno);
+       }
       else
        {
-         rtx part = adjust_address (src, BLKmode, offset);
-         if (!mips_expand_unaligned_load (regs[i], part, bits, 0))
-           gcc_unreachable ();
+         gcc_assert (info.stack_words == 0);
+         real = gen_rtx_EXPR_LIST (VOIDmode,
+                                   gen_rtx_REG (inner, regno),
+                                   const0_rtx);
+         imag = gen_rtx_EXPR_LIST (VOIDmode,
+                                   gen_rtx_REG (inner,
+                                                regno + info.reg_words / 2),
+                                   GEN_INT (GET_MODE_SIZE (inner)));
+         return gen_rtx_PARALLEL (mode, gen_rtvec (2, real, imag));
        }
     }
 
-  /* Copy the chunks to the destination.  */
-  for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
-    if (MEM_ALIGN (dest) >= bits)
-      mips_emit_move (adjust_address (dest, mode, offset), regs[i]);
-    else
-      {
-       rtx part = adjust_address (dest, BLKmode, offset);
-       if (!mips_expand_unaligned_store (part, regs[i], bits, 0))
-         gcc_unreachable ();
-      }
-
-  /* Mop up any left-over bytes.  */
-  if (offset < length)
-    {
-      src = adjust_address (src, BLKmode, offset);
-      dest = adjust_address (dest, BLKmode, offset);
-      move_by_pieces (dest, src, length - offset,
-                     MIN (MEM_ALIGN (src), MEM_ALIGN (dest)), 0);
-    }
+  return gen_rtx_REG (mode, mips_arg_regno (&info, TARGET_HARD_FLOAT));
 }
-\f
-#define MAX_MOVE_REGS 4
-#define MAX_MOVE_BYTES (MAX_MOVE_REGS * UNITS_PER_WORD)
-
 
-/* Helper function for doing a loop-based block operation on memory
-   reference MEM.  Each iteration of the loop will operate on LENGTH
-   bytes of MEM.
-
-   Create a new base register for use within the loop and point it to
-   the start of MEM.  Create a new memory reference that uses this
-   register.  Store them in *LOOP_REG and *LOOP_MEM respectively.  */
+/* Implement FUNCTION_ARG_ADVANCE.  */
 
-static void
-mips_adjust_block_mem (rtx mem, HOST_WIDE_INT length,
-                      rtx *loop_reg, rtx *loop_mem)
+void
+mips_function_arg_advance (CUMULATIVE_ARGS *cum, enum machine_mode mode,
+                          tree type, int named)
 {
-  *loop_reg = copy_addr_to_reg (XEXP (mem, 0));
+  struct mips_arg_info info;
 
-  /* Although the new mem does not refer to a known location,
-     it does keep up to LENGTH bytes of alignment.  */
-  *loop_mem = change_address (mem, BLKmode, *loop_reg);
-  set_mem_align (*loop_mem, MIN (MEM_ALIGN (mem), length * BITS_PER_UNIT));
-}
+  mips_get_arg_info (&info, cum, mode, type, named);
 
+  if (!info.fpr_p)
+    cum->gp_reg_found = true;
 
-/* Move LENGTH bytes from SRC to DEST using a loop that moves MAX_MOVE_BYTES
-   per iteration.  LENGTH must be at least MAX_MOVE_BYTES.  Assume that the
-   memory regions do not overlap.  */
+  /* See the comment above the CUMULATIVE_ARGS structure in mips.h for
+     an explanation of what this code does.  It assumes that we're using
+     either the o32 or the o64 ABI, both of which pass at most 2 arguments
+     in FPRs.  */
+  if (cum->arg_number < 2 && info.fpr_p)
+    cum->fp_code += (mode == SFmode ? 1 : 2) << (cum->arg_number * 2);
 
-static void
-mips_block_move_loop (rtx dest, rtx src, HOST_WIDE_INT length)
-{
-  rtx label, src_reg, dest_reg, final_src;
-  HOST_WIDE_INT leftover;
+  /* Advance the register count.  This has the effect of setting
+     num_gprs to MAX_ARGS_IN_REGISTERS if a doubleword-aligned
+     argument required us to skip the final GPR and pass the whole
+     argument on the stack.  */
+  if (mips_abi != ABI_EABI || !info.fpr_p)
+    cum->num_gprs = info.reg_offset + info.reg_words;
+  else if (info.reg_words > 0)
+    cum->num_fprs += MAX_FPRS_PER_FMT;
 
-  leftover = length % MAX_MOVE_BYTES;
-  length -= leftover;
+  /* Advance the stack word count.  */
+  if (info.stack_words > 0)
+    cum->stack_words = info.stack_offset + info.stack_words;
 
-  /* Create registers and memory references for use within the loop.  */
-  mips_adjust_block_mem (src, MAX_MOVE_BYTES, &src_reg, &src);
-  mips_adjust_block_mem (dest, MAX_MOVE_BYTES, &dest_reg, &dest);
+  cum->arg_number++;
+}
 
-  /* Calculate the value that SRC_REG should have after the last iteration
-     of the loop.  */
-  final_src = expand_simple_binop (Pmode, PLUS, src_reg, GEN_INT (length),
-                                  0, 0, OPTAB_WIDEN);
+/* Implement TARGET_ARG_PARTIAL_BYTES.  */
 
-  /* Emit the start of the loop.  */
-  label = gen_label_rtx ();
-  emit_label (label);
+static int
+mips_arg_partial_bytes (CUMULATIVE_ARGS *cum,
+                       enum machine_mode mode, tree type, bool named)
+{
+  struct mips_arg_info info;
 
-  /* Emit the loop body.  */
-  mips_block_move_straight (dest, src, MAX_MOVE_BYTES);
+  mips_get_arg_info (&info, cum, mode, type, named);
+  return info.stack_words > 0 ? info.reg_words * UNITS_PER_WORD : 0;
+}
 
-  /* Move on to the next block.  */
-  mips_emit_move (src_reg, plus_constant (src_reg, MAX_MOVE_BYTES));
-  mips_emit_move (dest_reg, plus_constant (dest_reg, MAX_MOVE_BYTES));
+/* Implement FUNCTION_ARG_BOUNDARY.  Every parameter gets at least
+   PARM_BOUNDARY bits of alignment, but will be given anything up
+   to STACK_BOUNDARY bits if the type requires it.  */
 
-  /* Emit the loop condition.  */
-  if (Pmode == DImode)
-    emit_insn (gen_cmpdi (src_reg, final_src));
-  else
-    emit_insn (gen_cmpsi (src_reg, final_src));
-  emit_jump_insn (gen_bne (label));
+int
+mips_function_arg_boundary (enum machine_mode mode, tree type)
+{
+  unsigned int alignment;
 
-  /* Mop up any left-over bytes.  */
-  if (leftover)
-    mips_block_move_straight (dest, src, leftover);
+  alignment = type ? TYPE_ALIGN (type) : GET_MODE_ALIGNMENT (mode);
+  if (alignment < PARM_BOUNDARY)
+    alignment = PARM_BOUNDARY;
+  if (alignment > STACK_BOUNDARY)
+    alignment = STACK_BOUNDARY;
+  return alignment;
 }
-\f
 
-/* Expand a loop of synci insns for the address range [BEGIN, END).  */
+/* Return true if FUNCTION_ARG_PADDING (MODE, TYPE) should return
+   upward rather than downward.  In other words, return true if the
+   first byte of the stack slot has useful data, false if the last
+   byte does.  */
 
-void
-mips_expand_synci_loop (rtx begin, rtx end)
+bool
+mips_pad_arg_upward (enum machine_mode mode, const_tree type)
 {
-  rtx inc, label, cmp, cmp_result;
+  /* On little-endian targets, the first byte of every stack argument
+     is passed in the first byte of the stack slot.  */
+  if (!BYTES_BIG_ENDIAN)
+    return true;
 
-  /* Load INC with the cache line size (rdhwr INC,$1). */
-  inc = gen_reg_rtx (SImode);
-  emit_insn (gen_rdhwr (inc, const1_rtx));
+  /* Otherwise, integral types are padded downward: the last byte of a
+     stack argument is passed in the last byte of the stack slot.  */
+  if (type != 0
+      ? (INTEGRAL_TYPE_P (type)
+        || POINTER_TYPE_P (type)
+        || FIXED_POINT_TYPE_P (type))
+      : (SCALAR_INT_MODE_P (mode)
+        || ALL_SCALAR_FIXED_POINT_MODE_P (mode)))
+    return false;
 
-  /* Loop back to here.  */
-  label = gen_label_rtx ();
-  emit_label (label);
+  /* Big-endian o64 pads floating-point arguments downward.  */
+  if (mips_abi == ABI_O64)
+    if (type != 0 ? FLOAT_TYPE_P (type) : GET_MODE_CLASS (mode) == MODE_FLOAT)
+      return false;
 
-  emit_insn (gen_synci (begin));
+  /* Other types are padded upward for o32, o64, n32 and n64.  */
+  if (mips_abi != ABI_EABI)
+    return true;
 
-  cmp = gen_reg_rtx (Pmode);
-  mips_emit_binary (GTU, cmp, begin, end);
-
-  mips_emit_binary (PLUS, begin, begin, inc);
-
-  cmp_result = gen_rtx_EQ (VOIDmode, cmp, const0_rtx);
-  emit_jump_insn (gen_condjump (cmp_result, label));
+  /* Arguments smaller than a stack slot are padded downward.  */
+  if (mode != BLKmode)
+    return GET_MODE_BITSIZE (mode) >= PARM_BOUNDARY;
+  else
+    return int_size_in_bytes (type) >= (PARM_BOUNDARY / BITS_PER_UNIT);
 }
-\f
-/* Expand a movmemsi instruction.  */
+
+/* Likewise BLOCK_REG_PADDING (MODE, TYPE, ...).  Return !BYTES_BIG_ENDIAN
+   if the least significant byte of the register has useful data.  Return
+   the opposite if the most significant byte does.  */
 
 bool
-mips_expand_block_move (rtx dest, rtx src, rtx length)
+mips_pad_reg_upward (enum machine_mode mode, tree type)
 {
-  if (GET_CODE (length) == CONST_INT)
-    {
-      if (INTVAL (length) <= 2 * MAX_MOVE_BYTES)
-       {
-         mips_block_move_straight (dest, src, INTVAL (length));
-         return true;
-       }
-      else if (optimize)
-       {
-         mips_block_move_loop (dest, src, INTVAL (length));
-         return true;
-       }
-    }
-  return false;
+  /* No shifting is required for floating-point arguments.  */
+  if (type != 0 ? FLOAT_TYPE_P (type) : GET_MODE_CLASS (mode) == MODE_FLOAT)
+    return !BYTES_BIG_ENDIAN;
+
+  /* Otherwise, apply the same padding to register arguments as we do
+     to stack arguments.  */
+  return mips_pad_arg_upward (mode, type);
 }
-\f
-/* Argument support functions.  */
 
-/* Initialize CUMULATIVE_ARGS for a function.  */
+/* Return nonzero when an argument must be passed by reference.  */
 
-void
-init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype,
-                     rtx libname ATTRIBUTE_UNUSED)
+static bool
+mips_pass_by_reference (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
+                       enum machine_mode mode, const_tree type,
+                       bool named ATTRIBUTE_UNUSED)
 {
-  static CUMULATIVE_ARGS zero_cum;
-  tree param, next_param;
-
-  *cum = zero_cum;
-  cum->prototype = (fntype && TYPE_ARG_TYPES (fntype));
+  if (mips_abi == ABI_EABI)
+    {
+      int size;
 
-  /* Determine if this function has variable arguments.  This is
-     indicated by the last argument being 'void_type_mode' if there
-     are no variable arguments.  The standard MIPS calling sequence
-     passes all arguments in the general purpose registers in this case.  */
+      /* ??? How should SCmode be handled?  */
+      if (mode == DImode || mode == DFmode
+         || mode == DQmode || mode == UDQmode
+         || mode == DAmode || mode == UDAmode)
+       return 0;
 
-  for (param = fntype ? TYPE_ARG_TYPES (fntype) : 0;
-       param != 0; param = next_param)
+      size = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode);
+      return size == -1 || size > UNITS_PER_WORD;
+    }
+  else
     {
-      next_param = TREE_CHAIN (param);
-      if (next_param == 0 && TREE_VALUE (param) != void_type_node)
-       cum->gp_reg_found = 1;
+      /* If we have a variable-sized parameter, we have no choice.  */
+      return targetm.calls.must_pass_in_stack (mode, type);
     }
 }
 
+/* Implement TARGET_CALLEE_COPIES.  */
 
-/* Fill INFO with information about a single argument.  CUM is the
-   cumulative state for earlier arguments.  MODE is the mode of this
-   argument and TYPE is its type (if known).  NAMED is true if this
-   is a named (fixed) argument rather than a variable one.  */
-
-static void
-mips_arg_info (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
-              tree type, int named, struct mips_arg_info *info)
+static bool
+mips_callee_copies (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
+                   enum machine_mode mode ATTRIBUTE_UNUSED,
+                   const_tree type ATTRIBUTE_UNUSED, bool named)
 {
-  bool doubleword_aligned_p;
-  unsigned int num_bytes, num_words, max_regs;
-
-  /* Work out the size of the argument.  */
-  num_bytes = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode);
-  num_words = (num_bytes + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
+  return mips_abi == ABI_EABI && named;
+}
+\f
+/* See whether VALTYPE is a record whose fields should be returned in
+   floating-point registers.  If so, return the number of fields and
+   list them in FIELDS (which should have two elements).  Return 0
+   otherwise.
 
-  /* Decide whether it should go in a floating-point register, assuming
-     one is free.  Later code checks for availability.
+   For n32 & n64, a structure with one or two fields is returned in
+   floating-point registers as long as every field has a floating-point
+   type.  */
 
-     The checks against UNITS_PER_FPVALUE handle the soft-float and
-     single-float cases.  */
-  switch (mips_abi)
-    {
-    case ABI_EABI:
-      /* The EABI conventions have traditionally been defined in terms
-        of TYPE_MODE, regardless of the actual type.  */
-      info->fpr_p = ((GET_MODE_CLASS (mode) == MODE_FLOAT
-                     || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
-                    && GET_MODE_SIZE (mode) <= UNITS_PER_FPVALUE);
-      break;
+static int
+mips_fpr_return_fields (const_tree valtype, tree *fields)
+{
+  tree field;
+  int i;
 
-    case ABI_32:
-    case ABI_O64:
-      /* Only leading floating-point scalars are passed in
-        floating-point registers.  We also handle vector floats the same
-        say, which is OK because they are not covered by the standard ABI.  */
-      info->fpr_p = (!cum->gp_reg_found
-                    && cum->arg_number < 2
-                    && (type == 0 || SCALAR_FLOAT_TYPE_P (type)
-                        || VECTOR_FLOAT_TYPE_P (type))
-                    && (GET_MODE_CLASS (mode) == MODE_FLOAT
-                        || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
-                    && GET_MODE_SIZE (mode) <= UNITS_PER_FPVALUE);
-      break;
+  if (!TARGET_NEWABI)
+    return 0;
 
-    case ABI_N32:
-    case ABI_64:
-      /* Scalar and complex floating-point types are passed in
-        floating-point registers.  */
-      info->fpr_p = (named
-                    && (type == 0 || FLOAT_TYPE_P (type))
-                    && (GET_MODE_CLASS (mode) == MODE_FLOAT
-                        || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT
-                        || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
-                    && GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_FPVALUE);
+  if (TREE_CODE (valtype) != RECORD_TYPE)
+    return 0;
 
-      /* ??? According to the ABI documentation, the real and imaginary
-        parts of complex floats should be passed in individual registers.
-        The real and imaginary parts of stack arguments are supposed
-        to be contiguous and there should be an extra word of padding
-        at the end.
+  i = 0;
+  for (field = TYPE_FIELDS (valtype); field != 0; field = TREE_CHAIN (field))
+    {
+      if (TREE_CODE (field) != FIELD_DECL)
+       continue;
 
-        This has two problems.  First, it makes it impossible to use a
-        single "void *" va_list type, since register and stack arguments
-        are passed differently.  (At the time of writing, MIPSpro cannot
-        handle complex float varargs correctly.)  Second, it's unclear
-        what should happen when there is only one register free.
+      if (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (field)))
+       return 0;
 
-        For now, we assume that named complex floats should go into FPRs
-        if there are two FPRs free, otherwise they should be passed in the
-        same way as a struct containing two floats.  */
-      if (info->fpr_p
-         && GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT
-         && GET_MODE_UNIT_SIZE (mode) < UNITS_PER_FPVALUE)
-       {
-         if (cum->num_gprs >= MAX_ARGS_IN_REGISTERS - 1)
-           info->fpr_p = false;
-         else
-           num_words = 2;
-       }
-      break;
+      if (i == 2)
+       return 0;
 
-    default:
-      gcc_unreachable ();
+      fields[i++] = field;
     }
+  return i;
+}
 
-  /* See whether the argument has doubleword alignment.  */
-  doubleword_aligned_p = FUNCTION_ARG_BOUNDARY (mode, type) > BITS_PER_WORD;
+/* Implement TARGET_RETURN_IN_MSB.  For n32 & n64, we should return
+   a value in the most significant part of $2/$3 if:
 
-  /* Set REG_OFFSET to the register count we're interested in.
-     The EABI allocates the floating-point registers separately,
-     but the other ABIs allocate them like integer registers.  */
-  info->reg_offset = (mips_abi == ABI_EABI && info->fpr_p
-                     ? cum->num_fprs
-                     : cum->num_gprs);
+      - the target is big-endian;
 
-  /* Advance to an even register if the argument is doubleword-aligned.  */
-  if (doubleword_aligned_p)
-    info->reg_offset += info->reg_offset & 1;
+      - the value has a structure or union type (we generalize this to
+       cover aggregates from other languages too); and
 
-  /* Work out the offset of a stack argument.  */
-  info->stack_offset = cum->stack_words;
-  if (doubleword_aligned_p)
-    info->stack_offset += info->stack_offset & 1;
+      - the structure is not returned in floating-point registers.  */
 
-  max_regs = MAX_ARGS_IN_REGISTERS - info->reg_offset;
+static bool
+mips_return_in_msb (const_tree valtype)
+{
+  tree fields[2];
 
-  /* Partition the argument between registers and stack.  */
-  info->reg_words = MIN (num_words, max_regs);
-  info->stack_words = num_words - info->reg_words;
+  return (TARGET_NEWABI
+         && TARGET_BIG_ENDIAN
+         && AGGREGATE_TYPE_P (valtype)
+         && mips_fpr_return_fields (valtype, fields) == 0);
 }
 
+/* Return true if the function return value MODE will get returned in a
+   floating-point register.  */
 
-/* INFO describes an argument that is passed in a single-register value.
-   Return the register it uses, assuming that FPRs are available if
-   HARD_FLOAT_P.  */
-
-static unsigned int
-mips_arg_regno (const struct mips_arg_info *info, bool hard_float_p)
+static bool
+mips_return_mode_in_fpr_p (enum machine_mode mode)
 {
-  if (!info->fpr_p || !hard_float_p)
-    return GP_ARG_FIRST + info->reg_offset;
-  else if (mips_abi == ABI_32 && TARGET_DOUBLE_FLOAT && info->reg_offset > 0)
-    /* In o32, the second argument is always passed in $f14
-       for TARGET_DOUBLE_FLOAT, regardless of whether the
-       first argument was a word or doubleword.  */
-    return FP_ARG_FIRST + 2;
-  else
-    return FP_ARG_FIRST + info->reg_offset;
+  return ((GET_MODE_CLASS (mode) == MODE_FLOAT
+          || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT
+          || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
+         && GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_HWFPVALUE);
 }
 
-/* Implement FUNCTION_ARG_ADVANCE.  */
-
-void
-function_arg_advance (CUMULATIVE_ARGS *cum, enum machine_mode mode,
-                     tree type, int named)
-{
-  struct mips_arg_info info;
-
-  mips_arg_info (cum, mode, type, named, &info);
-
-  if (!info.fpr_p)
-    cum->gp_reg_found = true;
-
-  /* See the comment above the cumulative args structure in mips.h
-     for an explanation of what this code does.  It assumes the O32
-     ABI, which passes at most 2 arguments in float registers.  */
-  if (cum->arg_number < 2 && info.fpr_p)
-    cum->fp_code += (mode == SFmode ? 1 : 2) << (cum->arg_number * 2);
-
-  if (mips_abi != ABI_EABI || !info.fpr_p)
-    cum->num_gprs = info.reg_offset + info.reg_words;
-  else if (info.reg_words > 0)
-    cum->num_fprs += MAX_FPRS_PER_FMT;
-
-  if (info.stack_words > 0)
-    cum->stack_words = info.stack_offset + info.stack_words;
+/* Return the representation of an FPR return register when the
+   value being returned in FP_RETURN has mode VALUE_MODE and the
+   return type itself has mode TYPE_MODE.  On NewABI targets,
+   the two modes may be different for structures like:
 
-  cum->arg_number++;
-}
+       struct __attribute__((packed)) foo { float f; }
 
-/* Implement FUNCTION_ARG.  */
+   where we return the SFmode value of "f" in FP_RETURN, but where
+   the structure itself has mode BLKmode.  */
 
-struct rtx_def *
-function_arg (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
-             tree type, int named)
+static rtx
+mips_return_fpr_single (enum machine_mode type_mode,
+                       enum machine_mode value_mode)
 {
-  struct mips_arg_info info;
+  rtx x;
 
-  /* We will be called with a mode of VOIDmode after the last argument
-     has been seen.  Whatever we return will be passed to the call
-     insn.  If we need a mips16 fp_code, return a REG with the code
-     stored as the mode.  */
-  if (mode == VOIDmode)
+  x = gen_rtx_REG (value_mode, FP_RETURN);
+  if (type_mode != value_mode)
     {
-      if (TARGET_MIPS16 && cum->fp_code != 0)
-       return gen_rtx_REG ((enum machine_mode) cum->fp_code, 0);
-
-      else
-       return 0;
+      x = gen_rtx_EXPR_LIST (VOIDmode, x, const0_rtx);
+      x = gen_rtx_PARALLEL (type_mode, gen_rtvec (1, x));
     }
+  return x;
+}
 
-  mips_arg_info (cum, mode, type, named, &info);
+/* Return a composite value in a pair of floating-point registers.
+   MODE1 and OFFSET1 are the mode and byte offset for the first value,
+   likewise MODE2 and OFFSET2 for the second.  MODE is the mode of the
+   complete value.
 
-  /* Return straight away if the whole argument is passed on the stack.  */
-  if (info.reg_offset == MAX_ARGS_IN_REGISTERS)
-    return 0;
+   For n32 & n64, $f0 always holds the first value and $f2 the second.
+   Otherwise the values are packed together as closely as possible.  */
 
-  if (type != 0
-      && TREE_CODE (type) == RECORD_TYPE
-      && TARGET_NEWABI
-      && TYPE_SIZE_UNIT (type)
-      && host_integerp (TYPE_SIZE_UNIT (type), 1)
-      && named)
-    {
-      /* The Irix 6 n32/n64 ABIs say that if any 64-bit chunk of the
-        structure contains a double in its entirety, then that 64-bit
-        chunk is passed in a floating point register.  */
-      tree field;
+static rtx
+mips_return_fpr_pair (enum machine_mode mode,
+                     enum machine_mode mode1, HOST_WIDE_INT offset1,
+                     enum machine_mode mode2, HOST_WIDE_INT offset2)
+{
+  int inc;
 
-      /* First check to see if there is any such field.  */
-      for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
-       if (TREE_CODE (field) == FIELD_DECL
-           && TREE_CODE (TREE_TYPE (field)) == REAL_TYPE
-           && TYPE_PRECISION (TREE_TYPE (field)) == BITS_PER_WORD
-           && host_integerp (bit_position (field), 0)
-           && int_bit_position (field) % BITS_PER_WORD == 0)
-         break;
+  inc = (TARGET_NEWABI ? 2 : MAX_FPRS_PER_FMT);
+  return gen_rtx_PARALLEL
+    (mode,
+     gen_rtvec (2,
+               gen_rtx_EXPR_LIST (VOIDmode,
+                                  gen_rtx_REG (mode1, FP_RETURN),
+                                  GEN_INT (offset1)),
+               gen_rtx_EXPR_LIST (VOIDmode,
+                                  gen_rtx_REG (mode2, FP_RETURN + inc),
+                                  GEN_INT (offset2))));
 
-      if (field != 0)
-       {
-         /* Now handle the special case by returning a PARALLEL
-            indicating where each 64-bit chunk goes.  INFO.REG_WORDS
-            chunks are passed in registers.  */
-         unsigned int i;
-         HOST_WIDE_INT bitpos;
-         rtx ret;
+}
 
-         /* assign_parms checks the mode of ENTRY_PARM, so we must
-            use the actual mode here.  */
-         ret = gen_rtx_PARALLEL (mode, rtvec_alloc (info.reg_words));
+/* Implement FUNCTION_VALUE and LIBCALL_VALUE.  For normal calls,
+   VALTYPE is the return type and MODE is VOIDmode.  For libcalls,
+   VALTYPE is null and MODE is the mode of the return value.  */
 
-         bitpos = 0;
-         field = TYPE_FIELDS (type);
-         for (i = 0; i < info.reg_words; i++)
-           {
-             rtx reg;
+rtx
+mips_function_value (const_tree valtype, enum machine_mode mode)
+{
+  if (valtype)
+    {
+      tree fields[2];
+      int unsigned_p;
 
-             for (; field; field = TREE_CHAIN (field))
-               if (TREE_CODE (field) == FIELD_DECL
-                   && int_bit_position (field) >= bitpos)
-                 break;
+      mode = TYPE_MODE (valtype);
+      unsigned_p = TYPE_UNSIGNED (valtype);
 
-             if (field
-                 && int_bit_position (field) == bitpos
-                 && TREE_CODE (TREE_TYPE (field)) == REAL_TYPE
-                 && !TARGET_SOFT_FLOAT
-                 && TYPE_PRECISION (TREE_TYPE (field)) == BITS_PER_WORD)
-               reg = gen_rtx_REG (DFmode, FP_ARG_FIRST + info.reg_offset + i);
-             else
-               reg = gen_rtx_REG (DImode, GP_ARG_FIRST + info.reg_offset + i);
+      /* Since TARGET_PROMOTE_FUNCTION_RETURN unconditionally returns true,
+        we must promote the mode just as PROMOTE_MODE does.  */
+      mode = promote_mode (valtype, mode, &unsigned_p, 1);
 
-             XVECEXP (ret, 0, i)
-               = gen_rtx_EXPR_LIST (VOIDmode, reg,
-                                    GEN_INT (bitpos / BITS_PER_UNIT));
+      /* Handle structures whose fields are returned in $f0/$f2.  */
+      switch (mips_fpr_return_fields (valtype, fields))
+       {
+       case 1:
+         return mips_return_fpr_single (mode,
+                                        TYPE_MODE (TREE_TYPE (fields[0])));
 
-             bitpos += BITS_PER_WORD;
+       case 2:
+         return mips_return_fpr_pair (mode,
+                                      TYPE_MODE (TREE_TYPE (fields[0])),
+                                      int_byte_position (fields[0]),
+                                      TYPE_MODE (TREE_TYPE (fields[1])),
+                                      int_byte_position (fields[1]));
+       }
+
+      /* If a value is passed in the most significant part of a register, see
+        whether we have to round the mode up to a whole number of words.  */
+      if (mips_return_in_msb (valtype))
+       {
+         HOST_WIDE_INT size = int_size_in_bytes (valtype);
+         if (size % UNITS_PER_WORD != 0)
+           {
+             size += UNITS_PER_WORD - size % UNITS_PER_WORD;
+             mode = mode_for_size (size * BITS_PER_UNIT, MODE_INT, 0);
            }
-         return ret;
        }
+
+      /* For EABI, the class of return register depends entirely on MODE.
+        For example, "struct { some_type x; }" and "union { some_type x; }"
+        are returned in the same way as a bare "some_type" would be.
+        Other ABIs only use FPRs for scalar, complex or vector types.  */
+      if (mips_abi != ABI_EABI && !FLOAT_TYPE_P (valtype))
+       return gen_rtx_REG (mode, GP_RETURN);
     }
 
-  /* Handle the n32/n64 conventions for passing complex floating-point
-     arguments in FPR pairs.  The real part goes in the lower register
-     and the imaginary part goes in the upper register.  */
-  if (TARGET_NEWABI
-      && info.fpr_p
-      && GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
+  if (!TARGET_MIPS16)
     {
-      rtx real, imag;
-      enum machine_mode inner;
-      int reg;
+      /* Handle long doubles for n32 & n64.  */
+      if (mode == TFmode)
+       return mips_return_fpr_pair (mode,
+                                    DImode, 0,
+                                    DImode, GET_MODE_SIZE (mode) / 2);
 
-      inner = GET_MODE_INNER (mode);
-      reg = FP_ARG_FIRST + info.reg_offset;
-      if (info.reg_words * UNITS_PER_WORD == GET_MODE_SIZE (inner))
-       {
-         /* Real part in registers, imaginary part on stack.  */
-         gcc_assert (info.stack_words == info.reg_words);
-         return gen_rtx_REG (inner, reg);
-       }
-      else
+      if (mips_return_mode_in_fpr_p (mode))
        {
-         gcc_assert (info.stack_words == 0);
-         real = gen_rtx_EXPR_LIST (VOIDmode,
-                                   gen_rtx_REG (inner, reg),
-                                   const0_rtx);
-         imag = gen_rtx_EXPR_LIST (VOIDmode,
-                                   gen_rtx_REG (inner,
-                                                reg + info.reg_words / 2),
-                                   GEN_INT (GET_MODE_SIZE (inner)));
-         return gen_rtx_PARALLEL (mode, gen_rtvec (2, real, imag));
+         if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
+           return mips_return_fpr_pair (mode,
+                                        GET_MODE_INNER (mode), 0,
+                                        GET_MODE_INNER (mode),
+                                        GET_MODE_SIZE (mode) / 2);
+         else
+           return gen_rtx_REG (mode, FP_RETURN);
        }
     }
 
-  return gen_rtx_REG (mode, mips_arg_regno (&info, TARGET_HARD_FLOAT));
-}
-
-
-/* Implement TARGET_ARG_PARTIAL_BYTES.  */
-
-static int
-mips_arg_partial_bytes (CUMULATIVE_ARGS *cum,
-                       enum machine_mode mode, tree type, bool named)
-{
-  struct mips_arg_info info;
-
-  mips_arg_info (cum, mode, type, named, &info);
-  return info.stack_words > 0 ? info.reg_words * UNITS_PER_WORD : 0;
-}
-
-
-/* Implement FUNCTION_ARG_BOUNDARY.  Every parameter gets at least
-   PARM_BOUNDARY bits of alignment, but will be given anything up
-   to STACK_BOUNDARY bits if the type requires it.  */
-
-int
-function_arg_boundary (enum machine_mode mode, tree type)
-{
-  unsigned int alignment;
-
-  alignment = type ? TYPE_ALIGN (type) : GET_MODE_ALIGNMENT (mode);
-  if (alignment < PARM_BOUNDARY)
-    alignment = PARM_BOUNDARY;
-  if (alignment > STACK_BOUNDARY)
-    alignment = STACK_BOUNDARY;
-  return alignment;
-}
-
-/* Return true if FUNCTION_ARG_PADDING (MODE, TYPE) should return
-   upward rather than downward.  In other words, return true if the
-   first byte of the stack slot has useful data, false if the last
-   byte does.  */
-
-bool
-mips_pad_arg_upward (enum machine_mode mode, const_tree type)
-{
-  /* On little-endian targets, the first byte of every stack argument
-     is passed in the first byte of the stack slot.  */
-  if (!BYTES_BIG_ENDIAN)
-    return true;
-
-  /* Otherwise, integral types are padded downward: the last byte of a
-     stack argument is passed in the last byte of the stack slot.  */
-  if (type != 0
-      ? (INTEGRAL_TYPE_P (type)
-        || POINTER_TYPE_P (type)
-        || FIXED_POINT_TYPE_P (type))
-      : (GET_MODE_CLASS (mode) == MODE_INT
-        || ALL_SCALAR_FIXED_POINT_MODE_P (mode)))
-    return false;
-
-  /* Big-endian o64 pads floating-point arguments downward.  */
-  if (mips_abi == ABI_O64)
-    if (type != 0 ? FLOAT_TYPE_P (type) : GET_MODE_CLASS (mode) == MODE_FLOAT)
-      return false;
-
-  /* Other types are padded upward for o32, o64, n32 and n64.  */
-  if (mips_abi != ABI_EABI)
-    return true;
-
-  /* Arguments smaller than a stack slot are padded downward.  */
-  if (mode != BLKmode)
-    return (GET_MODE_BITSIZE (mode) >= PARM_BOUNDARY);
-  else
-    return (int_size_in_bytes (type) >= (PARM_BOUNDARY / BITS_PER_UNIT));
+  return gen_rtx_REG (mode, GP_RETURN);
 }
 
+/* Implement TARGET_RETURN_IN_MEMORY.  Under the o32 and o64 ABIs,
+   all BLKmode objects are returned in memory.  Under the n32, n64
+   and embedded ABIs, small structures are returned in a register.
+   Objects with varying size must still be returned in memory, of
+   course.  */
 
-/* Likewise BLOCK_REG_PADDING (MODE, TYPE, ...).  Return !BYTES_BIG_ENDIAN
-   if the least significant byte of the register has useful data.  Return
-   the opposite if the most significant byte does.  */
-
-bool
-mips_pad_reg_upward (enum machine_mode mode, tree type)
+static bool
+mips_return_in_memory (const_tree type, const_tree fndecl ATTRIBUTE_UNUSED)
 {
-  /* No shifting is required for floating-point arguments.  */
-  if (type != 0 ? FLOAT_TYPE_P (type) : GET_MODE_CLASS (mode) == MODE_FLOAT)
-    return !BYTES_BIG_ENDIAN;
-
-  /* Otherwise, apply the same padding to register arguments as we do
-     to stack arguments.  */
-  return mips_pad_arg_upward (mode, type);
+  return (TARGET_OLDABI
+         ? TYPE_MODE (type) == BLKmode
+         : !IN_RANGE (int_size_in_bytes (type), 0, 2 * UNITS_PER_WORD));
 }
 \f
+/* Implement TARGET_SETUP_INCOMING_VARARGS.  */
+
 static void
 mips_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
                             tree type, int *pretend_size ATTRIBUTE_UNUSED,
@@ -4916,9 +4642,8 @@ mips_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
   /* The caller has advanced CUM up to, but not beyond, the last named
      argument.  Advance a local copy of CUM past the last "real" named
      argument, to find out how many registers are left over.  */
-
   local_cum = *cum;
-  FUNCTION_ARG_ADVANCE (local_cum, mode, type, 1);
+  FUNCTION_ARG_ADVANCE (local_cum, mode, type, true);
 
   /* Found out how many registers we need to save.  */
   gp_saved = MAX_ARGS_IN_REGISTERS - local_cum.num_gprs;
@@ -4935,7 +4660,7 @@ mips_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
          ptr = plus_constant (virtual_incoming_args_rtx,
                               REG_PARM_STACK_SPACE (cfun->decl)
                               - gp_saved * UNITS_PER_WORD);
-         mem = gen_rtx_MEM (BLKmode, ptr);
+         mem = gen_frame_mem (BLKmode, ptr);
          set_mem_alias_set (mem, get_varargs_alias_set ());
 
          move_block_from_reg (local_cum.num_gprs + GP_ARG_FIRST,
@@ -4951,8 +4676,7 @@ mips_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
          /* Set OFF to the offset from virtual_incoming_args_rtx of
             the first float register.  The FP save area lies below
             the integer one, and is aligned to UNITS_PER_FPVALUE bytes.  */
-         off = -gp_saved * UNITS_PER_WORD;
-         off &= ~(UNITS_PER_FPVALUE - 1);
+         off = (-gp_saved * UNITS_PER_WORD) & -UNITS_PER_FPVALUE;
          off -= fp_saved * UNITS_PER_FPREG;
 
          mode = TARGET_SINGLE_FLOAT ? SFmode : DFmode;
@@ -4963,7 +4687,7 @@ mips_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
              rtx ptr, mem;
 
              ptr = plus_constant (virtual_incoming_args_rtx, off);
-             mem = gen_rtx_MEM (mode, ptr);
+             mem = gen_frame_mem (mode, ptr);
              set_mem_alias_set (mem, get_varargs_alias_set ());
              mips_emit_move (mem, gen_rtx_REG (mode, FP_ARG_FIRST + i));
              off += UNITS_PER_HWFPVALUE;
@@ -4975,46 +4699,44 @@ mips_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
                                   + fp_saved * UNITS_PER_FPREG);
 }
 
-/* Create the va_list data type.
-   We keep 3 pointers, and two offsets.
-   Two pointers are to the overflow area, which starts at the CFA.
-     One of these is constant, for addressing into the GPR save area below it.
-     The other is advanced up the stack through the overflow region.
-   The third pointer is to the GPR save area.  Since the FPR save area
-     is just below it, we can address FPR slots off this pointer.
-   We also keep two one-byte offsets, which are to be subtracted from the
-     constant pointers to yield addresses in the GPR and FPR save areas.
-     These are downcounted as float or non-float arguments are used,
-     and when they get to zero, the argument must be obtained from the
-     overflow region.
-   If !EABI_FLOAT_VARARGS_P, then no FPR save area exists, and a single
-     pointer is enough.  It's started at the GPR save area, and is
-     advanced, period.
-   Note that the GPR save area is not constant size, due to optimization
-     in the prologue.  Hence, we can't use a design with two pointers
-     and two offsets, although we could have designed this with two pointers
-     and three offsets.  */
+/* Implement TARGET_BUILTIN_VA_LIST.  */
 
 static tree
 mips_build_builtin_va_list (void)
 {
   if (EABI_FLOAT_VARARGS_P)
     {
+      /* We keep 3 pointers, and two offsets.
+
+        Two pointers are to the overflow area, which starts at the CFA.
+        One of these is constant, for addressing into the GPR save area
+        below it.  The other is advanced up the stack through the
+        overflow region.
+
+        The third pointer is to the bottom of the GPR save area.
+        Since the FPR save area is just below it, we can address
+        FPR slots off this pointer.
+
+        We also keep two one-byte offsets, which are to be subtracted
+        from the constant pointers to yield addresses in the GPR and
+        FPR save areas.  These are downcounted as float or non-float
+        arguments are used, and when they get to zero, the argument
+        must be obtained from the overflow region.  */
       tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff, f_res, record;
       tree array, index;
 
-      record = (*lang_hooks.types.make_type) (RECORD_TYPE);
+      record = lang_hooks.types.make_type (RECORD_TYPE);
 
       f_ovfl = build_decl (FIELD_DECL, get_identifier ("__overflow_argptr"),
-                         ptr_type_node);
+                          ptr_type_node);
       f_gtop = build_decl (FIELD_DECL, get_identifier ("__gpr_top"),
-                         ptr_type_node);
+                          ptr_type_node);
       f_ftop = build_decl (FIELD_DECL, get_identifier ("__fpr_top"),
-                         ptr_type_node);
+                          ptr_type_node);
       f_goff = build_decl (FIELD_DECL, get_identifier ("__gpr_offset"),
-                         unsigned_char_type_node);
+                          unsigned_char_type_node);
       f_foff = build_decl (FIELD_DECL, get_identifier ("__fpr_offset"),
-                         unsigned_char_type_node);
+                          unsigned_char_type_node);
       /* Explicitly pad to the size of a pointer, so that -Wpadded won't
         warn on every user file.  */
       index = build_int_cst (NULL_TREE, GET_MODE_SIZE (ptr_mode) - 2 - 1);
@@ -5047,9 +4769,9 @@ mips_build_builtin_va_list (void)
     return ptr_type_node;
 }
 
-/* Implement va_start.  */
+/* Implement TARGET_EXPAND_BUILTIN_VA_START.  */
 
-void
+static void
 mips_va_start (tree valist, rtx nextarg)
 {
   if (EABI_FLOAT_VARARGS_P)
@@ -5105,7 +4827,7 @@ mips_va_start (tree valist, rtx nextarg)
         down to the next fp-aligned boundary.  */
       t = make_tree (TREE_TYPE (ftop), virtual_incoming_args_rtx);
       fpr_offset = gpr_save_area_size + UNITS_PER_FPVALUE - 1;
-      fpr_offset &= ~(UNITS_PER_FPVALUE - 1);
+      fpr_offset &= -UNITS_PER_FPVALUE;
       if (fpr_offset)
        t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (ftop), t,
                    size_int (-fpr_offset));
@@ -5115,13 +4837,13 @@ mips_va_start (tree valist, rtx nextarg)
       /* Emit code to initialize GOFF, the offset from GTOP of the
         next GPR argument.  */
       t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (goff), goff,
-                 build_int_cst (NULL_TREE, gpr_save_area_size));
+                 build_int_cst (TREE_TYPE (goff), gpr_save_area_size));
       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
 
       /* Likewise emit code to initialize FOFF, the offset from FTOP
         of the next FPR argument.  */
       t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (foff), foff,
-                 build_int_cst (NULL_TREE, fpr_save_area_size));
+                 build_int_cst (TREE_TYPE (foff), fpr_save_area_size));
       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
     }
   else
@@ -5130,33 +4852,26 @@ mips_va_start (tree valist, rtx nextarg)
       std_expand_builtin_va_start (valist, nextarg);
     }
 }
-\f
-/* Implement va_arg.  */
+
+/* Implement TARGET_GIMPLIFY_VA_ARG_EXPR.  */
 
 static tree
 mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
 {
-  HOST_WIDE_INT size, rsize;
   tree addr;
-  bool indirect;
+  bool indirect_p;
 
-  indirect = pass_by_reference (NULL, TYPE_MODE (type), type, 0);
-
-  if (indirect)
+  indirect_p = pass_by_reference (NULL, TYPE_MODE (type), type, 0);
+  if (indirect_p)
     type = build_pointer_type (type);
 
-  size = int_size_in_bytes (type);
-  rsize = (size + UNITS_PER_WORD - 1) & -UNITS_PER_WORD;
-
-  if (mips_abi != ABI_EABI || !EABI_FLOAT_VARARGS_P)
+  if (!EABI_FLOAT_VARARGS_P)
     addr = std_gimplify_va_arg_expr (valist, type, pre_p, post_p);
   else
     {
-      /* Not a simple merged stack.     */
-
       tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff;
       tree ovfl, top, off, align;
-      HOST_WIDE_INT osize;
+      HOST_WIDE_INT size, rsize, osize;
       tree t, u;
 
       f_ovfl = TYPE_FIELDS (va_list_type_node);
@@ -5165,38 +4880,37 @@ mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
       f_goff = TREE_CHAIN (f_ftop);
       f_foff = TREE_CHAIN (f_goff);
 
-      /* We maintain separate pointers and offsets for floating-point
-        and integer arguments, but we need similar code in both cases.
-        Let:
+      /* Let:
 
-        TOP be the top of the register save area;
+        TOP be the top of the GPR or FPR save area;
         OFF be the offset from TOP of the next register;
         ADDR_RTX be the address of the argument;
+        SIZE be the number of bytes in the argument type;
         RSIZE be the number of bytes used to store the argument
-        when it's in the register save area;
+          when it's in the register save area; and
         OSIZE be the number of bytes used to store it when it's
-        in the stack overflow area; and
-        PADDING be (BYTES_BIG_ENDIAN ? OSIZE - RSIZE : 0)
+          in the stack overflow area.
 
         The code we want is:
 
         1: off &= -rsize;        // round down
         2: if (off != 0)
         3:   {
-        4:      addr_rtx = top - off;
-        5:      off -= rsize;
+        4:     addr_rtx = top - off + (BYTES_BIG_ENDIAN ? RSIZE - SIZE : 0);
+        5:     off -= rsize;
         6:   }
         7: else
         8:   {
-        9:      ovfl += ((intptr_t) ovfl + osize - 1) & -osize;
-        10:     addr_rtx = ovfl + PADDING;
-        11:     ovfl += osize;
-        14:   }
+        9:     ovfl = ((intptr_t) ovfl + osize - 1) & -osize;
+        10:    addr_rtx = ovfl + (BYTES_BIG_ENDIAN ? OSIZE - SIZE : 0);
+        11:    ovfl += osize;
+        14:  }
 
         [1] and [9] can sometimes be optimized away.  */
 
       ovfl = build3 (COMPONENT_REF, TREE_TYPE (f_ovfl), valist, f_ovfl,
                     NULL_TREE);
+      size = int_size_in_bytes (type);
 
       if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_FLOAT
          && GET_MODE_SIZE (TYPE_MODE (type)) <= UNITS_PER_FPVALUE)
@@ -5206,9 +4920,9 @@ mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
          off = build3 (COMPONENT_REF, TREE_TYPE (f_foff), valist, f_foff,
                        NULL_TREE);
 
-         /* When floating-point registers are saved to the stack,
-            each one will take up UNITS_PER_HWFPVALUE bytes, regardless
-            of the float's precision.  */
+         /* When va_start saves FPR arguments to the stack, each slot
+            takes up UNITS_PER_HWFPVALUE bytes, regardless of the
+            argument's precision.  */
          rsize = UNITS_PER_HWFPVALUE;
 
          /* Overflow arguments are padded to UNITS_PER_WORD bytes
@@ -5224,10 +4938,9 @@ mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
             up 4 bytes of memory, so OSIZE will only be 4.
 
             (2) In combinations such as -mgp64 -msingle-float
-            -fshort-double.  Doubles passed in registers
-            will then take up 4 (UNITS_PER_HWFPVALUE) bytes,
-            but those passed on the stack take up
-            UNITS_PER_WORD bytes.  */
+            -fshort-double.  Doubles passed in registers will then take
+            up 4 (UNITS_PER_HWFPVALUE) bytes, but those passed on the
+            stack take up UNITS_PER_WORD bytes.  */
          osize = MAX (GET_MODE_SIZE (TYPE_MODE (type)), UNITS_PER_WORD);
        }
       else
@@ -5236,6 +4949,7 @@ mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
                        NULL_TREE);
          off = build3 (COMPONENT_REF, TREE_TYPE (f_goff), valist, f_goff,
                        NULL_TREE);
+         rsize = (size + UNITS_PER_WORD - 1) & -UNITS_PER_WORD;
          if (rsize > UNITS_PER_WORD)
            {
              /* [1] Emit code for: off &= -rsize.      */
@@ -5253,15 +4967,14 @@ mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
       addr = build3 (COND_EXPR, ptr_type_node, t, NULL_TREE, NULL_TREE);
 
       /* [5] Emit code for: off -= rsize.  We do this as a form of
-        post-increment not available to C.  Also widen for the
-        coming pointer arithmetic.  */
+        post-decrement not available to C.  */
       t = fold_convert (TREE_TYPE (off), build_int_cst (NULL_TREE, rsize));
       t = build2 (POSTDECREMENT_EXPR, TREE_TYPE (off), off, t);
+
+      /* [4] Emit code for:
+        addr_rtx = top - off + (BYTES_BIG_ENDIAN ? RSIZE - SIZE : 0).  */
       t = fold_convert (sizetype, t);
       t = fold_build1 (NEGATE_EXPR, sizetype, t);
-
-      /* [4] Emit code for: addr_rtx = top - off.  On big endian machines,
-        the argument has RSIZE - SIZE bytes of leading padding.  */
       t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (top), top, t);
       if (BYTES_BIG_ENDIAN && rsize > size)
        {
@@ -5272,7 +4985,7 @@ mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
 
       if (osize > UNITS_PER_WORD)
        {
-         /* [9] Emit: ovfl += ((intptr_t) ovfl + osize - 1) & -osize.  */
+         /* [9] Emit: ovfl = ((intptr_t) ovfl + osize - 1) & -osize.  */
          u = size_int (osize - 1);
          t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (ovfl), ovfl, u);
          t = fold_convert (sizetype, t);
@@ -5284,11 +4997,10 @@ mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
       else
        align = NULL;
 
-      /* [10, 11].     Emit code to store ovfl in addr_rtx, then
-        post-increment ovfl by osize.  On big-endian machines,
-        the argument has OSIZE - SIZE bytes of leading padding.  */
-      u = fold_convert (TREE_TYPE (ovfl),
-                       build_int_cst (NULL_TREE, osize));
+      /* [10, 11] Emit code for:
+        addr_rtx = ovfl + (BYTES_BIG_ENDIAN ? OSIZE - SIZE : 0)
+        ovfl += osize.  */
+      u = fold_convert (TREE_TYPE (ovfl), build_int_cst (NULL_TREE, osize));
       t = build2 (POSTINCREMENT_EXPR, TREE_TYPE (ovfl), ovfl, u);
       if (BYTES_BIG_ENDIAN && osize > size)
        {
@@ -5296,7 +5008,7 @@ mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
          t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (t), t, u);
        }
 
-      /* String [9] and [10,11] together.  */
+      /* String [9] and [10, 11] together.  */
       if (align)
        t = build2 (COMPOUND_EXPR, TREE_TYPE (t), align, t);
       COND_EXPR_ELSE (addr) = t;
@@ -5305,1601 +5017,1560 @@ mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
       addr = build_va_arg_indirect_ref (addr);
     }
 
-  if (indirect)
+  if (indirect_p)
     addr = build_va_arg_indirect_ref (addr);
 
   return addr;
 }
 \f
-/* Return true if it is possible to use left/right accesses for a
-   bitfield of WIDTH bits starting BITPOS bits into *OP.  When
-   returning true, update *OP, *LEFT and *RIGHT as follows:
-
-   *OP is a BLKmode reference to the whole field.
-
-   *LEFT is a QImode reference to the first byte if big endian or
-   the last byte if little endian.  This address can be used in the
-   left-side instructions (lwl, swl, ldl, sdl).
+/* A chained list of functions for which mips16_build_call_stub has already
+   generated a stub.  NAME is the name of the function and FP_RET_P is true
+   if the function returns a value in floating-point registers.  */
+struct mips16_stub {
+  struct mips16_stub *next;
+  char *name;
+  bool fp_ret_p;
+};
+static struct mips16_stub *mips16_stubs;
 
-   *RIGHT is a QImode reference to the opposite end of the field and
-   can be used in the patterning right-side instruction.  */
+/* Return the two-character string that identifies floating-point
+   return mode MODE in the name of a MIPS16 function stub.  */
 
-static bool
-mips_get_unaligned_mem (rtx *op, unsigned int width, int bitpos,
-                       rtx *left, rtx *right)
+static const char *
+mips16_call_stub_mode_suffix (enum machine_mode mode)
 {
-  rtx first, last;
-
-  /* Check that the operand really is a MEM.  Not all the extv and
-     extzv predicates are checked.  */
-  if (!MEM_P (*op))
-    return false;
-
-  /* Check that the size is valid.  */
-  if (width != 32 && (!TARGET_64BIT || width != 64))
-    return false;
-
-  /* We can only access byte-aligned values.  Since we are always passed
-     a reference to the first byte of the field, it is not necessary to
-     do anything with BITPOS after this check.  */
-  if (bitpos % BITS_PER_UNIT != 0)
-    return false;
-
-  /* Reject aligned bitfields: we want to use a normal load or store
-     instead of a left/right pair.  */
-  if (MEM_ALIGN (*op) >= width)
-    return false;
-
-  /* Adjust *OP to refer to the whole field.  This also has the effect
-     of legitimizing *OP's address for BLKmode, possibly simplifying it.  */
-  *op = adjust_address (*op, BLKmode, 0);
-  set_mem_size (*op, GEN_INT (width / BITS_PER_UNIT));
-
-  /* Get references to both ends of the field.  We deliberately don't
-     use the original QImode *OP for FIRST since the new BLKmode one
-     might have a simpler address.  */
-  first = adjust_address (*op, QImode, 0);
-  last = adjust_address (*op, QImode, width / BITS_PER_UNIT - 1);
-
-  /* Allocate to LEFT and RIGHT according to endianness.  LEFT should
-     be the upper word and RIGHT the lower word.  */
-  if (TARGET_BIG_ENDIAN)
-    *left = first, *right = last;
+  if (mode == SFmode)
+    return "sf";
+  else if (mode == DFmode)
+    return "df";
+  else if (mode == SCmode)
+    return "sc";
+  else if (mode == DCmode)
+    return "dc";
+  else if (mode == V2SFmode)
+    return "df";
   else
-    *left = last, *right = first;
-
-  return true;
+    gcc_unreachable ();
 }
 
+/* Write instructions to move a 32-bit value between general register
+   GPREG and floating-point register FPREG.  DIRECTION is 't' to move
+   from GPREG to FPREG and 'f' to move in the opposite direction.  */
 
-/* Try to emit the equivalent of (set DEST (zero_extract SRC WIDTH BITPOS)).
-   Return true on success.  We only handle cases where zero_extract is
-   equivalent to sign_extract.  */
-
-bool
-mips_expand_unaligned_load (rtx dest, rtx src, unsigned int width, int bitpos)
+static void
+mips_output_32bit_xfer (char direction, unsigned int gpreg, unsigned int fpreg)
 {
-  rtx left, right, temp;
-
-  /* If TARGET_64BIT, the destination of a 32-bit load will be a
-     paradoxical word_mode subreg.  This is the only case in which
-     we allow the destination to be larger than the source.  */
-  if (GET_CODE (dest) == SUBREG
-      && GET_MODE (dest) == DImode
-      && SUBREG_BYTE (dest) == 0
-      && GET_MODE (SUBREG_REG (dest)) == SImode)
-    dest = SUBREG_REG (dest);
-
-  /* After the above adjustment, the destination must be the same
-     width as the source.  */
-  if (GET_MODE_BITSIZE (GET_MODE (dest)) != width)
-    return false;
+  fprintf (asm_out_file, "\tm%cc1\t%s,%s\n", direction,
+          reg_names[gpreg], reg_names[fpreg]);
+}
 
-  if (!mips_get_unaligned_mem (&src, width, bitpos, &left, &right))
-    return false;
+/* Likewise for 64-bit values.  */
 
-  temp = gen_reg_rtx (GET_MODE (dest));
-  if (GET_MODE (dest) == DImode)
+static void
+mips_output_64bit_xfer (char direction, unsigned int gpreg, unsigned int fpreg)
+{
+  if (TARGET_64BIT)
+    fprintf (asm_out_file, "\tdm%cc1\t%s,%s\n", direction,
+            reg_names[gpreg], reg_names[fpreg]);
+  else if (TARGET_FLOAT64)
     {
-      emit_insn (gen_mov_ldl (temp, src, left));
-      emit_insn (gen_mov_ldr (dest, copy_rtx (src), right, temp));
+      fprintf (asm_out_file, "\tm%cc1\t%s,%s\n", direction,
+              reg_names[gpreg + TARGET_BIG_ENDIAN], reg_names[fpreg]);
+      fprintf (asm_out_file, "\tm%chc1\t%s,%s\n", direction,
+              reg_names[gpreg + TARGET_LITTLE_ENDIAN], reg_names[fpreg]);
     }
   else
     {
-      emit_insn (gen_mov_lwl (temp, src, left));
-      emit_insn (gen_mov_lwr (dest, copy_rtx (src), right, temp));
+      /* Move the least-significant word.  */
+      fprintf (asm_out_file, "\tm%cc1\t%s,%s\n", direction,
+              reg_names[gpreg + TARGET_BIG_ENDIAN], reg_names[fpreg]);
+      /* ...then the most significant word.  */
+      fprintf (asm_out_file, "\tm%cc1\t%s,%s\n", direction,
+              reg_names[gpreg + TARGET_LITTLE_ENDIAN], reg_names[fpreg + 1]);
     }
-  return true;
 }
 
+/* Write out code to move floating-point arguments into or out of
+   general registers.  FP_CODE is the code describing which arguments
+   are present (see the comment above the definition of CUMULATIVE_ARGS
+   in mips.h).  DIRECTION is as for mips_output_32bit_xfer.  */
 
-/* Try to expand (set (zero_extract DEST WIDTH BITPOS) SRC).  Return
-   true on success.  */
-
-bool
-mips_expand_unaligned_store (rtx dest, rtx src, unsigned int width, int bitpos)
+static void
+mips_output_args_xfer (int fp_code, char direction)
 {
-  rtx left, right;
-  enum machine_mode mode;
+  unsigned int gparg, fparg, f;
+  CUMULATIVE_ARGS cum;
 
-  if (!mips_get_unaligned_mem (&dest, width, bitpos, &left, &right))
-    return false;
+  /* This code only works for o32 and o64.  */
+  gcc_assert (TARGET_OLDABI);
 
-  mode = mode_for_size (width, MODE_INT, 0);
-  src = gen_lowpart (mode, src);
+  mips_init_cumulative_args (&cum, NULL);
 
-  if (mode == DImode)
-    {
-      emit_insn (gen_mov_sdl (dest, src, left));
-      emit_insn (gen_mov_sdr (copy_rtx (dest), copy_rtx (src), right));
-    }
-  else
+  for (f = (unsigned int) fp_code; f != 0; f >>= 2)
     {
-      emit_insn (gen_mov_swl (dest, src, left));
-      emit_insn (gen_mov_swr (copy_rtx (dest), copy_rtx (src), right));
-    }
-  return true;
-}
+      enum machine_mode mode;
+      struct mips_arg_info info;
 
-/* Return true if X is a MEM with the same size as MODE.  */
+      if ((f & 3) == 1)
+       mode = SFmode;
+      else if ((f & 3) == 2)
+       mode = DFmode;
+      else
+       gcc_unreachable ();
 
-bool
-mips_mem_fits_mode_p (enum machine_mode mode, rtx x)
-{
-  rtx size;
+      mips_get_arg_info (&info, &cum, mode, NULL, true);
+      gparg = mips_arg_regno (&info, false);
+      fparg = mips_arg_regno (&info, true);
 
-  if (!MEM_P (x))
-    return false;
+      if (mode == SFmode)
+       mips_output_32bit_xfer (direction, gparg, fparg);
+      else
+       mips_output_64bit_xfer (direction, gparg, fparg);
 
-  size = MEM_SIZE (x);
-  return size && INTVAL (size) == GET_MODE_SIZE (mode);
+      mips_function_arg_advance (&cum, mode, NULL, true);
+    }
 }
 
-/* Return true if (zero_extract OP SIZE POSITION) can be used as the
-   source of an "ext" instruction or the destination of an "ins"
-   instruction.  OP must be a register operand and the following
-   conditions must hold:
-
-     0 <= POSITION < GET_MODE_BITSIZE (GET_MODE (op))
-     0 < SIZE <= GET_MODE_BITSIZE (GET_MODE (op))
-     0 < POSITION + SIZE <= GET_MODE_BITSIZE (GET_MODE (op))
+/* Write a MIPS16 stub for the current function.  This stub is used
+   for functions which take arguments in the floating-point registers.
+   It is normal-mode code that moves the floating-point arguments
+   into the general registers and then jumps to the MIPS16 code.  */
 
-   Also reject lengths equal to a word as they are better handled
-   by the move patterns.  */
-
-bool
-mips_use_ins_ext_p (rtx op, rtx size, rtx position)
+static void
+mips16_build_function_stub (void)
 {
-  HOST_WIDE_INT len, pos;
-
-  if (!ISA_HAS_EXT_INS
-      || !register_operand (op, VOIDmode)
-      || GET_MODE_BITSIZE (GET_MODE (op)) > BITS_PER_WORD)
-    return false;
+  const char *fnname, *separator;
+  char *secname, *stubname;
+  tree stubdecl;
+  unsigned int f;
 
-  len = INTVAL (size);
-  pos = INTVAL (position);
+  /* Create the name of the stub, and its unique section.  */
+  fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
+  fnname = targetm.strip_name_encoding (fnname);
+  secname = ACONCAT ((".mips16.fn.", fnname, NULL));
+  stubname = ACONCAT (("__fn_stub_", fnname, NULL));
 
-  if (len <= 0 || len >= GET_MODE_BITSIZE (GET_MODE (op))
-      || pos < 0 || pos + len > GET_MODE_BITSIZE (GET_MODE (op)))
-    return false;
+  /* Build a decl for the stub.  */
+  stubdecl = build_decl (FUNCTION_DECL, get_identifier (stubname),
+                        build_function_type (void_type_node, NULL_TREE));
+  DECL_SECTION_NAME (stubdecl) = build_string (strlen (secname), secname);
+  DECL_RESULT (stubdecl) = build_decl (RESULT_DECL, NULL_TREE, void_type_node);
 
-  return true;
-}
+  /* Output a comment.  */
+  fprintf (asm_out_file, "\t# Stub function for %s (",
+          current_function_name ());
+  separator = "";
+  for (f = (unsigned int) current_function_args_info.fp_code; f != 0; f >>= 2)
+    {
+      fprintf (asm_out_file, "%s%s", separator,
+              (f & 3) == 1 ? "float" : "double");
+      separator = ", ";
+    }
+  fprintf (asm_out_file, ")\n");
 
-/* Set up globals to generate code for the ISA or processor
-   described by INFO.  */
+  /* Write the preamble leading up to the function declaration.  */
+  fprintf (asm_out_file, "\t.set\tnomips16\n");
+  switch_to_section (function_section (stubdecl));
+  ASM_OUTPUT_ALIGN (asm_out_file,
+                   floor_log2 (FUNCTION_BOUNDARY / BITS_PER_UNIT));
 
-static void
-mips_set_architecture (const struct mips_cpu_info *info)
-{
-  if (info != 0)
+  /* ??? If FUNCTION_NAME_ALREADY_DECLARED is defined, then we are
+     within a .ent, and we cannot emit another .ent.  */
+  if (!FUNCTION_NAME_ALREADY_DECLARED)
     {
-      mips_arch_info = info;
-      mips_arch = info->cpu;
-      mips_isa = info->isa;
+      fputs ("\t.ent\t", asm_out_file);
+      assemble_name (asm_out_file, stubname);
+      fputs ("\n", asm_out_file);
     }
-}
 
+  /* Start the definition proper.  */
+  assemble_name (asm_out_file, stubname);
+  fputs (":\n", asm_out_file);
 
-/* Likewise for tuning.  */
+  /* Load the address of the MIPS16 function into $at.  Do this first so
+     that targets with coprocessor interlocks can use an MFC1 to fill the
+     delay slot.  */
+  fprintf (asm_out_file, "\t.set\tnoat\n");
+  fprintf (asm_out_file, "\tla\t%s,", reg_names[GP_REG_FIRST + 1]);
+  assemble_name (asm_out_file, fnname);
+  fprintf (asm_out_file, "\n");
 
-static void
-mips_set_tune (const struct mips_cpu_info *info)
-{
-  if (info != 0)
+  /* Move the arguments from floating-point registers to general registers.  */
+  mips_output_args_xfer (current_function_args_info.fp_code, 'f');
+
+  /* Jump to the MIPS16 function.  */
+  fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 1]);
+  fprintf (asm_out_file, "\t.set\tat\n");
+
+  if (!FUNCTION_NAME_ALREADY_DECLARED)
     {
-      mips_tune_info = info;
-      mips_tune = info->cpu;
+      fputs ("\t.end\t", asm_out_file);
+      assemble_name (asm_out_file, stubname);
+      fputs ("\n", asm_out_file);
     }
-}
-
-/* Initialize mips_split_addresses from the associated command-line
-   settings.
 
-   mips_split_addresses is a half-way house between explicit
-   relocations and the traditional assembler macros.  It can
-   split absolute 32-bit symbolic constants into a high/lo_sum
-   pair but uses macros for other sorts of access.
-   
-   Like explicit relocation support for REL targets, it relies
-   on GNU extensions in the assembler and the linker.
+  switch_to_section (function_section (current_function_decl));
+}
 
-   Although this code should work for -O0, it has traditionally
-   been treated as an optimization.  */
+/* The current function is a MIPS16 function that returns a value in an FPR.
+   Copy the return value from its soft-float to its hard-float location.
+   libgcc2 has special non-MIPS16 helper functions for each case.  */
 
 static void
-mips_init_split_addresses (void)
+mips16_copy_fpr_return_value (void)
 {
-  if (!TARGET_MIPS16 && TARGET_SPLIT_ADDRESSES
-      && optimize && !flag_pic
-      && !ABI_HAS_64BIT_SYMBOLS)
-    mips_split_addresses = 1;
-  else
-    mips_split_addresses = 0;
+  rtx fn, insn, arg, call;
+  tree id, return_type;
+  enum machine_mode return_mode;
+
+  return_type = DECL_RESULT (current_function_decl);
+  return_mode = DECL_MODE (return_type);
+
+  id = get_identifier (ACONCAT (("__mips16_ret_",
+                                mips16_call_stub_mode_suffix (return_mode),
+                                NULL)));
+  fn = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (id));
+  arg = gen_rtx_REG (return_mode, GP_RETURN);
+  call = gen_call_value_internal (arg, fn, const0_rtx);
+  insn = mips_emit_call_insn (call, false);
+  use_reg (&CALL_INSN_FUNCTION_USAGE (insn), arg);
 }
 
-/* (Re-)Initialize information about relocs.  */
+/* Consider building a stub for a MIPS16 call to function FN.
+   RETVAL is the location of the return value, or null if this is
+   a "call" rather than a "call_value".  ARGS_SIZE is the size of the
+   arguments and FP_CODE is the code built by mips_function_arg;
+   see the comment above CUMULATIVE_ARGS for details.
+
+   If a stub was needed, emit the call and return the call insn itself.
+   Return null otherwise.
 
-static void
-mips_init_relocs (void)
+   A stub is needed for calls to functions that, in normal mode,
+   receive arguments in FPRs or return values in FPRs.  The stub
+   copies the arguments from their soft-float positions to their
+   hard-float positions, calls the real function, then copies the
+   return value from its hard-float position to its soft-float
+   position.
+
+   We emit a JAL to FN even when FN might need a stub.  If FN turns out
+   to be to a non-MIPS16 function, the linker automatically redirects
+   the JAL to the stub, otherwise the JAL continues to call FN directly.  */
+
+static rtx
+mips16_build_call_stub (rtx retval, rtx fn, rtx args_size, int fp_code)
 {
-  memset (mips_split_p, '\0', sizeof (mips_split_p));
-  memset (mips_hi_relocs, '\0', sizeof (mips_hi_relocs));
-  memset (mips_lo_relocs, '\0', sizeof (mips_lo_relocs));
+  const char *fnname;
+  bool fp_ret_p;
+  struct mips16_stub *l;
+  rtx insn;
 
-  if (ABI_HAS_64BIT_SYMBOLS)
-    {
-      if (TARGET_EXPLICIT_RELOCS)
-       {
-         mips_split_p[SYMBOL_64_HIGH] = true;
-         mips_hi_relocs[SYMBOL_64_HIGH] = "%highest(";
-         mips_lo_relocs[SYMBOL_64_HIGH] = "%higher(";
+  /* We don't need to do anything if we aren't in MIPS16 mode, or if
+     we were invoked with the -msoft-float option.  */
+  if (!TARGET_MIPS16 || TARGET_SOFT_FLOAT_ABI)
+    return NULL_RTX;
 
-         mips_split_p[SYMBOL_64_MID] = true;
-         mips_hi_relocs[SYMBOL_64_MID] = "%higher(";
-         mips_lo_relocs[SYMBOL_64_MID] = "%hi(";
+  /* Figure out whether the value might come back in a floating-point
+     register.  */
+  fp_ret_p = retval && mips_return_mode_in_fpr_p (GET_MODE (retval));
 
-         mips_split_p[SYMBOL_64_LOW] = true;
-         mips_hi_relocs[SYMBOL_64_LOW] = "%hi(";
-         mips_lo_relocs[SYMBOL_64_LOW] = "%lo(";
+  /* We don't need to do anything if there were no floating-point
+     arguments and the value will not be returned in a floating-point
+     register.  */
+  if (fp_code == 0 && !fp_ret_p)
+    return NULL_RTX;
 
-         mips_split_p[SYMBOL_ABSOLUTE] = true;
-         mips_lo_relocs[SYMBOL_ABSOLUTE] = "%lo(";
-       }
-    }
-  else
-    {
-      if (TARGET_EXPLICIT_RELOCS || mips_split_addresses || TARGET_MIPS16)
-       {
-         mips_split_p[SYMBOL_ABSOLUTE] = true;
-         mips_hi_relocs[SYMBOL_ABSOLUTE] = "%hi(";
-         mips_lo_relocs[SYMBOL_ABSOLUTE] = "%lo(";
+  /* We don't need to do anything if this is a call to a special
+     MIPS16 support function.  */
+  if (GET_CODE (fn) == SYMBOL_REF
+      && strncmp (XSTR (fn, 0), "__mips16_", 9) == 0)
+    return NULL_RTX;
 
-         mips_lo_relocs[SYMBOL_32_HIGH] = "%hi(";
-       }
-    }
+  /* This code will only work for o32 and o64 abis.  The other ABI's
+     require more sophisticated support.  */
+  gcc_assert (TARGET_OLDABI);
 
-  if (TARGET_MIPS16)
+  /* If we're calling via a function pointer, use one of the magic
+     libgcc.a stubs provided for each (FP_CODE, FP_RET_P) combination.
+     Each stub expects the function address to arrive in register $2.  */
+  if (GET_CODE (fn) != SYMBOL_REF)
     {
-      /* The high part is provided by a pseudo copy of $gp.  */
-      mips_split_p[SYMBOL_GP_RELATIVE] = true;
-      mips_lo_relocs[SYMBOL_GP_RELATIVE] = "%gprel(";
-    }
+      char buf[30];
+      tree id;
+      rtx stub_fn, insn;
 
-  if (TARGET_EXPLICIT_RELOCS)
-    {
-      /* Small data constants are kept whole until after reload,
-        then lowered by mips_rewrite_small_data.  */
-      mips_lo_relocs[SYMBOL_GP_RELATIVE] = "%gp_rel(";
+      /* Create a SYMBOL_REF for the libgcc.a function.  */
+      if (fp_ret_p)
+       sprintf (buf, "__mips16_call_stub_%s_%d",
+                mips16_call_stub_mode_suffix (GET_MODE (retval)),
+                fp_code);
+      else
+       sprintf (buf, "__mips16_call_stub_%d", fp_code);
+      id = get_identifier (buf);
+      stub_fn = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (id));
 
-      mips_split_p[SYMBOL_GOT_PAGE_OFST] = true;
-      if (TARGET_NEWABI)
-       {
-         mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got_page(";
-         mips_lo_relocs[SYMBOL_GOT_PAGE_OFST] = "%got_ofst(";
-       }
+      /* Load the target function into $2.  */
+      mips_emit_move (gen_rtx_REG (Pmode, 2), fn);
+
+      /* Emit the call.  */
+      if (retval == NULL_RTX)
+       insn = gen_call_internal (stub_fn, args_size);
       else
-       {
-         mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got(";
-         mips_lo_relocs[SYMBOL_GOT_PAGE_OFST] = "%lo(";
-       }
+       insn = gen_call_value_internal (retval, stub_fn, args_size);
+      insn = mips_emit_call_insn (insn, false);
 
-      if (TARGET_XGOT)
-       {
-         /* The HIGH and LO_SUM are matched by special .md patterns.  */
-         mips_split_p[SYMBOL_GOT_DISP] = true;
+      /* Tell GCC that this call does indeed use the value of $2.  */
+      CALL_INSN_FUNCTION_USAGE (insn) =
+       gen_rtx_EXPR_LIST (VOIDmode,
+                          gen_rtx_USE (VOIDmode, gen_rtx_REG (Pmode, 2)),
+                          CALL_INSN_FUNCTION_USAGE (insn));
 
-         mips_split_p[SYMBOL_GOTOFF_DISP] = true;
-         mips_hi_relocs[SYMBOL_GOTOFF_DISP] = "%got_hi(";
-         mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got_lo(";
+      /* If we are handling a floating-point return value, we need to
+         save $18 in the function prologue.  Putting a note on the
+         call will mean that df_regs_ever_live_p ($18) will be true if the
+         call is not eliminated, and we can check that in the prologue
+         code.  */
+      if (fp_ret_p)
+       CALL_INSN_FUNCTION_USAGE (insn) =
+         gen_rtx_EXPR_LIST (VOIDmode,
+                            gen_rtx_USE (VOIDmode,
+                                         gen_rtx_REG (word_mode, 18)),
+                            CALL_INSN_FUNCTION_USAGE (insn));
 
-         mips_split_p[SYMBOL_GOTOFF_CALL] = true;
-         mips_hi_relocs[SYMBOL_GOTOFF_CALL] = "%call_hi(";
-         mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call_lo(";
-       }
-      else
-       {
-         if (TARGET_NEWABI)
-           mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got_disp(";
-         else
-           mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got(";
-         mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call16(";
-       }
+      return insn;
     }
 
-  if (TARGET_NEWABI)
+  /* We know the function we are going to call.  If we have already
+     built a stub, we don't need to do anything further.  */
+  fnname = targetm.strip_name_encoding (XSTR (fn, 0));
+  for (l = mips16_stubs; l != NULL; l = l->next)
+    if (strcmp (l->name, fnname) == 0)
+      break;
+
+  if (l == NULL)
     {
-      mips_split_p[SYMBOL_GOTOFF_LOADGP] = true;
-      mips_hi_relocs[SYMBOL_GOTOFF_LOADGP] = "%hi(%neg(%gp_rel(";
-      mips_lo_relocs[SYMBOL_GOTOFF_LOADGP] = "%lo(%neg(%gp_rel(";
-    }
+      const char *separator;
+      char *secname, *stubname;
+      tree stubid, stubdecl;
+      unsigned int f;
 
-  /* Thread-local relocation operators.  */
-  mips_lo_relocs[SYMBOL_TLSGD] = "%tlsgd(";
-  mips_lo_relocs[SYMBOL_TLSLDM] = "%tlsldm(";
-  mips_split_p[SYMBOL_DTPREL] = 1;
-  mips_hi_relocs[SYMBOL_DTPREL] = "%dtprel_hi(";
-  mips_lo_relocs[SYMBOL_DTPREL] = "%dtprel_lo(";
-  mips_lo_relocs[SYMBOL_GOTTPREL] = "%gottprel(";
-  mips_split_p[SYMBOL_TPREL] = 1;
-  mips_hi_relocs[SYMBOL_TPREL] = "%tprel_hi(";
-  mips_lo_relocs[SYMBOL_TPREL] = "%tprel_lo(";
+      /* If the function does not return in FPRs, the special stub
+        section is named
+            .mips16.call.FNNAME
 
-  mips_lo_relocs[SYMBOL_HALF] = "%half(";
-}
+        If the function does return in FPRs, the stub section is named
+            .mips16.call.fp.FNNAME
 
-static GTY(()) int was_mips16_p = -1;
+        Build a decl for the stub.  */
+      secname = ACONCAT ((".mips16.call.", fp_ret_p ? "fp." : "",
+                         fnname, NULL));
+      stubname = ACONCAT (("__call_stub_", fp_ret_p ? "fp_" : "",
+                          fnname, NULL));
+      stubid = get_identifier (stubname);
+      stubdecl = build_decl (FUNCTION_DECL, stubid,
+                            build_function_type (void_type_node, NULL_TREE));
+      DECL_SECTION_NAME (stubdecl) = build_string (strlen (secname), secname);
+      DECL_RESULT (stubdecl) = build_decl (RESULT_DECL, NULL_TREE,
+                                          void_type_node);
 
-/* Set up the target-dependent global state so that it matches the
-   current function's ISA mode.  */
+      /* Output a comment.  */
+      fprintf (asm_out_file, "\t# Stub function to call %s%s (",
+              (fp_ret_p
+               ? (GET_MODE (retval) == SFmode ? "float " : "double ")
+               : ""),
+              fnname);
+      separator = "";
+      for (f = (unsigned int) fp_code; f != 0; f >>= 2)
+       {
+         fprintf (asm_out_file, "%s%s", separator,
+                  (f & 3) == 1 ? "float" : "double");
+         separator = ", ";
+       }
+      fprintf (asm_out_file, ")\n");
 
-static void
-mips_set_mips16_mode (int mips16_p)
-{
-  if (mips16_p == was_mips16_p)
-    return;
+      /* Write the preamble leading up to the function declaration.  */
+      fprintf (asm_out_file, "\t.set\tnomips16\n");
+      assemble_start_function (stubdecl, stubname);
 
-  /* Restore base settings of various flags.  */
-  target_flags = mips_base_target_flags;
-  align_loops = mips_base_align_loops;
-  align_jumps = mips_base_align_jumps;
-  align_functions = mips_base_align_functions;
-  flag_schedule_insns = mips_base_schedule_insns;
-  flag_reorder_blocks_and_partition = mips_base_reorder_blocks_and_partition;
-  flag_move_loop_invariants = mips_base_move_loop_invariants;
-  flag_delayed_branch = mips_flag_delayed_branch;
-  
-  if (mips16_p) 
-    {
-      /* Select mips16 instruction set.  */
-      target_flags |= MASK_MIPS16;
+      if (!FUNCTION_NAME_ALREADY_DECLARED)
+       {
+         fputs ("\t.ent\t", asm_out_file);
+         assemble_name (asm_out_file, stubname);
+         fputs ("\n", asm_out_file);
 
-      /* Don't run the scheduler before reload, since it tends to
-         increase register pressure.  */
-      flag_schedule_insns = 0;
+         assemble_name (asm_out_file, stubname);
+         fputs (":\n", asm_out_file);
+       }
 
-      /* Don't do hot/cold partitioning.  The constant layout code expects
-        the whole function to be in a single section.  */
-      flag_reorder_blocks_and_partition = 0;
+      if (!fp_ret_p)
+       {
+         /* Load the address of the MIPS16 function into $at.  Do this
+            first so that targets with coprocessor interlocks can use
+            an MFC1 to fill the delay slot.  */
+         fprintf (asm_out_file, "\t.set\tnoat\n");
+         fprintf (asm_out_file, "\tla\t%s,%s\n", reg_names[GP_REG_FIRST + 1],
+                  fnname);
+       }
 
-      /* Don't move loop invariants, because it tends to increase
-        register pressure.  It also introduces an extra move in cases
-        where the constant is the first operand in a two-operand binary
-        instruction, or when it forms a register argument to a functon
-        call.  */
-      flag_move_loop_invariants = 0;
+      /* Move the arguments from general registers to floating-point
+        registers.  */
+      mips_output_args_xfer (fp_code, 't');
 
-      /* Silently disable -mexplicit-relocs since it doesn't apply
-        to mips16 code.  Even so, it would overly pedantic to warn
-        about "-mips16 -mexplicit-relocs", especially given that
-        we use a %gprel() operator.  */
-      target_flags &= ~MASK_EXPLICIT_RELOCS;
+      if (!fp_ret_p)
+       {
+         /* Jump to the previously-loaded address.  */
+         fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 1]);
+         fprintf (asm_out_file, "\t.set\tat\n");
+       }
+      else
+       {
+         /* Save the return address in $18 and call the non-MIPS16 function.
+            The stub's caller knows that $18 might be clobbered, even though
+            $18 is usually a call-saved register.  */
+         fprintf (asm_out_file, "\tmove\t%s,%s\n",
+                  reg_names[GP_REG_FIRST + 18], reg_names[GP_REG_FIRST + 31]);
+         fprintf (asm_out_file, "\tjal\t%s\n", fnname);
 
-      /* Experiments suggest we get the best overall results from using
-        the range of an unextended lw or sw.  Code that makes heavy use
-        of byte or short accesses can do better with ranges of 0...31
-        and 0...63 respectively, but most code is sensitive to the range
-        of lw and sw instead.  */
-      targetm.min_anchor_offset = 0;
-      targetm.max_anchor_offset = 127;
+         /* Move the result from floating-point registers to
+            general registers.  */
+         switch (GET_MODE (retval))
+           {
+           case SCmode:
+             mips_output_32bit_xfer ('f', GP_RETURN + 1,
+                                     FP_REG_FIRST + MAX_FPRS_PER_FMT);
+             /* Fall though.  */
+           case SFmode:
+             mips_output_32bit_xfer ('f', GP_RETURN, FP_REG_FIRST);
+             if (GET_MODE (retval) == SCmode && TARGET_64BIT)
+               {
+                 /* On 64-bit targets, complex floats are returned in
+                    a single GPR, such that "sd" on a suitably-aligned
+                    target would store the value correctly.  */
+                 fprintf (asm_out_file, "\tdsll\t%s,%s,32\n",
+                          reg_names[GP_RETURN + TARGET_LITTLE_ENDIAN],
+                          reg_names[GP_RETURN + TARGET_LITTLE_ENDIAN]);
+                 fprintf (asm_out_file, "\tor\t%s,%s,%s\n",
+                          reg_names[GP_RETURN],
+                          reg_names[GP_RETURN],
+                          reg_names[GP_RETURN + 1]);
+               }
+             break;
 
-      if (flag_pic || TARGET_ABICALLS)
-       sorry ("MIPS16 PIC");
-    }
-  else 
-    {
-      /* Reset to select base non-mips16 ISA.  */
-      target_flags &= ~MASK_MIPS16;
+           case DCmode:
+             mips_output_64bit_xfer ('f', GP_RETURN + (8 / UNITS_PER_WORD),
+                                     FP_REG_FIRST + MAX_FPRS_PER_FMT);
+             /* Fall though.  */
+           case DFmode:
+           case V2SFmode:
+             mips_output_64bit_xfer ('f', GP_RETURN, FP_REG_FIRST);
+             break;
 
-      /* When using explicit relocs, we call dbr_schedule from within
-        mips_reorg.  */
-      if (TARGET_EXPLICIT_RELOCS)
-       flag_delayed_branch = 0;
+           default:
+             gcc_unreachable ();
+           }
+         fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 18]);
+       }
 
-      /* Provide default values for align_* for 64-bit targets.  */
-      if (TARGET_64BIT)
+#ifdef ASM_DECLARE_FUNCTION_SIZE
+      ASM_DECLARE_FUNCTION_SIZE (asm_out_file, stubname, stubdecl);
+#endif
+
+      if (!FUNCTION_NAME_ALREADY_DECLARED)
        {
-         if (align_loops == 0)
-           align_loops = 8;
-         if (align_jumps == 0)
-           align_jumps = 8;
-         if (align_functions == 0)
-           align_functions = 8;
+         fputs ("\t.end\t", asm_out_file);
+         assemble_name (asm_out_file, stubname);
+         fputs ("\n", asm_out_file);
        }
 
-      targetm.min_anchor_offset = TARGET_MIN_ANCHOR_OFFSET;
-      targetm.max_anchor_offset = TARGET_MAX_ANCHOR_OFFSET;
+      /* Record this stub.  */
+      l = XNEW (struct mips16_stub);
+      l->name = xstrdup (fnname);
+      l->fp_ret_p = fp_ret_p;
+      l->next = mips16_stubs;
+      mips16_stubs = l;
     }
 
-  /* (Re)initialize mips target internals for new ISA.  */
-  mips_init_split_addresses ();
-  mips_init_relocs ();
-
-  if (was_mips16_p >= 0)
-    /* Reinitialize target-dependent state.  */
-    target_reinit ();
-
-  was_mips16_p = TARGET_MIPS16;
-}
-
-/* Use a hash table to keep track of implicit mips16/nomips16 attributes
-   for -mflip_mips16.  It maps decl names onto a boolean mode setting.  */
-
-struct mflip_mips16_entry GTY (()) {
-  const char *name;
-  bool mips16_p;
-};
-static GTY ((param_is (struct mflip_mips16_entry))) htab_t mflip_mips16_htab;
+  /* If we expect a floating-point return value, but we've built a
+     stub which does not expect one, then we're in trouble.  We can't
+     use the existing stub, because it won't handle the floating-point
+     value.  We can't build a new stub, because the linker won't know
+     which stub to use for the various calls in this object file.
+     Fortunately, this case is illegal, since it means that a function
+     was declared in two different ways in a single compilation.  */
+  if (fp_ret_p && !l->fp_ret_p)
+    error ("cannot handle inconsistent calls to %qs", fnname);
 
-/* Hash table callbacks for mflip_mips16_htab.  */
+  if (retval == NULL_RTX)
+    insn = gen_call_internal_direct (fn, args_size);
+  else
+    insn = gen_call_value_internal_direct (retval, fn, args_size);
+  insn = mips_emit_call_insn (insn, false);
+
+  /* If we are calling a stub which handles a floating-point return
+     value, we need to arrange to save $18 in the prologue.  We do this
+     by marking the function call as using the register.  The prologue
+     will later see that it is used, and emit code to save it.  */
+  if (fp_ret_p)
+    CALL_INSN_FUNCTION_USAGE (insn) =
+      gen_rtx_EXPR_LIST (VOIDmode,
+                        gen_rtx_USE (VOIDmode, gen_rtx_REG (word_mode, 18)),
+                        CALL_INSN_FUNCTION_USAGE (insn));
 
-static hashval_t
-mflip_mips16_htab_hash (const void *entry)
-{
-  return htab_hash_string (((const struct mflip_mips16_entry *) entry)->name);
+  return insn;
 }
+\f
+/* Return true if calls to X can use R_MIPS_CALL* relocations.  */
 
-static int
-mflip_mips16_htab_eq (const void *entry, const void *name)
+static bool
+mips_ok_for_lazy_binding_p (rtx x)
 {
-  return strcmp (((const struct mflip_mips16_entry *) entry)->name,
-                (const char *) name) == 0;
+  return (TARGET_USE_GOT
+         && GET_CODE (x) == SYMBOL_REF
+         && !mips_symbol_binds_local_p (x));
 }
 
-/* DECL is a function that needs a default "mips16" or "nomips16" attribute
-   for -mflip-mips16.  Return true if it should use "mips16" and false if
-   it should use "nomips16".  */
+/* Load function address ADDR into register DEST.  SIBCALL_P is true
+   if the address is needed for a sibling call.  Return true if we
+   used an explicit lazy-binding sequence.  */
 
 static bool
-mflip_mips16_use_mips16_p (tree decl)
+mips_load_call_address (rtx dest, rtx addr, bool sibcall_p)
 {
-  struct mflip_mips16_entry *entry;
-  const char *name;
-  hashval_t hash;
-  void **slot;
-
-  /* Use the opposite of the command-line setting for anonymous decls.  */
-  if (!DECL_NAME (decl))
-    return !mips_base_mips16;
-
-  if (!mflip_mips16_htab)
-    mflip_mips16_htab = htab_create_ggc (37, mflip_mips16_htab_hash,
-                                        mflip_mips16_htab_eq, NULL);
+  /* If we're generating PIC, and this call is to a global function,
+     try to allow its address to be resolved lazily.  This isn't
+     possible for sibcalls when $gp is call-saved because the value
+     of $gp on entry to the stub would be our caller's gp, not ours.  */
+  if (TARGET_EXPLICIT_RELOCS
+      && !(sibcall_p && TARGET_CALL_SAVED_GP)
+      && mips_ok_for_lazy_binding_p (addr))
+    {
+      rtx high, lo_sum_symbol;
 
-  name = IDENTIFIER_POINTER (DECL_NAME (decl));
-  hash = htab_hash_string (name);
-  slot = htab_find_slot_with_hash (mflip_mips16_htab, name, hash, INSERT);
-  entry = (struct mflip_mips16_entry *) *slot;
-  if (!entry)
+      high = mips_unspec_offset_high (dest, pic_offset_table_rtx,
+                                     addr, SYMBOL_GOTOFF_CALL);
+      lo_sum_symbol = mips_unspec_address (addr, SYMBOL_GOTOFF_CALL);
+      if (Pmode == SImode)
+       emit_insn (gen_load_callsi (dest, high, lo_sum_symbol));
+      else
+       emit_insn (gen_load_calldi (dest, high, lo_sum_symbol));
+      return true;
+    }
+  else
     {
-      mips16_flipper = !mips16_flipper;
-      entry = GGC_NEW (struct mflip_mips16_entry);
-      entry->name = name;
-      entry->mips16_p = mips16_flipper ? !mips_base_mips16 : mips_base_mips16;
-      *slot = entry;
+      mips_emit_move (dest, addr);
+      return false;
     }
-  return entry->mips16_p;
 }
 
-/* Implement TARGET_INSERT_ATTRIBUTES.  */
+/* Expand a "call", "sibcall", "call_value" or "sibcall_value" instruction.
+   RESULT is where the result will go (null for "call"s and "sibcall"s),
+   ADDR is the address of the function, ARGS_SIZE is the size of the
+   arguments and AUX is the value passed to us by mips_function_arg.
+   SIBCALL_P is true if we are expanding a sibling call, false if we're
+   expanding a normal call.
 
-static void
-mips_insert_attributes (tree decl, tree *attributes)
+   Return the call itself.  */
+
+rtx
+mips_expand_call (rtx result, rtx addr, rtx args_size, rtx aux, bool sibcall_p)
 {
-  const char *name;
-  bool mips16_p, nomips16_p;
+  rtx orig_addr, pattern, insn;
+  bool lazy_p;
 
-  /* Check for "mips16" and "nomips16" attributes.  */
-  mips16_p = lookup_attribute ("mips16", *attributes) != NULL;
-  nomips16_p = lookup_attribute ("nomips16", *attributes) != NULL;
-  if (TREE_CODE (decl) != FUNCTION_DECL)
+  orig_addr = addr;
+  lazy_p = false;
+  if (!call_insn_operand (addr, VOIDmode))
     {
-      if (mips16_p)
-       error ("%qs attribute only applies to functions", "mips16");
-      if (nomips16_p)
-       error ("%qs attribute only applies to functions", "nomips16");
+      addr = gen_reg_rtx (Pmode);
+      lazy_p = mips_load_call_address (addr, orig_addr, sibcall_p);
     }
-  else
+
+  insn = mips16_build_call_stub (result, addr, args_size,
+                                aux == 0 ? 0 : (int) GET_MODE (aux));
+  if (insn)
     {
-      mips16_p |= mips_mips16_decl_p (decl);
-      nomips16_p |= mips_nomips16_decl_p (decl);
-      if (mips16_p || nomips16_p)
-       {
-         /* DECL cannot be simultaneously mips16 and nomips16.  */
-         if (mips16_p && nomips16_p)
-           error ("%qs cannot have both %<mips16%> and "
-                  "%<nomips16%> attributes",
-                  IDENTIFIER_POINTER (DECL_NAME (decl)));
-       }
-      else if (TARGET_FLIP_MIPS16 && !DECL_ARTIFICIAL (decl))
-       {
-         /* Implement -mflip-mips16.  If DECL has neither a "nomips16" nor a
-            "mips16" attribute, arbitrarily pick one.  We must pick the same
-            setting for duplicate declarations of a function.  */
-         name = mflip_mips16_use_mips16_p (decl) ? "mips16" : "nomips16";
-         *attributes = tree_cons (get_identifier (name), NULL, *attributes);
-       }
+      gcc_assert (!sibcall_p && !lazy_p);
+      return insn;
     }
-}
 
-/* Implement TARGET_MERGE_DECL_ATTRIBUTES.  */
+  if (result == 0)
+    pattern = (sibcall_p
+              ? gen_sibcall_internal (addr, args_size)
+              : gen_call_internal (addr, args_size));
+  else if (GET_CODE (result) == PARALLEL && XVECLEN (result, 0) == 2)
+    {
+      /* Handle return values created by mips_return_fpr_pair.  */
+      rtx reg1, reg2;
 
-static tree
-mips_merge_decl_attributes (tree olddecl, tree newdecl)
-{
-  /* The decls' "mips16" and "nomips16" attributes must match exactly.  */
-  if (mips_mips16_decl_p (olddecl) != mips_mips16_decl_p (newdecl))
-    error ("%qs redeclared with conflicting %qs attributes",
-          IDENTIFIER_POINTER (DECL_NAME (newdecl)), "mips16");
-  if (mips_nomips16_decl_p (olddecl) != mips_nomips16_decl_p (newdecl))
-    error ("%qs redeclared with conflicting %qs attributes",
-          IDENTIFIER_POINTER (DECL_NAME (newdecl)), "nomips16");
+      reg1 = XEXP (XVECEXP (result, 0, 0), 0);
+      reg2 = XEXP (XVECEXP (result, 0, 1), 0);
+      pattern =
+       (sibcall_p
+        ? gen_sibcall_value_multiple_internal (reg1, addr, args_size, reg2)
+        : gen_call_value_multiple_internal (reg1, addr, args_size, reg2));
+    }
+  else
+    {
+      /* Handle return values created by mips_return_fpr_single.  */
+      if (GET_CODE (result) == PARALLEL && XVECLEN (result, 0) == 1)
+       result = XEXP (XVECEXP (result, 0, 0), 0);
+      pattern = (sibcall_p
+                ? gen_sibcall_value_internal (result, addr, args_size)
+                : gen_call_value_internal (result, addr, args_size));
+    }
 
-  return merge_attributes (DECL_ATTRIBUTES (olddecl),
-                          DECL_ATTRIBUTES (newdecl));
+  return mips_emit_call_insn (pattern, lazy_p);
 }
 
-/* Implement TARGET_SET_CURRENT_FUNCTION.  Decide whether the current 
-   function should use the MIPS16 ISA and switch modes accordingly.  */
+/* Implement TARGET_FUNCTION_OK_FOR_SIBCALL.  */
 
-static void
-mips_set_current_function (tree fndecl)
+static bool
+mips_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
 {
-  mips_set_mips16_mode (mips_use_mips16_mode_p (fndecl));
-}
+  if (!TARGET_SIBCALLS)
+    return false;
 
-/* Implement TARGET_HANDLE_OPTION.  */
+  /* We can't do a sibcall if the called function is a MIPS16 function
+     because there is no direct "jx" instruction equivalent to "jalx" to
+     switch the ISA mode.  We only care about cases where the sibling
+     and normal calls would both be direct.  */
+  if (mips_use_mips16_mode_p (decl)
+      && const_call_insn_operand (XEXP (DECL_RTL (decl), 0), VOIDmode))
+    return false;
 
-static bool
-mips_handle_option (size_t code, const char *arg, int value)
-{
-  switch (code)
-    {
-    case OPT_mabi_:
-      if (strcmp (arg, "32") == 0)
-       mips_abi = ABI_32;
-      else if (strcmp (arg, "o64") == 0)
-       mips_abi = ABI_O64;
-      else if (strcmp (arg, "n32") == 0)
-       mips_abi = ABI_N32;
-      else if (strcmp (arg, "64") == 0)
-       mips_abi = ABI_64;
-      else if (strcmp (arg, "eabi") == 0)
-       mips_abi = ABI_EABI;
-      else
-       return false;
-      return true;
+  /* When -minterlink-mips16 is in effect, assume that non-locally-binding
+     functions could be MIPS16 ones unless an attribute explicitly tells
+     us otherwise.  */
+  if (TARGET_INTERLINK_MIPS16
+      && decl
+      && (DECL_EXTERNAL (decl) || !targetm.binds_local_p (decl))
+      && !mips_nomips16_decl_p (decl)
+      && const_call_insn_operand (XEXP (DECL_RTL (decl), 0), VOIDmode))
+    return false;
 
-    case OPT_march_:
-    case OPT_mtune_:
-      return mips_parse_cpu (arg) != 0;
+  /* Otherwise OK.  */
+  return true;
+}
+\f
+/* Emit code to move general operand SRC into condition-code
+   register DEST given that SCRATCH is a scratch TFmode FPR.
+   The sequence is:
 
-    case OPT_mips:
-      mips_isa_info = mips_parse_cpu (ACONCAT (("mips", arg, NULL)));
-      return mips_isa_info != 0;
+       FP1 = SRC
+       FP2 = 0.0f
+       DEST = FP2 < FP1
 
-    case OPT_mno_flush_func:
-      mips_cache_flush_func = NULL;
-      return true;
+   where FP1 and FP2 are single-precision FPRs taken from SCRATCH.  */
 
-    case OPT_mcode_readable_:
-      if (strcmp (arg, "yes") == 0)
-       mips_code_readable = CODE_READABLE_YES;
-      else if (strcmp (arg, "pcrel") == 0)
-       mips_code_readable = CODE_READABLE_PCREL;
-      else if (strcmp (arg, "no") == 0)
-       mips_code_readable = CODE_READABLE_NO;
-      else
-       return false;
-      return true;
+void
+mips_expand_fcc_reload (rtx dest, rtx src, rtx scratch)
+{
+  rtx fp1, fp2;
 
-    case OPT_mllsc:
-      mips_llsc = value ? LLSC_YES : LLSC_NO;
-      return true;
+  /* Change the source to SFmode.  */
+  if (MEM_P (src))
+    src = adjust_address (src, SFmode, 0);
+  else if (REG_P (src) || GET_CODE (src) == SUBREG)
+    src = gen_rtx_REG (SFmode, true_regnum (src));
 
-    default:
-      return true;
-    }
-}
+  fp1 = gen_rtx_REG (SFmode, REGNO (scratch));
+  fp2 = gen_rtx_REG (SFmode, REGNO (scratch) + MAX_FPRS_PER_FMT);
 
-/* Set up the threshold for data to go into the small data area, instead
-   of the normal data area, and detect any conflicts in the switches.  */
+  mips_emit_move (copy_rtx (fp1), src);
+  mips_emit_move (copy_rtx (fp2), CONST0_RTX (SFmode));
+  emit_insn (gen_slt_sf (dest, fp2, fp1));
+}
+\f
+/* Emit straight-line code to move LENGTH bytes from SRC to DEST.
+   Assume that the areas do not overlap.  */
 
-void
-override_options (void)
+static void
+mips_block_move_straight (rtx dest, rtx src, HOST_WIDE_INT length)
 {
-  int i, start, regno;
+  HOST_WIDE_INT offset, delta;
+  unsigned HOST_WIDE_INT bits;
+  int i;
   enum machine_mode mode;
+  rtx *regs;
 
-#ifdef SUBTARGET_OVERRIDE_OPTIONS
-  SUBTARGET_OVERRIDE_OPTIONS;
-#endif
-
-  mips_section_threshold = g_switch_set ? g_switch_value : MIPS_DEFAULT_GVALUE;
+  /* Work out how many bits to move at a time.  If both operands have
+     half-word alignment, it is usually better to move in half words.
+     For instance, lh/lh/sh/sh is usually better than lwl/lwr/swl/swr
+     and lw/lw/sw/sw is usually better than ldl/ldr/sdl/sdr.
+     Otherwise move word-sized chunks.  */
+  if (MEM_ALIGN (src) == BITS_PER_WORD / 2
+      && MEM_ALIGN (dest) == BITS_PER_WORD / 2)
+    bits = BITS_PER_WORD / 2;
+  else
+    bits = BITS_PER_WORD;
 
-  /* The following code determines the architecture and register size.
-     Similar code was added to GAS 2.14 (see tc-mips.c:md_after_parse_args()).
-     The GAS and GCC code should be kept in sync as much as possible.  */
+  mode = mode_for_size (bits, MODE_INT, 0);
+  delta = bits / BITS_PER_UNIT;
 
-  if (mips_arch_string != 0)
-    mips_set_architecture (mips_parse_cpu (mips_arch_string));
+  /* Allocate a buffer for the temporary registers.  */
+  regs = alloca (sizeof (rtx) * length / delta);
 
-  if (mips_isa_info != 0)
+  /* Load as many BITS-sized chunks as possible.  Use a normal load if
+     the source has enough alignment, otherwise use left/right pairs.  */
+  for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
     {
-      if (mips_arch_info == 0)
-       mips_set_architecture (mips_isa_info);
-      else if (mips_arch_info->isa != mips_isa_info->isa)
-       error ("-%s conflicts with the other architecture options, "
-              "which specify a %s processor",
-              mips_isa_info->name,
-              mips_cpu_info_from_isa (mips_arch_info->isa)->name);
+      regs[i] = gen_reg_rtx (mode);
+      if (MEM_ALIGN (src) >= bits)
+       mips_emit_move (regs[i], adjust_address (src, mode, offset));
+      else
+       {
+         rtx part = adjust_address (src, BLKmode, offset);
+         if (!mips_expand_ext_as_unaligned_load (regs[i], part, bits, 0))
+           gcc_unreachable ();
+       }
     }
 
-  if (mips_arch_info == 0)
+  /* Copy the chunks to the destination.  */
+  for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
+    if (MEM_ALIGN (dest) >= bits)
+      mips_emit_move (adjust_address (dest, mode, offset), regs[i]);
+    else
+      {
+       rtx part = adjust_address (dest, BLKmode, offset);
+       if (!mips_expand_ins_as_unaligned_store (part, regs[i], bits, 0))
+         gcc_unreachable ();
+      }
+
+  /* Mop up any left-over bytes.  */
+  if (offset < length)
     {
-#ifdef MIPS_CPU_STRING_DEFAULT
-      mips_set_architecture (mips_parse_cpu (MIPS_CPU_STRING_DEFAULT));
-#else
-      mips_set_architecture (mips_cpu_info_from_isa (MIPS_ISA_DEFAULT));
-#endif
+      src = adjust_address (src, BLKmode, offset);
+      dest = adjust_address (dest, BLKmode, offset);
+      move_by_pieces (dest, src, length - offset,
+                     MIN (MEM_ALIGN (src), MEM_ALIGN (dest)), 0);
     }
+}
 
-  if (ABI_NEEDS_64BIT_REGS && !ISA_HAS_64BIT_REGS)
-    error ("-march=%s is not compatible with the selected ABI",
-          mips_arch_info->name);
+/* Helper function for doing a loop-based block operation on memory
+   reference MEM.  Each iteration of the loop will operate on LENGTH
+   bytes of MEM.
 
-  /* Optimize for mips_arch, unless -mtune selects a different processor.  */
-  if (mips_tune_string != 0)
-    mips_set_tune (mips_parse_cpu (mips_tune_string));
+   Create a new base register for use within the loop and point it to
+   the start of MEM.  Create a new memory reference that uses this
+   register.  Store them in *LOOP_REG and *LOOP_MEM respectively.  */
 
-  if (mips_tune_info == 0)
-    mips_set_tune (mips_arch_info);
-
-  /* Set cost structure for the processor.  */
-  if (optimize_size)
-    mips_cost = &mips_rtx_cost_optimize_size;
-  else
-    mips_cost = &mips_rtx_cost_data[mips_tune];
-
-  /* If the user hasn't specified a branch cost, use the processor's
-     default.  */
-  if (mips_branch_cost == 0)
-    mips_branch_cost = mips_cost->branch_cost;
+static void
+mips_adjust_block_mem (rtx mem, HOST_WIDE_INT length,
+                      rtx *loop_reg, rtx *loop_mem)
+{
+  *loop_reg = copy_addr_to_reg (XEXP (mem, 0));
 
-  if ((target_flags_explicit & MASK_64BIT) != 0)
-    {
-      /* The user specified the size of the integer registers.  Make sure
-        it agrees with the ABI and ISA.  */
-      if (TARGET_64BIT && !ISA_HAS_64BIT_REGS)
-       error ("-mgp64 used with a 32-bit processor");
-      else if (!TARGET_64BIT && ABI_NEEDS_64BIT_REGS)
-       error ("-mgp32 used with a 64-bit ABI");
-      else if (TARGET_64BIT && ABI_NEEDS_32BIT_REGS)
-       error ("-mgp64 used with a 32-bit ABI");
-    }
-  else
-    {
-      /* Infer the integer register size from the ABI and processor.
-        Restrict ourselves to 32-bit registers if that's all the
-        processor has, or if the ABI cannot handle 64-bit registers.  */
-      if (ABI_NEEDS_32BIT_REGS || !ISA_HAS_64BIT_REGS)
-       target_flags &= ~MASK_64BIT;
-      else
-       target_flags |= MASK_64BIT;
-    }
+  /* Although the new mem does not refer to a known location,
+     it does keep up to LENGTH bytes of alignment.  */
+  *loop_mem = change_address (mem, BLKmode, *loop_reg);
+  set_mem_align (*loop_mem, MIN (MEM_ALIGN (mem), length * BITS_PER_UNIT));
+}
 
-  if ((target_flags_explicit & MASK_FLOAT64) != 0)
-    {
-      /* Really, -mfp32 and -mfp64 are ornamental options.  There's
-        only one right answer here.  */
-      if (TARGET_64BIT && TARGET_DOUBLE_FLOAT && !TARGET_FLOAT64)
-       error ("unsupported combination: %s", "-mgp64 -mfp32 -mdouble-float");
-      else if (!TARGET_64BIT && TARGET_FLOAT64
-              && !(ISA_HAS_MXHC1 && mips_abi == ABI_32))
-       error ("-mgp32 and -mfp64 can only be combined if the target"
-              " supports the mfhc1 and mthc1 instructions");
-      else if (TARGET_SINGLE_FLOAT && TARGET_FLOAT64)
-       error ("unsupported combination: %s", "-mfp64 -msingle-float");
-    }
-  else
-    {
-      /* -msingle-float selects 32-bit float registers.  Otherwise the
-        float registers should be the same size as the integer ones.  */
-      if (TARGET_64BIT && TARGET_DOUBLE_FLOAT)
-       target_flags |= MASK_FLOAT64;
-      else
-       target_flags &= ~MASK_FLOAT64;
-    }
+/* Move LENGTH bytes from SRC to DEST using a loop that moves BYTES_PER_ITER
+   bytes at a time.  LENGTH must be at least BYTES_PER_ITER.  Assume that
+   the memory regions do not overlap.  */
 
-  /* End of code shared with GAS.  */
+static void
+mips_block_move_loop (rtx dest, rtx src, HOST_WIDE_INT length,
+                     HOST_WIDE_INT bytes_per_iter)
+{
+  rtx label, src_reg, dest_reg, final_src;
+  HOST_WIDE_INT leftover;
 
-  if ((target_flags_explicit & MASK_LONG64) == 0)
-    {
-      if ((mips_abi == ABI_EABI && TARGET_64BIT) || mips_abi == ABI_64)
-       target_flags |= MASK_LONG64;
-      else
-       target_flags &= ~MASK_LONG64;
-    }
+  leftover = length % bytes_per_iter;
+  length -= leftover;
 
-  if (!TARGET_OLDABI)
-    flag_pcc_struct_return = 0;
+  /* Create registers and memory references for use within the loop.  */
+  mips_adjust_block_mem (src, bytes_per_iter, &src_reg, &src);
+  mips_adjust_block_mem (dest, bytes_per_iter, &dest_reg, &dest);
 
-  if ((target_flags_explicit & MASK_BRANCHLIKELY) == 0)
-    {
-      /* If neither -mbranch-likely nor -mno-branch-likely was given
-        on the command line, set MASK_BRANCHLIKELY based on the target
-        architecture.
-
-        By default, we enable use of Branch Likely instructions on
-        all architectures which support them with the following
-        exceptions: when creating MIPS32 or MIPS64 code, and when
-        tuning for architectures where their use tends to hurt
-        performance.
-
-        The MIPS32 and MIPS64 architecture specifications say "Software
-        is strongly encouraged to avoid use of Branch Likely
-        instructions, as they will be removed from a future revision
-        of the [MIPS32 and MIPS64] architecture."  Therefore, we do not
-        issue those instructions unless instructed to do so by
-        -mbranch-likely.  */
-      if (ISA_HAS_BRANCHLIKELY
-         && !(ISA_MIPS32 || ISA_MIPS32R2 || ISA_MIPS64)
-         && !(TUNE_MIPS5500 || TUNE_SB1))
-       target_flags |= MASK_BRANCHLIKELY;
-      else
-       target_flags &= ~MASK_BRANCHLIKELY;
-    }
-  if (TARGET_BRANCHLIKELY && !ISA_HAS_BRANCHLIKELY)
-    warning (0, "generation of Branch Likely instructions enabled, but not supported by architecture");
+  /* Calculate the value that SRC_REG should have after the last iteration
+     of the loop.  */
+  final_src = expand_simple_binop (Pmode, PLUS, src_reg, GEN_INT (length),
+                                  0, 0, OPTAB_WIDEN);
 
-  /* The effect of -mabicalls isn't defined for the EABI.  */
-  if (mips_abi == ABI_EABI && TARGET_ABICALLS)
-    {
-      error ("unsupported combination: %s", "-mabicalls -mabi=eabi");
-      target_flags &= ~MASK_ABICALLS;
-    }
+  /* Emit the start of the loop.  */
+  label = gen_label_rtx ();
+  emit_label (label);
 
-  /* MIPS16 cannot generate PIC yet.  */
-  if (TARGET_MIPS16 && (flag_pic || TARGET_ABICALLS))
-    {
-      sorry ("MIPS16 PIC");
-      target_flags &= ~MASK_ABICALLS;
-      flag_pic = flag_pie = flag_shlib = 0;
-    }
+  /* Emit the loop body.  */
+  mips_block_move_straight (dest, src, bytes_per_iter);
 
-  if (TARGET_ABICALLS)
-    /* We need to set flag_pic for executables as well as DSOs
-       because we may reference symbols that are not defined in
-       the final executable.  (MIPS does not use things like
-       copy relocs, for example.)
+  /* Move on to the next block.  */
+  mips_emit_move (src_reg, plus_constant (src_reg, bytes_per_iter));
+  mips_emit_move (dest_reg, plus_constant (dest_reg, bytes_per_iter));
 
-       Also, there is a body of code that uses __PIC__ to distinguish
-       between -mabicalls and -mno-abicalls code.  */
-    flag_pic = 1;
+  /* Emit the loop condition.  */
+  if (Pmode == DImode)
+    emit_insn (gen_cmpdi (src_reg, final_src));
+  else
+    emit_insn (gen_cmpsi (src_reg, final_src));
+  emit_jump_insn (gen_bne (label));
 
-  /* -mvr4130-align is a "speed over size" optimization: it usually produces
-     faster code, but at the expense of more nops.  Enable it at -O3 and
-     above.  */
-  if (optimize > 2 && (target_flags_explicit & MASK_VR4130_ALIGN) == 0)
-    target_flags |= MASK_VR4130_ALIGN;
+  /* Mop up any left-over bytes.  */
+  if (leftover)
+    mips_block_move_straight (dest, src, leftover);
+}
 
-  /* Prefer a call to memcpy over inline code when optimizing for size,
-     though see MOVE_RATIO in mips.h.  */
-  if (optimize_size && (target_flags_explicit & MASK_MEMCPY) == 0)
-    target_flags |= MASK_MEMCPY;
+/* Expand a movmemsi instruction, which copies LENGTH bytes from
+   memory reference SRC to memory reference DEST.  */
 
-  /* If we have a nonzero small-data limit, check that the -mgpopt
-     setting is consistent with the other target flags.  */
-  if (mips_section_threshold > 0)
+bool
+mips_expand_block_move (rtx dest, rtx src, rtx length)
+{
+  if (GET_CODE (length) == CONST_INT)
     {
-      if (!TARGET_GPOPT)
+      if (INTVAL (length) <= MIPS_MAX_MOVE_BYTES_STRAIGHT)
        {
-         if (!TARGET_MIPS16 && !TARGET_EXPLICIT_RELOCS)
-           error ("%<-mno-gpopt%> needs %<-mexplicit-relocs%>");
-
-         TARGET_LOCAL_SDATA = false;
-         TARGET_EXTERN_SDATA = false;
+         mips_block_move_straight (dest, src, INTVAL (length));
+         return true;
        }
-      else
+      else if (optimize)
        {
-         if (TARGET_VXWORKS_RTP)
-           warning (0, "cannot use small-data accesses for %qs", "-mrtp");
-
-         if (TARGET_ABICALLS)
-           warning (0, "cannot use small-data accesses for %qs",
-                    "-mabicalls");
+         mips_block_move_loop (dest, src, INTVAL (length),
+                               MIPS_MAX_MOVE_BYTES_PER_LOOP_ITER);
+         return true;
        }
     }
+  return false;
+}
+\f
+/* Expand a loop of synci insns for the address range [BEGIN, END).  */
 
-#ifdef MIPS_TFMODE_FORMAT
-  REAL_MODE_FORMAT (TFmode) = &MIPS_TFMODE_FORMAT;
-#endif
-
-  /* Make sure that the user didn't turn off paired single support when
-     MIPS-3D support is requested.  */
-  if (TARGET_MIPS3D && (target_flags_explicit & MASK_PAIRED_SINGLE_FLOAT)
-      && !TARGET_PAIRED_SINGLE_FLOAT)
-    error ("-mips3d requires -mpaired-single");
-
-  /* If TARGET_MIPS3D, enable MASK_PAIRED_SINGLE_FLOAT.  */
-  if (TARGET_MIPS3D)
-    target_flags |= MASK_PAIRED_SINGLE_FLOAT;
+void
+mips_expand_synci_loop (rtx begin, rtx end)
+{
+  rtx inc, label, cmp, cmp_result;
 
-  /* Make sure that when TARGET_PAIRED_SINGLE_FLOAT is true, TARGET_FLOAT64
-     and TARGET_HARD_FLOAT_ABI are both true.  */
-  if (TARGET_PAIRED_SINGLE_FLOAT && !(TARGET_FLOAT64 && TARGET_HARD_FLOAT_ABI))
-    error ("-mips3d/-mpaired-single must be used with -mfp64 -mhard-float");
+  /* Load INC with the cache line size (rdhwr INC,$1).  */
+  inc = gen_reg_rtx (SImode);
+  emit_insn (gen_rdhwr (inc, const1_rtx));
 
-  /* Make sure that the ISA supports TARGET_PAIRED_SINGLE_FLOAT when it is
-     enabled.  */
-  if (TARGET_PAIRED_SINGLE_FLOAT && !ISA_MIPS64)
-    error ("-mips3d/-mpaired-single must be used with -mips64");
+  /* Loop back to here.  */
+  label = gen_label_rtx ();
+  emit_label (label);
 
-  /* If TARGET_DSPR2, enable MASK_DSP.  */
-  if (TARGET_DSPR2)
-    target_flags |= MASK_DSP;
+  emit_insn (gen_synci (begin));
 
-  mips_print_operand_punct['?'] = 1;
-  mips_print_operand_punct['#'] = 1;
-  mips_print_operand_punct['/'] = 1;
-  mips_print_operand_punct['&'] = 1;
-  mips_print_operand_punct['!'] = 1;
-  mips_print_operand_punct['*'] = 1;
-  mips_print_operand_punct['@'] = 1;
-  mips_print_operand_punct['.'] = 1;
-  mips_print_operand_punct['('] = 1;
-  mips_print_operand_punct[')'] = 1;
-  mips_print_operand_punct['['] = 1;
-  mips_print_operand_punct[']'] = 1;
-  mips_print_operand_punct['<'] = 1;
-  mips_print_operand_punct['>'] = 1;
-  mips_print_operand_punct['{'] = 1;
-  mips_print_operand_punct['}'] = 1;
-  mips_print_operand_punct['^'] = 1;
-  mips_print_operand_punct['$'] = 1;
-  mips_print_operand_punct['+'] = 1;
-  mips_print_operand_punct['~'] = 1;
-  mips_print_operand_punct['|'] = 1;
-  mips_print_operand_punct['-'] = 1;
+  cmp = gen_reg_rtx (Pmode);
+  mips_emit_binary (GTU, cmp, begin, end);
 
-  /* Set up array to map GCC register number to debug register number.
-     Ignore the special purpose register numbers.  */
+  mips_emit_binary (PLUS, begin, begin, inc);
 
-  for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
-    {
-      mips_dbx_regno[i] = INVALID_REGNUM;
-      if (GP_REG_P (i) || FP_REG_P (i) || ALL_COP_REG_P (i))
-       mips_dwarf_regno[i] = i;
-      else
-       mips_dwarf_regno[i] = INVALID_REGNUM;
-    }
+  cmp_result = gen_rtx_EQ (VOIDmode, cmp, const0_rtx);
+  emit_jump_insn (gen_condjump (cmp_result, label));
+}
+\f
+/* Return true if it is possible to use left/right accesses for a
+   bitfield of WIDTH bits starting BITPOS bits into *OP.  When
+   returning true, update *OP, *LEFT and *RIGHT as follows:
 
-  start = GP_DBX_FIRST - GP_REG_FIRST;
-  for (i = GP_REG_FIRST; i <= GP_REG_LAST; i++)
-    mips_dbx_regno[i] = i + start;
+   *OP is a BLKmode reference to the whole field.
 
-  start = FP_DBX_FIRST - FP_REG_FIRST;
-  for (i = FP_REG_FIRST; i <= FP_REG_LAST; i++)
-    mips_dbx_regno[i] = i + start;
+   *LEFT is a QImode reference to the first byte if big endian or
+   the last byte if little endian.  This address can be used in the
+   left-side instructions (LWL, SWL, LDL, SDL).
 
-  /* HI and LO debug registers use big-endian ordering.  */
-  mips_dbx_regno[HI_REGNUM] = MD_DBX_FIRST + 0;
-  mips_dbx_regno[LO_REGNUM] = MD_DBX_FIRST + 1;
-  mips_dwarf_regno[HI_REGNUM] = MD_REG_FIRST + 0;
-  mips_dwarf_regno[LO_REGNUM] = MD_REG_FIRST + 1;
-  for (i = DSP_ACC_REG_FIRST; i <= DSP_ACC_REG_LAST; i += 2)
-    {
-      mips_dwarf_regno[i + TARGET_LITTLE_ENDIAN] = i;
-      mips_dwarf_regno[i + TARGET_BIG_ENDIAN] = i + 1;
-    }
+   *RIGHT is a QImode reference to the opposite end of the field and
+   can be used in the patterning right-side instruction.  */
 
-  /* Set up array giving whether a given register can hold a given mode.  */
+static bool
+mips_get_unaligned_mem (rtx *op, HOST_WIDE_INT width, HOST_WIDE_INT bitpos,
+                       rtx *left, rtx *right)
+{
+  rtx first, last;
 
-  for (mode = VOIDmode;
-       mode != MAX_MACHINE_MODE;
-       mode = (enum machine_mode) ((int)mode + 1))
-    {
-      register int size                     = GET_MODE_SIZE (mode);
-      register enum mode_class class = GET_MODE_CLASS (mode);
+  /* Check that the operand really is a MEM.  Not all the extv and
+     extzv predicates are checked.  */
+  if (!MEM_P (*op))
+    return false;
 
-      for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
-       {
-         register int temp;
+  /* Check that the size is valid.  */
+  if (width != 32 && (!TARGET_64BIT || width != 64))
+    return false;
 
-         if (mode == CCV2mode)
-           temp = (ISA_HAS_8CC
-                   && ST_REG_P (regno)
-                   && (regno - ST_REG_FIRST) % 2 == 0);
+  /* We can only access byte-aligned values.  Since we are always passed
+     a reference to the first byte of the field, it is not necessary to
+     do anything with BITPOS after this check.  */
+  if (bitpos % BITS_PER_UNIT != 0)
+    return false;
 
-         else if (mode == CCV4mode)
-           temp = (ISA_HAS_8CC
-                   && ST_REG_P (regno)
-                   && (regno - ST_REG_FIRST) % 4 == 0);
+  /* Reject aligned bitfields: we want to use a normal load or store
+     instead of a left/right pair.  */
+  if (MEM_ALIGN (*op) >= width)
+    return false;
 
-         else if (mode == CCmode)
-           {
-             if (! ISA_HAS_8CC)
-               temp = (regno == FPSW_REGNUM);
-             else
-               temp = (ST_REG_P (regno) || GP_REG_P (regno)
-                       || FP_REG_P (regno));
-           }
+  /* Adjust *OP to refer to the whole field.  This also has the effect
+     of legitimizing *OP's address for BLKmode, possibly simplifying it.  */
+  *op = adjust_address (*op, BLKmode, 0);
+  set_mem_size (*op, GEN_INT (width / BITS_PER_UNIT));
 
-         else if (GP_REG_P (regno))
-           temp = ((regno & 1) == 0 || size <= UNITS_PER_WORD);
-
-         else if (FP_REG_P (regno))
-           temp = ((((regno % MAX_FPRS_PER_FMT) == 0)
-                    || (MIN_FPRS_PER_FMT == 1
-                        && size <= UNITS_PER_FPREG))
-                   && (((class == MODE_FLOAT || class == MODE_COMPLEX_FLOAT
-                         || class == MODE_VECTOR_FLOAT)
-                        && size <= UNITS_PER_FPVALUE)
-                       /* Allow integer modes that fit into a single
-                          register.  We need to put integers into FPRs
-                          when using instructions like cvt and trunc.
-                          We can't allow sizes smaller than a word,
-                          the FPU has no appropriate load/store
-                          instructions for those.  */
-                       || (class == MODE_INT
-                           && size >= MIN_UNITS_PER_WORD
-                           && size <= UNITS_PER_FPREG)
-                       /* Allow TFmode for CCmode reloads.  */
-                       || (ISA_HAS_8CC && mode == TFmode)));
-
-          else if (ACC_REG_P (regno))
-           temp = ((INTEGRAL_MODE_P (mode) || ALL_FIXED_POINT_MODE_P (mode))
-                   && size <= UNITS_PER_WORD * 2
-                   && (size <= UNITS_PER_WORD
-                       || regno == MD_REG_FIRST
-                       || (DSP_ACC_REG_P (regno)
-                           && ((regno - DSP_ACC_REG_FIRST) & 1) == 0)));
-
-         else if (ALL_COP_REG_P (regno))
-           temp = (class == MODE_INT && size <= UNITS_PER_WORD);
-         else
-           temp = 0;
+  /* Get references to both ends of the field.  We deliberately don't
+     use the original QImode *OP for FIRST since the new BLKmode one
+     might have a simpler address.  */
+  first = adjust_address (*op, QImode, 0);
+  last = adjust_address (*op, QImode, width / BITS_PER_UNIT - 1);
 
-         mips_hard_regno_mode_ok[(int)mode][regno] = temp;
-       }
-    }
+  /* Allocate to LEFT and RIGHT according to endianness.  LEFT should
+     correspond to the MSB and RIGHT to the LSB.  */
+  if (TARGET_BIG_ENDIAN)
+    *left = first, *right = last;
+  else
+    *left = last, *right = first;
 
-  /* Save GPR registers in word_mode sized hunks.  word_mode hasn't been
-     initialized yet, so we can't use that here.  */
-  gpr_mode = TARGET_64BIT ? DImode : SImode;
+  return true;
+}
 
-  /* Function to allocate machine-dependent function status.  */
-  init_machine_status = &mips_init_machine_status;
+/* Try to use left/right loads to expand an "extv" or "extzv" pattern.
+   DEST, SRC, WIDTH and BITPOS are the operands passed to the expander;
+   the operation is the equivalent of:
 
-  /* Default to working around R4000 errata only if the processor
-     was selected explicitly.  */
-  if ((target_flags_explicit & MASK_FIX_R4000) == 0
-      && mips_matching_cpu_name_p (mips_arch_info->name, "r4000"))
-    target_flags |= MASK_FIX_R4000;
+      (set DEST (*_extract SRC WIDTH BITPOS))
 
-  /* Default to working around R4400 errata only if the processor
-     was selected explicitly.  */
-  if ((target_flags_explicit & MASK_FIX_R4400) == 0
-      && mips_matching_cpu_name_p (mips_arch_info->name, "r4400"))
-    target_flags |= MASK_FIX_R4400;
+   Return true on success.  */
 
-  /* Save base state of options.  */
-  mips_base_mips16 = TARGET_MIPS16;
-  mips_base_target_flags = target_flags;
-  mips_base_schedule_insns = flag_schedule_insns;
-  mips_base_reorder_blocks_and_partition = flag_reorder_blocks_and_partition;
-  mips_base_move_loop_invariants = flag_move_loop_invariants;
-  mips_base_align_loops = align_loops;
-  mips_base_align_jumps = align_jumps;
-  mips_base_align_functions = align_functions;
-  mips_flag_delayed_branch = flag_delayed_branch;
+bool
+mips_expand_ext_as_unaligned_load (rtx dest, rtx src, HOST_WIDE_INT width,
+                                  HOST_WIDE_INT bitpos)
+{
+  rtx left, right, temp;
 
-  /* Now select the mips16 or 32-bit instruction set, as requested.  */
-  mips_set_mips16_mode (mips_base_mips16);
-}
+  /* If TARGET_64BIT, the destination of a 32-bit "extz" or "extzv" will
+     be a paradoxical word_mode subreg.  This is the only case in which
+     we allow the destination to be larger than the source.  */
+  if (GET_CODE (dest) == SUBREG
+      && GET_MODE (dest) == DImode
+      && GET_MODE (SUBREG_REG (dest)) == SImode)
+    dest = SUBREG_REG (dest);
 
-/* Swap the register information for registers I and I + 1, which
-   currently have the wrong endianness.  Note that the registers'
-   fixedness and call-clobberedness might have been set on the
-   command line.  */
+  /* After the above adjustment, the destination must be the same
+     width as the source.  */
+  if (GET_MODE_BITSIZE (GET_MODE (dest)) != width)
+    return false;
 
-static void
-mips_swap_registers (unsigned int i)
-{
-  int tmpi;
-  const char *tmps;
+  if (!mips_get_unaligned_mem (&src, width, bitpos, &left, &right))
+    return false;
 
-#define SWAP_INT(X, Y) (tmpi = (X), (X) = (Y), (Y) = tmpi)
-#define SWAP_STRING(X, Y) (tmps = (X), (X) = (Y), (Y) = tmps)
+  temp = gen_reg_rtx (GET_MODE (dest));
+  if (GET_MODE (dest) == DImode)
+    {
+      emit_insn (gen_mov_ldl (temp, src, left));
+      emit_insn (gen_mov_ldr (dest, copy_rtx (src), right, temp));
+    }
+  else
+    {
+      emit_insn (gen_mov_lwl (temp, src, left));
+      emit_insn (gen_mov_lwr (dest, copy_rtx (src), right, temp));
+    }
+  return true;
+}
 
-  SWAP_INT (fixed_regs[i], fixed_regs[i + 1]);
-  SWAP_INT (call_used_regs[i], call_used_regs[i + 1]);
-  SWAP_INT (call_really_used_regs[i], call_really_used_regs[i + 1]);
-  SWAP_STRING (reg_names[i], reg_names[i + 1]);
+/* Try to use left/right stores to expand an "ins" pattern.  DEST, WIDTH,
+   BITPOS and SRC are the operands passed to the expander; the operation
+   is the equivalent of:
 
-#undef SWAP_STRING
-#undef SWAP_INT
-}
+       (set (zero_extract DEST WIDTH BITPOS) SRC)
 
-/* Implement CONDITIONAL_REGISTER_USAGE.  */
+   Return true on success.  */
 
-void
-mips_conditional_register_usage (void)
+bool
+mips_expand_ins_as_unaligned_store (rtx dest, rtx src, HOST_WIDE_INT width,
+                                   HOST_WIDE_INT bitpos)
 {
-  if (!ISA_HAS_DSP)
-    {
-      int regno;
-
-      for (regno = DSP_ACC_REG_FIRST; regno <= DSP_ACC_REG_LAST; regno++)
-       fixed_regs[regno] = call_used_regs[regno] = 1;
-    }
-  if (!TARGET_HARD_FLOAT)
-    {
-      int regno;
+  rtx left, right;
+  enum machine_mode mode;
 
-      for (regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
-       fixed_regs[regno] = call_used_regs[regno] = 1;
-      for (regno = ST_REG_FIRST; regno <= ST_REG_LAST; regno++)
-       fixed_regs[regno] = call_used_regs[regno] = 1;
-    }
-  else if (! ISA_HAS_8CC)
-    {
-      int regno;
+  if (!mips_get_unaligned_mem (&dest, width, bitpos, &left, &right))
+    return false;
 
-      /* We only have a single condition code register.  We
-        implement this by hiding all the condition code registers,
-        and generating RTL that refers directly to ST_REG_FIRST.  */
-      for (regno = ST_REG_FIRST; regno <= ST_REG_LAST; regno++)
-       fixed_regs[regno] = call_used_regs[regno] = 1;
-    }
-  /* In mips16 mode, we permit the $t temporary registers to be used
-     for reload.  We prohibit the unused $s registers, since they
-     are caller saved, and saving them via a mips16 register would
-     probably waste more time than just reloading the value.  */
-  if (TARGET_MIPS16)
-    {
-      fixed_regs[18] = call_used_regs[18] = 1;
-      fixed_regs[19] = call_used_regs[19] = 1;
-      fixed_regs[20] = call_used_regs[20] = 1;
-      fixed_regs[21] = call_used_regs[21] = 1;
-      fixed_regs[22] = call_used_regs[22] = 1;
-      fixed_regs[23] = call_used_regs[23] = 1;
-      fixed_regs[26] = call_used_regs[26] = 1;
-      fixed_regs[27] = call_used_regs[27] = 1;
-      fixed_regs[30] = call_used_regs[30] = 1;
-    }
-  /* fp20-23 are now caller saved.  */
-  if (mips_abi == ABI_64)
-    {
-      int regno;
-      for (regno = FP_REG_FIRST + 20; regno < FP_REG_FIRST + 24; regno++)
-       call_really_used_regs[regno] = call_used_regs[regno] = 1;
-    }
-  /* Odd registers from fp21 to fp31 are now caller saved.  */
-  if (mips_abi == ABI_N32)
+  mode = mode_for_size (width, MODE_INT, 0);
+  src = gen_lowpart (mode, src);
+  if (mode == DImode)
     {
-      int regno;
-      for (regno = FP_REG_FIRST + 21; regno <= FP_REG_FIRST + 31; regno+=2)
-       call_really_used_regs[regno] = call_used_regs[regno] = 1;
+      emit_insn (gen_mov_sdl (dest, src, left));
+      emit_insn (gen_mov_sdr (copy_rtx (dest), copy_rtx (src), right));
     }
-  /* Make sure that double-register accumulator values are correctly
-     ordered for the current endianness.  */
-  if (TARGET_LITTLE_ENDIAN)
+  else
     {
-      int regno;
-      mips_swap_registers (MD_REG_FIRST);
-      for (regno = DSP_ACC_REG_FIRST; regno <= DSP_ACC_REG_LAST; regno += 2)
-       mips_swap_registers (regno);
+      emit_insn (gen_mov_swl (dest, src, left));
+      emit_insn (gen_mov_swr (copy_rtx (dest), copy_rtx (src), right));
     }
+  return true;
 }
 
-/* Allocate a chunk of memory for per-function machine-dependent data.  */
-static struct machine_function *
-mips_init_machine_status (void)
-{
-  return ((struct machine_function *)
-         ggc_alloc_cleared (sizeof (struct machine_function)));
-}
-
-/* On the mips16, we want to allocate $24 (T_REG) before other
-   registers for instructions for which it is possible.  This helps
-   avoid shuffling registers around in order to set up for an xor,
-   encouraging the compiler to use a cmp instead.  */
+/* Return true if X is a MEM with the same size as MODE.  */
 
-void
-mips_order_regs_for_local_alloc (void)
+bool
+mips_mem_fits_mode_p (enum machine_mode mode, rtx x)
 {
-  register int i;
+  rtx size;
 
-  for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
-    reg_alloc_order[i] = i;
+  if (!MEM_P (x))
+    return false;
 
-  if (TARGET_MIPS16)
-    {
-      /* It really doesn't matter where we put register 0, since it is
-         a fixed register anyhow.  */
-      reg_alloc_order[0] = 24;
-      reg_alloc_order[24] = 0;
-    }
+  size = MEM_SIZE (x);
+  return size && INTVAL (size) == GET_MODE_SIZE (mode);
 }
 
-\f
-/* The MIPS debug format wants all automatic variables and arguments
-   to be in terms of the virtual frame pointer (stack pointer before
-   any adjustment in the function), while the MIPS 3.0 linker wants
-   the frame pointer to be the stack pointer after the initial
-   adjustment.  So, we do the adjustment here.  The arg pointer (which
-   is eliminated) points to the virtual frame pointer, while the frame
-   pointer (which may be eliminated) points to the stack pointer after
-   the initial adjustments.  */
-
-HOST_WIDE_INT
-mips_debugger_offset (rtx addr, HOST_WIDE_INT offset)
-{
-  rtx offset2 = const0_rtx;
-  rtx reg = eliminate_constant_term (addr, &offset2);
+/* Return true if (zero_extract OP WIDTH BITPOS) can be used as the
+   source of an "ext" instruction or the destination of an "ins"
+   instruction.  OP must be a register operand and the following
+   conditions must hold:
 
-  if (offset == 0)
-    offset = INTVAL (offset2);
+     0 <= BITPOS < GET_MODE_BITSIZE (GET_MODE (op))
+     0 < WIDTH <= GET_MODE_BITSIZE (GET_MODE (op))
+     0 < BITPOS + WIDTH <= GET_MODE_BITSIZE (GET_MODE (op))
 
-  if (reg == stack_pointer_rtx || reg == frame_pointer_rtx
-      || reg == hard_frame_pointer_rtx)
-    {
-      HOST_WIDE_INT frame_size = (!cfun->machine->frame.initialized)
-                                 ? compute_frame_size (get_frame_size ())
-                                 : cfun->machine->frame.total_size;
+   Also reject lengths equal to a word as they are better handled
+   by the move patterns.  */
 
-      /* MIPS16 frame is smaller */
-      if (frame_pointer_needed && TARGET_MIPS16)
-       frame_size -= cfun->machine->frame.args_size;
+bool
+mips_use_ins_ext_p (rtx op, HOST_WIDE_INT width, HOST_WIDE_INT bitpos)
+{
+  if (!ISA_HAS_EXT_INS
+      || !register_operand (op, VOIDmode)
+      || GET_MODE_BITSIZE (GET_MODE (op)) > BITS_PER_WORD)
+    return false;
 
-      offset = offset - frame_size;
-    }
+  if (!IN_RANGE (width, 1, GET_MODE_BITSIZE (GET_MODE (op)) - 1))
+    return false;
 
-  /* sdbout_parms does not want this to crash for unrecognized cases.  */
-#if 0
-  else if (reg != arg_pointer_rtx)
-    fatal_insn ("mips_debugger_offset called with non stack/frame/arg pointer",
-               addr);
-#endif
+  if (bitpos < 0 || bitpos + width > GET_MODE_BITSIZE (GET_MODE (op)))
+    return false;
 
-  return offset;
+  return true;
 }
 \f
-/* If OP is an UNSPEC address, return the address to which it refers,
-   otherwise return OP itself.  */
-
-static rtx
-mips_strip_unspec_address (rtx op)
-{
-  rtx base, offset;
+/* Return true if -msplit-addresses is selected and should be honored.
 
-  split_const (op, &base, &offset);
-  if (UNSPEC_ADDRESS_P (base))
-    op = plus_constant (UNSPEC_ADDRESS (base), INTVAL (offset));
-  return op;
-}
+   -msplit-addresses is a half-way house between explicit relocations
+   and the traditional assembler macros.  It can split absolute 32-bit
+   symbolic constants into a high/lo_sum pair but uses macros for other
+   sorts of access.
 
-/* Implement the PRINT_OPERAND macro.  The MIPS-specific operand codes are:
+   Like explicit relocation support for REL targets, it relies
+   on GNU extensions in the assembler and the linker.
 
-   'X'  OP is CONST_INT, prints 32 bits in hexadecimal format = "0x%08x",
-   'x'  OP is CONST_INT, prints 16 bits in hexadecimal format = "0x%04x",
-   'h'  OP is HIGH, prints %hi(X),
-   'd'  output integer constant in decimal,
-   'z' if the operand is 0, use $0 instead of normal operand.
-   'D'  print second part of double-word register or memory operand.
-   'L'  print low-order register of double-word register operand.
-   'M'  print high-order register of double-word register operand.
-   'C'  print part of opcode for a branch condition.
-   'F'  print part of opcode for a floating-point branch condition.
-   'N'  print part of opcode for a branch condition, inverted.
-   'W'  print part of opcode for a floating-point branch condition, inverted.
-   'T'  print 'f' for (eq:CC ...), 't' for (ne:CC ...),
-             'z' for (eq:?I ...), 'n' for (ne:?I ...).
-   't'  like 'T', but with the EQ/NE cases reversed
-   'Y'  for a CONST_INT X, print mips_fp_conditions[X]
-   'Z'  print the operand and a comma for ISA_HAS_8CC, otherwise print nothing
-   'R'  print the reloc associated with LO_SUM
-   'q'  print DSP accumulator registers
+   Although this code should work for -O0, it has traditionally
+   been treated as an optimization.  */
 
-   The punctuation characters are:
+static bool
+mips_split_addresses_p (void)
+{
+  return (TARGET_SPLIT_ADDRESSES
+         && optimize
+         && !TARGET_MIPS16
+         && !flag_pic
+         && !ABI_HAS_64BIT_SYMBOLS);
+}
 
-   '(' Turn on .set noreorder
-   ')' Turn on .set reorder
-   '[' Turn on .set noat
-   ']' Turn on .set at
-   '<' Turn on .set nomacro
-   '>' Turn on .set macro
-   '{' Turn on .set volatile (not GAS)
-   '}' Turn on .set novolatile (not GAS)
-   '&' Turn on .set noreorder if filling delay slots
-   '*' Turn on both .set noreorder and .set nomacro if filling delay slots
-   '!' Turn on .set nomacro if filling delay slots
-   '#' Print nop if in a .set noreorder section.
-   '/' Like '#', but does nothing within a delayed branch sequence
-   '?' Print 'l' if we are to use a branch likely instead of normal branch.
-   '@' Print the name of the assembler temporary register (at or $1).
-   '.' Print the name of the register with a hard-wired zero (zero or $0).
-   '^' Print the name of the pic call-through register (t9 or $25).
-   '$' Print the name of the stack pointer register (sp or $29).
-   '+' Print the name of the gp register (usually gp or $28).
-   '~' Output a branch alignment to LABEL_ALIGN(NULL).
-   '|'  Print .set push; .set mips2 if mips_llsc == LLSC_YES
-        && !ISA_HAS_LL_SC.
-   '-'  Print .set pop under the same conditions for '|'.  */
+/* (Re-)Initialize mips_split_p, mips_lo_relocs and mips_hi_relocs.  */
 
-void
-print_operand (FILE *file, rtx op, int letter)
+static void
+mips_init_relocs (void)
 {
-  register enum rtx_code code;
+  memset (mips_split_p, '\0', sizeof (mips_split_p));
+  memset (mips_hi_relocs, '\0', sizeof (mips_hi_relocs));
+  memset (mips_lo_relocs, '\0', sizeof (mips_lo_relocs));
 
-  if (PRINT_OPERAND_PUNCT_VALID_P (letter))
+  if (ABI_HAS_64BIT_SYMBOLS)
     {
-      switch (letter)
+      if (TARGET_EXPLICIT_RELOCS)
        {
-       case '?':
-         if (mips_branch_likely)
-           putc ('l', file);
-         break;
-
-       case '@':
-         fputs (reg_names [GP_REG_FIRST + 1], file);
-         break;
+         mips_split_p[SYMBOL_64_HIGH] = true;
+         mips_hi_relocs[SYMBOL_64_HIGH] = "%highest(";
+         mips_lo_relocs[SYMBOL_64_HIGH] = "%higher(";
 
-       case '^':
-         fputs (reg_names [PIC_FUNCTION_ADDR_REGNUM], file);
-         break;
-
-       case '.':
-         fputs (reg_names [GP_REG_FIRST + 0], file);
-         break;
-
-       case '$':
-         fputs (reg_names[STACK_POINTER_REGNUM], file);
-         break;
+         mips_split_p[SYMBOL_64_MID] = true;
+         mips_hi_relocs[SYMBOL_64_MID] = "%higher(";
+         mips_lo_relocs[SYMBOL_64_MID] = "%hi(";
 
-       case '+':
-         fputs (reg_names[PIC_OFFSET_TABLE_REGNUM], file);
-         break;
+         mips_split_p[SYMBOL_64_LOW] = true;
+         mips_hi_relocs[SYMBOL_64_LOW] = "%hi(";
+         mips_lo_relocs[SYMBOL_64_LOW] = "%lo(";
 
-       case '&':
-         if (final_sequence != 0 && set_noreorder++ == 0)
-           fputs (".set\tnoreorder\n\t", file);
-         break;
+         mips_split_p[SYMBOL_ABSOLUTE] = true;
+         mips_lo_relocs[SYMBOL_ABSOLUTE] = "%lo(";
+       }
+    }
+  else
+    {
+      if (TARGET_EXPLICIT_RELOCS || mips_split_addresses_p () || TARGET_MIPS16)
+       {
+         mips_split_p[SYMBOL_ABSOLUTE] = true;
+         mips_hi_relocs[SYMBOL_ABSOLUTE] = "%hi(";
+         mips_lo_relocs[SYMBOL_ABSOLUTE] = "%lo(";
 
-       case '*':
-         if (final_sequence != 0)
-           {
-             if (set_noreorder++ == 0)
-               fputs (".set\tnoreorder\n\t", file);
+         mips_lo_relocs[SYMBOL_32_HIGH] = "%hi(";
+       }
+    }
 
-             if (set_nomacro++ == 0)
-               fputs (".set\tnomacro\n\t", file);
-           }
-         break;
+  if (TARGET_MIPS16)
+    {
+      /* The high part is provided by a pseudo copy of $gp.  */
+      mips_split_p[SYMBOL_GP_RELATIVE] = true;
+      mips_lo_relocs[SYMBOL_GP_RELATIVE] = "%gprel(";
+    }
 
-       case '!':
-         if (final_sequence != 0 && set_nomacro++ == 0)
-           fputs ("\n\t.set\tnomacro", file);
-         break;
+  if (TARGET_EXPLICIT_RELOCS)
+    {
+      /* Small data constants are kept whole until after reload,
+        then lowered by mips_rewrite_small_data.  */
+      mips_lo_relocs[SYMBOL_GP_RELATIVE] = "%gp_rel(";
 
-       case '#':
-         if (set_noreorder != 0)
-           fputs ("\n\tnop", file);
-         break;
+      mips_split_p[SYMBOL_GOT_PAGE_OFST] = true;
+      if (TARGET_NEWABI)
+       {
+         mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got_page(";
+         mips_lo_relocs[SYMBOL_GOT_PAGE_OFST] = "%got_ofst(";
+       }
+      else
+       {
+         mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got(";
+         mips_lo_relocs[SYMBOL_GOT_PAGE_OFST] = "%lo(";
+       }
 
-       case '/':
-         /* Print an extra newline so that the delayed insn is separated
-            from the following ones.  This looks neater and is consistent
-            with non-nop delayed sequences.  */
-         if (set_noreorder != 0 && final_sequence == 0)
-           fputs ("\n\tnop\n", file);
-         break;
+      if (TARGET_XGOT)
+       {
+         /* The HIGH and LO_SUM are matched by special .md patterns.  */
+         mips_split_p[SYMBOL_GOT_DISP] = true;
 
-       case '(':
-         if (set_noreorder++ == 0)
-           fputs (".set\tnoreorder\n\t", file);
-         break;
+         mips_split_p[SYMBOL_GOTOFF_DISP] = true;
+         mips_hi_relocs[SYMBOL_GOTOFF_DISP] = "%got_hi(";
+         mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got_lo(";
 
-       case ')':
-         if (set_noreorder == 0)
-           error ("internal error: %%) found without a %%( in assembler pattern");
+         mips_split_p[SYMBOL_GOTOFF_CALL] = true;
+         mips_hi_relocs[SYMBOL_GOTOFF_CALL] = "%call_hi(";
+         mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call_lo(";
+       }
+      else
+       {
+         if (TARGET_NEWABI)
+           mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got_disp(";
+         else
+           mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got(";
+         mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call16(";
+       }
+    }
 
-         else if (--set_noreorder == 0)
-           fputs ("\n\t.set\treorder", file);
+  if (TARGET_NEWABI)
+    {
+      mips_split_p[SYMBOL_GOTOFF_LOADGP] = true;
+      mips_hi_relocs[SYMBOL_GOTOFF_LOADGP] = "%hi(%neg(%gp_rel(";
+      mips_lo_relocs[SYMBOL_GOTOFF_LOADGP] = "%lo(%neg(%gp_rel(";
+    }
 
-         break;
+  mips_lo_relocs[SYMBOL_TLSGD] = "%tlsgd(";
+  mips_lo_relocs[SYMBOL_TLSLDM] = "%tlsldm(";
 
-       case '[':
-         if (set_noat++ == 0)
-           fputs (".set\tnoat\n\t", file);
-         break;
+  mips_split_p[SYMBOL_DTPREL] = true;
+  mips_hi_relocs[SYMBOL_DTPREL] = "%dtprel_hi(";
+  mips_lo_relocs[SYMBOL_DTPREL] = "%dtprel_lo(";
 
-       case ']':
-         if (set_noat == 0)
-           error ("internal error: %%] found without a %%[ in assembler pattern");
-         else if (--set_noat == 0)
-           fputs ("\n\t.set\tat", file);
+  mips_lo_relocs[SYMBOL_GOTTPREL] = "%gottprel(";
 
-         break;
+  mips_split_p[SYMBOL_TPREL] = true;
+  mips_hi_relocs[SYMBOL_TPREL] = "%tprel_hi(";
+  mips_lo_relocs[SYMBOL_TPREL] = "%tprel_lo(";
 
-       case '<':
-         if (set_nomacro++ == 0)
-           fputs (".set\tnomacro\n\t", file);
-         break;
+  mips_lo_relocs[SYMBOL_HALF] = "%half(";
+}
 
-       case '>':
-         if (set_nomacro == 0)
-           error ("internal error: %%> found without a %%< in assembler pattern");
-         else if (--set_nomacro == 0)
-           fputs ("\n\t.set\tmacro", file);
+/* If OP is an UNSPEC address, return the address to which it refers,
+   otherwise return OP itself.  */
 
-         break;
+static rtx
+mips_strip_unspec_address (rtx op)
+{
+  rtx base, offset;
 
-       case '{':
-         if (set_volatile++ == 0)
-           fputs ("#.set\tvolatile\n\t", file);
-         break;
+  split_const (op, &base, &offset);
+  if (UNSPEC_ADDRESS_P (base))
+    op = plus_constant (UNSPEC_ADDRESS (base), INTVAL (offset));
+  return op;
+}
 
-       case '}':
-         if (set_volatile == 0)
-           error ("internal error: %%} found without a %%{ in assembler pattern");
-         else if (--set_volatile == 0)
-           fputs ("\n\t#.set\tnovolatile", file);
+/* Print symbolic operand OP, which is part of a HIGH or LO_SUM
+   in context CONTEXT.  RELOCS is the array of relocations to use.  */
 
-         break;
+static void
+mips_print_operand_reloc (FILE *file, rtx op, enum mips_symbol_context context,
+                         const char **relocs)
+{
+  enum mips_symbol_type symbol_type;
+  const char *p;
 
-       case '~':
-         {
-           if (align_labels_log > 0)
-             ASM_OUTPUT_ALIGN (file, align_labels_log);
-         }
-         break;
+  symbol_type = mips_classify_symbolic_expression (op, context);
+  gcc_assert (relocs[symbol_type]);
 
-       case '|':
-         if (!ISA_HAS_LL_SC)
-           fputs (".set\tpush\n\t.set\tmips2\n\t", file);
-         break;
+  fputs (relocs[symbol_type], file);
+  output_addr_const (file, mips_strip_unspec_address (op));
+  for (p = relocs[symbol_type]; *p != 0; p++)
+    if (*p == '(')
+      fputc (')', file);
+}
 
-       case '-':
-         if (!ISA_HAS_LL_SC)
-           fputs ("\n\t.set\tpop", file);
-         break;
+/* Print the text for PRINT_OPERAND punctation character CH to FILE.
+   The punctuation characters are:
 
-       default:
-         error ("PRINT_OPERAND: unknown punctuation '%c'", letter);
-         break;
-       }
+   '(' Start a nested ".set noreorder" block.
+   ')' End a nested ".set noreorder" block.
+   '[' Start a nested ".set noat" block.
+   ']' End a nested ".set noat" block.
+   '<' Start a nested ".set nomacro" block.
+   '>' End a nested ".set nomacro" block.
+   '*' Behave like %(%< if generating a delayed-branch sequence.
+   '#' Print a nop if in a ".set noreorder" block.
+   '/' Like '#', but do nothing within a delayed-branch sequence.
+   '?' Print "l" if mips_branch_likely is true
+   '.' Print the name of the register with a hard-wired zero (zero or $0).
+   '@' Print the name of the assembler temporary register (at or $1).
+   '^' Print the name of the pic call-through register (t9 or $25).
+   '+' Print the name of the gp register (usually gp or $28).
+   '$' Print the name of the stack pointer register (sp or $29).
+   '|' Print ".set push; .set mips2" if !ISA_HAS_LL_SC.
+   '-' Print ".set pop" under the same conditions for '|'.
 
-      return;
-    }
+   See also mips_init_print_operand_pucnt.  */
 
-  if (! op)
+static void
+mips_print_operand_punctuation (FILE *file, int ch)
+{
+  switch (ch)
     {
-      error ("PRINT_OPERAND null pointer");
-      return;
-    }
-
-  code = GET_CODE (op);
+    case '(':
+      if (set_noreorder++ == 0)
+       fputs (".set\tnoreorder\n\t", file);
+      break;
 
-  if (letter == 'C')
-    switch (code)
-      {
-      case EQ: fputs ("eq",  file); break;
-      case NE: fputs ("ne",  file); break;
-      case GT: fputs ("gt",  file); break;
-      case GE: fputs ("ge",  file); break;
-      case LT: fputs ("lt",  file); break;
-      case LE: fputs ("le",  file); break;
-      case GTU: fputs ("gtu", file); break;
-      case GEU: fputs ("geu", file); break;
-      case LTU: fputs ("ltu", file); break;
-      case LEU: fputs ("leu", file); break;
-      default:
-       fatal_insn ("PRINT_OPERAND, invalid insn for %%C", op);
-      }
+    case ')':
+      gcc_assert (set_noreorder > 0);
+      if (--set_noreorder == 0)
+       fputs ("\n\t.set\treorder", file);
+      break;
 
-  else if (letter == 'N')
-    switch (code)
-      {
-      case EQ: fputs ("ne",  file); break;
-      case NE: fputs ("eq",  file); break;
-      case GT: fputs ("le",  file); break;
-      case GE: fputs ("lt",  file); break;
-      case LT: fputs ("ge",  file); break;
-      case LE: fputs ("gt",  file); break;
-      case GTU: fputs ("leu", file); break;
-      case GEU: fputs ("ltu", file); break;
-      case LTU: fputs ("geu", file); break;
-      case LEU: fputs ("gtu", file); break;
-      default:
-       fatal_insn ("PRINT_OPERAND, invalid insn for %%N", op);
-      }
+    case '[':
+      if (set_noat++ == 0)
+       fputs (".set\tnoat\n\t", file);
+      break;
 
-  else if (letter == 'F')
-    switch (code)
-      {
-      case EQ: fputs ("c1f", file); break;
-      case NE: fputs ("c1t", file); break;
-      default:
-       fatal_insn ("PRINT_OPERAND, invalid insn for %%F", op);
-      }
+    case ']':
+      gcc_assert (set_noat > 0);
+      if (--set_noat == 0)
+       fputs ("\n\t.set\tat", file);
+      break;
 
-  else if (letter == 'W')
-    switch (code)
-      {
-      case EQ: fputs ("c1t", file); break;
-      case NE: fputs ("c1f", file); break;
-      default:
-       fatal_insn ("PRINT_OPERAND, invalid insn for %%W", op);
-      }
+    case '<':
+      if (set_nomacro++ == 0)
+       fputs (".set\tnomacro\n\t", file);
+      break;
 
-  else if (letter == 'h')
-    {
-      if (GET_CODE (op) == HIGH)
-       op = XEXP (op, 0);
+    case '>':
+      gcc_assert (set_nomacro > 0);
+      if (--set_nomacro == 0)
+       fputs ("\n\t.set\tmacro", file);
+      break;
 
-      print_operand_reloc (file, op, SYMBOL_CONTEXT_LEA, mips_hi_relocs);
-    }
+    case '*':
+      if (final_sequence != 0)
+       {
+         mips_print_operand_punctuation (file, '(');
+         mips_print_operand_punctuation (file, '<');
+       }
+      break;
 
-  else if (letter == 'R')
-    print_operand_reloc (file, op, SYMBOL_CONTEXT_LEA, mips_lo_relocs);
+    case '#':
+      if (set_noreorder != 0)
+       fputs ("\n\tnop", file);
+      break;
 
-  else if (letter == 'Y')
-    {
-      if (GET_CODE (op) == CONST_INT
-         && ((unsigned HOST_WIDE_INT) INTVAL (op)
-             < ARRAY_SIZE (mips_fp_conditions)))
-       fputs (mips_fp_conditions[INTVAL (op)], file);
-      else
-       output_operand_lossage ("invalid %%Y value");
-    }
+    case '/':
+      /* Print an extra newline so that the delayed insn is separated
+        from the following ones.  This looks neater and is consistent
+        with non-nop delayed sequences.  */
+      if (set_noreorder != 0 && final_sequence == 0)
+       fputs ("\n\tnop\n", file);
+      break;
 
-  else if (letter == 'Z')
-    {
-      if (ISA_HAS_8CC)
-       {
-         print_operand (file, op, 0);
-         fputc (',', file);
-       }
-    }
+    case '?':
+      if (mips_branch_likely)
+       putc ('l', file);
+      break;
 
-  else if (letter == 'q')
-    {
-      int regnum;
+    case '.':
+      fputs (reg_names[GP_REG_FIRST + 0], file);
+      break;
 
-      if (code != REG)
-       fatal_insn ("PRINT_OPERAND, invalid insn for %%q", op);
+    case '@':
+      fputs (reg_names[GP_REG_FIRST + 1], file);
+      break;
 
-      regnum = REGNO (op);
-      if (MD_REG_P (regnum))
-       fprintf (file, "$ac0");
-      else if (DSP_ACC_REG_P (regnum))
-       fprintf (file, "$ac%c", reg_names[regnum][3]);
-      else
-       fatal_insn ("PRINT_OPERAND, invalid insn for %%q", op);
-    }
+    case '^':
+      fputs (reg_names[PIC_FUNCTION_ADDR_REGNUM], file);
+      break;
 
-  else if (code == REG || code == SUBREG)
-    {
-      register int regnum;
+    case '+':
+      fputs (reg_names[PIC_OFFSET_TABLE_REGNUM], file);
+      break;
 
-      if (code == REG)
-       regnum = REGNO (op);
-      else
-       regnum = true_regnum (op);
+    case '$':
+      fputs (reg_names[STACK_POINTER_REGNUM], file);
+      break;
 
-      if ((letter == 'M' && ! WORDS_BIG_ENDIAN)
-         || (letter == 'L' && WORDS_BIG_ENDIAN)
-         || letter == 'D')
-       regnum++;
+    case '|':
+      if (!ISA_HAS_LL_SC)
+       fputs (".set\tpush\n\t.set\tmips2\n\t", file);
+      break;
 
-      fprintf (file, "%s", reg_names[regnum]);
-    }
+    case '-':
+      if (!ISA_HAS_LL_SC)
+       fputs ("\n\t.set\tpop", file);
+      break;
 
-  else if (code == MEM)
-    {
-      if (letter == 'D')
-       output_address (plus_constant (XEXP (op, 0), 4));
-      else
-       output_address (XEXP (op, 0));
+    default:
+      gcc_unreachable ();
+      break;
     }
+}
 
-  else if (letter == 'x' && GET_CODE (op) == CONST_INT)
-    fprintf (file, HOST_WIDE_INT_PRINT_HEX, 0xffff & INTVAL(op));
-
-  else if (letter == 'X' && GET_CODE(op) == CONST_INT)
-    fprintf (file, HOST_WIDE_INT_PRINT_HEX, INTVAL (op));
+/* Initialize mips_print_operand_punct.  */
 
-  else if (letter == 'd' && GET_CODE(op) == CONST_INT)
-    fprintf (file, HOST_WIDE_INT_PRINT_DEC, (INTVAL(op)));
+static void
+mips_init_print_operand_punct (void)
+{
+  const char *p;
 
-  else if (letter == 'z' && op == CONST0_RTX (GET_MODE (op)))
-    fputs (reg_names[GP_REG_FIRST], file);
+  for (p = "()[]<>*#/?.@^+$|-"; *p; p++)
+    mips_print_operand_punct[(unsigned char) *p] = true;
+}
 
-  else if (letter == 'd' || letter == 'x' || letter == 'X')
-    output_operand_lossage ("invalid use of %%d, %%x, or %%X");
+/* PRINT_OPERAND prefix LETTER refers to the integer branch instruction
+   associated with condition CODE.  Print the condition part of the
+   opcode to FILE.  */
 
-  else if (letter == 'T' || letter == 't')
+static void
+mips_print_int_branch_condition (FILE *file, enum rtx_code code, int letter)
+{
+  switch (code)
     {
-      int truth = (code == NE) == (letter == 'T');
-      fputc ("zfnt"[truth * 2 + (GET_MODE (op) == CCmode)], file);
-    }
-
-  else if (CONST_GP_P (op))
-    fputs (reg_names[GLOBAL_POINTER_REGNUM], file);
+    case EQ:
+    case NE:
+    case GT:
+    case GE:
+    case LT:
+    case LE:
+    case GTU:
+    case GEU:
+    case LTU:
+    case LEU:
+      /* Conveniently, the MIPS names for these conditions are the same
+        as their RTL equivalents.  */
+      fputs (GET_RTX_NAME (code), file);
+      break;
 
-  else
-    output_addr_const (file, mips_strip_unspec_address (op));
+    default:
+      output_operand_lossage ("'%%%c' is not a valid operand prefix", letter);
+      break;
+    }
 }
 
-
-/* Print symbolic operand OP, which is part of a HIGH or LO_SUM
-   in context CONTEXT.  RELOCS is the array of relocations to use.  */
+/* Likewise floating-point branches.  */
 
 static void
-print_operand_reloc (FILE *file, rtx op, enum mips_symbol_context context,
-                    const char **relocs)
+mips_print_float_branch_condition (FILE *file, enum rtx_code code, int letter)
 {
-  enum mips_symbol_type symbol_type;
-  const char *p;
+  switch (code)
+    {
+    case EQ:
+      fputs ("c1f", file);
+      break;
 
-  symbol_type = mips_classify_symbolic_expression (op, context);
-  if (relocs[symbol_type] == 0)
-    fatal_insn ("PRINT_OPERAND, invalid operand for relocation", op);
+    case NE:
+      fputs ("c1t", file);
+      break;
 
-  fputs (relocs[symbol_type], file);
-  output_addr_const (file, mips_strip_unspec_address (op));
-  for (p = relocs[symbol_type]; *p != 0; p++)
-    if (*p == '(')
-      fputc (')', file);
+    default:
+      output_operand_lossage ("'%%%c' is not a valid operand prefix", letter);
+      break;
+    }
 }
-\f
-/* Output address operand X to FILE.  */
+
+/* Implement the PRINT_OPERAND macro.  The MIPS-specific operand codes are:
+
+   'X' Print CONST_INT OP in hexadecimal format.
+   'x' Print the low 16 bits of CONST_INT OP in hexadecimal format.
+   'd' Print CONST_INT OP in decimal.
+   'h' Print the high-part relocation associated with OP, after stripping
+         any outermost HIGH.
+   'R' Print the low-part relocation associated with OP.
+   'C' Print the integer branch condition for comparison OP.
+   'N' Print the inverse of the integer branch condition for comparison OP.
+   'F' Print the FPU branch condition for comparison OP.
+   'W' Print the inverse of the FPU branch condition for comparison OP.
+   'T' Print 'f' for (eq:CC ...), 't' for (ne:CC ...),
+             'z' for (eq:?I ...), 'n' for (ne:?I ...).
+   't' Like 'T', but with the EQ/NE cases reversed
+   'Y' Print mips_fp_conditions[INTVAL (OP)]
+   'Z' Print OP and a comma for ISA_HAS_8CC, otherwise print nothing.
+   'q' Print a DSP accumulator register.
+   'D' Print the second part of a double-word register or memory operand.
+   'L' Print the low-order register in a double-word register operand.
+   'M' Print high-order register in a double-word register operand.
+   'z' Print $0 if OP is zero, otherwise print OP normally.  */
 
 void
-print_operand_address (FILE *file, rtx x)
+mips_print_operand (FILE *file, rtx op, int letter)
 {
-  struct mips_address_info addr;
+  enum rtx_code code;
 
-  if (mips_classify_address (&addr, x, word_mode, true))
-    switch (addr.type)
-      {
-      case ADDRESS_REG:
-       print_operand (file, addr.offset, 0);
-       fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
+  if (PRINT_OPERAND_PUNCT_VALID_P (letter))
+    {
+      mips_print_operand_punctuation (file, letter);
+      return;
+    }
+
+  gcc_assert (op);
+  code = GET_CODE (op);
+
+  switch (letter)
+    {
+    case 'X':
+      if (GET_CODE (op) == CONST_INT)
+       fprintf (file, HOST_WIDE_INT_PRINT_HEX, INTVAL (op));
+      else
+       output_operand_lossage ("invalid use of '%%%c'", letter);
+      break;
+
+    case 'x':
+      if (GET_CODE (op) == CONST_INT)
+       fprintf (file, HOST_WIDE_INT_PRINT_HEX, INTVAL (op) & 0xffff);
+      else
+       output_operand_lossage ("invalid use of '%%%c'", letter);
+      break;
+
+    case 'd':
+      if (GET_CODE (op) == CONST_INT)
+       fprintf (file, HOST_WIDE_INT_PRINT_DEC, INTVAL (op));
+      else
+       output_operand_lossage ("invalid use of '%%%c'", letter);
+      break;
+
+    case 'h':
+      if (code == HIGH)
+       op = XEXP (op, 0);
+      mips_print_operand_reloc (file, op, SYMBOL_CONTEXT_LEA, mips_hi_relocs);
+      break;
+
+    case 'R':
+      mips_print_operand_reloc (file, op, SYMBOL_CONTEXT_LEA, mips_lo_relocs);
+      break;
+
+    case 'C':
+      mips_print_int_branch_condition (file, code, letter);
+      break;
+
+    case 'N':
+      mips_print_int_branch_condition (file, reverse_condition (code), letter);
+      break;
+
+    case 'F':
+      mips_print_float_branch_condition (file, code, letter);
+      break;
+
+    case 'W':
+      mips_print_float_branch_condition (file, reverse_condition (code),
+                                        letter);
+      break;
+
+    case 'T':
+    case 't':
+      {
+       int truth = (code == NE) == (letter == 'T');
+       fputc ("zfnt"[truth * 2 + (GET_MODE (op) == CCmode)], file);
+      }
+      break;
+
+    case 'Y':
+      if (code == CONST_INT && UINTVAL (op) < ARRAY_SIZE (mips_fp_conditions))
+       fputs (mips_fp_conditions[UINTVAL (op)], file);
+      else
+       output_operand_lossage ("'%%%c' is not a valid operand prefix",
+                               letter);
+      break;
+
+    case 'Z':
+      if (ISA_HAS_8CC)
+       {
+         mips_print_operand (file, op, 0);
+         fputc (',', file);
+       }
+      break;
+
+    case 'q':
+      if (code == REG && MD_REG_P (REGNO (op)))
+       fprintf (file, "$ac0");
+      else if (code == REG && DSP_ACC_REG_P (REGNO (op)))
+       fprintf (file, "$ac%c", reg_names[REGNO (op)][3]);
+      else
+       output_operand_lossage ("invalid use of '%%%c'", letter);
+      break;
+
+    default:
+      switch (code)
+       {
+       case REG:
+         {
+           unsigned int regno = REGNO (op);
+           if ((letter == 'M' && TARGET_LITTLE_ENDIAN)
+               || (letter == 'L' && TARGET_BIG_ENDIAN)
+               || letter == 'D')
+             regno++;
+           fprintf (file, "%s", reg_names[regno]);
+         }
+         break;
+
+       case MEM:
+         if (letter == 'D')
+           output_address (plus_constant (XEXP (op, 0), 4));
+         else
+           output_address (XEXP (op, 0));
+         break;
+
+       default:
+         if (letter == 'z' && op == CONST0_RTX (GET_MODE (op)))
+           fputs (reg_names[GP_REG_FIRST], file);
+         else if (CONST_GP_P (op))
+           fputs (reg_names[GLOBAL_POINTER_REGNUM], file);
+         else
+           output_addr_const (file, mips_strip_unspec_address (op));
+         break;
+       }
+    }
+}
+
+/* Output address operand X to FILE.  */
+
+void
+mips_print_operand_address (FILE *file, rtx x)
+{
+  struct mips_address_info addr;
+
+  if (mips_classify_address (&addr, x, word_mode, true))
+    switch (addr.type)
+      {
+      case ADDRESS_REG:
+       mips_print_operand (file, addr.offset, 0);
+       fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
        return;
 
       case ADDRESS_LO_SUM:
-       print_operand_reloc (file, addr.offset, SYMBOL_CONTEXT_MEM,
-                            mips_lo_relocs);
+       mips_print_operand_reloc (file, addr.offset, SYMBOL_CONTEXT_MEM,
+                                 mips_lo_relocs);
        fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
        return;
 
       case ADDRESS_CONST_INT:
        output_addr_const (file, x);
-       fprintf (file, "(%s)", reg_names[0]);
+       fprintf (file, "(%s)", reg_names[GP_REG_FIRST]);
        return;
 
       case ADDRESS_SYMBOLIC:
@@ -6909,13 +6580,192 @@ print_operand_address (FILE *file, rtx x)
   gcc_unreachable ();
 }
 \f
-/* When using assembler macros, keep track of all of small-data externs
-   so that mips_file_end can emit the appropriate declarations for them.
+/* Implement TARGET_ENCODE_SECTION_INFO.  */
+
+static void
+mips_encode_section_info (tree decl, rtx rtl, int first)
+{
+  default_encode_section_info (decl, rtl, first);
+
+  if (TREE_CODE (decl) == FUNCTION_DECL)
+    {
+      rtx symbol = XEXP (rtl, 0);
+      tree type = TREE_TYPE (decl);
+
+      /* Encode whether the symbol is short or long.  */
+      if ((TARGET_LONG_CALLS && !mips_near_type_p (type))
+         || mips_far_type_p (type))
+       SYMBOL_REF_FLAGS (symbol) |= SYMBOL_FLAG_LONG_CALL;
+    }
+}
+
+/* Implement TARGET_SELECT_RTX_SECTION.  */
+
+static section *
+mips_select_rtx_section (enum machine_mode mode, rtx x,
+                        unsigned HOST_WIDE_INT align)
+{
+  /* ??? Consider using mergeable small data sections.  */
+  if (mips_rtx_constant_in_small_data_p (mode))
+    return get_named_section (NULL, ".sdata", 0);
+
+  return default_elf_select_rtx_section (mode, x, align);
+}
+
+/* Implement TARGET_ASM_FUNCTION_RODATA_SECTION.
+
+   The complication here is that, with the combination TARGET_ABICALLS
+   && !TARGET_GPWORD, jump tables will use absolute addresses, and should
+   therefore not be included in the read-only part of a DSO.  Handle such
+   cases by selecting a normal data section instead of a read-only one.
+   The logic apes that in default_function_rodata_section.  */
+
+static section *
+mips_function_rodata_section (tree decl)
+{
+  if (!TARGET_ABICALLS || TARGET_GPWORD)
+    return default_function_rodata_section (decl);
+
+  if (decl && DECL_SECTION_NAME (decl))
+    {
+      const char *name = TREE_STRING_POINTER (DECL_SECTION_NAME (decl));
+      if (DECL_ONE_ONLY (decl) && strncmp (name, ".gnu.linkonce.t.", 16) == 0)
+       {
+         char *rname = ASTRDUP (name);
+         rname[14] = 'd';
+         return get_section (rname, SECTION_LINKONCE | SECTION_WRITE, decl);
+       }
+      else if (flag_function_sections
+              && flag_data_sections
+              && strncmp (name, ".text.", 6) == 0)
+       {
+         char *rname = ASTRDUP (name);
+         memcpy (rname + 1, "data", 4);
+         return get_section (rname, SECTION_WRITE, decl);
+       }
+    }
+  return data_section;
+}
+
+/* Implement TARGET_IN_SMALL_DATA_P.  */
+
+static bool
+mips_in_small_data_p (const_tree decl)
+{
+  unsigned HOST_WIDE_INT size;
+
+  if (TREE_CODE (decl) == STRING_CST || TREE_CODE (decl) == FUNCTION_DECL)
+    return false;
+
+  /* We don't yet generate small-data references for -mabicalls
+     or VxWorks RTP code.  See the related -G handling in
+     mips_override_options.  */
+  if (TARGET_ABICALLS || TARGET_VXWORKS_RTP)
+    return false;
+
+  if (TREE_CODE (decl) == VAR_DECL && DECL_SECTION_NAME (decl) != 0)
+    {
+      const char *name;
+
+      /* Reject anything that isn't in a known small-data section.  */
+      name = TREE_STRING_POINTER (DECL_SECTION_NAME (decl));
+      if (strcmp (name, ".sdata") != 0 && strcmp (name, ".sbss") != 0)
+       return false;
+
+      /* If a symbol is defined externally, the assembler will use the
+        usual -G rules when deciding how to implement macros.  */
+      if (mips_lo_relocs[SYMBOL_GP_RELATIVE] || !DECL_EXTERNAL (decl))
+       return true;
+    }
+  else if (TARGET_EMBEDDED_DATA)
+    {
+      /* Don't put constants into the small data section: we want them
+        to be in ROM rather than RAM.  */
+      if (TREE_CODE (decl) != VAR_DECL)
+       return false;
+
+      if (TREE_READONLY (decl)
+         && !TREE_SIDE_EFFECTS (decl)
+         && (!DECL_INITIAL (decl) || TREE_CONSTANT (DECL_INITIAL (decl))))
+       return false;
+    }
+
+  /* Enforce -mlocal-sdata.  */
+  if (!TARGET_LOCAL_SDATA && !TREE_PUBLIC (decl))
+    return false;
+
+  /* Enforce -mextern-sdata.  */
+  if (!TARGET_EXTERN_SDATA && DECL_P (decl))
+    {
+      if (DECL_EXTERNAL (decl))
+       return false;
+      if (DECL_COMMON (decl) && DECL_INITIAL (decl) == NULL)
+       return false;
+    }
+
+  /* We have traditionally not treated zero-sized objects as small data,
+     so this is now effectively part of the ABI.  */
+  size = int_size_in_bytes (TREE_TYPE (decl));
+  return size > 0 && size <= mips_small_data_threshold;
+}
+
+/* Implement TARGET_USE_ANCHORS_FOR_SYMBOL_P.  We don't want to use
+   anchors for small data: the GP register acts as an anchor in that
+   case.  We also don't want to use them for PC-relative accesses,
+   where the PC acts as an anchor.  */
+
+static bool
+mips_use_anchors_for_symbol_p (const_rtx symbol)
+{
+  switch (mips_classify_symbol (symbol, SYMBOL_CONTEXT_MEM))
+    {
+    case SYMBOL_PC_RELATIVE:
+    case SYMBOL_GP_RELATIVE:
+      return false;
+
+    default:
+      return default_use_anchors_for_symbol_p (symbol);
+    }
+}
+\f
+/* The MIPS debug format wants all automatic variables and arguments
+   to be in terms of the virtual frame pointer (stack pointer before
+   any adjustment in the function), while the MIPS 3.0 linker wants
+   the frame pointer to be the stack pointer after the initial
+   adjustment.  So, we do the adjustment here.  The arg pointer (which
+   is eliminated) points to the virtual frame pointer, while the frame
+   pointer (which may be eliminated) points to the stack pointer after
+   the initial adjustments.  */
+
+HOST_WIDE_INT
+mips_debugger_offset (rtx addr, HOST_WIDE_INT offset)
+{
+  rtx offset2 = const0_rtx;
+  rtx reg = eliminate_constant_term (addr, &offset2);
 
-   In most cases it would be safe (though pointless) to emit .externs
-   for other symbols too.  One exception is when an object is within
-   the -G limit but declared by the user to be in a section other
-   than .sbss or .sdata.  */
+  if (offset == 0)
+    offset = INTVAL (offset2);
+
+  if (reg == stack_pointer_rtx
+      || reg == frame_pointer_rtx
+      || reg == hard_frame_pointer_rtx)
+    {
+      offset -= cfun->machine->frame.total_size;
+      if (reg == hard_frame_pointer_rtx)
+       offset += cfun->machine->frame.hard_frame_pointer_offset;
+    }
+
+  /* sdbout_parms does not want this to crash for unrecognized cases.  */
+#if 0
+  else if (reg != arg_pointer_rtx)
+    fatal_insn ("mips_debugger_offset called with non stack/frame/arg pointer",
+               addr);
+#endif
+
+  return offset;
+}
+\f
+/* Implement ASM_OUTPUT_EXTERNAL.  */
 
 void
 mips_output_external (FILE *file, tree decl, const char *name)
@@ -6929,6 +6779,14 @@ mips_output_external (FILE *file, tree decl, const char *name)
     {
       if (!TARGET_EXPLICIT_RELOCS && mips_in_small_data_p (decl))
        {
+         /* When using assembler macros, emit .extern directives for
+            all small-data externs so that the assembler knows how
+            big they are.
+
+            In most cases it would be safe (though pointless) to emit
+            .externs for other symbols too.  One exception is when an
+            object is within the -G limit but declared by the user to
+            be in a section other than .sbss or .sdata.  */
          fputs ("\t.extern\t", file);
          assemble_name (file, name);
          fprintf (file, ", " HOST_WIDE_INT_PRINT_DEC "\n",
@@ -6949,14 +6807,12 @@ mips_output_external (FILE *file, tree decl, const char *name)
        }
     }
 }
-\f
-/* Emit a new filename to a stream.  If we are smuggling stabs, try to
-   put out a MIPS ECOFF file and a stab.  */
+
+/* Implement ASM_OUTPUT_SOURCE_FILENAME.  */
 
 void
 mips_output_filename (FILE *stream, const char *name)
 {
-
   /* If we are emitting DWARF-2, let dwarf2out handle the ".file"
      directives.  */
   if (write_symbols == DWARF2_DEBUG)
@@ -6970,12 +6826,10 @@ mips_output_filename (FILE *stream, const char *name)
       output_quoted_string (stream, name);
       putc ('\n', stream);
     }
-
   /* If we are emitting stabs, let dbxout.c handle this (except for
      the mips_output_filename_first_time case).  */
   else if (write_symbols == DBX_DEBUG)
     return;
-
   else if (name != current_function_file
           && strcmp (name, current_function_file) != 0)
     {
@@ -6986,25 +6840,70 @@ mips_output_filename (FILE *stream, const char *name)
       putc ('\n', stream);
     }
 }
-\f
-/* Output an ASCII string, in a space-saving way.  PREFIX is the string
-   that should be written before the opening quote, such as "\t.ascii\t"
-   for real string data or "\t# " for a comment.  */
 
-void
-mips_output_ascii (FILE *stream, const char *string_param, size_t len,
-                  const char *prefix)
-{
-  size_t i;
-  int cur_pos = 17;
-  register const unsigned char *string =
-    (const unsigned char *)string_param;
+/* Implement TARGET_ASM_OUTPUT_DWARF_DTPREL.  */
 
-  fprintf (stream, "%s\"", prefix);
-  for (i = 0; i < len; i++)
+static void ATTRIBUTE_UNUSED
+mips_output_dwarf_dtprel (FILE *file, int size, rtx x)
+{
+  switch (size)
     {
-      register int c = string[i];
-
+    case 4:
+      fputs ("\t.dtprelword\t", file);
+      break;
+
+    case 8:
+      fputs ("\t.dtpreldword\t", file);
+      break;
+
+    default:
+      gcc_unreachable ();
+    }
+  output_addr_const (file, x);
+  fputs ("+0x8000", file);
+}
+
+/* Implement TARGET_DWARF_REGISTER_SPAN.  */
+
+static rtx
+mips_dwarf_register_span (rtx reg)
+{
+  rtx high, low;
+  enum machine_mode mode;
+
+  /* By default, GCC maps increasing register numbers to increasing
+     memory locations, but paired FPRs are always little-endian,
+     regardless of the prevailing endianness.  */
+  mode = GET_MODE (reg);
+  if (FP_REG_P (REGNO (reg))
+      && TARGET_BIG_ENDIAN
+      && MAX_FPRS_PER_FMT > 1
+      && GET_MODE_SIZE (mode) > UNITS_PER_FPREG)
+    {
+      gcc_assert (GET_MODE_SIZE (mode) == UNITS_PER_HWFPVALUE);
+      high = mips_subword (reg, true);
+      low = mips_subword (reg, false);
+      return gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, high, low));
+    }
+
+  return NULL_RTX;
+}
+
+/* Implement ASM_OUTPUT_ASCII.  */
+
+void
+mips_output_ascii (FILE *stream, const char *string, size_t len)
+{
+  size_t i;
+  int cur_pos;
+
+  cur_pos = 17;
+  fprintf (stream, "\t.ascii\t\"");
+  for (i = 0; i < len; i++)
+    {
+      int c;
+
+      c = (unsigned char) string[i];
       if (ISPRINT (c))
        {
          if (c == '\\' || c == '\"')
@@ -7024,118 +6923,37 @@ mips_output_ascii (FILE *stream, const char *string_param, size_t len,
       if (cur_pos > 72 && i+1 < len)
        {
          cur_pos = 17;
-         fprintf (stream, "\"\n%s\"", prefix);
+         fprintf (stream, "\"\n\t.ascii\t\"");
        }
     }
   fprintf (stream, "\"\n");
 }
-\f
-/* Implement TARGET_ASM_FILE_START.  */
-
-static void
-mips_file_start (void)
-{
-  default_file_start ();
-
-  if (!TARGET_IRIX)
-    {
-      /* Generate a special section to describe the ABI switches used to
-        produce the resultant binary.  This used to be done by the assembler
-        setting bits in the ELF header's flags field, but we have run out of
-        bits.  GDB needs this information in order to be able to correctly
-        debug these binaries.  See the function mips_gdbarch_init() in
-        gdb/mips-tdep.c.  This is unnecessary for the IRIX 5/6 ABIs and
-        causes unnecessary IRIX 6 ld warnings.  */
-      const char * abi_string = NULL;
-
-      switch (mips_abi)
-       {
-       case ABI_32:   abi_string = "abi32"; break;
-       case ABI_N32:  abi_string = "abiN32"; break;
-       case ABI_64:   abi_string = "abi64"; break;
-       case ABI_O64:  abi_string = "abiO64"; break;
-       case ABI_EABI: abi_string = TARGET_64BIT ? "eabi64" : "eabi32"; break;
-       default:
-         gcc_unreachable ();
-       }
-      /* Note - we use fprintf directly rather than calling switch_to_section
-        because in this way we can avoid creating an allocated section.  We
-        do not want this section to take up any space in the running
-        executable.  */
-      fprintf (asm_out_file, "\t.section .mdebug.%s\n\t.previous\n",
-              abi_string);
-
-      /* There is no ELF header flag to distinguish long32 forms of the
-        EABI from long64 forms.  Emit a special section to help tools
-        such as GDB.  Do the same for o64, which is sometimes used with
-        -mlong64.  */
-      if (mips_abi == ABI_EABI || mips_abi == ABI_O64)
-       fprintf (asm_out_file, "\t.section .gcc_compiled_long%d\n"
-                "\t.previous\n", TARGET_LONG64 ? 64 : 32);
-
-#ifdef HAVE_AS_GNU_ATTRIBUTE
-      fprintf (asm_out_file, "\t.gnu_attribute 4, %d\n",
-              TARGET_HARD_FLOAT_ABI ? (TARGET_DOUBLE_FLOAT ? 1 : 2) : 3);
-#endif
-    }
-
-  /* Generate the pseudo ops that System V.4 wants.  */
-  if (TARGET_ABICALLS)
-    fprintf (asm_out_file, "\t.abicalls\n");
-
-  if (flag_verbose_asm)
-    fprintf (asm_out_file, "\n%s -G value = %d, Arch = %s, ISA = %d\n",
-            ASM_COMMENT_START,
-            mips_section_threshold, mips_arch_info->name, mips_isa);
-}
 
-#ifdef BSS_SECTION_ASM_OP
-/* Implement ASM_OUTPUT_ALIGNED_BSS.  This differs from the default only
-   in the use of sbss.  */
+/* Emit either a label, .comm, or .lcomm directive.  When using assembler
+   macros, mark the symbol as written so that mips_asm_output_external
+   won't emit an .extern for it.  STREAM is the output file, NAME is the
+   name of the symbol, INIT_STRING is the string that should be written
+   before the symbol and FINAL_STRING is the string that should be
+   written after it.  FINAL_STRING is a printf format that consumes the
+   remaining arguments.  */
 
 void
-mips_output_aligned_bss (FILE *stream, tree decl, const char *name,
-                        unsigned HOST_WIDE_INT size, int align)
+mips_declare_object (FILE *stream, const char *name, const char *init_string,
+                    const char *final_string, ...)
 {
-  extern tree last_assemble_variable_decl;
+  va_list ap;
 
-  if (mips_in_small_data_p (decl))
-    switch_to_section (get_named_section (NULL, ".sbss", 0));
-  else
-    switch_to_section (bss_section);
-  ASM_OUTPUT_ALIGN (stream, floor_log2 (align / BITS_PER_UNIT));
-  last_assemble_variable_decl = decl;
-  ASM_DECLARE_OBJECT_NAME (stream, name, decl);
-  ASM_OUTPUT_SKIP (stream, size != 0 ? size : 1);
-}
-#endif
-\f
-/* Implement ASM_OUTPUT_ALIGNED_DECL_COMMON.  This is usually the same as the
-   elfos.h version, but we also need to handle -muninit-const-in-rodata.  */
+  fputs (init_string, stream);
+  assemble_name (stream, name);
+  va_start (ap, final_string);
+  vfprintf (stream, final_string, ap);
+  va_end (ap);
 
-void
-mips_output_aligned_decl_common (FILE *stream, tree decl, const char *name,
-                                unsigned HOST_WIDE_INT size,
-                                unsigned int align)
-{
-  /* If the target wants uninitialized const declarations in
-     .rdata then don't put them in .comm.  */
-  if (TARGET_EMBEDDED_DATA && TARGET_UNINIT_CONST_IN_RODATA
-      && TREE_CODE (decl) == VAR_DECL && TREE_READONLY (decl)
-      && (DECL_INITIAL (decl) == 0 || DECL_INITIAL (decl) == error_mark_node))
+  if (!TARGET_EXPLICIT_RELOCS)
     {
-      if (TREE_PUBLIC (decl) && DECL_NAME (decl))
-       targetm.asm_out.globalize_label (stream, name);
-
-      switch_to_section (readonly_data_section);
-      ASM_OUTPUT_ALIGN (stream, floor_log2 (align / BITS_PER_UNIT));
-      mips_declare_object (stream, name, "",
-                          ":\n\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED "\n",
-                          size);
+      tree name_tree = get_identifier (name);
+      TREE_ASM_WRITTEN (name_tree) = 1;
     }
-  else
-    mips_declare_common_object (stream, name, "\n\t.comm\t",
-                               size, align, true);
 }
 
 /* Declare a common object of SIZE bytes using asm directive INIT_STRING.
@@ -7162,37 +6980,41 @@ mips_declare_common_object (FILE *stream, const char *name,
                         size, align / BITS_PER_UNIT);
 }
 
-/* Emit either a label, .comm, or .lcomm directive.  When using assembler
-   macros, mark the symbol as written so that mips_file_end won't emit an
-   .extern for it.  STREAM is the output file, NAME is the name of the
-   symbol, INIT_STRING is the string that should be written before the
-   symbol and FINAL_STRING is the string that should be written after it.
-   FINAL_STRING is a printf() format that consumes the remaining arguments.  */
+/* Implement ASM_OUTPUT_ALIGNED_DECL_COMMON.  This is usually the same as the
+   elfos.h version, but we also need to handle -muninit-const-in-rodata.  */
 
 void
-mips_declare_object (FILE *stream, const char *name, const char *init_string,
-                    const char *final_string, ...)
+mips_output_aligned_decl_common (FILE *stream, tree decl, const char *name,
+                                unsigned HOST_WIDE_INT size,
+                                unsigned int align)
 {
-  va_list ap;
-
-  fputs (init_string, stream);
-  assemble_name (stream, name);
-  va_start (ap, final_string);
-  vfprintf (stream, final_string, ap);
-  va_end (ap);
-
-  if (!TARGET_EXPLICIT_RELOCS)
+  /* If the target wants uninitialized const declarations in
+     .rdata then don't put them in .comm.  */
+  if (TARGET_EMBEDDED_DATA
+      && TARGET_UNINIT_CONST_IN_RODATA
+      && TREE_CODE (decl) == VAR_DECL
+      && TREE_READONLY (decl)
+      && (DECL_INITIAL (decl) == 0 || DECL_INITIAL (decl) == error_mark_node))
     {
-      tree name_tree = get_identifier (name);
-      TREE_ASM_WRITTEN (name_tree) = 1;
+      if (TREE_PUBLIC (decl) && DECL_NAME (decl))
+       targetm.asm_out.globalize_label (stream, name);
+
+      switch_to_section (readonly_data_section);
+      ASM_OUTPUT_ALIGN (stream, floor_log2 (align / BITS_PER_UNIT));
+      mips_declare_object (stream, name, "",
+                          ":\n\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED "\n",
+                          size);
     }
+  else
+    mips_declare_common_object (stream, name, "\n\t.comm\t",
+                               size, align, true);
 }
 
 #ifdef ASM_OUTPUT_SIZE_DIRECTIVE
 extern int size_directive_output;
 
 /* Implement ASM_DECLARE_OBJECT_NAME.  This is like most of the standard ELF
-   definitions except that it uses mips_declare_object() to emit the label.  */
+   definitions except that it uses mips_declare_object to emit the label.  */
 
 void
 mips_declare_object_name (FILE *stream, const char *name,
@@ -7225,7 +7047,8 @@ mips_finish_declare_object (FILE *stream, tree decl, int top_level, int at_end)
   name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
   if (!flag_inhibit_size_directive
       && DECL_SIZE (decl) != 0
-      && !at_end && top_level
+      && !at_end
+      && top_level
       && DECL_INITIAL (decl) == error_mark_node
       && !size_directive_output)
     {
@@ -7238,262 +7061,126 @@ mips_finish_declare_object (FILE *stream, tree decl, int top_level, int at_end)
 }
 #endif
 \f
-/* Return true if X in context CONTEXT is a small data address that can
-   be rewritten as a LO_SUM.  */
+/* Return the FOO in the name of the ".mdebug.FOO" section associated
+   with the current ABI.  */
 
-static bool
-mips_rewrite_small_data_p (rtx x, enum mips_symbol_context context)
+static const char *
+mips_mdebug_abi_name (void)
 {
-  enum mips_symbol_type symbol_type;
-
-  return (TARGET_EXPLICIT_RELOCS
-         && mips_symbolic_constant_p (x, context, &symbol_type)
-         && symbol_type == SYMBOL_GP_RELATIVE);
+  switch (mips_abi)
+    {
+    case ABI_32:
+      return "abi32";
+    case ABI_O64:
+      return "abiO64";
+    case ABI_N32:
+      return "abiN32";
+    case ABI_64:
+      return "abiN64";
+    case ABI_EABI:
+      return TARGET_64BIT ? "eabi64" : "eabi32";
+    default:
+      gcc_unreachable ();
+    }
 }
 
+/* Implement TARGET_ASM_FILE_START.  */
 
-/* A for_each_rtx callback for mips_small_data_pattern_p.  DATA is the
-   containing MEM, or null if none.  */
-
-static int
-mips_small_data_pattern_1 (rtx *loc, void *data)
+static void
+mips_file_start (void)
 {
-  enum mips_symbol_context context;
-
-  if (GET_CODE (*loc) == LO_SUM)
-    return -1;
+  default_file_start ();
 
-  if (MEM_P (*loc))
+  /* Generate a special section to describe the ABI switches used to
+     produce the resultant binary.  This is unnecessary on IRIX and
+     causes unwanted warnings from the native linker.  */
+  if (!TARGET_IRIX)
     {
-      if (for_each_rtx (&XEXP (*loc, 0), mips_small_data_pattern_1, *loc))
-       return 1;
-      return -1;
-    }
+      /* Record the ABI itself.  Modern versions of binutils encode
+        this information in the ELF header flags, but GDB needs the
+        information in order to correctly debug binaries produced by
+        older binutils.  See the function mips_gdbarch_init in
+        gdb/mips-tdep.c.  */
+      fprintf (asm_out_file, "\t.section .mdebug.%s\n\t.previous\n",
+              mips_mdebug_abi_name ());
 
-  context = data ? SYMBOL_CONTEXT_MEM : SYMBOL_CONTEXT_LEA;
-  return mips_rewrite_small_data_p (*loc, context);
-}
+      /* There is no ELF header flag to distinguish long32 forms of the
+        EABI from long64 forms.  Emit a special section to help tools
+        such as GDB.  Do the same for o64, which is sometimes used with
+        -mlong64.  */
+      if (mips_abi == ABI_EABI || mips_abi == ABI_O64)
+       fprintf (asm_out_file, "\t.section .gcc_compiled_long%d\n"
+                "\t.previous\n", TARGET_LONG64 ? 64 : 32);
 
-/* Return true if OP refers to small data symbols directly, not through
-   a LO_SUM.  */
+#ifdef HAVE_AS_GNU_ATTRIBUTE
+      fprintf (asm_out_file, "\t.gnu_attribute 4, %d\n",
+              (TARGET_HARD_FLOAT_ABI
+               ? (TARGET_DOUBLE_FLOAT
+                  ? ((!TARGET_64BIT && TARGET_FLOAT64) ? 4 : 1) : 2) : 3));
+#endif
+    }
 
-bool
-mips_small_data_pattern_p (rtx op)
-{
-  return for_each_rtx (&op, mips_small_data_pattern_1, 0);
+  /* If TARGET_ABICALLS, tell GAS to generate -KPIC code.  */
+  if (TARGET_ABICALLS)
+    fprintf (asm_out_file, "\t.abicalls\n");
+
+  if (flag_verbose_asm)
+    fprintf (asm_out_file, "\n%s -G value = %d, Arch = %s, ISA = %d\n",
+            ASM_COMMENT_START,
+            mips_small_data_threshold, mips_arch_info->name, mips_isa);
 }
 \f
-/* A for_each_rtx callback, used by mips_rewrite_small_data.
-   DATA is the containing MEM, or null if none.  */
+/* Make the last instruction frame-related and note that it performs
+   the operation described by FRAME_PATTERN.  */
 
-static int
-mips_rewrite_small_data_1 (rtx *loc, void *data)
+static void
+mips_set_frame_expr (rtx frame_pattern)
 {
-  enum mips_symbol_context context;
+  rtx insn;
 
-  if (MEM_P (*loc))
-    {
-      for_each_rtx (&XEXP (*loc, 0), mips_rewrite_small_data_1, *loc);
-      return -1;
-    }
+  insn = get_last_insn ();
+  RTX_FRAME_RELATED_P (insn) = 1;
+  REG_NOTES (insn) = alloc_EXPR_LIST (REG_FRAME_RELATED_EXPR,
+                                     frame_pattern,
+                                     REG_NOTES (insn));
+}
 
-  context = data ? SYMBOL_CONTEXT_MEM : SYMBOL_CONTEXT_LEA;
-  if (mips_rewrite_small_data_p (*loc, context))
-    *loc = gen_rtx_LO_SUM (Pmode, pic_offset_table_rtx, *loc);
+/* Return a frame-related rtx that stores REG at MEM.
+   REG must be a single register.  */
 
-  if (GET_CODE (*loc) == LO_SUM)
-    return -1;
+static rtx
+mips_frame_set (rtx mem, rtx reg)
+{
+  rtx set;
 
-  return 0;
-}
+  /* If we're saving the return address register and the DWARF return
+     address column differs from the hard register number, adjust the
+     note reg to refer to the former.  */
+  if (REGNO (reg) == GP_REG_FIRST + 31
+      && DWARF_FRAME_RETURN_COLUMN != GP_REG_FIRST + 31)
+    reg = gen_rtx_REG (GET_MODE (reg), DWARF_FRAME_RETURN_COLUMN);
 
-/* If possible, rewrite OP so that it refers to small data using
-   explicit relocations.  */
+  set = gen_rtx_SET (VOIDmode, mem, reg);
+  RTX_FRAME_RELATED_P (set) = 1;
 
-rtx
-mips_rewrite_small_data (rtx op)
-{
-  op = copy_insn (op);
-  for_each_rtx (&op, mips_rewrite_small_data_1, 0);
-  return op;
+  return set;
 }
 \f
-/* Return true if the current function has an insn that implicitly
-   refers to $gp.  */
-
-static bool
-mips_function_has_gp_insn (void)
-{
-  /* Don't bother rechecking if we found one last time.  */
-  if (!cfun->machine->has_gp_insn_p)
-    {
-      rtx insn;
-
-      push_topmost_sequence ();
-      for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
-       if (INSN_P (insn)
-           && GET_CODE (PATTERN (insn)) != USE
-           && GET_CODE (PATTERN (insn)) != CLOBBER
-           && (get_attr_got (insn) != GOT_UNSET
-               || small_data_pattern (PATTERN (insn), VOIDmode)))
-         break;
-      pop_topmost_sequence ();
-
-      cfun->machine->has_gp_insn_p = (insn != 0);
-    }
-  return cfun->machine->has_gp_insn_p;
-}
-
-
-/* Return the register that should be used as the global pointer
-   within this function.  Return 0 if the function doesn't need
-   a global pointer.  */
-
-static unsigned int
-mips_global_pointer (void)
-{
-  unsigned int regno;
-
-  /* $gp is always available unless we're using a GOT.  */
-  if (!TARGET_USE_GOT)
-    return GLOBAL_POINTER_REGNUM;
-
-  /* We must always provide $gp when it is used implicitly.  */
-  if (!TARGET_EXPLICIT_RELOCS)
-    return GLOBAL_POINTER_REGNUM;
-
-  /* FUNCTION_PROFILER includes a jal macro, so we need to give it
-     a valid gp.  */
-  if (current_function_profile)
-    return GLOBAL_POINTER_REGNUM;
-
-  /* If the function has a nonlocal goto, $gp must hold the correct
-     global pointer for the target function.  */
-  if (current_function_has_nonlocal_goto)
-    return GLOBAL_POINTER_REGNUM;
-
-  /* If the gp is never referenced, there's no need to initialize it.
-     Note that reload can sometimes introduce constant pool references
-     into a function that otherwise didn't need them.  For example,
-     suppose we have an instruction like:
-
-         (set (reg:DF R1) (float:DF (reg:SI R2)))
-
-     If R2 turns out to be constant such as 1, the instruction may have a
-     REG_EQUAL note saying that R1 == 1.0.  Reload then has the option of
-     using this constant if R2 doesn't get allocated to a register.
-
-     In cases like these, reload will have added the constant to the pool
-     but no instruction will yet refer to it.  */
-  if (!df_regs_ever_live_p (GLOBAL_POINTER_REGNUM)
-      && !current_function_uses_const_pool
-      && !mips_function_has_gp_insn ())
-    return 0;
-
-  /* We need a global pointer, but perhaps we can use a call-clobbered
-     register instead of $gp.  */
-  if (TARGET_CALL_SAVED_GP && current_function_is_leaf)
-    for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
-      if (!df_regs_ever_live_p (regno)
-         && call_really_used_regs[regno]
-         && !fixed_regs[regno]
-         && regno != PIC_FUNCTION_ADDR_REGNUM)
-       return regno;
-
-  return GLOBAL_POINTER_REGNUM;
-}
-
-
-/* Return true if the function return value MODE will get returned in a
-   floating-point register.  */
-
-static bool
-mips_return_mode_in_fpr_p (enum machine_mode mode)
-{
-  return ((GET_MODE_CLASS (mode) == MODE_FLOAT
-          || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT
-          || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
-         && GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_HWFPVALUE);
-}
-
-/* Return a two-character string representing a function floating-point
-   return mode, used to name MIPS16 function stubs.  */
-
-static const char *
-mips16_call_stub_mode_suffix (enum machine_mode mode)
-{
-  if (mode == SFmode)
-    return "sf";
-  else if (mode == DFmode)
-    return "df";
-  else if (mode == SCmode)
-    return "sc";
-  else if (mode == DCmode)
-    return "dc";
-  else if (mode == V2SFmode)
-    return "df";
-  else
-    gcc_unreachable ();
-}
-
-/* Return true if the current function returns its value in a floating-point
-   register in MIPS16 mode.  */
-
-static bool
-mips16_cfun_returns_in_fpr_p (void)
-{
-  tree return_type = DECL_RESULT (current_function_decl);
-  return (TARGET_MIPS16
-         && TARGET_HARD_FLOAT_ABI
-         && !aggregate_value_p (return_type, current_function_decl)
-         && mips_return_mode_in_fpr_p (DECL_MODE (return_type)));
-}
-
-
-/* Return true if the current function must save REGNO.  */
-
-static bool
-mips_save_reg_p (unsigned int regno)
-{
-  /* We only need to save $gp if TARGET_CALL_SAVED_GP and only then
-     if we have not chosen a call-clobbered substitute.  */
-  if (regno == GLOBAL_POINTER_REGNUM)
-    return TARGET_CALL_SAVED_GP && cfun->machine->global_pointer == regno;
-
-  /* Check call-saved registers.  */
-  if ((current_function_saves_all_registers || df_regs_ever_live_p (regno))
-      && !call_really_used_regs[regno])
-    return true;
-
-  /* Save both registers in an FPR pair if either one is used.  This is
-     needed for the case when MIN_FPRS_PER_FMT == 1, which allows the odd
-     register to be used without the even register.  */
-  if (FP_REG_P (regno)
-      && MAX_FPRS_PER_FMT == 2
-      && df_regs_ever_live_p (regno + 1)
-      && !call_really_used_regs[regno + 1])
-    return true;
-
-  /* We need to save the old frame pointer before setting up a new one.  */
-  if (regno == HARD_FRAME_POINTER_REGNUM && frame_pointer_needed)
-    return true;
-
-  /* Check for registers that must be saved for FUNCTION_PROFILER.  */
-  if (current_function_profile && MIPS_SAVE_REG_FOR_PROFILING_P (regno))
-    return true;
-
-  /* We need to save the incoming return address if it is ever clobbered
-     within the function, if __builtin_eh_return is being used to set a
-     different return address, or if a stub is being used to return a
-     value in FPRs.  */
-  if (regno == GP_REG_FIRST + 31
-      && (df_regs_ever_live_p (regno)
-         || current_function_calls_eh_return
-         || mips16_cfun_returns_in_fpr_p ()))
-    return true;
+/* If a MIPS16e SAVE or RESTORE instruction saves or restores register
+   mips16e_s2_s8_regs[X], it must also save the registers in indexes
+   X + 1 onwards.  Likewise mips16e_a0_a3_regs.  */
+static const unsigned char mips16e_s2_s8_regs[] = {
+  30, 23, 22, 21, 20, 19, 18
+};
+static const unsigned char mips16e_a0_a3_regs[] = {
+  4, 5, 6, 7
+};
 
-  return false;
-}
+/* A list of the registers that can be saved by the MIPS16e SAVE instruction,
+   ordered from the uppermost in memory to the lowest in memory.  */
+static const unsigned char mips16e_save_restore_regs[] = {
+  31, 30, 23, 22, 21, 20, 19, 18, 17, 16, 7, 6, 5, 4
+};
 
 /* Return the index of the lowest X in the range [0, SIZE) for which
    bit REGS[X] is set in MASK.  Return SIZE if there is no such X.  */
@@ -7511,14 +7198,14 @@ mips16e_find_first_register (unsigned int mask, const unsigned char *regs,
   return i;
 }
 
-/* *MASK_PTR is a mask of general purpose registers and *GP_REG_SIZE_PTR
-   is the number of bytes that they occupy.  If *MASK_PTR contains REGS[X]
-   for some X in [0, SIZE), adjust *MASK_PTR and *GP_REG_SIZE_PTR so that
-   the same is true for all indexes (X, SIZE).  */
+/* *MASK_PTR is a mask of general-purpose registers and *NUM_REGS_PTR
+   is the number of set bits.  If *MASK_PTR contains REGS[X] for some X
+   in [0, SIZE), adjust *MASK_PTR and *NUM_REGS_PTR so that the same
+   is true for all indexes (X, SIZE).  */
 
 static void
 mips16e_mask_registers (unsigned int *mask_ptr, const unsigned char *regs,
-                       unsigned int size, HOST_WIDE_INT *gp_reg_size_ptr)
+                       unsigned int size, unsigned int *num_regs_ptr)
 {
   unsigned int i;
 
@@ -7526,676 +7213,248 @@ mips16e_mask_registers (unsigned int *mask_ptr, const unsigned char *regs,
   for (i++; i < size; i++)
     if (!BITSET_P (*mask_ptr, regs[i]))
       {
-       *gp_reg_size_ptr += GET_MODE_SIZE (gpr_mode);
+       *num_regs_ptr += 1;
        *mask_ptr |= 1 << regs[i];
       }
 }
 
-/* Return the bytes needed to compute the frame pointer from the current
-   stack pointer.  SIZE is the size (in bytes) of the local variables.
-
-   MIPS stack frames look like:
+/* Return a simplified form of X using the register values in REG_VALUES.
+   REG_VALUES[R] is the last value assigned to hard register R, or null
+   if R has not been modified.
 
-             Before call                       After call
-   high +-----------------------+      +-----------------------+
-   mem. |                      |       |                       |
-       |  caller's temps.      |       |  caller's temps.      |
-       |                       |       |                       |
-        +-----------------------+      +-----------------------+
-       |                       |       |                       |
-        |  arguments on stack.  |      |  arguments on stack.  |
-       |                       |       |                       |
-        +-----------------------+      +-----------------------+
-       |  4 words to save      |       |  4 words to save      |
-       |  arguments passed     |       |  arguments passed     |
-       |  in registers, even   |       |  in registers, even   |
-        |  if not passed.       |       |  if not passed.      |
-    SP->+-----------------------+  VFP->+-----------------------+
-               (VFP = SP+fp_sp_offset) |                       |\
-                                       |  fp register save     | | fp_reg_size
-                                       |                       |/
-                      SP+gp_sp_offset->+-----------------------+
-                                      /|                       |\
-                                     | |  gp register save     | | gp_reg_size
-                      gp_reg_rounded | |                       |/
-                                     | +-----------------------+
-                                      \|  alignment padding    |
-                                       +-----------------------+
-                                       |                       |\
-                                       |  local variables      | | var_size
-                                       |                       |/
-                                       +-----------------------+
-                                       |                       |
-                                       |  alloca allocations   |
-                                       |                       |
-                                       +-----------------------+
-                                      /|                       |
-                      cprestore_size | |  GP save for V.4 abi  |
-                                      \|                       |
-                                       +-----------------------+
-                                       |                       |\
-                                       |  arguments on stack   | |
-                                       |                       | |
-                                       +-----------------------+ |
-                                       |  4 words to save      | | args_size
-                                       |  arguments passed     | |
-                                       |  in registers, even   | |
-                                       |  if not passed.       | |
-   low                                 |  (TARGET_OLDABI only) |/
-   memory                          SP->+-----------------------+
-
-*/
+   This function is rather limited, but is good enough for our purposes.  */
 
-HOST_WIDE_INT
-compute_frame_size (HOST_WIDE_INT size)
+static rtx
+mips16e_collect_propagate_value (rtx x, rtx *reg_values)
 {
-  unsigned int regno;
-  HOST_WIDE_INT total_size;    /* # bytes that the entire frame takes up */
-  HOST_WIDE_INT var_size;      /* # bytes that variables take up */
-  HOST_WIDE_INT args_size;     /* # bytes that outgoing arguments take up */
-  HOST_WIDE_INT cprestore_size; /* # bytes that the cprestore slot takes up */
-  HOST_WIDE_INT gp_reg_rounded;        /* # bytes needed to store gp after rounding */
-  HOST_WIDE_INT gp_reg_size;   /* # bytes needed to store gp regs */
-  HOST_WIDE_INT fp_reg_size;   /* # bytes needed to store fp regs */
-  unsigned int mask;           /* mask of saved gp registers */
-  unsigned int fmask;          /* mask of saved fp registers */
-
-  cfun->machine->global_pointer = mips_global_pointer ();
-
-  gp_reg_size = 0;
-  fp_reg_size = 0;
-  mask = 0;
-  fmask        = 0;
-  var_size = MIPS_STACK_ALIGN (size);
-  args_size = current_function_outgoing_args_size;
-  cprestore_size = MIPS_STACK_ALIGN (STARTING_FRAME_OFFSET) - args_size;
-
-  /* The space set aside by STARTING_FRAME_OFFSET isn't needed in leaf
-     functions.  If the function has local variables, we're committed
-     to allocating it anyway.  Otherwise reclaim it here.  */
-  if (var_size == 0 && current_function_is_leaf)
-    cprestore_size = args_size = 0;
-
-  /* The MIPS 3.0 linker does not like functions that dynamically
-     allocate the stack and have 0 for STACK_DYNAMIC_OFFSET, since it
-     looks like we are trying to create a second frame pointer to the
-     function, so allocate some stack space to make it happy.  */
-
-  if (args_size == 0 && current_function_calls_alloca)
-    args_size = 4 * UNITS_PER_WORD;
-
-  total_size = var_size + args_size + cprestore_size;
-
-  /* Calculate space needed for gp registers.  */
-  for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
-    if (mips_save_reg_p (regno))
-      {
-       gp_reg_size += GET_MODE_SIZE (gpr_mode);
-       mask |= 1 << (regno - GP_REG_FIRST);
-      }
-
-  /* We need to restore these for the handler.  */
-  if (current_function_calls_eh_return)
-    {
-      unsigned int i;
-      for (i = 0; ; ++i)
-       {
-         regno = EH_RETURN_DATA_REGNO (i);
-         if (regno == INVALID_REGNUM)
-           break;
-         gp_reg_size += GET_MODE_SIZE (gpr_mode);
-         mask |= 1 << (regno - GP_REG_FIRST);
-       }
-    }
+  x = avoid_constant_pool_reference (x);
 
-  /* The MIPS16e SAVE and RESTORE instructions have two ranges of registers:
-     $a3-$a0 and $s2-$s8.  If we save one register in the range, we must
-     save all later registers too.  */
-  if (GENERATE_MIPS16E_SAVE_RESTORE)
+  if (UNARY_P (x))
     {
-      mips16e_mask_registers (&mask, mips16e_s2_s8_regs,
-                             ARRAY_SIZE (mips16e_s2_s8_regs), &gp_reg_size);
-      mips16e_mask_registers (&mask, mips16e_a0_a3_regs,
-                             ARRAY_SIZE (mips16e_a0_a3_regs), &gp_reg_size);
+      rtx x0 = mips16e_collect_propagate_value (XEXP (x, 0), reg_values);
+      return simplify_gen_unary (GET_CODE (x), GET_MODE (x),
+                                x0, GET_MODE (XEXP (x, 0)));
     }
 
-  /* This loop must iterate over the same space as its companion in
-     mips_for_each_saved_reg.  */
-  if (TARGET_HARD_FLOAT)
-    for (regno = (FP_REG_LAST - MAX_FPRS_PER_FMT + 1);
-        regno >= FP_REG_FIRST;
-        regno -= MAX_FPRS_PER_FMT)
-      if (mips_save_reg_p (regno))
-       {
-         fp_reg_size += MAX_FPRS_PER_FMT * UNITS_PER_FPREG;
-         fmask |= ((1 << MAX_FPRS_PER_FMT) - 1) << (regno - FP_REG_FIRST);
-       }
-
-  gp_reg_rounded = MIPS_STACK_ALIGN (gp_reg_size);
-  total_size += gp_reg_rounded + MIPS_STACK_ALIGN (fp_reg_size);
-
-  /* Add in the space required for saving incoming register arguments.  */
-  total_size += current_function_pretend_args_size;
-  total_size += MIPS_STACK_ALIGN (cfun->machine->varargs_size);
-
-  /* Save other computed information.  */
-  cfun->machine->frame.total_size = total_size;
-  cfun->machine->frame.var_size = var_size;
-  cfun->machine->frame.args_size = args_size;
-  cfun->machine->frame.cprestore_size = cprestore_size;
-  cfun->machine->frame.gp_reg_size = gp_reg_size;
-  cfun->machine->frame.fp_reg_size = fp_reg_size;
-  cfun->machine->frame.mask = mask;
-  cfun->machine->frame.fmask = fmask;
-  cfun->machine->frame.initialized = reload_completed;
-  cfun->machine->frame.num_gp = gp_reg_size / UNITS_PER_WORD;
-  cfun->machine->frame.num_fp = (fp_reg_size
-                                / (MAX_FPRS_PER_FMT * UNITS_PER_FPREG));
-
-  if (mask)
-    {
-      HOST_WIDE_INT offset;
-
-      if (GENERATE_MIPS16E_SAVE_RESTORE)
-       /* MIPS16e SAVE and RESTORE instructions require the GP save area
-          to be aligned at the high end with any padding at the low end.
-          It is only safe to use this calculation for o32, where we never
-          have pretend arguments, and where any varargs will be saved in
-          the caller-allocated area rather than at the top of the frame.  */
-       offset = (total_size - GET_MODE_SIZE (gpr_mode));
-      else
-       offset = (args_size + cprestore_size + var_size
-                 + gp_reg_size - GET_MODE_SIZE (gpr_mode));
-      cfun->machine->frame.gp_sp_offset = offset;
-      cfun->machine->frame.gp_save_offset = offset - total_size;
-    }
-  else
+  if (ARITHMETIC_P (x))
     {
-      cfun->machine->frame.gp_sp_offset = 0;
-      cfun->machine->frame.gp_save_offset = 0;
+      rtx x0 = mips16e_collect_propagate_value (XEXP (x, 0), reg_values);
+      rtx x1 = mips16e_collect_propagate_value (XEXP (x, 1), reg_values);
+      return simplify_gen_binary (GET_CODE (x), GET_MODE (x), x0, x1);
     }
 
-  if (fmask)
-    {
-      HOST_WIDE_INT offset;
-
-      offset = (args_size + cprestore_size + var_size
-               + gp_reg_rounded + fp_reg_size
-               - MAX_FPRS_PER_FMT * UNITS_PER_FPREG);
-      cfun->machine->frame.fp_sp_offset = offset;
-      cfun->machine->frame.fp_save_offset = offset - total_size;
-    }
-  else
-    {
-      cfun->machine->frame.fp_sp_offset = 0;
-      cfun->machine->frame.fp_save_offset = 0;
-    }
+  if (REG_P (x)
+      && reg_values[REGNO (x)]
+      && !rtx_unstable_p (reg_values[REGNO (x)]))
+    return reg_values[REGNO (x)];
 
-  /* Ok, we're done.  */
-  return total_size;
+  return x;
 }
-\f
-/* Implement INITIAL_ELIMINATION_OFFSET.  FROM is either the frame
-   pointer or argument pointer.  TO is either the stack pointer or
-   hard frame pointer.  */
 
-HOST_WIDE_INT
-mips_initial_elimination_offset (int from, int to)
+/* Return true if (set DEST SRC) stores an argument register into its
+   caller-allocated save slot, storing the number of that argument
+   register in *REGNO_PTR if so.  REG_VALUES is as for
+   mips16e_collect_propagate_value.  */
+
+static bool
+mips16e_collect_argument_save_p (rtx dest, rtx src, rtx *reg_values,
+                                unsigned int *regno_ptr)
 {
-  HOST_WIDE_INT offset;
+  unsigned int argno, regno;
+  HOST_WIDE_INT offset, required_offset;
+  rtx addr, base;
 
-  compute_frame_size (get_frame_size ());
+  /* Check that this is a word-mode store.  */
+  if (!MEM_P (dest) || !REG_P (src) || GET_MODE (dest) != word_mode)
+    return false;
 
-  /* Set OFFSET to the offset from the stack pointer.  */
-  switch (from)
-    {
-    case FRAME_POINTER_REGNUM:
-      offset = 0;
-      break;
+  /* Check that the register being saved is an unmodified argument
+     register.  */
+  regno = REGNO (src);
+  if (!IN_RANGE (regno, GP_ARG_FIRST, GP_ARG_LAST) || reg_values[regno])
+    return false;
+  argno = regno - GP_ARG_FIRST;
 
-    case ARG_POINTER_REGNUM:
-      offset = (cfun->machine->frame.total_size
-               - current_function_pretend_args_size);
-      break;
+  /* Check whether the address is an appropriate stack-pointer or
+     frame-pointer access.  */
+  addr = mips16e_collect_propagate_value (XEXP (dest, 0), reg_values);
+  mips_split_plus (addr, &base, &offset);
+  required_offset = cfun->machine->frame.total_size + argno * UNITS_PER_WORD;
+  if (base == hard_frame_pointer_rtx)
+    required_offset -= cfun->machine->frame.hard_frame_pointer_offset;
+  else if (base != stack_pointer_rtx)
+    return false;
+  if (offset != required_offset)
+    return false;
 
-    default:
-      gcc_unreachable ();
-    }
+  *regno_ptr = regno;
+  return true;
+}
 
-  if (TARGET_MIPS16 && to == HARD_FRAME_POINTER_REGNUM)
-    offset -= cfun->machine->frame.args_size;
+/* A subroutine of mips_expand_prologue, called only when generating
+   MIPS16e SAVE instructions.  Search the start of the function for any
+   instructions that save argument registers into their caller-allocated
+   save slots.  Delete such instructions and return a value N such that
+   saving [GP_ARG_FIRST, GP_ARG_FIRST + N) would make all the deleted
+   instructions redundant.  */
 
-  return offset;
-}
-\f
-/* Implement RETURN_ADDR_RTX.  Note, we do not support moving
-   back to a previous frame.  */
-rtx
-mips_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
+static unsigned int
+mips16e_collect_argument_saves (void)
 {
-  if (count != 0)
-    return const0_rtx;
+  rtx reg_values[FIRST_PSEUDO_REGISTER];
+  rtx insn, next, set, dest, src;
+  unsigned int nargs, regno;
 
-  return get_hard_reg_initial_val (Pmode, GP_REG_FIRST + 31);
-}
-\f
-/* Use FN to save or restore register REGNO.  MODE is the register's
-   mode and OFFSET is the offset of its save slot from the current
-   stack pointer.  */
+  push_topmost_sequence ();
+  nargs = 0;
+  memset (reg_values, 0, sizeof (reg_values));
+  for (insn = get_insns (); insn; insn = next)
+    {
+      next = NEXT_INSN (insn);
+      if (NOTE_P (insn))
+       continue;
 
-static void
-mips_save_restore_reg (enum machine_mode mode, int regno,
-                      HOST_WIDE_INT offset, mips_save_restore_fn fn)
-{
-  rtx mem;
+      if (!INSN_P (insn))
+       break;
 
-  mem = gen_frame_mem (mode, plus_constant (stack_pointer_rtx, offset));
+      set = PATTERN (insn);
+      if (GET_CODE (set) != SET)
+       break;
 
-  fn (gen_rtx_REG (mode, regno), mem);
-}
+      dest = SET_DEST (set);
+      src = SET_SRC (set);
+      if (mips16e_collect_argument_save_p (dest, src, reg_values, &regno))
+       {
+         if (!BITSET_P (cfun->machine->frame.mask, regno))
+           {
+             delete_insn (insn);
+             nargs = MAX (nargs, (regno - GP_ARG_FIRST) + 1);
+           }
+       }
+      else if (REG_P (dest) && GET_MODE (dest) == word_mode)
+       reg_values[REGNO (dest)]
+         = mips16e_collect_propagate_value (src, reg_values);
+      else
+       break;
+    }
+  pop_topmost_sequence ();
 
+  return nargs;
+}
 
-/* Call FN for each register that is saved by the current function.
-   SP_OFFSET is the offset of the current stack pointer from the start
-   of the frame.  */
+/* Return a move between register REGNO and memory location SP + OFFSET.
+   Make the move a load if RESTORE_P, otherwise make it a frame-related
+   store.  */
 
-static void
-mips_for_each_saved_reg (HOST_WIDE_INT sp_offset, mips_save_restore_fn fn)
+static rtx
+mips16e_save_restore_reg (bool restore_p, HOST_WIDE_INT offset,
+                         unsigned int regno)
 {
-  enum machine_mode fpr_mode;
-  HOST_WIDE_INT offset;
-  int regno;
-
-  /* Save registers starting from high to low.  The debuggers prefer at least
-     the return register be stored at func+4, and also it allows us not to
-     need a nop in the epilogue if at least one register is reloaded in
-     addition to return address.  */
-  offset = cfun->machine->frame.gp_sp_offset - sp_offset;
-  for (regno = GP_REG_LAST; regno >= GP_REG_FIRST; regno--)
-    if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
-      {
-       mips_save_restore_reg (gpr_mode, regno, offset, fn);
-       offset -= GET_MODE_SIZE (gpr_mode);
-      }
+  rtx reg, mem;
 
-  /* This loop must iterate over the same space as its companion in
-     compute_frame_size.  */
-  offset = cfun->machine->frame.fp_sp_offset - sp_offset;
-  fpr_mode = (TARGET_SINGLE_FLOAT ? SFmode : DFmode);
-  for (regno = (FP_REG_LAST - MAX_FPRS_PER_FMT + 1);
-       regno >= FP_REG_FIRST;
-       regno -= MAX_FPRS_PER_FMT)
-    if (BITSET_P (cfun->machine->frame.fmask, regno - FP_REG_FIRST))
-      {
-       mips_save_restore_reg (fpr_mode, regno, offset, fn);
-       offset -= GET_MODE_SIZE (fpr_mode);
-      }
+  mem = gen_frame_mem (SImode, plus_constant (stack_pointer_rtx, offset));
+  reg = gen_rtx_REG (SImode, regno);
+  return (restore_p
+         ? gen_rtx_SET (VOIDmode, reg, mem)
+         : mips_frame_set (mem, reg));
 }
-\f
-/* If we're generating n32 or n64 abicalls, and the current function
-   does not use $28 as its global pointer, emit a cplocal directive.
-   Use pic_offset_table_rtx as the argument to the directive.  */
 
-static void
-mips_output_cplocal (void)
-{
-  if (!TARGET_EXPLICIT_RELOCS
-      && cfun->machine->global_pointer > 0
-      && cfun->machine->global_pointer != GLOBAL_POINTER_REGNUM)
-    output_asm_insn (".cplocal %+", 0);
-}
+/* Return RTL for a MIPS16e SAVE or RESTORE instruction; RESTORE_P says which.
+   The instruction must:
 
-/* Return the style of GP load sequence that is being used for the
-   current function.  */
+     - Allocate or deallocate SIZE bytes in total; SIZE is known
+       to be nonzero.
 
-enum mips_loadgp_style
-mips_current_loadgp_style (void)
-{
-  if (!TARGET_USE_GOT || cfun->machine->global_pointer == 0)
-    return LOADGP_NONE;
+     - Save or restore as many registers in *MASK_PTR as possible.
+       The instruction saves the first registers at the top of the
+       allocated area, with the other registers below it.
 
-  if (TARGET_RTP_PIC)
-    return LOADGP_RTP;
+     - Save NARGS argument registers above the allocated area.
 
-  if (TARGET_ABSOLUTE_ABICALLS)
-    return LOADGP_ABSOLUTE;
+   (NARGS is always zero if RESTORE_P.)
 
-  return TARGET_NEWABI ? LOADGP_NEWABI : LOADGP_OLDABI;
-}
+   The SAVE and RESTORE instructions cannot save and restore all general
+   registers, so there may be some registers left over for the caller to
+   handle.  Destructively modify *MASK_PTR so that it contains the registers
+   that still need to be saved or restored.  The caller can save these
+   registers in the memory immediately below *OFFSET_PTR, which is a
+   byte offset from the bottom of the allocated stack area.  */
 
-/* The __gnu_local_gp symbol.  */
+static rtx
+mips16e_build_save_restore (bool restore_p, unsigned int *mask_ptr,
+                           HOST_WIDE_INT *offset_ptr, unsigned int nargs,
+                           HOST_WIDE_INT size)
+{
+  rtx pattern, set;
+  HOST_WIDE_INT offset, top_offset;
+  unsigned int i, regno;
+  int n;
 
-static GTY(()) rtx mips_gnu_local_gp;
+  gcc_assert (cfun->machine->frame.num_fp == 0);
 
-/* If we're generating n32 or n64 abicalls, emit instructions
-   to set up the global pointer.  */
+  /* Calculate the number of elements in the PARALLEL.  We need one element
+     for the stack adjustment, one for each argument register save, and one
+     for each additional register move.  */
+  n = 1 + nargs;
+  for (i = 0; i < ARRAY_SIZE (mips16e_save_restore_regs); i++)
+    if (BITSET_P (*mask_ptr, mips16e_save_restore_regs[i]))
+      n++;
 
-static void
-mips_emit_loadgp (void)
-{
-  rtx addr, offset, incoming_address, base, index;
+  /* Create the final PARALLEL.  */
+  pattern = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (n));
+  n = 0;
 
-  switch (mips_current_loadgp_style ())
+  /* Add the stack pointer adjustment.  */
+  set = gen_rtx_SET (VOIDmode, stack_pointer_rtx,
+                    plus_constant (stack_pointer_rtx,
+                                   restore_p ? size : -size));
+  RTX_FRAME_RELATED_P (set) = 1;
+  XVECEXP (pattern, 0, n++) = set;
+
+  /* Stack offsets in the PARALLEL are relative to the old stack pointer.  */
+  top_offset = restore_p ? size : 0;
+
+  /* Save the arguments.  */
+  for (i = 0; i < nargs; i++)
     {
-    case LOADGP_ABSOLUTE:
-      if (mips_gnu_local_gp == NULL)
+      offset = top_offset + i * UNITS_PER_WORD;
+      set = mips16e_save_restore_reg (restore_p, offset, GP_ARG_FIRST + i);
+      XVECEXP (pattern, 0, n++) = set;
+    }
+
+  /* Then fill in the other register moves.  */
+  offset = top_offset;
+  for (i = 0; i < ARRAY_SIZE (mips16e_save_restore_regs); i++)
+    {
+      regno = mips16e_save_restore_regs[i];
+      if (BITSET_P (*mask_ptr, regno))
        {
-         mips_gnu_local_gp = gen_rtx_SYMBOL_REF (Pmode, "__gnu_local_gp");
-         SYMBOL_REF_FLAGS (mips_gnu_local_gp) |= SYMBOL_FLAG_LOCAL;
+         offset -= UNITS_PER_WORD;
+         set = mips16e_save_restore_reg (restore_p, offset, regno);
+         XVECEXP (pattern, 0, n++) = set;
+         *mask_ptr &= ~(1 << regno);
        }
-      emit_insn (gen_loadgp_absolute (mips_gnu_local_gp));
-      break;
+    }
 
-    case LOADGP_NEWABI:
-      addr = XEXP (DECL_RTL (current_function_decl), 0);
-      offset = mips_unspec_address (addr, SYMBOL_GOTOFF_LOADGP);
-      incoming_address = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
-      emit_insn (gen_loadgp_newabi (offset, incoming_address));
-      if (!TARGET_EXPLICIT_RELOCS)
-       emit_insn (gen_loadgp_blockage ());
-      break;
+  /* Tell the caller what offset it should use for the remaining registers.  */
+  *offset_ptr = size + (offset - top_offset);
 
-    case LOADGP_RTP:
-      base = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (VXWORKS_GOTT_BASE));
-      index = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (VXWORKS_GOTT_INDEX));
-      emit_insn (gen_loadgp_rtp (base, index));
-      if (!TARGET_EXPLICIT_RELOCS)
-       emit_insn (gen_loadgp_blockage ());
-      break;
+  gcc_assert (n == XVECLEN (pattern, 0));
 
-    default:
-      break;
-    }
+  return pattern;
 }
 
-/* Set up the stack and frame (if desired) for the function.  */
+/* PATTERN is a PARALLEL whose first element adds ADJUST to the stack
+   pointer.  Return true if PATTERN matches the kind of instruction
+   generated by mips16e_build_save_restore.  If INFO is nonnull,
+   initialize it when returning true.  */
 
-static void
-mips_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
+bool
+mips16e_save_restore_pattern_p (rtx pattern, HOST_WIDE_INT adjust,
+                               struct mips16e_save_restore_info *info)
 {
-  const char *fnname;
-  HOST_WIDE_INT tsize = cfun->machine->frame.total_size;
-
-#ifdef SDB_DEBUGGING_INFO
-  if (debug_info_level != DINFO_LEVEL_TERSE && write_symbols == SDB_DEBUG)
-    SDB_OUTPUT_SOURCE_LINE (file, DECL_SOURCE_LINE (current_function_decl));
-#endif
-
-  /* In mips16 mode, we may need to generate a 32 bit to handle
-     floating point arguments.  The linker will arrange for any 32-bit
-     functions to call this stub, which will then jump to the 16-bit
-     function proper.  */
-  if (TARGET_MIPS16
-      && TARGET_HARD_FLOAT_ABI
-      && current_function_args_info.fp_code != 0)
-    build_mips16_function_stub (file);
-
-  /* Select the mips16 mode for this function.  */
-  if (TARGET_MIPS16)
-    fprintf (file, "\t.set\tmips16\n");
-  else 
-    fprintf (file, "\t.set\tnomips16\n");
-
-  if (!FUNCTION_NAME_ALREADY_DECLARED)
-    {
-      /* Get the function name the same way that toplev.c does before calling
-        assemble_start_function.  This is needed so that the name used here
-        exactly matches the name used in ASM_DECLARE_FUNCTION_NAME.  */
-      fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
-
-      if (!flag_inhibit_size_directive)
-       {
-         fputs ("\t.ent\t", file);
-         assemble_name (file, fnname);
-         fputs ("\n", file);
-       }
-
-      assemble_name (file, fnname);
-      fputs (":\n", file);
-    }
-
-  /* Stop mips_file_end from treating this function as external.  */
-  if (TARGET_IRIX && mips_abi == ABI_32)
-    TREE_ASM_WRITTEN (DECL_NAME (cfun->decl)) = 1;
-
-  if (!flag_inhibit_size_directive)
-    {
-      /* .frame FRAMEREG, FRAMESIZE, RETREG */
-      fprintf (file,
-              "\t.frame\t%s," HOST_WIDE_INT_PRINT_DEC ",%s\t\t"
-              "# vars= " HOST_WIDE_INT_PRINT_DEC ", regs= %d/%d"
-              ", args= " HOST_WIDE_INT_PRINT_DEC
-              ", gp= " HOST_WIDE_INT_PRINT_DEC "\n",
-              (reg_names[(frame_pointer_needed)
-                         ? HARD_FRAME_POINTER_REGNUM : STACK_POINTER_REGNUM]),
-              ((frame_pointer_needed && TARGET_MIPS16)
-               ? tsize - cfun->machine->frame.args_size
-               : tsize),
-              reg_names[GP_REG_FIRST + 31],
-              cfun->machine->frame.var_size,
-              cfun->machine->frame.num_gp,
-              cfun->machine->frame.num_fp,
-              cfun->machine->frame.args_size,
-              cfun->machine->frame.cprestore_size);
-
-      /* .mask MASK, GPOFFSET; .fmask FPOFFSET */
-      fprintf (file, "\t.mask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
-              cfun->machine->frame.mask,
-              cfun->machine->frame.gp_save_offset);
-      fprintf (file, "\t.fmask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
-              cfun->machine->frame.fmask,
-              cfun->machine->frame.fp_save_offset);
-
-      /* Require:
-        OLD_SP == *FRAMEREG + FRAMESIZE => can find old_sp from nominated FP reg.
-        HIGHEST_GP_SAVED == *FRAMEREG + FRAMESIZE + GPOFFSET => can find saved regs.  */
-    }
-
-  if (mips_current_loadgp_style () == LOADGP_OLDABI)
-    {
-      /* Handle the initialization of $gp for SVR4 PIC.  */
-      if (!cfun->machine->all_noreorder_p)
-       output_asm_insn ("%(.cpload\t%^%)", 0);
-      else
-       output_asm_insn ("%(.cpload\t%^\n\t%<", 0);
-    }
-  else if (cfun->machine->all_noreorder_p)
-    output_asm_insn ("%(%<", 0);
-
-  /* Tell the assembler which register we're using as the global
-     pointer.  This is needed for thunks, since they can use either
-     explicit relocs or assembler macros.  */
-  mips_output_cplocal ();
-}
-\f
-/* Make the last instruction frame related and note that it performs
-   the operation described by FRAME_PATTERN.  */
-
-static void
-mips_set_frame_expr (rtx frame_pattern)
-{
-  rtx insn;
-
-  insn = get_last_insn ();
-  RTX_FRAME_RELATED_P (insn) = 1;
-  REG_NOTES (insn) = alloc_EXPR_LIST (REG_FRAME_RELATED_EXPR,
-                                     frame_pattern,
-                                     REG_NOTES (insn));
-}
-
-
-/* Return a frame-related rtx that stores REG at MEM.
-   REG must be a single register.  */
-
-static rtx
-mips_frame_set (rtx mem, rtx reg)
-{
-  rtx set;
-
-  /* If we're saving the return address register and the dwarf return
-     address column differs from the hard register number, adjust the
-     note reg to refer to the former.  */
-  if (REGNO (reg) == GP_REG_FIRST + 31
-      && DWARF_FRAME_RETURN_COLUMN != GP_REG_FIRST + 31)
-    reg = gen_rtx_REG (GET_MODE (reg), DWARF_FRAME_RETURN_COLUMN);
-
-  set = gen_rtx_SET (VOIDmode, mem, reg);
-  RTX_FRAME_RELATED_P (set) = 1;
-
-  return set;
-}
-
-
-/* Save register REG to MEM.  Make the instruction frame-related.  */
-
-static void
-mips_save_reg (rtx reg, rtx mem)
-{
-  if (GET_MODE (reg) == DFmode && !TARGET_FLOAT64)
-    {
-      rtx x1, x2;
-
-      if (mips_split_64bit_move_p (mem, reg))
-       mips_split_64bit_move (mem, reg);
-      else
-       mips_emit_move (mem, reg);
-
-      x1 = mips_frame_set (mips_subword (mem, 0), mips_subword (reg, 0));
-      x2 = mips_frame_set (mips_subword (mem, 1), mips_subword (reg, 1));
-      mips_set_frame_expr (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, x1, x2)));
-    }
-  else
-    {
-      if (TARGET_MIPS16
-         && REGNO (reg) != GP_REG_FIRST + 31
-         && !M16_REG_P (REGNO (reg)))
-       {
-         /* Save a non-mips16 register by moving it through a temporary.
-            We don't need to do this for $31 since there's a special
-            instruction for it.  */
-         mips_emit_move (MIPS_PROLOGUE_TEMP (GET_MODE (reg)), reg);
-         mips_emit_move (mem, MIPS_PROLOGUE_TEMP (GET_MODE (reg)));
-       }
-      else
-       mips_emit_move (mem, reg);
-
-      mips_set_frame_expr (mips_frame_set (mem, reg));
-    }
-}
-
-/* Return a move between register REGNO and memory location SP + OFFSET.
-   Make the move a load if RESTORE_P, otherwise make it a frame-related
-   store.  */
-
-static rtx
-mips16e_save_restore_reg (bool restore_p, HOST_WIDE_INT offset,
-                         unsigned int regno)
-{
-  rtx reg, mem;
-
-  mem = gen_frame_mem (SImode, plus_constant (stack_pointer_rtx, offset));
-  reg = gen_rtx_REG (SImode, regno);
-  return (restore_p
-         ? gen_rtx_SET (VOIDmode, reg, mem)
-         : mips_frame_set (mem, reg));
-}
-
-/* Return RTL for a MIPS16e SAVE or RESTORE instruction; RESTORE_P says which.
-   The instruction must:
-
-     - Allocate or deallocate SIZE bytes in total; SIZE is known
-       to be nonzero.
-
-     - Save or restore as many registers in *MASK_PTR as possible.
-       The instruction saves the first registers at the top of the
-       allocated area, with the other registers below it.
-
-     - Save NARGS argument registers above the allocated area.
-
-   (NARGS is always zero if RESTORE_P.)
-
-   The SAVE and RESTORE instructions cannot save and restore all general
-   registers, so there may be some registers left over for the caller to
-   handle.  Destructively modify *MASK_PTR so that it contains the registers
-   that still need to be saved or restored.  The caller can save these
-   registers in the memory immediately below *OFFSET_PTR, which is a
-   byte offset from the bottom of the allocated stack area.  */
-
-static rtx
-mips16e_build_save_restore (bool restore_p, unsigned int *mask_ptr,
-                           HOST_WIDE_INT *offset_ptr, unsigned int nargs,
-                           HOST_WIDE_INT size)
-{
-  rtx pattern, set;
-  HOST_WIDE_INT offset, top_offset;
-  unsigned int i, regno;
-  int n;
-
-  gcc_assert (cfun->machine->frame.fp_reg_size == 0);
-
-  /* Calculate the number of elements in the PARALLEL.  We need one element
-     for the stack adjustment, one for each argument register save, and one
-     for each additional register move.  */
-  n = 1 + nargs;
-  for (i = 0; i < ARRAY_SIZE (mips16e_save_restore_regs); i++)
-    if (BITSET_P (*mask_ptr, mips16e_save_restore_regs[i]))
-      n++;
-
-  /* Create the final PARALLEL.  */
-  pattern = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (n));
-  n = 0;
-
-  /* Add the stack pointer adjustment.  */
-  set = gen_rtx_SET (VOIDmode, stack_pointer_rtx,
-                    plus_constant (stack_pointer_rtx,
-                                   restore_p ? size : -size));
-  RTX_FRAME_RELATED_P (set) = 1;
-  XVECEXP (pattern, 0, n++) = set;
-
-  /* Stack offsets in the PARALLEL are relative to the old stack pointer.  */
-  top_offset = restore_p ? size : 0;
-
-  /* Save the arguments.  */
-  for (i = 0; i < nargs; i++)
-    {
-      offset = top_offset + i * GET_MODE_SIZE (gpr_mode);
-      set = mips16e_save_restore_reg (restore_p, offset, GP_ARG_FIRST + i);
-      XVECEXP (pattern, 0, n++) = set;
-    }
-
-  /* Then fill in the other register moves.  */
-  offset = top_offset;
-  for (i = 0; i < ARRAY_SIZE (mips16e_save_restore_regs); i++)
-    {
-      regno = mips16e_save_restore_regs[i];
-      if (BITSET_P (*mask_ptr, regno))
-       {
-         offset -= UNITS_PER_WORD;
-         set = mips16e_save_restore_reg (restore_p, offset, regno);
-         XVECEXP (pattern, 0, n++) = set;
-         *mask_ptr &= ~(1 << regno);
-       }
-    }
-
-  /* Tell the caller what offset it should use for the remaining registers.  */
-  *offset_ptr = size + (offset - top_offset) + size;
-
-  gcc_assert (n == XVECLEN (pattern, 0));
-
-  return pattern;
-}
-
-/* PATTERN is a PARALLEL whose first element adds ADJUST to the stack
-   pointer.  Return true if PATTERN matches the kind of instruction
-   generated by mips16e_build_save_restore.  If INFO is nonnull,
-   initialize it when returning true.  */
-
-bool
-mips16e_save_restore_pattern_p (rtx pattern, HOST_WIDE_INT adjust,
-                               struct mips16e_save_restore_info *info)
-{
-  unsigned int i, nargs, mask;
-  HOST_WIDE_INT top_offset, save_offset, offset, extra;
+  unsigned int i, nargs, mask, extra;
+  HOST_WIDE_INT top_offset, save_offset, offset;
   rtx set, reg, mem, base;
   int n;
 
@@ -8206,7 +7465,7 @@ mips16e_save_restore_pattern_p (rtx pattern, HOST_WIDE_INT adjust,
   top_offset = adjust > 0 ? adjust : 0;
 
   /* Interpret all other members of the PARALLEL.  */
-  save_offset = top_offset - GET_MODE_SIZE (gpr_mode);
+  save_offset = top_offset - UNITS_PER_WORD;
   mask = 0;
   nargs = 0;
   i = 0;
@@ -8235,7 +7494,7 @@ mips16e_save_restore_pattern_p (rtx pattern, HOST_WIDE_INT adjust,
        return false;
 
       /* Check for argument saves.  */
-      if (offset == top_offset + nargs * GET_MODE_SIZE (gpr_mode)
+      if (offset == top_offset + nargs * UNITS_PER_WORD
          && REGNO (reg) == GP_ARG_FIRST + nargs)
        nargs++;
       else if (offset == save_offset)
@@ -8245,7 +7504,7 @@ mips16e_save_restore_pattern_p (rtx pattern, HOST_WIDE_INT adjust,
              return false;
 
          mask |= 1 << REGNO (reg);
-         save_offset -= GET_MODE_SIZE (gpr_mode);
+         save_offset -= UNITS_PER_WORD;
        }
       else
        return false;
@@ -8353,1034 +7612,1258 @@ mips16e_output_save_restore (rtx pattern, HOST_WIDE_INT adjust)
 
   return buffer;
 }
+\f
+/* Return true if the current function has an insn that implicitly
+   refers to $gp.  */
 
-/* Return a simplified form of X using the register values in REG_VALUES.
-   REG_VALUES[R] is the last value assigned to hard register R, or null
-   if R has not been modified.
-
-   This function is rather limited, but is good enough for our purposes.  */
-
-static rtx
-mips16e_collect_propagate_value (rtx x, rtx *reg_values)
+static bool
+mips_function_has_gp_insn (void)
 {
-  rtx x0, x1;
-
-  x = avoid_constant_pool_reference (x);
-
-  if (UNARY_P (x))
+  /* Don't bother rechecking if we found one last time.  */
+  if (!cfun->machine->has_gp_insn_p)
     {
-      x0 = mips16e_collect_propagate_value (XEXP (x, 0), reg_values);
-      return simplify_gen_unary (GET_CODE (x), GET_MODE (x),
-                                x0, GET_MODE (XEXP (x, 0)));
-    }
+      rtx insn;
 
-  if (ARITHMETIC_P (x))
-    {
-      x0 = mips16e_collect_propagate_value (XEXP (x, 0), reg_values);
-      x1 = mips16e_collect_propagate_value (XEXP (x, 1), reg_values);
-      return simplify_gen_binary (GET_CODE (x), GET_MODE (x), x0, x1);
+      push_topmost_sequence ();
+      for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
+       if (USEFUL_INSN_P (insn)
+           && (get_attr_got (insn) != GOT_UNSET
+               || mips_small_data_pattern_p (PATTERN (insn))))
+         {
+           cfun->machine->has_gp_insn_p = true;
+           break;
+         }
+      pop_topmost_sequence ();
     }
+  return cfun->machine->has_gp_insn_p;
+}
 
-  if (REG_P (x)
-      && reg_values[REGNO (x)]
-      && !rtx_unstable_p (reg_values[REGNO (x)]))
-    return reg_values[REGNO (x)];
+/* Return the register that should be used as the global pointer
+   within this function.  Return 0 if the function doesn't need
+   a global pointer.  */
 
-  return x;
+static unsigned int
+mips_global_pointer (void)
+{
+  unsigned int regno;
+
+  /* $gp is always available unless we're using a GOT.  */
+  if (!TARGET_USE_GOT)
+    return GLOBAL_POINTER_REGNUM;
+
+  /* We must always provide $gp when it is used implicitly.  */
+  if (!TARGET_EXPLICIT_RELOCS)
+    return GLOBAL_POINTER_REGNUM;
+
+  /* FUNCTION_PROFILER includes a jal macro, so we need to give it
+     a valid gp.  */
+  if (current_function_profile)
+    return GLOBAL_POINTER_REGNUM;
+
+  /* If the function has a nonlocal goto, $gp must hold the correct
+     global pointer for the target function.  */
+  if (current_function_has_nonlocal_goto)
+    return GLOBAL_POINTER_REGNUM;
+
+  /* If the gp is never referenced, there's no need to initialize it.
+     Note that reload can sometimes introduce constant pool references
+     into a function that otherwise didn't need them.  For example,
+     suppose we have an instruction like:
+
+         (set (reg:DF R1) (float:DF (reg:SI R2)))
+
+     If R2 turns out to be constant such as 1, the instruction may have a
+     REG_EQUAL note saying that R1 == 1.0.  Reload then has the option of
+     using this constant if R2 doesn't get allocated to a register.
+
+     In cases like these, reload will have added the constant to the pool
+     but no instruction will yet refer to it.  */
+  if (!df_regs_ever_live_p (GLOBAL_POINTER_REGNUM)
+      && !current_function_uses_const_pool
+      && !mips_function_has_gp_insn ())
+    return 0;
+
+  /* We need a global pointer, but perhaps we can use a call-clobbered
+     register instead of $gp.  */
+  if (TARGET_CALL_SAVED_GP && current_function_is_leaf)
+    for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
+      if (!df_regs_ever_live_p (regno)
+         && call_really_used_regs[regno]
+         && !fixed_regs[regno]
+         && regno != PIC_FUNCTION_ADDR_REGNUM)
+       return regno;
+
+  return GLOBAL_POINTER_REGNUM;
 }
 
-/* Return true if (set DEST SRC) stores an argument register into its
-   caller-allocated save slot, storing the number of that argument
-   register in *REGNO_PTR if so.  REG_VALUES is as for
-   mips16e_collect_propagate_value.  */
+/* Return true if the current function returns its value in a floating-point
+   register in MIPS16 mode.  */
 
 static bool
-mips16e_collect_argument_save_p (rtx dest, rtx src, rtx *reg_values,
-                                unsigned int *regno_ptr)
+mips16_cfun_returns_in_fpr_p (void)
 {
-  unsigned int argno, regno;
-  HOST_WIDE_INT offset, required_offset;
-  rtx addr, base;
+  tree return_type = DECL_RESULT (current_function_decl);
+  return (TARGET_MIPS16
+         && TARGET_HARD_FLOAT_ABI
+         && !aggregate_value_p (return_type, current_function_decl)
+         && mips_return_mode_in_fpr_p (DECL_MODE (return_type)));
+}
 
-  /* Check that this is a word-mode store.  */
-  if (!MEM_P (dest) || !REG_P (src) || GET_MODE (dest) != word_mode)
-    return false;
+/* Return true if the current function must save register REGNO.  */
 
-  /* Check that the register being saved is an unmodified argument
-     register.  */
-  regno = REGNO (src);
-  if (regno < GP_ARG_FIRST || regno > GP_ARG_LAST || reg_values[regno])
-    return false;
-  argno = regno - GP_ARG_FIRST;
+static bool
+mips_save_reg_p (unsigned int regno)
+{
+  /* We only need to save $gp if TARGET_CALL_SAVED_GP and only then
+     if we have not chosen a call-clobbered substitute.  */
+  if (regno == GLOBAL_POINTER_REGNUM)
+    return TARGET_CALL_SAVED_GP && cfun->machine->global_pointer == regno;
 
-  /* Check whether the address is an appropriate stack pointer or
-     frame pointer access.  The frame pointer is offset from the
-     stack pointer by the size of the outgoing arguments.  */
-  addr = mips16e_collect_propagate_value (XEXP (dest, 0), reg_values);
-  mips_split_plus (addr, &base, &offset);
-  required_offset = cfun->machine->frame.total_size + argno * UNITS_PER_WORD;
-  if (base == hard_frame_pointer_rtx)
-    required_offset -= cfun->machine->frame.args_size;
-  else if (base != stack_pointer_rtx)
-    return false;
-  if (offset != required_offset)
-    return false;
+  /* Check call-saved registers.  */
+  if ((current_function_saves_all_registers || df_regs_ever_live_p (regno))
+      && !call_really_used_regs[regno])
+    return true;
 
-  *regno_ptr = regno;
-  return true;
+  /* Save both registers in an FPR pair if either one is used.  This is
+     needed for the case when MIN_FPRS_PER_FMT == 1, which allows the odd
+     register to be used without the even register.  */
+  if (FP_REG_P (regno)
+      && MAX_FPRS_PER_FMT == 2
+      && df_regs_ever_live_p (regno + 1)
+      && !call_really_used_regs[regno + 1])
+    return true;
+
+  /* We need to save the old frame pointer before setting up a new one.  */
+  if (regno == HARD_FRAME_POINTER_REGNUM && frame_pointer_needed)
+    return true;
+
+  /* Check for registers that must be saved for FUNCTION_PROFILER.  */
+  if (current_function_profile && MIPS_SAVE_REG_FOR_PROFILING_P (regno))
+    return true;
+
+  /* We need to save the incoming return address if it is ever clobbered
+     within the function, if __builtin_eh_return is being used to set a
+     different return address, or if a stub is being used to return a
+     value in FPRs.  */
+  if (regno == GP_REG_FIRST + 31
+      && (df_regs_ever_live_p (regno)
+         || current_function_calls_eh_return
+         || mips16_cfun_returns_in_fpr_p ()))
+    return true;
+
+  return false;
 }
 
-/* A subroutine of mips_expand_prologue, called only when generating
-   MIPS16e SAVE instructions.  Search the start of the function for any
-   instructions that save argument registers into their caller-allocated
-   save slots.  Delete such instructions and return a value N such that
-   saving [GP_ARG_FIRST, GP_ARG_FIRST + N) would make all the deleted
-   instructions redundant.  */
+/* Populate the current function's mips_frame_info structure.
 
-static unsigned int
-mips16e_collect_argument_saves (void)
-{
-  rtx reg_values[FIRST_PSEUDO_REGISTER];
-  rtx insn, next, set, dest, src;
-  unsigned int nargs, regno;
+   MIPS stack frames look like:
 
-  push_topmost_sequence ();
-  nargs = 0;
-  memset (reg_values, 0, sizeof (reg_values));
-  for (insn = get_insns (); insn; insn = next)
-    {
-      next = NEXT_INSN (insn);
-      if (NOTE_P (insn))
-       continue;
+       +-------------------------------+
+       |                               |
+       |  incoming stack arguments     |
+       |                               |
+       +-------------------------------+
+       |                               |
+       |  caller-allocated save area   |
+      A |  for register arguments       |
+       |                               |
+       +-------------------------------+ <-- incoming stack pointer
+       |                               |
+       |  callee-allocated save area   |
+      B |  for arguments that are       |
+       |  split between registers and  |
+       |  the stack                    |
+       |                               |
+       +-------------------------------+ <-- arg_pointer_rtx
+       |                               |
+      C |  callee-allocated save area   |
+       |  for register varargs         |
+       |                               |
+       +-------------------------------+ <-- frame_pointer_rtx + fp_sp_offset
+       |                               |       + UNITS_PER_HWFPVALUE
+       |  FPR save area                |
+       |                               |
+       +-------------------------------+ <-- frame_pointer_rtx + gp_sp_offset
+       |                               |       + UNITS_PER_WORD
+       |  GPR save area                |
+       |                               |
+       +-------------------------------+
+       |                               | \
+       |  local variables              |  | var_size
+       |                               | /
+       +-------------------------------+
+       |                               | \
+       |  $gp save area                |  | cprestore_size
+       |                               | /
+      P +-------------------------------+ <-- hard_frame_pointer_rtx for
+       |                               |       MIPS16 code
+       |  outgoing stack arguments     |
+       |                               |
+       +-------------------------------+
+       |                               |
+       |  caller-allocated save area   |
+       |  for register arguments       |
+       |                               |
+       +-------------------------------+ <-- stack_pointer_rtx
+                                             frame_pointer_rtx
+                                             hard_frame_pointer_rtx for
+                                               non-MIPS16 code.
+
+   At least two of A, B and C will be empty.
+
+   Dynamic stack allocations such as alloca insert data at point P.
+   They decrease stack_pointer_rtx but leave frame_pointer_rtx and
+   hard_frame_pointer_rtx unchanged.  */
 
-      if (!INSN_P (insn))
-       break;
+static void
+mips_compute_frame_info (void)
+{
+  struct mips_frame_info *frame;
+  HOST_WIDE_INT offset, size;
+  unsigned int regno, i;
 
-      set = PATTERN (insn);
-      if (GET_CODE (set) != SET)
-       break;
+  frame = &cfun->machine->frame;
+  memset (frame, 0, sizeof (*frame));
+  size = get_frame_size ();
 
-      dest = SET_DEST (set);
-      src = SET_SRC (set);
-      if (mips16e_collect_argument_save_p (dest, src, reg_values, &regno))
-       {
-         if (!BITSET_P (cfun->machine->frame.mask, regno))
-           {
-             delete_insn (insn);
-             nargs = MAX (nargs, (regno - GP_ARG_FIRST) + 1);
-           }
-       }
-      else if (REG_P (dest) && GET_MODE (dest) == word_mode)
-       reg_values[REGNO (dest)]
-         = mips16e_collect_propagate_value (src, reg_values);
+  cfun->machine->global_pointer = mips_global_pointer ();
+
+  /* The first STARTING_FRAME_OFFSET bytes contain the outgoing argument
+     area and the $gp save slot.  This area isn't needed in leaf functions,
+     but if the target-independent frame size is nonzero, we're committed
+     to allocating it anyway.  */
+  if (size == 0 && current_function_is_leaf)
+    {
+      /* The MIPS 3.0 linker does not like functions that dynamically
+        allocate the stack and have 0 for STACK_DYNAMIC_OFFSET, since it
+        looks like we are trying to create a second frame pointer to the
+        function, so allocate some stack space to make it happy.  */
+      if (current_function_calls_alloca)
+       frame->args_size = REG_PARM_STACK_SPACE (cfun->decl);
       else
-       break;
+       frame->args_size = 0;
+      frame->cprestore_size = 0;
     }
-  pop_topmost_sequence ();
+  else
+    {
+      frame->args_size = current_function_outgoing_args_size;
+      frame->cprestore_size = STARTING_FRAME_OFFSET - frame->args_size;
+    }
+  offset = frame->args_size + frame->cprestore_size;
 
-  return nargs;
-}
+  /* Move above the local variables.  */
+  frame->var_size = MIPS_STACK_ALIGN (size);
+  offset += frame->var_size;
 
-/* Expand the prologue into a bunch of separate insns.  */
+  /* Find out which GPRs we need to save.  */
+  for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
+    if (mips_save_reg_p (regno))
+      {
+       frame->num_gp++;
+       frame->mask |= 1 << (regno - GP_REG_FIRST);
+      }
 
-void
-mips_expand_prologue (void)
-{
-  HOST_WIDE_INT size;
-  unsigned int nargs;
-  rtx insn;
+  /* If this function calls eh_return, we must also save and restore the
+     EH data registers.  */
+  if (current_function_calls_eh_return)
+    for (i = 0; EH_RETURN_DATA_REGNO (i) != INVALID_REGNUM; i++)
+      {
+       frame->num_gp++;
+       frame->mask |= 1 << (EH_RETURN_DATA_REGNO (i) - GP_REG_FIRST);
+      }
 
-  if (cfun->machine->global_pointer > 0)
-    SET_REGNO (pic_offset_table_rtx, cfun->machine->global_pointer);
+  /* The MIPS16e SAVE and RESTORE instructions have two ranges of registers:
+     $a3-$a0 and $s2-$s8.  If we save one register in the range, we must
+     save all later registers too.  */
+  if (GENERATE_MIPS16E_SAVE_RESTORE)
+    {
+      mips16e_mask_registers (&frame->mask, mips16e_s2_s8_regs,
+                             ARRAY_SIZE (mips16e_s2_s8_regs), &frame->num_gp);
+      mips16e_mask_registers (&frame->mask, mips16e_a0_a3_regs,
+                             ARRAY_SIZE (mips16e_a0_a3_regs), &frame->num_gp);
+    }
 
-  size = compute_frame_size (get_frame_size ());
+  /* Move above the GPR save area.  */
+  if (frame->num_gp > 0)
+    {
+      offset += MIPS_STACK_ALIGN (frame->num_gp * UNITS_PER_WORD);
+      frame->gp_sp_offset = offset - UNITS_PER_WORD;
+    }
 
-  /* Save the registers.  Allocate up to MIPS_MAX_FIRST_STACK_STEP
-     bytes beforehand; this is enough to cover the register save area
-     without going out of range.  */
-  if ((cfun->machine->frame.mask | cfun->machine->frame.fmask) != 0)
+  /* Find out which FPRs we need to save.  This loop must iterate over
+     the same space as its companion in mips_for_each_saved_reg.  */
+  if (TARGET_HARD_FLOAT)
+    for (regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno += MAX_FPRS_PER_FMT)
+      if (mips_save_reg_p (regno))
+       {
+         frame->num_fp += MAX_FPRS_PER_FMT;
+         frame->fmask |= ~(~0 << MAX_FPRS_PER_FMT) << (regno - FP_REG_FIRST);
+       }
+
+  /* Move above the FPR save area.  */
+  if (frame->num_fp > 0)
     {
-      HOST_WIDE_INT step1;
+      offset += MIPS_STACK_ALIGN (frame->num_fp * UNITS_PER_FPREG);
+      frame->fp_sp_offset = offset - UNITS_PER_HWFPVALUE;
+    }
 
-      step1 = MIN (size, MIPS_MAX_FIRST_STACK_STEP);
+  /* Move above the callee-allocated varargs save area.  */
+  offset += MIPS_STACK_ALIGN (cfun->machine->varargs_size);
+  frame->arg_pointer_offset = offset;
 
-      if (GENERATE_MIPS16E_SAVE_RESTORE)
-       {
-         HOST_WIDE_INT offset;
-         unsigned int mask, regno;
+  /* Move above the callee-allocated area for pretend stack arguments.  */
+  offset += current_function_pretend_args_size;
+  frame->total_size = offset;
 
-         /* Try to merge argument stores into the save instruction.  */
-         nargs = mips16e_collect_argument_saves ();
+  /* Work out the offsets of the save areas from the top of the frame.  */
+  if (frame->gp_sp_offset > 0)
+    frame->gp_save_offset = frame->gp_sp_offset - offset;
+  if (frame->fp_sp_offset > 0)
+    frame->fp_save_offset = frame->fp_sp_offset - offset;
 
-         /* Build the save instruction.  */
-         mask = cfun->machine->frame.mask;
-         insn = mips16e_build_save_restore (false, &mask, &offset,
-                                            nargs, step1);
-         RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
-         size -= step1;
+  /* MIPS16 code offsets the frame pointer by the size of the outgoing
+     arguments.  This tends to increase the chances of using unextended
+     instructions for local variables and incoming arguments.  */
+  if (TARGET_MIPS16)
+    frame->hard_frame_pointer_offset = frame->args_size;
+}
 
-         /* Check if we need to save other registers.  */
-         for (regno = GP_REG_FIRST; regno < GP_REG_LAST; regno++)
-           if (BITSET_P (mask, regno - GP_REG_FIRST))
-             {
-               offset -= GET_MODE_SIZE (gpr_mode);
-               mips_save_restore_reg (gpr_mode, regno, offset, mips_save_reg);
-             }
-       }
-      else
-       {
-         insn = gen_add3_insn (stack_pointer_rtx,
-                               stack_pointer_rtx,
-                               GEN_INT (-step1));
-         RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
-         size -= step1;
-         mips_for_each_saved_reg (size, mips_save_reg);
-       }
-    }
+/* Return the style of GP load sequence that is being used for the
+   current function.  */
 
-  /* Allocate the rest of the frame.  */
-  if (size > 0)
-    {
-      if (SMALL_OPERAND (-size))
-       RTX_FRAME_RELATED_P (emit_insn (gen_add3_insn (stack_pointer_rtx,
-                                                      stack_pointer_rtx,
-                                                      GEN_INT (-size)))) = 1;
-      else
-       {
-         mips_emit_move (MIPS_PROLOGUE_TEMP (Pmode), GEN_INT (size));
-         if (TARGET_MIPS16)
-           {
-             /* There are no instructions to add or subtract registers
-                from the stack pointer, so use the frame pointer as a
-                temporary.  We should always be using a frame pointer
-                in this case anyway.  */
-             gcc_assert (frame_pointer_needed);
-             mips_emit_move (hard_frame_pointer_rtx, stack_pointer_rtx);
-             emit_insn (gen_sub3_insn (hard_frame_pointer_rtx,
-                                       hard_frame_pointer_rtx,
-                                       MIPS_PROLOGUE_TEMP (Pmode)));
-             mips_emit_move (stack_pointer_rtx, hard_frame_pointer_rtx);
-           }
-         else
-           emit_insn (gen_sub3_insn (stack_pointer_rtx,
-                                     stack_pointer_rtx,
-                                     MIPS_PROLOGUE_TEMP (Pmode)));
+enum mips_loadgp_style
+mips_current_loadgp_style (void)
+{
+  if (!TARGET_USE_GOT || cfun->machine->global_pointer == 0)
+    return LOADGP_NONE;
 
-         /* Describe the combined effect of the previous instructions.  */
-         mips_set_frame_expr
-           (gen_rtx_SET (VOIDmode, stack_pointer_rtx,
-                         plus_constant (stack_pointer_rtx, -size)));
-       }
-    }
+  if (TARGET_RTP_PIC)
+    return LOADGP_RTP;
 
-  /* Set up the frame pointer, if we're using one.  In mips16 code,
-     we point the frame pointer ahead of the outgoing argument area.
-     This should allow more variables & incoming arguments to be
-     accessed with unextended instructions.  */
-  if (frame_pointer_needed)
-    {
-      if (TARGET_MIPS16 && cfun->machine->frame.args_size != 0)
-       {
-         rtx offset = GEN_INT (cfun->machine->frame.args_size);
-         if (SMALL_OPERAND (cfun->machine->frame.args_size))
-           RTX_FRAME_RELATED_P
-             (emit_insn (gen_add3_insn (hard_frame_pointer_rtx,
-                                        stack_pointer_rtx,
-                                        offset))) = 1;
-         else
-           {
-             mips_emit_move (MIPS_PROLOGUE_TEMP (Pmode), offset);
-             mips_emit_move (hard_frame_pointer_rtx, stack_pointer_rtx);
-             emit_insn (gen_add3_insn (hard_frame_pointer_rtx,
-                                       hard_frame_pointer_rtx,
-                                       MIPS_PROLOGUE_TEMP (Pmode)));
-             mips_set_frame_expr
-               (gen_rtx_SET (VOIDmode, hard_frame_pointer_rtx,
-                             plus_constant (stack_pointer_rtx,
-                                            cfun->machine->frame.args_size)));
-           }
-       }
-      else
-       RTX_FRAME_RELATED_P (mips_emit_move (hard_frame_pointer_rtx,
-                                            stack_pointer_rtx)) = 1;
-    }
+  if (TARGET_ABSOLUTE_ABICALLS)
+    return LOADGP_ABSOLUTE;
 
-  mips_emit_loadgp ();
+  return TARGET_NEWABI ? LOADGP_NEWABI : LOADGP_OLDABI;
+}
 
-  /* If generating o32/o64 abicalls, save $gp on the stack.  */
-  if (TARGET_ABICALLS && TARGET_OLDABI && !current_function_is_leaf)
-    emit_insn (gen_cprestore (GEN_INT (current_function_outgoing_args_size)));
+/* Implement FRAME_POINTER_REQUIRED.  */
 
-  /* If we are profiling, make sure no instructions are scheduled before
-     the call to mcount.  */
+bool
+mips_frame_pointer_required (void)
+{
+  /* If the function contains dynamic stack allocations, we need to
+     use the frame pointer to access the static parts of the frame.  */
+  if (current_function_calls_alloca)
+    return true;
 
-  if (current_function_profile)
-    emit_insn (gen_blockage ());
+  /* In MIPS16 mode, we need a frame pointer for a large frame; otherwise,
+     reload may be unable to compute the address of a local variable,
+     since there is no way to add a large constant to the stack pointer
+     without using a second temporary register.  */
+  if (TARGET_MIPS16)
+    {
+      mips_compute_frame_info ();
+      if (!SMALL_OPERAND (cfun->machine->frame.total_size))
+       return true;
+    }
+
+  return false;
 }
-\f
-/* Do any necessary cleanup after a function to restore stack, frame,
-   and regs.  */
 
-#define RA_MASK BITMASK_HIGH   /* 1 << 31 */
+/* Implement INITIAL_ELIMINATION_OFFSET.  FROM is either the frame pointer
+   or argument pointer.  TO is either the stack pointer or hard frame
+   pointer.  */
 
-static void
-mips_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
-                              HOST_WIDE_INT size ATTRIBUTE_UNUSED)
+HOST_WIDE_INT
+mips_initial_elimination_offset (int from, int to)
 {
-  /* Reinstate the normal $gp.  */
-  SET_REGNO (pic_offset_table_rtx, GLOBAL_POINTER_REGNUM);
-  mips_output_cplocal ();
+  HOST_WIDE_INT offset;
 
-  if (cfun->machine->all_noreorder_p)
-    {
-      /* Avoid using %>%) since it adds excess whitespace.  */
-      output_asm_insn (".set\tmacro", 0);
-      output_asm_insn (".set\treorder", 0);
-      set_noreorder = set_nomacro = 0;
-    }
+  mips_compute_frame_info ();
 
-  if (!FUNCTION_NAME_ALREADY_DECLARED && !flag_inhibit_size_directive)
+  /* Set OFFSET to the offset from the soft frame pointer, which is also
+     the offset from the end-of-prologue stack pointer.  */
+  switch (from)
     {
-      const char *fnname;
+    case FRAME_POINTER_REGNUM:
+      offset = 0;
+      break;
 
-      /* Get the function name the same way that toplev.c does before calling
-        assemble_start_function.  This is needed so that the name used here
-        exactly matches the name used in ASM_DECLARE_FUNCTION_NAME.  */
-      fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
-      fputs ("\t.end\t", file);
-      assemble_name (file, fnname);
-      fputs ("\n", file);
+    case ARG_POINTER_REGNUM:
+      offset = cfun->machine->frame.arg_pointer_offset;
+      break;
+
+    default:
+      gcc_unreachable ();
     }
+
+  if (to == HARD_FRAME_POINTER_REGNUM)
+    offset -= cfun->machine->frame.hard_frame_pointer_offset;
+
+  return offset;
 }
 \f
-/* Emit instructions to restore register REG from slot MEM.  */
+/* Implement TARGET_EXTRA_LIVE_ON_ENTRY.  */
 
 static void
-mips_restore_reg (rtx reg, rtx mem)
+mips_extra_live_on_entry (bitmap regs)
 {
-  /* There's no mips16 instruction to load $31 directly.  Load into
-     $7 instead and adjust the return insn appropriately.  */
-  if (TARGET_MIPS16 && REGNO (reg) == GP_REG_FIRST + 31)
-    reg = gen_rtx_REG (GET_MODE (reg), 7);
-
-  if (TARGET_MIPS16 && !M16_REG_P (REGNO (reg)))
+  if (TARGET_USE_GOT)
     {
-      /* Can't restore directly; move through a temporary.  */
-      mips_emit_move (MIPS_EPILOGUE_TEMP (GET_MODE (reg)), mem);
-      mips_emit_move (reg, MIPS_EPILOGUE_TEMP (GET_MODE (reg)));
+      /* PIC_FUNCTION_ADDR_REGNUM is live if we need it to set up
+        the global pointer.   */
+      if (!TARGET_ABSOLUTE_ABICALLS)
+       bitmap_set_bit (regs, PIC_FUNCTION_ADDR_REGNUM);
+
+      /* See the comment above load_call<mode> for details.  */
+      bitmap_set_bit (regs, GOT_VERSION_REGNUM);
     }
-  else
-    mips_emit_move (reg, mem);
 }
 
+/* Implement RETURN_ADDR_RTX.  We do not support moving back to a
+   previous frame.  */
 
-/* Expand the epilogue into a bunch of separate insns.  SIBCALL_P is true
-   if this epilogue precedes a sibling call, false if it is for a normal
-   "epilogue" pattern.  */
-
-void
-mips_expand_epilogue (int sibcall_p)
+rtx
+mips_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
 {
-  HOST_WIDE_INT step1, step2;
-  rtx base, target;
-
-  if (!sibcall_p && mips_can_use_return_insn ())
-    {
-      emit_jump_insn (gen_return ());
-      return;
-    }
-  
-  /* In mips16 mode, if the return value should go into a floating-point
-     register, we need to call a helper routine to copy it over.  */
-  if (mips16_cfun_returns_in_fpr_p ())
-    {
-      char *name;
-      rtx func;
-      rtx insn;
-      rtx retval;
-      rtx call;
-      tree id;
-      tree return_type;
-      enum machine_mode return_mode;
-
-      return_type = DECL_RESULT (current_function_decl);
-      return_mode = DECL_MODE (return_type);
+  if (count != 0)
+    return const0_rtx;
 
-      name = ACONCAT (("__mips16_ret_",
-                      mips16_call_stub_mode_suffix (return_mode),
-                      NULL));
-      id = get_identifier (name);
-      func = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (id));
-      retval = gen_rtx_REG (return_mode, GP_RETURN);
-      call = gen_call_value_internal (retval, func, const0_rtx);
-      insn = emit_call_insn (call);
-      use_reg (&CALL_INSN_FUNCTION_USAGE (insn), retval);
-    }
+  return get_hard_reg_initial_val (Pmode, GP_REG_FIRST + 31);
+}
 
-  /* Split the frame into two.  STEP1 is the amount of stack we should
-     deallocate before restoring the registers.  STEP2 is the amount we
-     should deallocate afterwards.
+/* Emit code to change the current function's return address to
+   ADDRESS.  SCRATCH is available as a scratch register, if needed.
+   ADDRESS and SCRATCH are both word-mode GPRs.  */
 
-     Start off by assuming that no registers need to be restored.  */
-  step1 = cfun->machine->frame.total_size;
-  step2 = 0;
+void
+mips_set_return_address (rtx address, rtx scratch)
+{
+  rtx slot_address;
 
-  /* Work out which register holds the frame address.  Account for the
-     frame pointer offset used by mips16 code.  */
-  if (!frame_pointer_needed)
-    base = stack_pointer_rtx;
-  else
-    {
-      base = hard_frame_pointer_rtx;
-      if (TARGET_MIPS16)
-       step1 -= cfun->machine->frame.args_size;
-    }
+  gcc_assert (BITSET_P (cfun->machine->frame.mask, 31));
+  slot_address = mips_add_offset (scratch, stack_pointer_rtx,
+                                 cfun->machine->frame.gp_sp_offset);
+  mips_emit_move (gen_frame_mem (GET_MODE (address), slot_address), address);
+}
 
-  /* If we need to restore registers, deallocate as much stack as
-     possible in the second step without going out of range.  */
-  if ((cfun->machine->frame.mask | cfun->machine->frame.fmask) != 0)
-    {
-      step2 = MIN (step1, MIPS_MAX_FIRST_STACK_STEP);
-      step1 -= step2;
-    }
+/* Restore $gp from its save slot.  Valid only when using o32 or
+   o64 abicalls.  */
 
-  /* Set TARGET to BASE + STEP1.  */
-  target = base;
-  if (step1 > 0)
-    {
-      rtx adjust;
+void
+mips_restore_gp (void)
+{
+  rtx base, address;
 
-      /* Get an rtx for STEP1 that we can add to BASE.  */
-      adjust = GEN_INT (step1);
-      if (!SMALL_OPERAND (step1))
-       {
-         mips_emit_move (MIPS_EPILOGUE_TEMP (Pmode), adjust);
-         adjust = MIPS_EPILOGUE_TEMP (Pmode);
-       }
+  gcc_assert (TARGET_ABICALLS && TARGET_OLDABI);
 
-      /* Normal mode code can copy the result straight into $sp.  */
-      if (!TARGET_MIPS16)
-       target = stack_pointer_rtx;
+  base = frame_pointer_needed ? hard_frame_pointer_rtx : stack_pointer_rtx;
+  address = mips_add_offset (pic_offset_table_rtx, base,
+                            current_function_outgoing_args_size);
+  mips_emit_move (pic_offset_table_rtx, gen_frame_mem (Pmode, address));
+  if (!TARGET_EXPLICIT_RELOCS)
+    emit_insn (gen_blockage ());
+}
+\f
+/* A function to save or store a register.  The first argument is the
+   register and the second is the stack slot.  */
+typedef void (*mips_save_restore_fn) (rtx, rtx);
 
-      emit_insn (gen_add3_insn (target, base, adjust));
-    }
+/* Use FN to save or restore register REGNO.  MODE is the register's
+   mode and OFFSET is the offset of its save slot from the current
+   stack pointer.  */
 
-  /* Copy TARGET into the stack pointer.  */
-  if (target != stack_pointer_rtx)
-    mips_emit_move (stack_pointer_rtx, target);
+static void
+mips_save_restore_reg (enum machine_mode mode, int regno,
+                      HOST_WIDE_INT offset, mips_save_restore_fn fn)
+{
+  rtx mem;
 
-  /* If we're using addressing macros, $gp is implicitly used by all
-     SYMBOL_REFs.  We must emit a blockage insn before restoring $gp
-     from the stack.  */
-  if (TARGET_CALL_SAVED_GP && !TARGET_EXPLICIT_RELOCS)
-    emit_insn (gen_blockage ());
+  mem = gen_frame_mem (mode, plus_constant (stack_pointer_rtx, offset));
+  fn (gen_rtx_REG (mode, regno), mem);
+}
 
-  if (GENERATE_MIPS16E_SAVE_RESTORE && cfun->machine->frame.mask != 0)
-    {
-      unsigned int regno, mask;
-      HOST_WIDE_INT offset;
-      rtx restore;
+/* Call FN for each register that is saved by the current function.
+   SP_OFFSET is the offset of the current stack pointer from the start
+   of the frame.  */
 
-      /* Generate the restore instruction.  */
-      mask = cfun->machine->frame.mask;
-      restore = mips16e_build_save_restore (true, &mask, &offset, 0, step2);
+static void
+mips_for_each_saved_reg (HOST_WIDE_INT sp_offset, mips_save_restore_fn fn)
+{
+  enum machine_mode fpr_mode;
+  HOST_WIDE_INT offset;
+  int regno;
 
-      /* Restore any other registers manually.  */
-      for (regno = GP_REG_FIRST; regno < GP_REG_LAST; regno++)
-       if (BITSET_P (mask, regno - GP_REG_FIRST))
-         {
-           offset -= GET_MODE_SIZE (gpr_mode);
-           mips_save_restore_reg (gpr_mode, regno, offset, mips_restore_reg);
-         }
+  /* Save registers starting from high to low.  The debuggers prefer at least
+     the return register be stored at func+4, and also it allows us not to
+     need a nop in the epilogue if at least one register is reloaded in
+     addition to return address.  */
+  offset = cfun->machine->frame.gp_sp_offset - sp_offset;
+  for (regno = GP_REG_LAST; regno >= GP_REG_FIRST; regno--)
+    if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
+      {
+       mips_save_restore_reg (word_mode, regno, offset, fn);
+       offset -= UNITS_PER_WORD;
+      }
 
-      /* Restore the remaining registers and deallocate the final bit
-        of the frame.  */
-      emit_insn (restore);
-    }
+  /* This loop must iterate over the same space as its companion in
+     mips_compute_frame_info.  */
+  offset = cfun->machine->frame.fp_sp_offset - sp_offset;
+  fpr_mode = (TARGET_SINGLE_FLOAT ? SFmode : DFmode);
+  for (regno = FP_REG_LAST - MAX_FPRS_PER_FMT + 1;
+       regno >= FP_REG_FIRST;
+       regno -= MAX_FPRS_PER_FMT)
+    if (BITSET_P (cfun->machine->frame.fmask, regno - FP_REG_FIRST))
+      {
+       mips_save_restore_reg (fpr_mode, regno, offset, fn);
+       offset -= GET_MODE_SIZE (fpr_mode);
+      }
+}
+\f
+/* If we're generating n32 or n64 abicalls, and the current function
+   does not use $28 as its global pointer, emit a cplocal directive.
+   Use pic_offset_table_rtx as the argument to the directive.  */
+
+static void
+mips_output_cplocal (void)
+{
+  if (!TARGET_EXPLICIT_RELOCS
+      && cfun->machine->global_pointer > 0
+      && cfun->machine->global_pointer != GLOBAL_POINTER_REGNUM)
+    output_asm_insn (".cplocal %+", 0);
+}
+
+/* Implement TARGET_OUTPUT_FUNCTION_PROLOGUE.  */
+
+static void
+mips_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
+{
+  const char *fnname;
+
+#ifdef SDB_DEBUGGING_INFO
+  if (debug_info_level != DINFO_LEVEL_TERSE && write_symbols == SDB_DEBUG)
+    SDB_OUTPUT_SOURCE_LINE (file, DECL_SOURCE_LINE (current_function_decl));
+#endif
+
+  /* In MIPS16 mode, we may need to generate a non-MIPS16 stub to handle
+     floating-point arguments.  */
+  if (TARGET_MIPS16
+      && TARGET_HARD_FLOAT_ABI
+      && current_function_args_info.fp_code != 0)
+    mips16_build_function_stub ();
+
+  /* Select the MIPS16 mode for this function.  */
+  if (TARGET_MIPS16)
+    fprintf (file, "\t.set\tmips16\n");
   else
+    fprintf (file, "\t.set\tnomips16\n");
+
+  if (!FUNCTION_NAME_ALREADY_DECLARED)
     {
-      /* Restore the registers.  */
-      mips_for_each_saved_reg (cfun->machine->frame.total_size - step2,
-                              mips_restore_reg);
+      /* Get the function name the same way that toplev.c does before calling
+        assemble_start_function.  This is needed so that the name used here
+        exactly matches the name used in ASM_DECLARE_FUNCTION_NAME.  */
+      fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
 
-      /* Deallocate the final bit of the frame.  */
-      if (step2 > 0)
-       emit_insn (gen_add3_insn (stack_pointer_rtx,
-                                 stack_pointer_rtx,
-                                 GEN_INT (step2)));
+      if (!flag_inhibit_size_directive)
+       {
+         fputs ("\t.ent\t", file);
+         assemble_name (file, fnname);
+         fputs ("\n", file);
+       }
+
+      assemble_name (file, fnname);
+      fputs (":\n", file);
     }
 
-  /* Add in the __builtin_eh_return stack adjustment.  We need to
-     use a temporary in mips16 code.  */
-  if (current_function_calls_eh_return)
+  /* Stop mips_file_end from treating this function as external.  */
+  if (TARGET_IRIX && mips_abi == ABI_32)
+    TREE_ASM_WRITTEN (DECL_NAME (cfun->decl)) = 1;
+
+  /* Output MIPS-specific frame information.  */
+  if (!flag_inhibit_size_directive)
     {
-      if (TARGET_MIPS16)
-       {
-         mips_emit_move (MIPS_EPILOGUE_TEMP (Pmode), stack_pointer_rtx);
-         emit_insn (gen_add3_insn (MIPS_EPILOGUE_TEMP (Pmode),
-                                   MIPS_EPILOGUE_TEMP (Pmode),
-                                   EH_RETURN_STACKADJ_RTX));
-         mips_emit_move (stack_pointer_rtx, MIPS_EPILOGUE_TEMP (Pmode));
-       }
-      else
-       emit_insn (gen_add3_insn (stack_pointer_rtx,
-                                 stack_pointer_rtx,
-                                 EH_RETURN_STACKADJ_RTX));
+      const struct mips_frame_info *frame;
+
+      frame = &cfun->machine->frame;
+
+      /* .frame FRAMEREG, FRAMESIZE, RETREG.  */
+      fprintf (file,
+              "\t.frame\t%s," HOST_WIDE_INT_PRINT_DEC ",%s\t\t"
+              "# vars= " HOST_WIDE_INT_PRINT_DEC
+              ", regs= %d/%d"
+              ", args= " HOST_WIDE_INT_PRINT_DEC
+              ", gp= " HOST_WIDE_INT_PRINT_DEC "\n",
+              reg_names[frame_pointer_needed
+                        ? HARD_FRAME_POINTER_REGNUM
+                        : STACK_POINTER_REGNUM],
+              (frame_pointer_needed
+               ? frame->total_size - frame->hard_frame_pointer_offset
+               : frame->total_size),
+              reg_names[GP_REG_FIRST + 31],
+              frame->var_size,
+              frame->num_gp, frame->num_fp,
+              frame->args_size,
+              frame->cprestore_size);
+
+      /* .mask MASK, OFFSET.  */
+      fprintf (file, "\t.mask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
+              frame->mask, frame->gp_save_offset);
+
+      /* .fmask MASK, OFFSET.  */
+      fprintf (file, "\t.fmask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
+              frame->fmask, frame->fp_save_offset);
     }
 
-  if (!sibcall_p)
+  /* Handle the initialization of $gp for SVR4 PIC, if applicable.
+     Also emit the ".set noreorder; .set nomacro" sequence for functions
+     that need it.  */
+  if (mips_current_loadgp_style () == LOADGP_OLDABI)
     {
-      /* When generating MIPS16 code, the normal mips_for_each_saved_reg
-        path will restore the return address into $7 rather than $31.  */
-      if (TARGET_MIPS16
-         && !GENERATE_MIPS16E_SAVE_RESTORE
-         && (cfun->machine->frame.mask & RA_MASK) != 0)
-       emit_jump_insn (gen_return_internal (gen_rtx_REG (Pmode,
-                                                         GP_REG_FIRST + 7)));
+      /* .cpload must be in a .set noreorder but not a .set nomacro block.  */
+      if (!cfun->machine->all_noreorder_p)
+       output_asm_insn ("%(.cpload\t%^%)", 0);
       else
-       emit_jump_insn (gen_return_internal (gen_rtx_REG (Pmode,
-                                                         GP_REG_FIRST + 31)));
+       output_asm_insn ("%(.cpload\t%^\n\t%<", 0);
     }
+  else if (cfun->machine->all_noreorder_p)
+    output_asm_insn ("%(%<", 0);
+
+  /* Tell the assembler which register we're using as the global
+     pointer.  This is needed for thunks, since they can use either
+     explicit relocs or assembler macros.  */
+  mips_output_cplocal ();
 }
-\f
-/* Return nonzero if this function is known to have a null epilogue.
-   This allows the optimizer to omit jumps to jumps if no stack
-   was created.  */
 
-int
-mips_can_use_return_insn (void)
-{
-  if (! reload_completed)
-    return 0;
+/* Implement TARGET_OUTPUT_FUNCTION_EPILOGUE.  */
 
-  if (df_regs_ever_live_p (31) || current_function_profile)
-    return 0;
+static void
+mips_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
+                              HOST_WIDE_INT size ATTRIBUTE_UNUSED)
+{
+  /* Reinstate the normal $gp.  */
+  SET_REGNO (pic_offset_table_rtx, GLOBAL_POINTER_REGNUM);
+  mips_output_cplocal ();
 
-  /* In mips16 mode, a function that returns a floating point value
-     needs to arrange to copy the return value into the floating point
-     registers.  */
-  if (mips16_cfun_returns_in_fpr_p ())
-    return 0;
+  if (cfun->machine->all_noreorder_p)
+    {
+      /* Avoid using %>%) since it adds excess whitespace.  */
+      output_asm_insn (".set\tmacro", 0);
+      output_asm_insn (".set\treorder", 0);
+      set_noreorder = set_nomacro = 0;
+    }
 
-  if (cfun->machine->frame.initialized)
-    return cfun->machine->frame.total_size == 0;
+  if (!FUNCTION_NAME_ALREADY_DECLARED && !flag_inhibit_size_directive)
+    {
+      const char *fnname;
 
-  return compute_frame_size (get_frame_size ()) == 0;
+      /* Get the function name the same way that toplev.c does before calling
+        assemble_start_function.  This is needed so that the name used here
+        exactly matches the name used in ASM_DECLARE_FUNCTION_NAME.  */
+      fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
+      fputs ("\t.end\t", file);
+      assemble_name (file, fnname);
+      fputs ("\n", file);
+    }
 }
 \f
-/* Implement TARGET_ASM_OUTPUT_MI_THUNK.  Generate rtl rather than asm text
-   in order to avoid duplicating too much logic from elsewhere.  */
+/* Save register REG to MEM.  Make the instruction frame-related.  */
 
 static void
-mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
-                     HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
-                     tree function)
+mips_save_reg (rtx reg, rtx mem)
 {
-  rtx this, temp1, temp2, insn, fnaddr;
-  bool use_sibcall_p;
-
-  /* Pretend to be a post-reload pass while generating rtl.  */
-  reload_completed = 1;
+  if (GET_MODE (reg) == DFmode && !TARGET_FLOAT64)
+    {
+      rtx x1, x2;
 
-  /* Mark the end of the (empty) prologue.  */
-  emit_note (NOTE_INSN_PROLOGUE_END);
+      if (mips_split_64bit_move_p (mem, reg))
+       mips_split_doubleword_move (mem, reg);
+      else
+       mips_emit_move (mem, reg);
 
-  /* Determine if we can use a sibcall to call FUNCTION directly.  */
-  fnaddr = XEXP (DECL_RTL (function), 0);
-  use_sibcall_p = (mips_function_ok_for_sibcall (function, NULL)
-                  && const_call_insn_operand (fnaddr, Pmode));
+      x1 = mips_frame_set (mips_subword (mem, false),
+                          mips_subword (reg, false));
+      x2 = mips_frame_set (mips_subword (mem, true),
+                          mips_subword (reg, true));
+      mips_set_frame_expr (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, x1, x2)));
+    }
+  else
+    {
+      if (TARGET_MIPS16
+         && REGNO (reg) != GP_REG_FIRST + 31
+         && !M16_REG_P (REGNO (reg)))
+       {
+         /* Save a non-MIPS16 register by moving it through a temporary.
+            We don't need to do this for $31 since there's a special
+            instruction for it.  */
+         mips_emit_move (MIPS_PROLOGUE_TEMP (GET_MODE (reg)), reg);
+         mips_emit_move (mem, MIPS_PROLOGUE_TEMP (GET_MODE (reg)));
+       }
+      else
+       mips_emit_move (mem, reg);
 
-  /* Determine if we need to load FNADDR from the GOT.  */
-  if (!use_sibcall_p)
-    switch (mips_classify_symbol (fnaddr, SYMBOL_CONTEXT_LEA))
-      {
-      case SYMBOL_GOT_PAGE_OFST:
-      case SYMBOL_GOT_DISP:
-       /* Pick a global pointer.  Use a call-clobbered register if
-          TARGET_CALL_SAVED_GP.  */
-       cfun->machine->global_pointer =
-         TARGET_CALL_SAVED_GP ? 15 : GLOBAL_POINTER_REGNUM;
-       SET_REGNO (pic_offset_table_rtx, cfun->machine->global_pointer);
+      mips_set_frame_expr (mips_frame_set (mem, reg));
+    }
+}
 
-       /* Set up the global pointer for n32 or n64 abicalls.  */
-       mips_emit_loadgp ();
-       break;
+/* The __gnu_local_gp symbol.  */
 
-      default:
-       break;
-      }
+static GTY(()) rtx mips_gnu_local_gp;
 
-  /* We need two temporary registers in some cases.  */
-  temp1 = gen_rtx_REG (Pmode, 2);
-  temp2 = gen_rtx_REG (Pmode, 3);
+/* If we're generating n32 or n64 abicalls, emit instructions
+   to set up the global pointer.  */
 
-  /* Find out which register contains the "this" pointer.  */
-  if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
-    this = gen_rtx_REG (Pmode, GP_ARG_FIRST + 1);
-  else
-    this = gen_rtx_REG (Pmode, GP_ARG_FIRST);
+static void
+mips_emit_loadgp (void)
+{
+  rtx addr, offset, incoming_address, base, index, pic_reg;
 
-  /* Add DELTA to THIS.  */
-  if (delta != 0)
+  pic_reg = pic_offset_table_rtx;
+  switch (mips_current_loadgp_style ())
     {
-      rtx offset = GEN_INT (delta);
-      if (!SMALL_OPERAND (delta))
+    case LOADGP_ABSOLUTE:
+      if (mips_gnu_local_gp == NULL)
        {
-         mips_emit_move (temp1, offset);
-         offset = temp1;
+         mips_gnu_local_gp = gen_rtx_SYMBOL_REF (Pmode, "__gnu_local_gp");
+         SYMBOL_REF_FLAGS (mips_gnu_local_gp) |= SYMBOL_FLAG_LOCAL;
        }
-      emit_insn (gen_add3_insn (this, this, offset));
-    }
-
-  /* If needed, add *(*THIS + VCALL_OFFSET) to THIS.  */
-  if (vcall_offset != 0)
-    {
-      rtx addr;
+      emit_insn (Pmode == SImode
+                ? gen_loadgp_absolute_si (pic_reg, mips_gnu_local_gp)
+                : gen_loadgp_absolute_di (pic_reg, mips_gnu_local_gp));
+      break;
 
-      /* Set TEMP1 to *THIS.  */
-      mips_emit_move (temp1, gen_rtx_MEM (Pmode, this));
+    case LOADGP_NEWABI:
+      addr = XEXP (DECL_RTL (current_function_decl), 0);
+      offset = mips_unspec_address (addr, SYMBOL_GOTOFF_LOADGP);
+      incoming_address = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
+      emit_insn (Pmode == SImode
+                ? gen_loadgp_newabi_si (pic_reg, offset, incoming_address)
+                : gen_loadgp_newabi_di (pic_reg, offset, incoming_address));
+      if (!TARGET_EXPLICIT_RELOCS)
+       emit_insn (gen_loadgp_blockage ());
+      break;
 
-      /* Set ADDR to a legitimate address for *THIS + VCALL_OFFSET.  */
-      addr = mips_add_offset (temp2, temp1, vcall_offset);
+    case LOADGP_RTP:
+      base = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (VXWORKS_GOTT_BASE));
+      index = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (VXWORKS_GOTT_INDEX));
+      emit_insn (Pmode == SImode
+                ? gen_loadgp_rtp_si (pic_reg, base, index)
+                : gen_loadgp_rtp_di (pic_reg, base, index));
+      if (!TARGET_EXPLICIT_RELOCS)
+       emit_insn (gen_loadgp_blockage ());
+      break;
 
-      /* Load the offset and add it to THIS.  */
-      mips_emit_move (temp1, gen_rtx_MEM (Pmode, addr));
-      emit_insn (gen_add3_insn (this, this, temp1));
+    default:
+      break;
     }
+}
 
-  /* Jump to the target function.  Use a sibcall if direct jumps are
-     allowed, otherwise load the address into a register first.  */
-  if (use_sibcall_p)
-    {
-      insn = emit_call_insn (gen_sibcall_internal (fnaddr, const0_rtx));
-      SIBLING_CALL_P (insn) = 1;
-    }
-  else
-    {
-      /* This is messy.  gas treats "la $25,foo" as part of a call
-        sequence and may allow a global "foo" to be lazily bound.
-        The general move patterns therefore reject this combination.
+/* Expand the "prologue" pattern.  */
 
-        In this context, lazy binding would actually be OK
-        for TARGET_CALL_CLOBBERED_GP, but it's still wrong for
-        TARGET_CALL_SAVED_GP; see mips_load_call_address.
-        We must therefore load the address via a temporary
-        register if mips_dangerous_for_la25_p.
+void
+mips_expand_prologue (void)
+{
+  const struct mips_frame_info *frame;
+  HOST_WIDE_INT size;
+  unsigned int nargs;
+  rtx insn;
 
-        If we jump to the temporary register rather than $25, the assembler
-        can use the move insn to fill the jump's delay slot.  */
-      if (TARGET_USE_PIC_FN_ADDR_REG
-         && !mips_dangerous_for_la25_p (fnaddr))
-       temp1 = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
-      mips_load_call_address (temp1, fnaddr, true);
+  if (cfun->machine->global_pointer > 0)
+    SET_REGNO (pic_offset_table_rtx, cfun->machine->global_pointer);
 
-      if (TARGET_USE_PIC_FN_ADDR_REG
-         && REGNO (temp1) != PIC_FUNCTION_ADDR_REGNUM)
-       mips_emit_move (gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM), temp1);
-      emit_jump_insn (gen_indirect_jump (temp1));
-    }
+  frame = &cfun->machine->frame;
+  size = frame->total_size;
 
-  /* Run just enough of rest_of_compilation.  This sequence was
-     "borrowed" from alpha.c.  */
-  insn = get_insns ();
-  insn_locators_alloc ();
-  split_all_insns_noflow ();
-  mips16_lay_out_constants ();
-  shorten_branches (insn);
-  final_start_function (insn, file, 1);
-  final (insn, file, 1);
-  final_end_function ();
+  /* Save the registers.  Allocate up to MIPS_MAX_FIRST_STACK_STEP
+     bytes beforehand; this is enough to cover the register save area
+     without going out of range.  */
+  if ((frame->mask | frame->fmask) != 0)
+    {
+      HOST_WIDE_INT step1;
 
-  /* Clean up the vars set above.  Note that final_end_function resets
-     the global pointer for us.  */
-  reload_completed = 0;
-}
-\f
-/* Implement TARGET_SELECT_RTX_SECTION.  */
+      step1 = MIN (size, MIPS_MAX_FIRST_STACK_STEP);
+      if (GENERATE_MIPS16E_SAVE_RESTORE)
+       {
+         HOST_WIDE_INT offset;
+         unsigned int mask, regno;
 
-static section *
-mips_select_rtx_section (enum machine_mode mode, rtx x,
-                        unsigned HOST_WIDE_INT align)
-{
-  /* ??? Consider using mergeable small data sections.  */
-  if (mips_rtx_constant_in_small_data_p (mode))
-    return get_named_section (NULL, ".sdata", 0);
+         /* Try to merge argument stores into the save instruction.  */
+         nargs = mips16e_collect_argument_saves ();
 
-  return default_elf_select_rtx_section (mode, x, align);
-}
+         /* Build the save instruction.  */
+         mask = frame->mask;
+         insn = mips16e_build_save_restore (false, &mask, &offset,
+                                            nargs, step1);
+         RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
+         size -= step1;
 
-/* Implement TARGET_ASM_FUNCTION_RODATA_SECTION.
+         /* Check if we need to save other registers.  */
+         for (regno = GP_REG_FIRST; regno < GP_REG_LAST; regno++)
+           if (BITSET_P (mask, regno - GP_REG_FIRST))
+             {
+               offset -= UNITS_PER_WORD;
+               mips_save_restore_reg (word_mode, regno,
+                                      offset, mips_save_reg);
+             }
+       }
+      else
+       {
+         insn = gen_add3_insn (stack_pointer_rtx,
+                               stack_pointer_rtx,
+                               GEN_INT (-step1));
+         RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
+         size -= step1;
+         mips_for_each_saved_reg (size, mips_save_reg);
+       }
+    }
 
-   The complication here is that, with the combination TARGET_ABICALLS
-   && !TARGET_GPWORD, jump tables will use absolute addresses, and should
-   therefore not be included in the read-only part of a DSO.  Handle such
-   cases by selecting a normal data section instead of a read-only one.
-   The logic apes that in default_function_rodata_section.  */
+  /* Allocate the rest of the frame.  */
+  if (size > 0)
+    {
+      if (SMALL_OPERAND (-size))
+       RTX_FRAME_RELATED_P (emit_insn (gen_add3_insn (stack_pointer_rtx,
+                                                      stack_pointer_rtx,
+                                                      GEN_INT (-size)))) = 1;
+      else
+       {
+         mips_emit_move (MIPS_PROLOGUE_TEMP (Pmode), GEN_INT (size));
+         if (TARGET_MIPS16)
+           {
+             /* There are no instructions to add or subtract registers
+                from the stack pointer, so use the frame pointer as a
+                temporary.  We should always be using a frame pointer
+                in this case anyway.  */
+             gcc_assert (frame_pointer_needed);
+             mips_emit_move (hard_frame_pointer_rtx, stack_pointer_rtx);
+             emit_insn (gen_sub3_insn (hard_frame_pointer_rtx,
+                                       hard_frame_pointer_rtx,
+                                       MIPS_PROLOGUE_TEMP (Pmode)));
+             mips_emit_move (stack_pointer_rtx, hard_frame_pointer_rtx);
+           }
+         else
+           emit_insn (gen_sub3_insn (stack_pointer_rtx,
+                                     stack_pointer_rtx,
+                                     MIPS_PROLOGUE_TEMP (Pmode)));
 
-static section *
-mips_function_rodata_section (tree decl)
-{
-  if (!TARGET_ABICALLS || TARGET_GPWORD)
-    return default_function_rodata_section (decl);
+         /* Describe the combined effect of the previous instructions.  */
+         mips_set_frame_expr
+           (gen_rtx_SET (VOIDmode, stack_pointer_rtx,
+                         plus_constant (stack_pointer_rtx, -size)));
+       }
+    }
 
-  if (decl && DECL_SECTION_NAME (decl))
+  /* Set up the frame pointer, if we're using one.  */
+  if (frame_pointer_needed)
     {
-      const char *name = TREE_STRING_POINTER (DECL_SECTION_NAME (decl));
-      if (DECL_ONE_ONLY (decl) && strncmp (name, ".gnu.linkonce.t.", 16) == 0)
+      HOST_WIDE_INT offset;
+
+      offset = frame->hard_frame_pointer_offset;
+      if (offset == 0)
        {
-         char *rname = ASTRDUP (name);
-         rname[14] = 'd';
-         return get_section (rname, SECTION_LINKONCE | SECTION_WRITE, decl);
+         insn = mips_emit_move (hard_frame_pointer_rtx, stack_pointer_rtx);
+         RTX_FRAME_RELATED_P (insn) = 1;
        }
-      else if (flag_function_sections && flag_data_sections
-              && strncmp (name, ".text.", 6) == 0)
+      else if (SMALL_OPERAND (offset))
        {
-         char *rname = ASTRDUP (name);
-         memcpy (rname + 1, "data", 4);
-         return get_section (rname, SECTION_WRITE, decl);
+         insn = gen_add3_insn (hard_frame_pointer_rtx,
+                               stack_pointer_rtx, GEN_INT (offset));
+         RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
+       }
+      else
+       {
+         mips_emit_move (MIPS_PROLOGUE_TEMP (Pmode), GEN_INT (offset));
+         mips_emit_move (hard_frame_pointer_rtx, stack_pointer_rtx);
+         emit_insn (gen_add3_insn (hard_frame_pointer_rtx,
+                                   hard_frame_pointer_rtx,
+                                   MIPS_PROLOGUE_TEMP (Pmode)));
+         mips_set_frame_expr
+           (gen_rtx_SET (VOIDmode, hard_frame_pointer_rtx,
+                         plus_constant (stack_pointer_rtx, offset)));
        }
     }
-  return data_section;
-}
 
-/* Implement TARGET_IN_SMALL_DATA_P.  This function controls whether
-   locally-defined objects go in a small data section.  It also controls
-   the setting of the SYMBOL_REF_SMALL_P flag, which in turn helps
-   mips_classify_symbol decide when to use %gp_rel(...)($gp) accesses.  */
+  mips_emit_loadgp ();
 
-static bool
-mips_in_small_data_p (const_tree decl)
-{
-  HOST_WIDE_INT size;
+  /* Initialize the $gp save slot.  */
+  if (frame->cprestore_size > 0)
+    emit_insn (gen_cprestore (GEN_INT (current_function_outgoing_args_size)));
 
-  if (TREE_CODE (decl) == STRING_CST || TREE_CODE (decl) == FUNCTION_DECL)
-    return false;
+  /* If we are profiling, make sure no instructions are scheduled before
+     the call to mcount.  */
+  if (current_function_profile)
+    emit_insn (gen_blockage ());
+}
+\f
+/* Emit instructions to restore register REG from slot MEM.  */
 
-  /* We don't yet generate small-data references for -mabicalls or
-     VxWorks RTP code.  See the related -G handling in override_options.  */
-  if (TARGET_ABICALLS || TARGET_VXWORKS_RTP)
-    return false;
+static void
+mips_restore_reg (rtx reg, rtx mem)
+{
+  /* There's no MIPS16 instruction to load $31 directly.  Load into
+     $7 instead and adjust the return insn appropriately.  */
+  if (TARGET_MIPS16 && REGNO (reg) == GP_REG_FIRST + 31)
+    reg = gen_rtx_REG (GET_MODE (reg), GP_REG_FIRST + 7);
 
-  if (TREE_CODE (decl) == VAR_DECL && DECL_SECTION_NAME (decl) != 0)
+  if (TARGET_MIPS16 && !M16_REG_P (REGNO (reg)))
     {
-      const char *name;
-
-      /* Reject anything that isn't in a known small-data section.  */
-      name = TREE_STRING_POINTER (DECL_SECTION_NAME (decl));
-      if (strcmp (name, ".sdata") != 0 && strcmp (name, ".sbss") != 0)
-       return false;
-
-      /* If a symbol is defined externally, the assembler will use the
-        usual -G rules when deciding how to implement macros.  */
-      if (mips_lo_relocs[SYMBOL_GP_RELATIVE] || !DECL_EXTERNAL (decl))
-       return true;
+      /* Can't restore directly; move through a temporary.  */
+      mips_emit_move (MIPS_EPILOGUE_TEMP (GET_MODE (reg)), mem);
+      mips_emit_move (reg, MIPS_EPILOGUE_TEMP (GET_MODE (reg)));
     }
-  else if (TARGET_EMBEDDED_DATA)
-    {
-      /* Don't put constants into the small data section: we want them
-        to be in ROM rather than RAM.  */
-      if (TREE_CODE (decl) != VAR_DECL)
-       return false;
+  else
+    mips_emit_move (reg, mem);
+}
 
-      if (TREE_READONLY (decl)
-         && !TREE_SIDE_EFFECTS (decl)
-         && (!DECL_INITIAL (decl) || TREE_CONSTANT (DECL_INITIAL (decl))))
-       return false;
-    }
+/* Expand an "epilogue" or "sibcall_epilogue" pattern; SIBCALL_P
+   says which.  */
 
-  /* Enforce -mlocal-sdata.  */
-  if (!TARGET_LOCAL_SDATA && !TREE_PUBLIC (decl))
-    return false;
+void
+mips_expand_epilogue (bool sibcall_p)
+{
+  const struct mips_frame_info *frame;
+  HOST_WIDE_INT step1, step2;
+  rtx base, target;
 
-  /* Enforce -mextern-sdata.  */
-  if (!TARGET_EXTERN_SDATA && DECL_P (decl))
+  if (!sibcall_p && mips_can_use_return_insn ())
     {
-      if (DECL_EXTERNAL (decl))
-       return false;
-      if (DECL_COMMON (decl) && DECL_INITIAL (decl) == NULL)
-       return false;
+      emit_jump_insn (gen_return ());
+      return;
     }
 
-  size = int_size_in_bytes (TREE_TYPE (decl));
-  return (size > 0 && size <= mips_section_threshold);
-}
+  /* In MIPS16 mode, if the return value should go into a floating-point
+     register, we need to call a helper routine to copy it over.  */
+  if (mips16_cfun_returns_in_fpr_p ())
+    mips16_copy_fpr_return_value ();
 
-/* Implement TARGET_USE_ANCHORS_FOR_SYMBOL_P.  We don't want to use
-   anchors for small data: the GP register acts as an anchor in that
-   case.  We also don't want to use them for PC-relative accesses,
-   where the PC acts as an anchor.  */
+  /* Split the frame into two.  STEP1 is the amount of stack we should
+     deallocate before restoring the registers.  STEP2 is the amount we
+     should deallocate afterwards.
 
-static bool
-mips_use_anchors_for_symbol_p (const_rtx symbol)
-{
-  switch (mips_classify_symbol (symbol, SYMBOL_CONTEXT_MEM))
-    {
-    case SYMBOL_PC_RELATIVE:
-    case SYMBOL_GP_RELATIVE:
-      return false;
+     Start off by assuming that no registers need to be restored.  */
+  frame = &cfun->machine->frame;
+  step1 = frame->total_size;
+  step2 = 0;
 
-    default:
-      return default_use_anchors_for_symbol_p (symbol);
+  /* Work out which register holds the frame address.  */
+  if (!frame_pointer_needed)
+    base = stack_pointer_rtx;
+  else
+    {
+      base = hard_frame_pointer_rtx;
+      step1 -= frame->hard_frame_pointer_offset;
     }
-}
-\f
-/* See whether VALTYPE is a record whose fields should be returned in
-   floating-point registers.  If so, return the number of fields and
-   list them in FIELDS (which should have two elements).  Return 0
-   otherwise.
-
-   For n32 & n64, a structure with one or two fields is returned in
-   floating-point registers as long as every field has a floating-point
-   type.  */
-
-static int
-mips_fpr_return_fields (const_tree valtype, tree *fields)
-{
-  tree field;
-  int i;
 
-  if (!TARGET_NEWABI)
-    return 0;
-
-  if (TREE_CODE (valtype) != RECORD_TYPE)
-    return 0;
+  /* If we need to restore registers, deallocate as much stack as
+     possible in the second step without going out of range.  */
+  if ((frame->mask | frame->fmask) != 0)
+    {
+      step2 = MIN (step1, MIPS_MAX_FIRST_STACK_STEP);
+      step1 -= step2;
+    }
 
-  i = 0;
-  for (field = TYPE_FIELDS (valtype); field != 0; field = TREE_CHAIN (field))
+  /* Set TARGET to BASE + STEP1.  */
+  target = base;
+  if (step1 > 0)
     {
-      if (TREE_CODE (field) != FIELD_DECL)
-       continue;
+      rtx adjust;
 
-      if (TREE_CODE (TREE_TYPE (field)) != REAL_TYPE)
-       return 0;
+      /* Get an rtx for STEP1 that we can add to BASE.  */
+      adjust = GEN_INT (step1);
+      if (!SMALL_OPERAND (step1))
+       {
+         mips_emit_move (MIPS_EPILOGUE_TEMP (Pmode), adjust);
+         adjust = MIPS_EPILOGUE_TEMP (Pmode);
+       }
 
-      if (i == 2)
-       return 0;
+      /* Normal mode code can copy the result straight into $sp.  */
+      if (!TARGET_MIPS16)
+       target = stack_pointer_rtx;
 
-      fields[i++] = field;
+      emit_insn (gen_add3_insn (target, base, adjust));
     }
-  return i;
-}
 
+  /* Copy TARGET into the stack pointer.  */
+  if (target != stack_pointer_rtx)
+    mips_emit_move (stack_pointer_rtx, target);
 
-/* Implement TARGET_RETURN_IN_MSB.  For n32 & n64, we should return
-   a value in the most significant part of $2/$3 if:
+  /* If we're using addressing macros, $gp is implicitly used by all
+     SYMBOL_REFs.  We must emit a blockage insn before restoring $gp
+     from the stack.  */
+  if (TARGET_CALL_SAVED_GP && !TARGET_EXPLICIT_RELOCS)
+    emit_insn (gen_blockage ());
 
-      - the target is big-endian;
+  if (GENERATE_MIPS16E_SAVE_RESTORE && frame->mask != 0)
+    {
+      unsigned int regno, mask;
+      HOST_WIDE_INT offset;
+      rtx restore;
 
-      - the value has a structure or union type (we generalize this to
-       cover aggregates from other languages too); and
+      /* Generate the restore instruction.  */
+      mask = frame->mask;
+      restore = mips16e_build_save_restore (true, &mask, &offset, 0, step2);
 
-      - the structure is not returned in floating-point registers.  */
+      /* Restore any other registers manually.  */
+      for (regno = GP_REG_FIRST; regno < GP_REG_LAST; regno++)
+       if (BITSET_P (mask, regno - GP_REG_FIRST))
+         {
+           offset -= UNITS_PER_WORD;
+           mips_save_restore_reg (word_mode, regno, offset, mips_restore_reg);
+         }
 
-static bool
-mips_return_in_msb (const_tree valtype)
-{
-  tree fields[2];
+      /* Restore the remaining registers and deallocate the final bit
+        of the frame.  */
+      emit_insn (restore);
+    }
+  else
+    {
+      /* Restore the registers.  */
+      mips_for_each_saved_reg (frame->total_size - step2, mips_restore_reg);
 
-  return (TARGET_NEWABI
-         && TARGET_BIG_ENDIAN
-         && AGGREGATE_TYPE_P (valtype)
-         && mips_fpr_return_fields (valtype, fields) == 0);
-}
+      /* Deallocate the final bit of the frame.  */
+      if (step2 > 0)
+       emit_insn (gen_add3_insn (stack_pointer_rtx,
+                                 stack_pointer_rtx,
+                                 GEN_INT (step2)));
+    }
 
+  /* Add in the __builtin_eh_return stack adjustment.  We need to
+     use a temporary in MIPS16 code.  */
+  if (current_function_calls_eh_return)
+    {
+      if (TARGET_MIPS16)
+       {
+         mips_emit_move (MIPS_EPILOGUE_TEMP (Pmode), stack_pointer_rtx);
+         emit_insn (gen_add3_insn (MIPS_EPILOGUE_TEMP (Pmode),
+                                   MIPS_EPILOGUE_TEMP (Pmode),
+                                   EH_RETURN_STACKADJ_RTX));
+         mips_emit_move (stack_pointer_rtx, MIPS_EPILOGUE_TEMP (Pmode));
+       }
+      else
+       emit_insn (gen_add3_insn (stack_pointer_rtx,
+                                 stack_pointer_rtx,
+                                 EH_RETURN_STACKADJ_RTX));
+    }
 
-/* Return a composite value in a pair of floating-point registers.
-   MODE1 and OFFSET1 are the mode and byte offset for the first value,
-   likewise MODE2 and OFFSET2 for the second.  MODE is the mode of the
-   complete value.
+  if (!sibcall_p)
+    {
+      unsigned int regno;
 
-   For n32 & n64, $f0 always holds the first value and $f2 the second.
-   Otherwise the values are packed together as closely as possible.  */
+      /* When generating MIPS16 code, the normal mips_for_each_saved_reg
+        path will restore the return address into $7 rather than $31.  */
+      if (TARGET_MIPS16
+         && !GENERATE_MIPS16E_SAVE_RESTORE
+         && BITSET_P (frame->mask, 31))
+       regno = GP_REG_FIRST + 7;
+      else
+       regno = GP_REG_FIRST + 31;
+      emit_jump_insn (gen_return_internal (gen_rtx_REG (Pmode, regno)));
+    }
+}
+\f
+/* Return nonzero if this function is known to have a null epilogue.
+   This allows the optimizer to omit jumps to jumps if no stack
+   was created.  */
 
-static rtx
-mips_return_fpr_pair (enum machine_mode mode,
-                     enum machine_mode mode1, HOST_WIDE_INT offset1,
-                     enum machine_mode mode2, HOST_WIDE_INT offset2)
+bool
+mips_can_use_return_insn (void)
 {
-  int inc;
+  if (!reload_completed)
+    return false;
 
-  inc = (TARGET_NEWABI ? 2 : MAX_FPRS_PER_FMT);
-  return gen_rtx_PARALLEL
-    (mode,
-     gen_rtvec (2,
-               gen_rtx_EXPR_LIST (VOIDmode,
-                                  gen_rtx_REG (mode1, FP_RETURN),
-                                  GEN_INT (offset1)),
-               gen_rtx_EXPR_LIST (VOIDmode,
-                                  gen_rtx_REG (mode2, FP_RETURN + inc),
-                                  GEN_INT (offset2))));
+  if (current_function_profile)
+    return false;
+
+  /* In MIPS16 mode, a function that returns a floating-point value
+     needs to arrange to copy the return value into the floating-point
+     registers.  */
+  if (mips16_cfun_returns_in_fpr_p ())
+    return false;
 
+  return cfun->machine->frame.total_size == 0;
 }
+\f
+/* Return true if register REGNO can store a value of mode MODE.
+   The result of this function is cached in mips_hard_regno_mode_ok.  */
 
+static bool
+mips_hard_regno_mode_ok_p (unsigned int regno, enum machine_mode mode)
+{
+  unsigned int size;
+  enum mode_class class;
 
-/* Implement FUNCTION_VALUE and LIBCALL_VALUE.  For normal calls,
-   VALTYPE is the return type and MODE is VOIDmode.  For libcalls,
-   VALTYPE is null and MODE is the mode of the return value.  */
+  if (mode == CCV2mode)
+    return (ISA_HAS_8CC
+           && ST_REG_P (regno)
+           && (regno - ST_REG_FIRST) % 2 == 0);
 
-rtx
-mips_function_value (const_tree valtype, const_tree func ATTRIBUTE_UNUSED,
-                    enum machine_mode mode)
-{
-  if (valtype)
+  if (mode == CCV4mode)
+    return (ISA_HAS_8CC
+           && ST_REG_P (regno)
+           && (regno - ST_REG_FIRST) % 4 == 0);
+
+  if (mode == CCmode)
     {
-      tree fields[2];
-      int unsignedp;
+      if (!ISA_HAS_8CC)
+       return regno == FPSW_REGNUM;
 
-      mode = TYPE_MODE (valtype);
-      unsignedp = TYPE_UNSIGNED (valtype);
+      return (ST_REG_P (regno)
+             || GP_REG_P (regno)
+             || FP_REG_P (regno));
+    }
 
-      /* Since we define TARGET_PROMOTE_FUNCTION_RETURN that returns
-        true, we must promote the mode just as PROMOTE_MODE does.  */
-      mode = promote_mode (valtype, mode, &unsignedp, 1);
+  size = GET_MODE_SIZE (mode);
+  class = GET_MODE_CLASS (mode);
 
-      /* Handle structures whose fields are returned in $f0/$f2.  */
-      switch (mips_fpr_return_fields (valtype, fields))
-       {
-       case 1:
-         return gen_rtx_REG (mode, FP_RETURN);
+  if (GP_REG_P (regno))
+    return ((regno - GP_REG_FIRST) & 1) == 0 || size <= UNITS_PER_WORD;
 
-       case 2:
-         return mips_return_fpr_pair (mode,
-                                      TYPE_MODE (TREE_TYPE (fields[0])),
-                                      int_byte_position (fields[0]),
-                                      TYPE_MODE (TREE_TYPE (fields[1])),
-                                      int_byte_position (fields[1]));
-       }
+  if (FP_REG_P (regno)
+      && (((regno - FP_REG_FIRST) % MAX_FPRS_PER_FMT) == 0
+         || (MIN_FPRS_PER_FMT == 1 && size <= UNITS_PER_FPREG)))
+    {
+      /* Allow TFmode for CCmode reloads.  */
+      if (mode == TFmode && ISA_HAS_8CC)
+       return true;
 
-      /* If a value is passed in the most significant part of a register, see
-        whether we have to round the mode up to a whole number of words.  */
-      if (mips_return_in_msb (valtype))
-       {
-         HOST_WIDE_INT size = int_size_in_bytes (valtype);
-         if (size % UNITS_PER_WORD != 0)
-           {
-             size += UNITS_PER_WORD - size % UNITS_PER_WORD;
-             mode = mode_for_size (size * BITS_PER_UNIT, MODE_INT, 0);
-           }
-       }
+      if (class == MODE_FLOAT
+         || class == MODE_COMPLEX_FLOAT
+         || class == MODE_VECTOR_FLOAT)
+       return size <= UNITS_PER_FPVALUE;
 
-      /* For EABI, the class of return register depends entirely on MODE.
-        For example, "struct { some_type x; }" and "union { some_type x; }"
-        are returned in the same way as a bare "some_type" would be.
-        Other ABIs only use FPRs for scalar, complex or vector types.  */
-      if (mips_abi != ABI_EABI && !FLOAT_TYPE_P (valtype))
-       return gen_rtx_REG (mode, GP_RETURN);
+      /* Allow integer modes that fit into a single register.  We need
+        to put integers into FPRs when using instructions like CVT
+        and TRUNC.  There's no point allowing sizes smaller than a word,
+        because the FPU has no appropriate load/store instructions.  */
+      if (class == MODE_INT)
+       return size >= MIN_UNITS_PER_WORD && size <= UNITS_PER_FPREG;
     }
 
-  if (!TARGET_MIPS16)
+  if (ACC_REG_P (regno)
+      && (INTEGRAL_MODE_P (mode) || ALL_FIXED_POINT_MODE_P (mode)))
     {
-      /* Handle long doubles for n32 & n64.  */
-      if (mode == TFmode)
-       return mips_return_fpr_pair (mode,
-                                    DImode, 0,
-                                    DImode, GET_MODE_SIZE (mode) / 2);
+      if (size <= UNITS_PER_WORD)
+       return true;
 
-      if (mips_return_mode_in_fpr_p (mode))
-       {
-         if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
-           return mips_return_fpr_pair (mode,
-                                        GET_MODE_INNER (mode), 0,
-                                        GET_MODE_INNER (mode),
-                                        GET_MODE_SIZE (mode) / 2);
-         else
-           return gen_rtx_REG (mode, FP_RETURN);
-       }
+      if (size <= UNITS_PER_WORD * 2)
+       return (DSP_ACC_REG_P (regno)
+               ? ((regno - DSP_ACC_REG_FIRST) & 1) == 0
+               : regno == MD_REG_FIRST);
     }
 
-  return gen_rtx_REG (mode, GP_RETURN);
+  if (ALL_COP_REG_P (regno))
+    return class == MODE_INT && size <= UNITS_PER_WORD;
+
+  if (regno == GOT_VERSION_REGNUM)
+    return mode == SImode;
+
+  return false;
 }
 
-/* Return nonzero when an argument must be passed by reference.  */
+/* Implement HARD_REGNO_NREGS.  */
 
-static bool
-mips_pass_by_reference (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
-                       enum machine_mode mode, const_tree type,
-                       bool named ATTRIBUTE_UNUSED)
+unsigned int
+mips_hard_regno_nregs (int regno, enum machine_mode mode)
 {
-  if (mips_abi == ABI_EABI)
-    {
-      int size;
+  if (ST_REG_P (regno))
+    /* The size of FP status registers is always 4, because they only hold
+       CCmode values, and CCmode is always considered to be 4 bytes wide.  */
+    return (GET_MODE_SIZE (mode) + 3) / 4;
 
-      /* ??? How should SCmode be handled?  */
-      if (mode == DImode || mode == DFmode
-         || mode == DQmode || mode == UDQmode
-         || mode == DAmode || mode == UDAmode)
-       return 0;
+  if (FP_REG_P (regno))
+    return (GET_MODE_SIZE (mode) + UNITS_PER_FPREG - 1) / UNITS_PER_FPREG;
 
-      size = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode);
-      return size == -1 || size > UNITS_PER_WORD;
+  /* All other registers are word-sized.  */
+  return (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
+}
+
+/* Implement CLASS_MAX_NREGS, taking the maximum of the cases
+   in mips_hard_regno_nregs.  */
+
+int
+mips_class_max_nregs (enum reg_class class, enum machine_mode mode)
+{
+  int size;
+  HARD_REG_SET left;
+
+  size = 0x8000;
+  COPY_HARD_REG_SET (left, reg_class_contents[(int) class]);
+  if (hard_reg_set_intersect_p (left, reg_class_contents[(int) ST_REGS]))
+    {
+      size = MIN (size, 4);
+      AND_COMPL_HARD_REG_SET (left, reg_class_contents[(int) ST_REGS]);
     }
-  else
+  if (hard_reg_set_intersect_p (left, reg_class_contents[(int) FP_REGS]))
     {
-      /* If we have a variable-sized parameter, we have no choice.  */
-      return targetm.calls.must_pass_in_stack (mode, type);
+      size = MIN (size, UNITS_PER_FPREG);
+      AND_COMPL_HARD_REG_SET (left, reg_class_contents[(int) FP_REGS]);
     }
+  if (!hard_reg_set_empty_p (left))
+    size = MIN (size, UNITS_PER_WORD);
+  return (GET_MODE_SIZE (mode) + size - 1) / size;
 }
 
-static bool
-mips_callee_copies (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
-                   enum machine_mode mode ATTRIBUTE_UNUSED,
-                   const_tree type ATTRIBUTE_UNUSED, bool named)
+/* Implement CANNOT_CHANGE_MODE_CLASS.  */
+
+bool
+mips_cannot_change_mode_class (enum machine_mode from ATTRIBUTE_UNUSED,
+                              enum machine_mode to ATTRIBUTE_UNUSED,
+                              enum reg_class class)
 {
-  return mips_abi == ABI_EABI && named;
+  /* There are several problems with changing the modes of values
+     in floating-point registers:
+
+     - When a multi-word value is stored in paired floating-point
+       registers, the first register always holds the low word.
+       We therefore can't allow FPRs to change between single-word
+       and multi-word modes on big-endian targets.
+
+     - GCC assumes that each word of a multiword register can be accessed
+       individually using SUBREGs.  This is not true for floating-point
+       registers if they are bigger than a word.
+
+     - Loading a 32-bit value into a 64-bit floating-point register
+       will not sign-extend the value, despite what LOAD_EXTEND_OP says.
+       We can't allow FPRs to change from SImode to to a wider mode on
+       64-bit targets.
+
+     - If the FPU has already interpreted a value in one format, we must
+       not ask it to treat the value as having a different format.
+
+     We therefore disallow all mode changes involving FPRs.  */
+  return reg_classes_intersect_p (FP_REGS, class);
 }
 
-/* Return true if registers of class CLASS cannot change from mode FROM
-   to mode TO.  */
+/* Return true if moves in mode MODE can use the FPU's mov.fmt instruction.  */
 
-bool
-mips_cannot_change_mode_class (enum machine_mode from,
-                              enum machine_mode to, enum reg_class class)
+static bool
+mips_mode_ok_for_mov_fmt_p (enum machine_mode mode)
 {
-  if (MIN (GET_MODE_SIZE (from), GET_MODE_SIZE (to)) <= UNITS_PER_WORD
-      && MAX (GET_MODE_SIZE (from), GET_MODE_SIZE (to)) > UNITS_PER_WORD)
+  switch (mode)
     {
-      if (TARGET_BIG_ENDIAN)
-       {
-         /* When a multi-word value is stored in paired floating-point
-            registers, the first register always holds the low word.
-            We therefore can't allow FPRs to change between single-word
-            and multi-word modes.  */
-         if (MAX_FPRS_PER_FMT > 1 && reg_classes_intersect_p (FP_REGS, class))
-           return true;
-       }
-    }
+    case SFmode:
+      return TARGET_HARD_FLOAT;
 
-  /* gcc assumes that each word of a multiword register can be accessed
-     individually using SUBREGs.  This is not true for floating-point
-     registers if they are bigger than a word.  */
-  if (UNITS_PER_FPREG > UNITS_PER_WORD
-      && GET_MODE_SIZE (from) > UNITS_PER_WORD
-      && GET_MODE_SIZE (to) < UNITS_PER_FPREG
-      && reg_classes_intersect_p (FP_REGS, class))
-    return true;
+    case DFmode:
+      return TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT;
 
-  /* Loading a 32-bit value into a 64-bit floating-point register
-     will not sign-extend the value, despite what LOAD_EXTEND_OP says.
-     We can't allow 64-bit float registers to change from SImode to
-     to a wider mode.  */
-  if (TARGET_64BIT
-      && TARGET_FLOAT64
-      && from == SImode
-      && GET_MODE_SIZE (to) >= UNITS_PER_WORD
-      && reg_classes_intersect_p (FP_REGS, class))
-    return true;
+    case V2SFmode:
+      return TARGET_HARD_FLOAT && TARGET_PAIRED_SINGLE_FLOAT;
 
-  return false;
+    default:
+      return false;
+    }
 }
 
-/* Return true if X should not be moved directly into register $25.
-   We need this because many versions of GAS will treat "la $25,foo" as
-   part of a call sequence and so allow a global "foo" to be lazily bound.  */
+/* Implement MODES_TIEABLE_P.  */
 
 bool
-mips_dangerous_for_la25_p (rtx x)
+mips_modes_tieable_p (enum machine_mode mode1, enum machine_mode mode2)
 {
-  return (!TARGET_EXPLICIT_RELOCS
-         && TARGET_USE_GOT
-         && GET_CODE (x) == SYMBOL_REF
-         && mips_global_symbol_p (x));
+  /* FPRs allow no mode punning, so it's not worth tying modes if we'd
+     prefer to put one of them in FPRs.  */
+  return (mode1 == mode2
+         || (!mips_mode_ok_for_mov_fmt_p (mode1)
+             && !mips_mode_ok_for_mov_fmt_p (mode2)));
 }
 
 /* Implement PREFERRED_RELOAD_CLASS.  */
@@ -9391,9 +8874,8 @@ mips_preferred_reload_class (rtx x, enum reg_class class)
   if (mips_dangerous_for_la25_p (x) && reg_class_subset_p (LEA_REGS, class))
     return LEA_REGS;
 
-  if (TARGET_HARD_FLOAT
-      && FLOAT_MODE_P (GET_MODE (x))
-      && reg_class_subset_p (FP_REGS, class))
+  if (reg_class_subset_p (FP_REGS, class)
+      && mips_mode_ok_for_mov_fmt_p (GET_MODE (x)))
     return FP_REGS;
 
   if (reg_class_subset_p (GR_REGS, class))
@@ -9405,157 +8887,171 @@ mips_preferred_reload_class (rtx x, enum reg_class class)
   return class;
 }
 
-/* This function returns the register class required for a secondary
-   register when copying between one of the registers in CLASS, and X,
-   using MODE.  If IN_P is nonzero, the copy is going from X to the
-   register, otherwise the register is the source.  A return value of
-   NO_REGS means that no secondary register is required.  */
+/* Implement REGISTER_MOVE_COST.  */
 
-enum reg_class
-mips_secondary_reload_class (enum reg_class class,
-                            enum machine_mode mode, rtx x, int in_p)
+int
+mips_register_move_cost (enum machine_mode mode,
+                        enum reg_class to, enum reg_class from)
 {
-  enum reg_class gr_regs = TARGET_MIPS16 ? M16_REGS : GR_REGS;
-  int regno = -1;
-  int gp_reg_p;
+  if (TARGET_MIPS16)
+    {
+      /* ??? We cannot move general registers into HI and LO because
+        MIPS16 has no MTHI and MTLO instructions.  Make the cost of
+        moves in the opposite direction just as high, which stops the
+        register allocators from using HI and LO for pseudos.  */
+      if (reg_class_subset_p (from, GENERAL_REGS)
+         && reg_class_subset_p (to, GENERAL_REGS))
+       {
+         if (reg_class_subset_p (from, M16_REGS)
+             || reg_class_subset_p (to, M16_REGS))
+           return 2;
+         /* Two MOVEs.  */
+         return 4;
+       }
+    }
+  else if (reg_class_subset_p (from, GENERAL_REGS))
+    {
+      if (reg_class_subset_p (to, GENERAL_REGS))
+       return 2;
+      if (reg_class_subset_p (to, FP_REGS))
+       return 4;
+      if (reg_class_subset_p (to, ALL_COP_AND_GR_REGS))
+       return 5;
+      if (reg_class_subset_p (to, ACC_REGS))
+       return 6;
+    }
+  else if (reg_class_subset_p (to, GENERAL_REGS))
+    {
+      if (reg_class_subset_p (from, FP_REGS))
+       return 4;
+      if (reg_class_subset_p (from, ST_REGS))
+       /* LUI followed by MOVF.  */
+       return 4;
+      if (reg_class_subset_p (from, ALL_COP_AND_GR_REGS))
+       return 5;
+      if (reg_class_subset_p (from, ACC_REGS))
+       return 6;
+    }
+  else if (reg_class_subset_p (from, FP_REGS))
+    {
+      if (reg_class_subset_p (to, FP_REGS)
+         && mips_mode_ok_for_mov_fmt_p (mode))
+       return 4;
+      if (reg_class_subset_p (to, ST_REGS))
+       /* An expensive sequence.  */
+       return 8;
+    }
 
-  if (REG_P (x)|| GET_CODE (x) == SUBREG)
-    regno = true_regnum (x);
+  return 12;
+}
 
-  gp_reg_p = TARGET_MIPS16 ? M16_REG_P (regno) : GP_REG_P (regno);
+/* Return the register class required for a secondary register when
+   copying between one of the registers in CLASS and value X, which
+   has mode MODE.  X is the source of the move if IN_P, otherwise it
+   is the destination.  Return NO_REGS if no secondary register is
+   needed.  */
+
+enum reg_class
+mips_secondary_reload_class (enum reg_class class,
+                            enum machine_mode mode, rtx x, bool in_p)
+{
+  int regno;
 
+  /* If X is a constant that cannot be loaded into $25, it must be loaded
+     into some other GPR.  No other register class allows a direct move.  */
   if (mips_dangerous_for_la25_p (x))
+    return reg_class_subset_p (class, LEA_REGS) ? NO_REGS : LEA_REGS;
+
+  regno = true_regnum (x);
+  if (TARGET_MIPS16)
     {
-      gr_regs = LEA_REGS;
-      if (TEST_HARD_REG_BIT (reg_class_contents[(int) class], 25))
-       return gr_regs;
+      /* In MIPS16 mode, every move must involve a member of M16_REGS.  */
+      if (!reg_class_subset_p (class, M16_REGS) && !M16_REG_P (regno))
+       return M16_REGS;
+
+      /* We can't really copy to HI or LO at all in MIPS16 mode.  */
+      if (in_p ? reg_classes_intersect_p (class, ACC_REGS) : ACC_REG_P (regno))
+       return M16_REGS;
+
+      return NO_REGS;
     }
 
-  /* Copying from HI or LO to anywhere other than a general register
-     requires a general register.
-     This rule applies to both the original HI/LO pair and the new
-     DSP accumulators.  */
+  /* Copying from accumulator registers to anywhere other than a general
+     register requires a temporary general register.  */
   if (reg_class_subset_p (class, ACC_REGS))
-    {
-      if (TARGET_MIPS16 && in_p)
-       {
-         /* We can't really copy to HI or LO at all in mips16 mode.  */
-         return M16_REGS;
-       }
-      return gp_reg_p ? NO_REGS : gr_regs;
-    }
+    return GP_REG_P (regno) ? NO_REGS : GR_REGS;
   if (ACC_REG_P (regno))
-    {
-      if (TARGET_MIPS16 && ! in_p)
-       {
-         /* We can't really copy to HI or LO at all in mips16 mode.  */
-         return M16_REGS;
-       }
-      return class == gr_regs ? NO_REGS : gr_regs;
-    }
+    return reg_class_subset_p (class, GR_REGS) ? NO_REGS : GR_REGS;
 
   /* We can only copy a value to a condition code register from a
-     floating point register, and even then we require a scratch
-     floating point register.  We can only copy a value out of a
-     condition code register into a general register.  */
-  if (class == ST_REGS)
+     floating-point register, and even then we require a scratch
+     floating-point register.  We can only copy a value out of a
+     condition-code register into a general register.  */
+  if (reg_class_subset_p (class, ST_REGS))
     {
       if (in_p)
        return FP_REGS;
-      return gp_reg_p ? NO_REGS : gr_regs;
+      return GP_REG_P (regno) ? NO_REGS : GR_REGS;
     }
   if (ST_REG_P (regno))
     {
-      if (! in_p)
+      if (!in_p)
        return FP_REGS;
-      return class == gr_regs ? NO_REGS : gr_regs;
+      return reg_class_subset_p (class, GR_REGS) ? NO_REGS : GR_REGS;
     }
 
-  if (class == FP_REGS)
+  if (reg_class_subset_p (class, FP_REGS))
     {
-      if (MEM_P (x))
-       {
-         /* In this case we can use lwc1, swc1, ldc1 or sdc1.  */
-         return NO_REGS;
-       }
-      else if (CONSTANT_P (x) && GET_MODE_CLASS (mode) == MODE_FLOAT)
-       {
-         /* We can use the l.s and l.d macros to load floating-point
-            constants.  ??? For l.s, we could probably get better
-            code by returning GR_REGS here.  */
-         return NO_REGS;
-       }
-      else if (gp_reg_p || x == CONST0_RTX (mode))
-       {
-         /* In this case we can use mtc1, mfc1, dmtc1 or dmfc1.  */
-         return NO_REGS;
-       }
-      else if (FP_REG_P (regno))
-       {
-         /* In this case we can use mov.s or mov.d.  */
-         return NO_REGS;
-       }
-      else
-       {
-         /* Otherwise, we need to reload through an integer register.  */
-         return gr_regs;
-       }
-    }
+      if (MEM_P (x)
+         && (GET_MODE_SIZE (mode) == 4 || GET_MODE_SIZE (mode) == 8))
+       /* In this case we can use lwc1, swc1, ldc1 or sdc1.  We'll use
+          pairs of lwc1s and swc1s if ldc1 and sdc1 are not supported.  */
+       return NO_REGS;
 
-  /* In mips16 mode, going between memory and anything but M16_REGS
-     requires an M16_REG.  */
-  if (TARGET_MIPS16)
-    {
-      if (class != M16_REGS && class != M16_NA_REGS)
-       {
-         if (gp_reg_p)
-           return NO_REGS;
-         return M16_REGS;
-       }
-      if (! gp_reg_p)
-       {
-         if (class == M16_REGS || class == M16_NA_REGS)
-           return NO_REGS;
-         return M16_REGS;
-       }
-    }
+      if (GP_REG_P (regno) || x == CONST0_RTX (mode))
+       /* In this case we can use mtc1, mfc1, dmtc1 or dmfc1.  */
+       return NO_REGS;
 
-  return NO_REGS;
-}
+      if (CONSTANT_P (x) && !targetm.cannot_force_const_mem (x))
+       /* We can force the constant to memory and use lwc1
+          and ldc1.  As above, we will use pairs of lwc1s if
+          ldc1 is not supported.  */
+       return NO_REGS;
 
-/* Implement CLASS_MAX_NREGS.
+      if (FP_REG_P (regno) && mips_mode_ok_for_mov_fmt_p (mode))
+       /* In this case we can use mov.fmt.  */
+       return NO_REGS;
 
-   - UNITS_PER_FPREG controls the number of registers needed by FP_REGS.
+      /* Otherwise, we need to reload through an integer register.  */
+      return GR_REGS;
+    }
+  if (FP_REG_P (regno))
+    return reg_class_subset_p (class, GR_REGS) ? NO_REGS : GR_REGS;
 
-   - ST_REGS are always hold CCmode values, and CCmode values are
-     considered to be 4 bytes wide.
+  return NO_REGS;
+}
 
-   All other register classes are covered by UNITS_PER_WORD.  Note that
-   this is true even for unions of integer and float registers when the
-   latter are smaller than the former.  The only supported combination
-   in which case this occurs is -mgp64 -msingle-float, which has 64-bit
-   words but 32-bit float registers.  A word-based calculation is correct
-   in that case since -msingle-float disallows multi-FPR values.  */
+/* Implement TARGET_MODE_REP_EXTENDED.  */
 
-int
-mips_class_max_nregs (enum reg_class class ATTRIBUTE_UNUSED,
-                     enum machine_mode mode)
+static int
+mips_mode_rep_extended (enum machine_mode mode, enum machine_mode mode_rep)
 {
-  if (class == ST_REGS)
-    return (GET_MODE_SIZE (mode) + 3) / 4;
-  else if (class == FP_REGS)
-    return (GET_MODE_SIZE (mode) + UNITS_PER_FPREG - 1) / UNITS_PER_FPREG;
-  else
-    return (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
+  /* On 64-bit targets, SImode register values are sign-extended to DImode.  */
+  if (TARGET_64BIT && mode == SImode && mode_rep == DImode)
+    return SIGN_EXTEND;
+
+  return UNKNOWN;
 }
+\f
+/* Implement TARGET_VALID_POINTER_MODE.  */
 
 static bool
 mips_valid_pointer_mode (enum machine_mode mode)
 {
-  return (mode == SImode || (TARGET_64BIT && mode == DImode));
+  return mode == SImode || (TARGET_64BIT && mode == DImode);
 }
 
-/* Target hook for vector_mode_supported_p.  */
+/* Implement TARGET_VECTOR_MODE_SUPPORTED_P.  */
 
 static bool
 mips_vector_mode_supported_p (enum machine_mode mode)
@@ -9592,3344 +9088,3485 @@ mips_scalar_mode_supported_p (enum machine_mode mode)
   return default_scalar_mode_supported_p (mode);
 }
 \f
-/* If we can access small data directly (using gp-relative relocation
-   operators) return the small data pointer, otherwise return null.
+/* Implement TARGET_INIT_LIBFUNCS.  */
 
-   For each mips16 function which refers to GP relative symbols, we
-   use a pseudo register, initialized at the start of the function, to
-   hold the $gp value.  */
+#include "config/gofast.h"
 
-static rtx
-mips16_gp_pseudo_reg (void)
+static void
+mips_init_libfuncs (void)
 {
-  if (cfun->machine->mips16_gp_pseudo_rtx == NULL_RTX)
-    cfun->machine->mips16_gp_pseudo_rtx = gen_reg_rtx (Pmode);
+  if (TARGET_FIX_VR4120)
+    {
+      /* Register the special divsi3 and modsi3 functions needed to work
+        around VR4120 division errata.  */
+      set_optab_libfunc (sdiv_optab, SImode, "__vr4120_divsi3");
+      set_optab_libfunc (smod_optab, SImode, "__vr4120_modsi3");
+    }
 
-  /* Don't initialize the pseudo register if we are being called from
-     the tree optimizers' cost-calculation routines.  */
-  if (!cfun->machine->initialized_mips16_gp_pseudo_p
-      && (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl))
+  if (TARGET_MIPS16 && TARGET_HARD_FLOAT_ABI)
     {
-      rtx insn, scan;
+      /* Register the MIPS16 -mhard-float stubs.  */
+      set_optab_libfunc (add_optab, SFmode, "__mips16_addsf3");
+      set_optab_libfunc (sub_optab, SFmode, "__mips16_subsf3");
+      set_optab_libfunc (smul_optab, SFmode, "__mips16_mulsf3");
+      set_optab_libfunc (sdiv_optab, SFmode, "__mips16_divsf3");
 
-      /* We want to initialize this to a value which gcc will believe
-         is constant.  */
-      insn = gen_load_const_gp (cfun->machine->mips16_gp_pseudo_rtx);
+      set_optab_libfunc (eq_optab, SFmode, "__mips16_eqsf2");
+      set_optab_libfunc (ne_optab, SFmode, "__mips16_nesf2");
+      set_optab_libfunc (gt_optab, SFmode, "__mips16_gtsf2");
+      set_optab_libfunc (ge_optab, SFmode, "__mips16_gesf2");
+      set_optab_libfunc (lt_optab, SFmode, "__mips16_ltsf2");
+      set_optab_libfunc (le_optab, SFmode, "__mips16_lesf2");
+      set_optab_libfunc (unord_optab, SFmode, "__mips16_unordsf2");
 
-      push_topmost_sequence ();
-      /* We need to emit the initialization after the FUNCTION_BEG
-         note, so that it will be integrated.  */
-      for (scan = get_insns (); scan != NULL_RTX; scan = NEXT_INSN (scan))
-       if (NOTE_P (scan)
-           && NOTE_KIND (scan) == NOTE_INSN_FUNCTION_BEG)
-         break;
-      if (scan == NULL_RTX)
-       scan = get_insns ();
-      insn = emit_insn_after (insn, scan);
-      pop_topmost_sequence ();
+      set_conv_libfunc (sfix_optab, SImode, SFmode, "__mips16_fix_truncsfsi");
+      set_conv_libfunc (sfloat_optab, SFmode, SImode, "__mips16_floatsisf");
+      set_conv_libfunc (ufloat_optab, SFmode, SImode, "__mips16_floatunsisf");
 
-      cfun->machine->initialized_mips16_gp_pseudo_p = true;
-    }
+      if (TARGET_DOUBLE_FLOAT)
+       {
+         set_optab_libfunc (add_optab, DFmode, "__mips16_adddf3");
+         set_optab_libfunc (sub_optab, DFmode, "__mips16_subdf3");
+         set_optab_libfunc (smul_optab, DFmode, "__mips16_muldf3");
+         set_optab_libfunc (sdiv_optab, DFmode, "__mips16_divdf3");
 
-  return cfun->machine->mips16_gp_pseudo_rtx;
+         set_optab_libfunc (eq_optab, DFmode, "__mips16_eqdf2");
+         set_optab_libfunc (ne_optab, DFmode, "__mips16_nedf2");
+         set_optab_libfunc (gt_optab, DFmode, "__mips16_gtdf2");
+         set_optab_libfunc (ge_optab, DFmode, "__mips16_gedf2");
+         set_optab_libfunc (lt_optab, DFmode, "__mips16_ltdf2");
+         set_optab_libfunc (le_optab, DFmode, "__mips16_ledf2");
+         set_optab_libfunc (unord_optab, DFmode, "__mips16_unorddf2");
+
+         set_conv_libfunc (sext_optab, DFmode, SFmode,
+                           "__mips16_extendsfdf2");
+         set_conv_libfunc (trunc_optab, SFmode, DFmode,
+                           "__mips16_truncdfsf2");
+         set_conv_libfunc (sfix_optab, SImode, DFmode,
+                           "__mips16_fix_truncdfsi");
+         set_conv_libfunc (sfloat_optab, DFmode, SImode,
+                           "__mips16_floatsidf");
+         set_conv_libfunc (ufloat_optab, DFmode, SImode,
+                           "__mips16_floatunsidf");
+       }
+    }
+  else
+    /* Register the gofast functions if selected using --enable-gofast.  */
+    gofast_maybe_init_libfuncs ();
 }
 
-/* Write out code to move floating point arguments in or out of
-   general registers.  Output the instructions to FILE.  FP_CODE is
-   the code describing which arguments are present (see the comment at
-   the definition of CUMULATIVE_ARGS in mips.h).  FROM_FP_P is nonzero if
-   we are copying from the floating point registers.  */
+/* Return the length of INSN.  LENGTH is the initial length computed by
+   attributes in the machine-description file.  */
 
-static void
-mips16_fp_args (FILE *file, int fp_code, int from_fp_p)
+int
+mips_adjust_insn_length (rtx insn, int length)
 {
-  const char *s;
-  int gparg, fparg;
-  unsigned int f;
-  CUMULATIVE_ARGS cum;
-
-  /* This code only works for the original 32-bit ABI and the O64 ABI.  */
-  gcc_assert (TARGET_OLDABI);
-
-  if (from_fp_p)
-    s = "mfc1";
-  else
-    s = "mtc1";
-
-  init_cumulative_args (&cum, NULL, NULL);
+  /* A unconditional jump has an unfilled delay slot if it is not part
+     of a sequence.  A conditional jump normally has a delay slot, but
+     does not on MIPS16.  */
+  if (CALL_P (insn) || (TARGET_MIPS16 ? simplejump_p (insn) : JUMP_P (insn)))
+    length += 4;
 
-  for (f = (unsigned int) fp_code; f != 0; f >>= 2)
-    {
-      enum machine_mode mode;
-      struct mips_arg_info info;
+  /* See how many nops might be needed to avoid hardware hazards.  */
+  if (!cfun->machine->ignore_hazard_length_p && INSN_CODE (insn) >= 0)
+    switch (get_attr_hazard (insn))
+      {
+      case HAZARD_NONE:
+       break;
 
-      if ((f & 3) == 1)
-       mode = SFmode;
-      else if ((f & 3) == 2)
-       mode = DFmode;
-      else
-       gcc_unreachable ();
+      case HAZARD_DELAY:
+       length += 4;
+       break;
 
-      mips_arg_info (&cum, mode, NULL, true, &info);
-      gparg = mips_arg_regno (&info, false);
-      fparg = mips_arg_regno (&info, true);
+      case HAZARD_HILO:
+       length += 8;
+       break;
+      }
 
-      if (mode == SFmode)
-       fprintf (file, "\t%s\t%s,%s\n", s,
-                reg_names[gparg], reg_names[fparg]);
-      else if (TARGET_64BIT)
-       fprintf (file, "\td%s\t%s,%s\n", s,
-                reg_names[gparg], reg_names[fparg]);
-      else if (ISA_HAS_MXHC1)
-       /* -mips32r2 -mfp64 */
-       fprintf (file, "\t%s\t%s,%s\n\t%s\t%s,%s\n", 
-                s,
-                reg_names[gparg + (WORDS_BIG_ENDIAN ? 1 : 0)],
-                reg_names[fparg],
-                from_fp_p ? "mfhc1" : "mthc1",
-                reg_names[gparg + (WORDS_BIG_ENDIAN ? 0 : 1)],
-                reg_names[fparg]);
-      else if (TARGET_BIG_ENDIAN)
-       fprintf (file, "\t%s\t%s,%s\n\t%s\t%s,%s\n", s,
-                reg_names[gparg], reg_names[fparg + 1], s,
-                reg_names[gparg + 1], reg_names[fparg]);
-      else
-       fprintf (file, "\t%s\t%s,%s\n\t%s\t%s,%s\n", s,
-                reg_names[gparg], reg_names[fparg], s,
-                reg_names[gparg + 1], reg_names[fparg + 1]);
+  /* In order to make it easier to share MIPS16 and non-MIPS16 patterns,
+     the .md file length attributes are 4-based for both modes.
+     Adjust the MIPS16 ones here.  */
+  if (TARGET_MIPS16)
+    length /= 2;
 
-      function_arg_advance (&cum, mode, NULL, true);
-    }
+  return length;
 }
 
-/* Build a mips16 function stub.  This is used for functions which
-   take arguments in the floating point registers.  It is 32-bit code
-   that moves the floating point args into the general registers, and
-   then jumps to the 16-bit code.  */
+/* Return an asm sequence to start a noat block and load the address
+   of a label into $1.  */
 
-static void
-build_mips16_function_stub (FILE *file)
+const char *
+mips_output_load_label (void)
 {
-  const char *fnname;
-  char *secname, *stubname;
-  tree stubid, stubdecl;
-  int need_comma;
-  unsigned int f;
+  if (TARGET_EXPLICIT_RELOCS)
+    switch (mips_abi)
+      {
+      case ABI_N32:
+       return "%[lw\t%@,%%got_page(%0)(%+)\n\taddiu\t%@,%@,%%got_ofst(%0)";
 
-  fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
-  fnname = targetm.strip_name_encoding (fnname);
-  secname = (char *) alloca (strlen (fnname) + 20);
-  sprintf (secname, ".mips16.fn.%s", fnname);
-  stubname = (char *) alloca (strlen (fnname) + 20);
-  sprintf (stubname, "__fn_stub_%s", fnname);
-  stubid = get_identifier (stubname);
-  stubdecl = build_decl (FUNCTION_DECL, stubid,
-                        build_function_type (void_type_node, NULL_TREE));
-  DECL_SECTION_NAME (stubdecl) = build_string (strlen (secname), secname);
-  DECL_RESULT (stubdecl) = build_decl (RESULT_DECL, NULL_TREE, void_type_node);
+      case ABI_64:
+       return "%[ld\t%@,%%got_page(%0)(%+)\n\tdaddiu\t%@,%@,%%got_ofst(%0)";
 
-  fprintf (file, "\t# Stub function for %s (", current_function_name ());
-  need_comma = 0;
-  for (f = (unsigned int) current_function_args_info.fp_code; f != 0; f >>= 2)
+      default:
+       if (ISA_HAS_LOAD_DELAY)
+         return "%[lw\t%@,%%got(%0)(%+)%#\n\taddiu\t%@,%@,%%lo(%0)";
+       return "%[lw\t%@,%%got(%0)(%+)\n\taddiu\t%@,%@,%%lo(%0)";
+      }
+  else
     {
-      fprintf (file, "%s%s",
-              need_comma ? ", " : "",
-              (f & 3) == 1 ? "float" : "double");
-      need_comma = 1;
+      if (Pmode == DImode)
+       return "%[dla\t%@,%0";
+      else
+       return "%[la\t%@,%0";
     }
-  fprintf (file, ")\n");
+}
 
-  fprintf (file, "\t.set\tnomips16\n");
-  switch_to_section (function_section (stubdecl));
-  ASM_OUTPUT_ALIGN (file, floor_log2 (FUNCTION_BOUNDARY / BITS_PER_UNIT));
+/* Return the assembly code for INSN, which has the operands given by
+   OPERANDS, and which branches to OPERANDS[1] if some condition is true.
+   BRANCH_IF_TRUE is the asm template that should be used if OPERANDS[1]
+   is in range of a direct branch.  BRANCH_IF_FALSE is an inverted
+   version of BRANCH_IF_TRUE.  */
 
-  /* ??? If FUNCTION_NAME_ALREADY_DECLARED is defined, then we are
-     within a .ent, and we cannot emit another .ent.  */
-  if (!FUNCTION_NAME_ALREADY_DECLARED)
+const char *
+mips_output_conditional_branch (rtx insn, rtx *operands,
+                               const char *branch_if_true,
+                               const char *branch_if_false)
+{
+  unsigned int length;
+  rtx taken, not_taken;
+
+  length = get_attr_length (insn);
+  if (length <= 8)
     {
-      fputs ("\t.ent\t", file);
-      assemble_name (file, stubname);
-      fputs ("\n", file);
+      /* Just a simple conditional branch.  */
+      mips_branch_likely = (final_sequence && INSN_ANNULLED_BRANCH_P (insn));
+      return branch_if_true;
     }
 
-  assemble_name (file, stubname);
-  fputs (":\n", file);
-
-  /* We don't want the assembler to insert any nops here.  */
-  fprintf (file, "\t.set\tnoreorder\n");
-
-  mips16_fp_args (file, current_function_args_info.fp_code, 1);
+  /* Generate a reversed branch around a direct jump.  This fallback does
+     not use branch-likely instructions.  */
+  mips_branch_likely = false;
+  not_taken = gen_label_rtx ();
+  taken = operands[1];
 
-  fprintf (asm_out_file, "\t.set\tnoat\n");
-  fprintf (asm_out_file, "\tla\t%s,", reg_names[GP_REG_FIRST + 1]);
-  assemble_name (file, fnname);
-  fprintf (file, "\n");
-  fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 1]);
-  fprintf (asm_out_file, "\t.set\tat\n");
+  /* Generate the reversed branch to NOT_TAKEN.  */
+  operands[1] = not_taken;
+  output_asm_insn (branch_if_false, operands);
 
-  /* Unfortunately, we can't fill the jump delay slot.  We can't fill
-     with one of the mfc1 instructions, because the result is not
-     available for one instruction, so if the very first instruction
-     in the function refers to the register, it will see the wrong
-     value.  */
-  fprintf (file, "\tnop\n");
+  /* If INSN has a delay slot, we must provide delay slots for both the
+     branch to NOT_TAKEN and the conditional jump.  We must also ensure
+     that INSN's delay slot is executed in the appropriate cases.  */
+  if (final_sequence)
+    {
+      /* This first delay slot will always be executed, so use INSN's
+        delay slot if is not annulled.  */
+      if (!INSN_ANNULLED_BRANCH_P (insn))
+       {
+         final_scan_insn (XVECEXP (final_sequence, 0, 1),
+                          asm_out_file, optimize, 1, NULL);
+         INSN_DELETED_P (XVECEXP (final_sequence, 0, 1)) = 1;
+       }
+      else
+       output_asm_insn ("nop", 0);
+      fprintf (asm_out_file, "\n");
+    }
 
-  fprintf (file, "\t.set\treorder\n");
+  /* Output the unconditional branch to TAKEN.  */
+  if (length <= 16)
+    output_asm_insn ("j\t%0%/", &taken);
+  else
+    {
+      output_asm_insn (mips_output_load_label (), &taken);
+      output_asm_insn ("jr\t%@%]%/", 0);
+    }
 
-  if (!FUNCTION_NAME_ALREADY_DECLARED)
+  /* Now deal with its delay slot; see above.  */
+  if (final_sequence)
     {
-      fputs ("\t.end\t", file);
-      assemble_name (file, stubname);
-      fputs ("\n", file);
+      /* This delay slot will only be executed if the branch is taken.
+        Use INSN's delay slot if is annulled.  */
+      if (INSN_ANNULLED_BRANCH_P (insn))
+       {
+         final_scan_insn (XVECEXP (final_sequence, 0, 1),
+                          asm_out_file, optimize, 1, NULL);
+         INSN_DELETED_P (XVECEXP (final_sequence, 0, 1)) = 1;
+       }
+      else
+       output_asm_insn ("nop", 0);
+      fprintf (asm_out_file, "\n");
     }
 
-  switch_to_section (function_section (current_function_decl));
+  /* Output NOT_TAKEN.  */
+  targetm.asm_out.internal_label (asm_out_file, "L",
+                                 CODE_LABEL_NUMBER (not_taken));
+  return "";
 }
 
-/* We keep a list of functions for which we have already built stubs
-   in build_mips16_call_stub.  */
+/* Return the assembly code for INSN, which branches to OPERANDS[1]
+   if some ordering condition is true.  The condition is given by
+   OPERANDS[0] if !INVERTED_P, otherwise it is the inverse of
+   OPERANDS[0].  OPERANDS[2] is the comparison's first operand;
+   its second is always zero.  */
 
-struct mips16_stub
+const char *
+mips_output_order_conditional_branch (rtx insn, rtx *operands, bool inverted_p)
 {
-  struct mips16_stub *next;
-  char *name;
-  int fpret;
-};
+  const char *branch[2];
 
-static struct mips16_stub *mips16_stubs;
+  /* Make BRANCH[1] branch to OPERANDS[1] when the condition is true.
+     Make BRANCH[0] branch on the inverse condition.  */
+  switch (GET_CODE (operands[0]))
+    {
+      /* These cases are equivalent to comparisons against zero.  */
+    case LEU:
+      inverted_p = !inverted_p;
+      /* Fall through.  */
+    case GTU:
+      branch[!inverted_p] = MIPS_BRANCH ("bne", "%2,%.,%1");
+      branch[inverted_p] = MIPS_BRANCH ("beq", "%2,%.,%1");
+      break;
 
-/* Emit code to return a double value from a mips16 stub.  GPREG is the
-   first GP reg to use, FPREG is the first FP reg to use.  */
+      /* These cases are always true or always false.  */
+    case LTU:
+      inverted_p = !inverted_p;
+      /* Fall through.  */
+    case GEU:
+      branch[!inverted_p] = MIPS_BRANCH ("beq", "%.,%.,%1");
+      branch[inverted_p] = MIPS_BRANCH ("bne", "%.,%.,%1");
+      break;
 
-static void
-mips16_fpret_double (int gpreg, int fpreg)
-{
-  if (TARGET_64BIT)
-    fprintf (asm_out_file, "\tdmfc1\t%s,%s\n",
-            reg_names[gpreg], reg_names[fpreg]);
-  else if (TARGET_FLOAT64)
-    {
-      fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
-              reg_names[gpreg + WORDS_BIG_ENDIAN],
-              reg_names[fpreg]);
-      fprintf (asm_out_file, "\tmfhc1\t%s,%s\n",
-              reg_names[gpreg + !WORDS_BIG_ENDIAN],
-              reg_names[fpreg]);
-    }
-  else
-    {
-      if (TARGET_BIG_ENDIAN)
-       {
-         fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
-                  reg_names[gpreg + 0],
-                  reg_names[fpreg + 1]);
-         fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
-                  reg_names[gpreg + 1],
-                  reg_names[fpreg + 0]);
-       }
-      else
-       {
-         fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
-                  reg_names[gpreg + 0],
-                  reg_names[fpreg + 0]);
-         fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
-                  reg_names[gpreg + 1],
-                  reg_names[fpreg + 1]);
-       }
+    default:
+      branch[!inverted_p] = MIPS_BRANCH ("b%C0z", "%2,%1");
+      branch[inverted_p] = MIPS_BRANCH ("b%N0z", "%2,%1");
+      break;
     }
+  return mips_output_conditional_branch (insn, operands, branch[1], branch[0]);
 }
+\f
+/* Return the assembly code for DIV or DDIV instruction DIVISION, which has
+   the operands given by OPERANDS.  Add in a divide-by-zero check if needed.
 
-/* Build a call stub for a mips16 call.  A stub is needed if we are
-   passing any floating point values which should go into the floating
-   point registers.  If we are, and the call turns out to be to a
-   32-bit function, the stub will be used to move the values into the
-   floating point registers before calling the 32-bit function.  The
-   linker will magically adjust the function call to either the 16-bit
-   function or the 32-bit stub, depending upon where the function call
-   is actually defined.
-
-   Similarly, we need a stub if the return value might come back in a
-   floating point register.
+   When working around R4000 and R4400 errata, we need to make sure that
+   the division is not immediately followed by a shift[1][2].  We also
+   need to stop the division from being put into a branch delay slot[3].
+   The easiest way to avoid both problems is to add a nop after the
+   division.  When a divide-by-zero check is needed, this nop can be
+   used to fill the branch delay slot.
 
-   RETVAL is the location of the return value, or null if this is
-   a call rather than a call_value.  FN is the address of the
-   function and ARG_SIZE is the size of the arguments.  FP_CODE
-   is the code built by function_arg.  This function returns a nonzero
-   value if it builds the call instruction itself.  */
+   [1] If a double-word or a variable shift executes immediately
+       after starting an integer division, the shift may give an
+       incorrect result.  See quotations of errata #16 and #28 from
+       "MIPS R4000PC/SC Errata, Processor Revision 2.2 and 3.0"
+       in mips.md for details.
 
-int
-build_mips16_call_stub (rtx retval, rtx fn, rtx arg_size, int fp_code)
-{
-  int fpret = 0;
-  const char *fnname;
-  char *secname, *stubname;
-  struct mips16_stub *l;
-  tree stubid, stubdecl;
-  int need_comma;
-  unsigned int f;
-  rtx insn;
+   [2] A similar bug to [1] exists for all revisions of the
+       R4000 and the R4400 when run in an MC configuration.
+       From "MIPS R4000MC Errata, Processor Revision 2.2 and 3.0":
 
-  /* We don't need to do anything if we aren't in mips16 mode, or if
-     we were invoked with the -msoft-float option.  */
-  if (!TARGET_MIPS16 || TARGET_SOFT_FLOAT_ABI)
-    return 0;
+       "19. In this following sequence:
 
-  /* Figure out whether the value might come back in a floating point
-     register.  */
-  if (retval)
-    fpret = mips_return_mode_in_fpr_p (GET_MODE (retval));
+                   ddiv                (or ddivu or div or divu)
+                   dsll32              (or dsrl32, dsra32)
 
-  /* We don't need to do anything if there were no floating point
-     arguments and the value will not be returned in a floating point
-     register.  */
-  if (fp_code == 0 && ! fpret)
-    return 0;
+           if an MPT stall occurs, while the divide is slipping the cpu
+           pipeline, then the following double shift would end up with an
+           incorrect result.
 
-  /* We don't need to do anything if this is a call to a special
-     mips16 support function.  */
-  if (GET_CODE (fn) == SYMBOL_REF
-      && strncmp (XSTR (fn, 0), "__mips16_", 9) == 0)
-    return 0;
+           Workaround: The compiler needs to avoid generating any
+           sequence with divide followed by extended double shift."
 
-  /* This code will only work for o32 and o64 abis.  The other ABI's
-     require more sophisticated support.  */
-  gcc_assert (TARGET_OLDABI);
+       This erratum is also present in "MIPS R4400MC Errata, Processor
+       Revision 1.0" and "MIPS R4400MC Errata, Processor Revision 2.0
+       & 3.0" as errata #10 and #4, respectively.
 
-  /* If we're calling via a function pointer, then we must always call
-     via a stub.  There are magic stubs provided in libgcc.a for each
-     of the required cases.  Each of them expects the function address
-     to arrive in register $2.  */
+   [3] From "MIPS R4000PC/SC Errata, Processor Revision 2.2 and 3.0"
+       (also valid for MIPS R4000MC processors):
 
-  if (GET_CODE (fn) != SYMBOL_REF)
-    {
-      char buf[30];
-      tree id;
-      rtx stub_fn, insn;
+       "52. R4000SC: This bug does not apply for the R4000PC.
 
-      /* ??? If this code is modified to support other ABI's, we need
-         to handle PARALLEL return values here.  */
+           There are two flavors of this bug:
 
-      if (fpret)
-       sprintf (buf, "__mips16_call_stub_%s_%d",
-                mips16_call_stub_mode_suffix (GET_MODE (retval)),
-                fp_code);
-      else
-       sprintf (buf, "__mips16_call_stub_%d",
-                fp_code);
+           1) If the instruction just after divide takes an RF exception
+              (tlb-refill, tlb-invalid) and gets an instruction cache
+              miss (both primary and secondary) and the line which is
+              currently in secondary cache at this index had the first
+              data word, where the bits 5..2 are set, then R4000 would
+              get a wrong result for the div.
 
-      id = get_identifier (buf);
-      stub_fn = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (id));
+           ##1
+                   nop
+                   div r8, r9
+                   -------------------         # end-of page. -tlb-refill
+                   nop
+           ##2
+                   nop
+                   div r8, r9
+                   -------------------         # end-of page. -tlb-invalid
+                   nop
 
-      mips_emit_move (gen_rtx_REG (Pmode, 2), fn);
+           2) If the divide is in the taken branch delay slot, where the
+              target takes RF exception and gets an I-cache miss for the
+              exception vector or where I-cache miss occurs for the
+              target address, under the above mentioned scenarios, the
+              div would get wrong results.
 
-      if (retval == NULL_RTX)
-       insn = gen_call_internal (stub_fn, arg_size);
-      else
-       insn = gen_call_value_internal (retval, stub_fn, arg_size);
-      insn = emit_call_insn (insn);
+           ##1
+                   j   r2              # to next page mapped or unmapped
+                   div r8,r9           # this bug would be there as long
+                                       # as there is an ICache miss and
+                   nop                 # the "data pattern" is present
 
-      /* Put the register usage information on the CALL.  */
-      CALL_INSN_FUNCTION_USAGE (insn) =
-       gen_rtx_EXPR_LIST (VOIDmode,
-                          gen_rtx_USE (VOIDmode, gen_rtx_REG (Pmode, 2)),
-                          CALL_INSN_FUNCTION_USAGE (insn));
+           ##2
+                   beq r0, r0, NextPage        # to Next page
+                   div r8,r9
+                   nop
 
-      /* If we are handling a floating point return value, we need to
-         save $18 in the function prologue.  Putting a note on the
-         call will mean that df_regs_ever_live_p ($18) will be true if the
-         call is not eliminated, and we can check that in the prologue
-         code.  */
-      if (fpret)
-       CALL_INSN_FUNCTION_USAGE (insn) =
-         gen_rtx_EXPR_LIST (VOIDmode,
-                            gen_rtx_USE (VOIDmode,
-                                         gen_rtx_REG (word_mode, 18)),
-                            CALL_INSN_FUNCTION_USAGE (insn));
+           This bug is present for div, divu, ddiv, and ddivu
+           instructions.
 
-      /* Return 1 to tell the caller that we've generated the call
-         insn.  */
-      return 1;
-    }
+           Workaround: For item 1), OS could make sure that the next page
+           after the divide instruction is also mapped.  For item 2), the
+           compiler could make sure that the divide instruction is not in
+           the branch delay slot."
 
-  /* We know the function we are going to call.  If we have already
-     built a stub, we don't need to do anything further.  */
+       These processors have PRId values of 0x00004220 and 0x00004300 for
+       the R4000 and 0x00004400, 0x00004500 and 0x00004600 for the R4400.  */
 
-  fnname = targetm.strip_name_encoding (XSTR (fn, 0));
-  for (l = mips16_stubs; l != NULL; l = l->next)
-    if (strcmp (l->name, fnname) == 0)
-      break;
+const char *
+mips_output_division (const char *division, rtx *operands)
+{
+  const char *s;
 
-  if (l == NULL)
+  s = division;
+  if (TARGET_FIX_R4000 || TARGET_FIX_R4400)
     {
-      /* Build a special purpose stub.  When the linker sees a
-        function call in mips16 code, it will check where the target
-        is defined.  If the target is a 32-bit call, the linker will
-        search for the section defined here.  It can tell which
-        symbol this section is associated with by looking at the
-        relocation information (the name is unreliable, since this
-        might be a static function).  If such a section is found, the
-        linker will redirect the call to the start of the magic
-        section.
-
-        If the function does not return a floating point value, the
-        special stub section is named
-            .mips16.call.FNNAME
-
-        If the function does return a floating point value, the stub
-        section is named
-            .mips16.call.fp.FNNAME
-        */
-
-      secname = (char *) alloca (strlen (fnname) + 40);
-      sprintf (secname, ".mips16.call.%s%s",
-              fpret ? "fp." : "",
-              fnname);
-      stubname = (char *) alloca (strlen (fnname) + 20);
-      sprintf (stubname, "__call_stub_%s%s",
-              fpret ? "fp_" : "",
-              fnname);
-      stubid = get_identifier (stubname);
-      stubdecl = build_decl (FUNCTION_DECL, stubid,
-                            build_function_type (void_type_node, NULL_TREE));
-      DECL_SECTION_NAME (stubdecl) = build_string (strlen (secname), secname);
-      DECL_RESULT (stubdecl) = build_decl (RESULT_DECL, NULL_TREE, void_type_node);
-
-      fprintf (asm_out_file, "\t# Stub function to call %s%s (",
-              (fpret
-               ? (GET_MODE (retval) == SFmode ? "float " : "double ")
-               : ""),
-              fnname);
-      need_comma = 0;
-      for (f = (unsigned int) fp_code; f != 0; f >>= 2)
+      output_asm_insn (s, operands);
+      s = "nop";
+    }
+  if (TARGET_CHECK_ZERO_DIV)
+    {
+      if (TARGET_MIPS16)
        {
-         fprintf (asm_out_file, "%s%s",
-                  need_comma ? ", " : "",
-                  (f & 3) == 1 ? "float" : "double");
-         need_comma = 1;
+         output_asm_insn (s, operands);
+         s = "bnez\t%2,1f\n\tbreak\t7\n1:";
        }
-      fprintf (asm_out_file, ")\n");
-
-      fprintf (asm_out_file, "\t.set\tnomips16\n");
-      assemble_start_function (stubdecl, stubname);
-
-      if (!FUNCTION_NAME_ALREADY_DECLARED)
+      else if (GENERATE_DIVIDE_TRAPS)
+        {
+         output_asm_insn (s, operands);
+         s = "teq\t%2,%.,7";
+        }
+      else
        {
-         fputs ("\t.ent\t", asm_out_file);
-         assemble_name (asm_out_file, stubname);
-         fputs ("\n", asm_out_file);
-
-         assemble_name (asm_out_file, stubname);
-         fputs (":\n", asm_out_file);
+         output_asm_insn ("%(bne\t%2,%.,1f", operands);
+         output_asm_insn (s, operands);
+         s = "break\t7%)\n1:";
        }
+    }
+  return s;
+}
+\f
+/* Return true if IN_INSN is a multiply-add or multiply-subtract
+   instruction and if OUT_INSN assigns to the accumulator operand.  */
 
-      /* We build the stub code by hand.  That's the only way we can
-        do it, since we can't generate 32-bit code during a 16-bit
-        compilation.  */
+bool
+mips_linked_madd_p (rtx out_insn, rtx in_insn)
+{
+  rtx x;
 
-      /* We don't want the assembler to insert any nops here.  */
-      fprintf (asm_out_file, "\t.set\tnoreorder\n");
+  x = single_set (in_insn);
+  if (x == 0)
+    return false;
 
-      mips16_fp_args (asm_out_file, fp_code, 0);
+  x = SET_SRC (x);
 
-      if (! fpret)
-       {
-         fprintf (asm_out_file, "\t.set\tnoat\n");
-         fprintf (asm_out_file, "\tla\t%s,%s\n", reg_names[GP_REG_FIRST + 1],
-                  fnname);
-         fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 1]);
-         fprintf (asm_out_file, "\t.set\tat\n");
-         /* Unfortunately, we can't fill the jump delay slot.  We
-            can't fill with one of the mtc1 instructions, because the
-            result is not available for one instruction, so if the
-            very first instruction in the function refers to the
-            register, it will see the wrong value.  */
-         fprintf (asm_out_file, "\tnop\n");
-       }
-      else
-       {
-         fprintf (asm_out_file, "\tmove\t%s,%s\n",
-                  reg_names[GP_REG_FIRST + 18], reg_names[GP_REG_FIRST + 31]);
-         fprintf (asm_out_file, "\tjal\t%s\n", fnname);
-         /* As above, we can't fill the delay slot.  */
-         fprintf (asm_out_file, "\tnop\n");
-         switch (GET_MODE (retval))
-           {
-           case SCmode:
-             fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
-                      reg_names[GP_REG_FIRST + 3],
-                      reg_names[FP_REG_FIRST + MAX_FPRS_PER_FMT]);
-             /* Fall though.  */
-           case SFmode:
-             fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
-                      reg_names[GP_REG_FIRST + 2],
-                      reg_names[FP_REG_FIRST + 0]);
-             break;
+  if (GET_CODE (x) == PLUS
+      && GET_CODE (XEXP (x, 0)) == MULT
+      && reg_set_p (XEXP (x, 1), out_insn))
+    return true;
 
-           case DCmode:
-             mips16_fpret_double (GP_REG_FIRST + 2 + (8 / UNITS_PER_WORD),
-                                  FP_REG_FIRST + MAX_FPRS_PER_FMT);
-             /* Fall though.  */
-           case DFmode:
-           case V2SFmode:
-             mips16_fpret_double (GP_REG_FIRST + 2, FP_REG_FIRST + 0);
-             break;
+  if (GET_CODE (x) == MINUS
+      && GET_CODE (XEXP (x, 1)) == MULT
+      && reg_set_p (XEXP (x, 0), out_insn))
+    return true;
 
-           default:
-             gcc_unreachable ();
-           }
-         fprintf (asm_out_file, "\tj\t%s\n", reg_names[GP_REG_FIRST + 18]);
-         /* As above, we can't fill the delay slot.  */
-         fprintf (asm_out_file, "\tnop\n");
-       }
+  return false;
+}
 
-      fprintf (asm_out_file, "\t.set\treorder\n");
+/* True if the dependency between OUT_INSN and IN_INSN is on the store
+   data rather than the address.  We need this because the cprestore
+   pattern is type "store", but is defined using an UNSPEC_VOLATILE,
+   which causes the default routine to abort.  We just return false
+   for that case.  */
 
-#ifdef ASM_DECLARE_FUNCTION_SIZE
-      ASM_DECLARE_FUNCTION_SIZE (asm_out_file, stubname, stubdecl);
-#endif
+bool
+mips_store_data_bypass_p (rtx out_insn, rtx in_insn)
+{
+  if (GET_CODE (PATTERN (in_insn)) == UNSPEC_VOLATILE)
+    return false;
 
-      if (!FUNCTION_NAME_ALREADY_DECLARED)
-       {
-         fputs ("\t.end\t", asm_out_file);
-         assemble_name (asm_out_file, stubname);
-         fputs ("\n", asm_out_file);
-       }
+  return !store_data_bypass_p (out_insn, in_insn);
+}
+\f
+/* Implement TARGET_SCHED_ADJUST_COST.  We assume that anti and output
+   dependencies have no cost, except on the 20Kc where output-dependence
+   is treated like input-dependence.  */
 
-      /* Record this stub.  */
-      l = (struct mips16_stub *) xmalloc (sizeof *l);
-      l->name = xstrdup (fnname);
-      l->fpret = fpret;
-      l->next = mips16_stubs;
-      mips16_stubs = l;
-    }
+static int
+mips_adjust_cost (rtx insn ATTRIBUTE_UNUSED, rtx link,
+                 rtx dep ATTRIBUTE_UNUSED, int cost)
+{
+  if (REG_NOTE_KIND (link) == REG_DEP_OUTPUT
+      && TUNE_20KC)
+    return cost;
+  if (REG_NOTE_KIND (link) != 0)
+    return 0;
+  return cost;
+}
 
-  /* If we expect a floating point return value, but we've built a
-     stub which does not expect one, then we're in trouble.  We can't
-     use the existing stub, because it won't handle the floating point
-     value.  We can't build a new stub, because the linker won't know
-     which stub to use for the various calls in this object file.
-     Fortunately, this case is illegal, since it means that a function
-     was declared in two different ways in a single compilation.  */
-  if (fpret && ! l->fpret)
-    error ("cannot handle inconsistent calls to %qs", fnname);
+/* Return the number of instructions that can be issued per cycle.  */
 
-  if (retval == NULL_RTX)
-    insn = gen_call_internal_direct (fn, arg_size);
-  else
-    insn = gen_call_value_internal_direct (retval, fn, arg_size);
-  insn = emit_call_insn (insn);
-
-  /* If we are calling a stub which handles a floating point return
-     value, we need to arrange to save $18 in the prologue.  We do
-     this by marking the function call as using the register.  The
-     prologue will later see that it is used, and emit code to save
-     it.  */
-  if (l->fpret)
-    CALL_INSN_FUNCTION_USAGE (insn) =
-      gen_rtx_EXPR_LIST (VOIDmode,
-                        gen_rtx_USE (VOIDmode, gen_rtx_REG (word_mode, 18)),
-                        CALL_INSN_FUNCTION_USAGE (insn));
+static int
+mips_issue_rate (void)
+{
+  switch (mips_tune)
+    {
+    case PROCESSOR_74KC:
+    case PROCESSOR_74KF2_1:
+    case PROCESSOR_74KF1_1:
+    case PROCESSOR_74KF3_2:
+      /* The 74k is not strictly quad-issue cpu, but can be seen as one
+        by the scheduler.  It can issue 1 ALU, 1 AGEN and 2 FPU insns,
+        but in reality only a maximum of 3 insns can be issued as
+        floating-point loads and stores also require a slot in the
+        AGEN pipe.  */
+     return 4;
 
-  /* Return 1 to tell the caller that we've generated the call
-     insn.  */
-  return 1;
-}
+    case PROCESSOR_20KC:
+    case PROCESSOR_R4130:
+    case PROCESSOR_R5400:
+    case PROCESSOR_R5500:
+    case PROCESSOR_R7000:
+    case PROCESSOR_R9000:
+      return 2;
 
-/* An entry in the mips16 constant pool.  VALUE is the pool constant,
-   MODE is its mode, and LABEL is the CODE_LABEL associated with it.  */
+    case PROCESSOR_SB1:
+    case PROCESSOR_SB1A:
+      /* This is actually 4, but we get better performance if we claim 3.
+        This is partly because of unwanted speculative code motion with the
+        larger number, and partly because in most common cases we can't
+        reach the theoretical max of 4.  */
+      return 3;
 
-struct mips16_constant {
-  struct mips16_constant *next;
-  rtx value;
-  rtx label;
-  enum machine_mode mode;
-};
+    default:
+      return 1;
+    }
+}
 
-/* Information about an incomplete mips16 constant pool.  FIRST is the
-   first constant, HIGHEST_ADDRESS is the highest address that the first
-   byte of the pool can have, and INSN_ADDRESS is the current instruction
-   address.  */
+/* Implement TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD.  This should
+   be as wide as the scheduling freedom in the DFA.  */
 
-struct mips16_constant_pool {
-  struct mips16_constant *first;
-  int highest_address;
-  int insn_address;
-};
+static int
+mips_multipass_dfa_lookahead (void)
+{
+  /* Can schedule up to 4 of the 6 function units in any one cycle.  */
+  if (TUNE_SB1)
+    return 4;
 
-/* Add constant VALUE to POOL and return its label.  MODE is the
-   value's mode (used for CONST_INTs, etc.).  */
+  return 0;
+}
+\f
+/* Remove the instruction at index LOWER from ready queue READY and
+   reinsert it in front of the instruction at index HIGHER.  LOWER must
+   be <= HIGHER.  */
 
-static rtx
-add_constant (struct mips16_constant_pool *pool,
-             rtx value, enum machine_mode mode)
+static void
+mips_promote_ready (rtx *ready, int lower, int higher)
 {
-  struct mips16_constant **p, *c;
-  bool first_of_size_p;
+  rtx new_head;
+  int i;
 
-  /* See whether the constant is already in the pool.  If so, return the
-     existing label, otherwise leave P pointing to the place where the
-     constant should be added.
+  new_head = ready[lower];
+  for (i = lower; i < higher; i++)
+    ready[i] = ready[i + 1];
+  ready[i] = new_head;
+}
 
-     Keep the pool sorted in increasing order of mode size so that we can
-     reduce the number of alignments needed.  */
-  first_of_size_p = true;
-  for (p = &pool->first; *p != 0; p = &(*p)->next)
+/* If the priority of the instruction at POS2 in the ready queue READY
+   is within LIMIT units of that of the instruction at POS1, swap the
+   instructions if POS2 is not already less than POS1.  */
+
+static void
+mips_maybe_swap_ready (rtx *ready, int pos1, int pos2, int limit)
+{
+  if (pos1 < pos2
+      && INSN_PRIORITY (ready[pos1]) + limit >= INSN_PRIORITY (ready[pos2]))
     {
-      if (mode == (*p)->mode && rtx_equal_p (value, (*p)->value))
-       return (*p)->label;
-      if (GET_MODE_SIZE (mode) < GET_MODE_SIZE ((*p)->mode))
-       break;
-      if (GET_MODE_SIZE (mode) == GET_MODE_SIZE ((*p)->mode))
-       first_of_size_p = false;
-    }
+      rtx temp;
 
-  /* In the worst case, the constant needed by the earliest instruction
-     will end up at the end of the pool.  The entire pool must then be
-     accessible from that instruction.
-
-     When adding the first constant, set the pool's highest address to
-     the address of the first out-of-range byte.  Adjust this address
-     downwards each time a new constant is added.  */
-  if (pool->first == 0)
-    /* For pc-relative lw, addiu and daddiu instructions, the base PC value
-       is the address of the instruction with the lowest two bits clear.
-       The base PC value for ld has the lowest three bits clear.  Assume
-       the worst case here.  */
-    pool->highest_address = pool->insn_address - (UNITS_PER_WORD - 2) + 0x8000;
-  pool->highest_address -= GET_MODE_SIZE (mode);
-  if (first_of_size_p)
-    /* Take into account the worst possible padding due to alignment.  */
-    pool->highest_address -= GET_MODE_SIZE (mode) - 1;
-
-  /* Create a new entry.  */
-  c = (struct mips16_constant *) xmalloc (sizeof *c);
-  c->value = value;
-  c->mode = mode;
-  c->label = gen_label_rtx ();
-  c->next = *p;
-  *p = c;
-
-  return c->label;
+      temp = ready[pos1];
+      ready[pos1] = ready[pos2];
+      ready[pos2] = temp;
+    }
 }
+\f
+/* Used by TUNE_MACC_CHAINS to record the last scheduled instruction
+   that may clobber hi or lo.  */
+static rtx mips_macc_chains_last_hilo;
 
-/* Output constant VALUE after instruction INSN and return the last
-   instruction emitted.  MODE is the mode of the constant.  */
+/* A TUNE_MACC_CHAINS helper function.  Record that instruction INSN has
+   been scheduled, updating mips_macc_chains_last_hilo appropriately.  */
 
-static rtx
-dump_constants_1 (enum machine_mode mode, rtx value, rtx insn)
+static void
+mips_macc_chains_record (rtx insn)
 {
-  if (SCALAR_INT_MODE_P (mode)
-      || ALL_SCALAR_FRACT_MODE_P (mode)
-      || ALL_SCALAR_ACCUM_MODE_P (mode))
-    {
-      rtx size = GEN_INT (GET_MODE_SIZE (mode));
-      return emit_insn_after (gen_consttable_int (value, size), insn);
-    }
-
-  if (SCALAR_FLOAT_MODE_P (mode))
-    return emit_insn_after (gen_consttable_float (value), insn);
-
-  if (VECTOR_MODE_P (mode))
-    {
-      int i;
-
-      for (i = 0; i < CONST_VECTOR_NUNITS (value); i++)
-       insn = dump_constants_1 (GET_MODE_INNER (mode),
-                                CONST_VECTOR_ELT (value, i), insn);
-      return insn;
-    }
-
-  gcc_unreachable ();
+  if (get_attr_may_clobber_hilo (insn))
+    mips_macc_chains_last_hilo = insn;
 }
 
-
-/* Dump out the constants in CONSTANTS after INSN.  */
+/* A TUNE_MACC_CHAINS helper function.  Search ready queue READY, which
+   has NREADY elements, looking for a multiply-add or multiply-subtract
+   instruction that is cumulative with mips_macc_chains_last_hilo.
+   If there is one, promote it ahead of anything else that might
+   clobber hi or lo.  */
 
 static void
-dump_constants (struct mips16_constant *constants, rtx insn)
+mips_macc_chains_reorder (rtx *ready, int nready)
 {
-  struct mips16_constant *c, *next;
-  int align;
+  int i, j;
 
-  align = 0;
-  for (c = constants; c != NULL; c = next)
-    {
-      /* If necessary, increase the alignment of PC.  */
-      if (align < GET_MODE_SIZE (c->mode))
+  if (mips_macc_chains_last_hilo != 0)
+    for (i = nready - 1; i >= 0; i--)
+      if (mips_linked_madd_p (mips_macc_chains_last_hilo, ready[i]))
        {
-         int align_log = floor_log2 (GET_MODE_SIZE (c->mode));
-         insn = emit_insn_after (gen_align (GEN_INT (align_log)), insn);
+         for (j = nready - 1; j > i; j--)
+           if (recog_memoized (ready[j]) >= 0
+               && get_attr_may_clobber_hilo (ready[j]))
+             {
+               mips_promote_ready (ready, i, j);
+               break;
+             }
+         break;
        }
-      align = GET_MODE_SIZE (c->mode);
+}
+\f
+/* The last instruction to be scheduled.  */
+static rtx vr4130_last_insn;
 
-      insn = emit_label_after (c->label, insn);
-      insn = dump_constants_1 (c->mode, c->value, insn);
+/* A note_stores callback used by vr4130_true_reg_dependence_p.  DATA
+   points to an rtx that is initially an instruction.  Nullify the rtx
+   if the instruction uses the value of register X.  */
 
-      next = c->next;
-      free (c);
-    }
+static void
+vr4130_true_reg_dependence_p_1 (rtx x, const_rtx pat ATTRIBUTE_UNUSED,
+                               void *data)
+{
+  rtx *insn_ptr;
 
-  emit_barrier_after (insn);
+  insn_ptr = (rtx *) data;
+  if (REG_P (x)
+      && *insn_ptr != 0
+      && reg_referenced_p (x, PATTERN (*insn_ptr)))
+    *insn_ptr = 0;
 }
 
-/* Return the length of instruction INSN.  */
+/* Return true if there is true register dependence between vr4130_last_insn
+   and INSN.  */
 
-static int
-mips16_insn_length (rtx insn)
+static bool
+vr4130_true_reg_dependence_p (rtx insn)
 {
-  if (JUMP_P (insn))
-    {
-      rtx body = PATTERN (insn);
-      if (GET_CODE (body) == ADDR_VEC)
-       return GET_MODE_SIZE (GET_MODE (body)) * XVECLEN (body, 0);
-      if (GET_CODE (body) == ADDR_DIFF_VEC)
-       return GET_MODE_SIZE (GET_MODE (body)) * XVECLEN (body, 1);
-    }
-  return get_attr_length (insn);
+  note_stores (PATTERN (vr4130_last_insn),
+              vr4130_true_reg_dependence_p_1, &insn);
+  return insn == 0;
 }
 
-/* If *X is a symbolic constant that refers to the constant pool, add
-   the constant to POOL and rewrite *X to use the constant's label.  */
+/* A TUNE_MIPS4130 helper function.  Given that INSN1 is at the head of
+   the ready queue and that INSN2 is the instruction after it, return
+   true if it is worth promoting INSN2 ahead of INSN1.  Look for cases
+   in which INSN1 and INSN2 can probably issue in parallel, but for
+   which (INSN2, INSN1) should be less sensitive to instruction
+   alignment than (INSN1, INSN2).  See 4130.md for more details.  */
 
-static void
-mips16_rewrite_pool_constant (struct mips16_constant_pool *pool, rtx *x)
+static bool
+vr4130_swap_insns_p (rtx insn1, rtx insn2)
 {
-  rtx base, offset, label;
+  sd_iterator_def sd_it;
+  dep_t dep;
 
-  split_const (*x, &base, &offset);
-  if (GET_CODE (base) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (base))
+  /* Check for the following case:
+
+     1) there is some other instruction X with an anti dependence on INSN1;
+     2) X has a higher priority than INSN2; and
+     3) X is an arithmetic instruction (and thus has no unit restrictions).
+
+     If INSN1 is the last instruction blocking X, it would better to
+     choose (INSN1, X) over (INSN2, INSN1).  */
+  FOR_EACH_DEP (insn1, SD_LIST_FORW, sd_it, dep)
+    if (DEP_TYPE (dep) == REG_DEP_ANTI
+       && INSN_PRIORITY (DEP_CON (dep)) > INSN_PRIORITY (insn2)
+       && recog_memoized (DEP_CON (dep)) >= 0
+       && get_attr_vr4130_class (DEP_CON (dep)) == VR4130_CLASS_ALU)
+      return false;
+
+  if (vr4130_last_insn != 0
+      && recog_memoized (insn1) >= 0
+      && recog_memoized (insn2) >= 0)
     {
-      label = add_constant (pool, get_pool_constant (base),
-                           get_pool_mode (base));
-      base = gen_rtx_LABEL_REF (Pmode, label);
-      *x = mips_unspec_address_offset (base, offset, SYMBOL_PC_RELATIVE);
+      /* See whether INSN1 and INSN2 use different execution units,
+        or if they are both ALU-type instructions.  If so, they can
+        probably execute in parallel.  */
+      enum attr_vr4130_class class1 = get_attr_vr4130_class (insn1);
+      enum attr_vr4130_class class2 = get_attr_vr4130_class (insn2);
+      if (class1 != class2 || class1 == VR4130_CLASS_ALU)
+       {
+         /* If only one of the instructions has a dependence on
+            vr4130_last_insn, prefer to schedule the other one first.  */
+         bool dep1_p = vr4130_true_reg_dependence_p (insn1);
+         bool dep2_p = vr4130_true_reg_dependence_p (insn2);
+         if (dep1_p != dep2_p)
+           return dep1_p;
+
+         /* Prefer to schedule INSN2 ahead of INSN1 if vr4130_last_insn
+            is not an ALU-type instruction and if INSN1 uses the same
+            execution unit.  (Note that if this condition holds, we already
+            know that INSN2 uses a different execution unit.)  */
+         if (class1 != VR4130_CLASS_ALU
+             && recog_memoized (vr4130_last_insn) >= 0
+             && class1 == get_attr_vr4130_class (vr4130_last_insn))
+           return true;
+       }
     }
+  return false;
 }
 
-/* This structure is used to communicate with mips16_rewrite_pool_refs.
-   INSN is the instruction we're rewriting and POOL points to the current
-   constant pool.  */
-struct mips16_rewrite_pool_refs_info {
-  rtx insn;
-  struct mips16_constant_pool *pool;
-};
-
-/* Rewrite *X so that constant pool references refer to the constant's
-   label instead.  DATA points to a mips16_rewrite_pool_refs_info
-   structure.  */
+/* A TUNE_MIPS4130 helper function.  (READY, NREADY) describes a ready
+   queue with at least two instructions.  Swap the first two if
+   vr4130_swap_insns_p says that it could be worthwhile.  */
 
-static int
-mips16_rewrite_pool_refs (rtx *x, void *data)
+static void
+vr4130_reorder (rtx *ready, int nready)
 {
-  struct mips16_rewrite_pool_refs_info *info = data;
+  if (vr4130_swap_insns_p (ready[nready - 1], ready[nready - 2]))
+    mips_promote_ready (ready, nready - 2, nready - 1);
+}
+\f
+/* Record whether last 74k AGEN instruction was a load or store.  */
+static enum attr_type mips_last_74k_agen_insn = TYPE_UNKNOWN;
 
-  if (force_to_mem_operand (*x, Pmode))
-    {
-      rtx mem = force_const_mem (GET_MODE (*x), *x);
-      validate_change (info->insn, x, mem, false);
-    }
+/* Initialize mips_last_74k_agen_insn from INSN.  A null argument
+   resets to TYPE_UNKNOWN state.  */
 
-  if (MEM_P (*x))
+static void
+mips_74k_agen_init (rtx insn)
+{
+  if (!insn || !NONJUMP_INSN_P (insn))
+    mips_last_74k_agen_insn = TYPE_UNKNOWN;
+  else
     {
-      mips16_rewrite_pool_constant (info->pool, &XEXP (*x, 0));
-      return -1;
+      enum attr_type type = get_attr_type (insn);
+      if (type == TYPE_LOAD || type == TYPE_STORE)
+       mips_last_74k_agen_insn = type;
     }
-
-  if (TARGET_MIPS16_TEXT_LOADS)
-    mips16_rewrite_pool_constant (info->pool, x);
-
-  return GET_CODE (*x) == CONST ? -1 : 0;
 }
 
-/* Build MIPS16 constant pools.  */
+/* A TUNE_74K helper function.  The 74K AGEN pipeline likes multiple
+   loads to be grouped together, and multiple stores to be grouped
+   together.  Swap things around in the ready queue to make this happen.  */
 
 static void
-mips16_lay_out_constants (void)
+mips_74k_agen_reorder (rtx *ready, int nready)
 {
-  struct mips16_constant_pool pool;
-  struct mips16_rewrite_pool_refs_info info;
-  rtx insn, barrier;
+  int i;
+  int store_pos, load_pos;
 
-  if (!TARGET_MIPS16_PCREL_LOADS)
-    return;
+  store_pos = -1;
+  load_pos = -1;
 
-  barrier = 0;
-  memset (&pool, 0, sizeof (pool));
-  for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
+  for (i = nready - 1; i >= 0; i--)
     {
-      /* Rewrite constant pool references in INSN.  */
-      if (INSN_P (insn))
-       {
-         info.insn = insn;
-         info.pool = &pool;
-         for_each_rtx (&PATTERN (insn), mips16_rewrite_pool_refs, &info);
-       }
-
-      pool.insn_address += mips16_insn_length (insn);
-
-      if (pool.first != NULL)
-       {
-         /* If there are no natural barriers between the first user of
-            the pool and the highest acceptable address, we'll need to
-            create a new instruction to jump around the constant pool.
-            In the worst case, this instruction will be 4 bytes long.
-
-            If it's too late to do this transformation after INSN,
-            do it immediately before INSN.  */
-         if (barrier == 0 && pool.insn_address + 4 > pool.highest_address)
-           {
-             rtx label, jump;
+      rtx insn = ready[i];
+      if (USEFUL_INSN_P (insn))
+       switch (get_attr_type (insn))
+         {
+         case TYPE_STORE:
+           if (store_pos == -1)
+             store_pos = i;
+           break;
 
-             label = gen_label_rtx ();
+         case TYPE_LOAD:
+           if (load_pos == -1)
+             load_pos = i;
+           break;
 
-             jump = emit_jump_insn_before (gen_jump (label), insn);
-             JUMP_LABEL (jump) = label;
-             LABEL_NUSES (label) = 1;
-             barrier = emit_barrier_after (jump);
+         default:
+           break;
+         }
+    }
 
-             emit_label_after (label, barrier);
-             pool.insn_address += 4;
-           }
+  if (load_pos == -1 || store_pos == -1)
+    return;
 
-         /* See whether the constant pool is now out of range of the first
-            user.  If so, output the constants after the previous barrier.
-            Note that any instructions between BARRIER and INSN (inclusive)
-            will use negative offsets to refer to the pool.  */
-         if (pool.insn_address > pool.highest_address)
-           {
-             dump_constants (pool.first, barrier);
-             pool.first = NULL;
-             barrier = 0;
-           }
-         else if (BARRIER_P (insn))
-           barrier = insn;
-       }
+  switch (mips_last_74k_agen_insn)
+    {
+    case TYPE_UNKNOWN:
+      /* Prefer to schedule loads since they have a higher latency.  */
+    case TYPE_LOAD:
+      /* Swap loads to the front of the queue.  */
+      mips_maybe_swap_ready (ready, load_pos, store_pos, 4);
+      break;
+    case TYPE_STORE:
+      /* Swap stores to the front of the queue.  */
+      mips_maybe_swap_ready (ready, store_pos, load_pos, 4);
+      break;
+    default:
+      break;
     }
-  dump_constants (pool.first, get_last_insn ());
 }
 \f
-/* A temporary variable used by for_each_rtx callbacks, etc.  */
-static rtx mips_sim_insn;
-
-/* A structure representing the state of the processor pipeline.
-   Used by the mips_sim_* family of functions.  */
-struct mips_sim {
-  /* The maximum number of instructions that can be issued in a cycle.
-     (Caches mips_issue_rate.)  */
-  unsigned int issue_rate;
-
-  /* The current simulation time.  */
-  unsigned int time;
-
-  /* How many more instructions can be issued in the current cycle.  */
-  unsigned int insns_left;
-
-  /* LAST_SET[X].INSN is the last instruction to set register X.
-     LAST_SET[X].TIME is the time at which that instruction was issued.
-     INSN is null if no instruction has yet set register X.  */
-  struct {
-    rtx insn;
-    unsigned int time;
-  } last_set[FIRST_PSEUDO_REGISTER];
-
-  /* The pipeline's current DFA state.  */
-  state_t dfa_state;
-};
-
-/* Reset STATE to the initial simulation state.  */
-
-static void
-mips_sim_reset (struct mips_sim *state)
-{
-  state->time = 0;
-  state->insns_left = state->issue_rate;
-  memset (&state->last_set, 0, sizeof (state->last_set));
-  state_reset (state->dfa_state);
-}
-
-/* Initialize STATE before its first use.  DFA_STATE points to an
-   allocated but uninitialized DFA state.  */
+/* Implement TARGET_SCHED_INIT.  */
 
 static void
-mips_sim_init (struct mips_sim *state, state_t dfa_state)
+mips_sched_init (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
+                int max_ready ATTRIBUTE_UNUSED)
 {
-  state->issue_rate = mips_issue_rate ();
-  state->dfa_state = dfa_state;
-  mips_sim_reset (state);
+  mips_macc_chains_last_hilo = 0;
+  vr4130_last_insn = 0;
+  mips_74k_agen_init (NULL_RTX);
 }
 
-/* Advance STATE by one clock cycle.  */
+/* Implement TARGET_SCHED_REORDER and TARGET_SCHED_REORDER2.  */
 
-static void
-mips_sim_next_cycle (struct mips_sim *state)
+static int
+mips_sched_reorder (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
+                   rtx *ready, int *nreadyp, int cycle ATTRIBUTE_UNUSED)
 {
-  state->time++;
-  state->insns_left = state->issue_rate;
-  state_transition (state->dfa_state, 0);
-}
-
-/* Advance simulation state STATE until instruction INSN can read
-   register REG.  */
+  if (!reload_completed
+      && TUNE_MACC_CHAINS
+      && *nreadyp > 0)
+    mips_macc_chains_reorder (ready, *nreadyp);
 
-static void
-mips_sim_wait_reg (struct mips_sim *state, rtx insn, rtx reg)
-{
-  unsigned int i;
+  if (reload_completed
+      && TUNE_MIPS4130
+      && !TARGET_VR4130_ALIGN
+      && *nreadyp > 1)
+    vr4130_reorder (ready, *nreadyp);
 
-  for (i = 0; i < HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg)); i++)
-    if (state->last_set[REGNO (reg) + i].insn != 0)
-      {
-       unsigned int t;
+  if (TUNE_74K)
+    mips_74k_agen_reorder (ready, *nreadyp);
 
-       t = state->last_set[REGNO (reg) + i].time;
-       t += insn_latency (state->last_set[REGNO (reg) + i].insn, insn);
-       while (state->time < t)
-         mips_sim_next_cycle (state);
-    }
+  return mips_issue_rate ();
 }
 
-/* A for_each_rtx callback.  If *X is a register, advance simulation state
-   DATA until mips_sim_insn can read the register's value.  */
+/* Implement TARGET_SCHED_VARIABLE_ISSUE.  */
 
 static int
-mips_sim_wait_regs_2 (rtx *x, void *data)
+mips_variable_issue (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
+                    rtx insn, int more)
 {
-  if (REG_P (*x))
-    mips_sim_wait_reg (data, mips_sim_insn, *x);
-  return 0;
+  /* Ignore USEs and CLOBBERs; don't count them against the issue rate.  */
+  if (USEFUL_INSN_P (insn))
+    {
+      more--;
+      if (!reload_completed && TUNE_MACC_CHAINS)
+       mips_macc_chains_record (insn);
+      vr4130_last_insn = insn;
+      if (TUNE_74K)
+       mips_74k_agen_init (insn);
+    }
+  return more;
 }
+\f
+/* Given that we have an rtx of the form (prefetch ... WRITE LOCALITY),
+   return the first operand of the associated PREF or PREFX insn.  */
 
-/* Call mips_sim_wait_regs_2 (R, DATA) for each register R mentioned in *X.  */
-
-static void
-mips_sim_wait_regs_1 (rtx *x, void *data)
+rtx
+mips_prefetch_cookie (rtx write, rtx locality)
 {
-  for_each_rtx (x, mips_sim_wait_regs_2, data);
-}
+  /* store_streamed / load_streamed.  */
+  if (INTVAL (locality) <= 0)
+    return GEN_INT (INTVAL (write) + 4);
 
-/* Advance simulation state STATE until all of INSN's register
-   dependencies are satisfied.  */
+  /* store / load.  */
+  if (INTVAL (locality) <= 2)
+    return write;
 
-static void
-mips_sim_wait_regs (struct mips_sim *state, rtx insn)
-{
-  mips_sim_insn = insn;
-  note_uses (&PATTERN (insn), mips_sim_wait_regs_1, state);
+  /* store_retained / load_retained.  */
+  return GEN_INT (INTVAL (write) + 6);
 }
+\f
+/* This structure describes a single built-in function.  */
+struct mips_builtin_description {
+  /* The code of the main .md file instruction.  See mips_builtin_type
+     for more information.  */
+  enum insn_code icode;
 
-/* Advance simulation state STATE until the units required by
-   instruction INSN are available.  */
-
-static void
-mips_sim_wait_units (struct mips_sim *state, rtx insn)
-{
-  state_t tmp_state;
-
-  tmp_state = alloca (state_size ());
-  while (state->insns_left == 0
-        || (memcpy (tmp_state, state->dfa_state, state_size ()),
-            state_transition (tmp_state, insn) >= 0))
-    mips_sim_next_cycle (state);
-}
+  /* The floating-point comparison code to use with ICODE, if any.  */
+  enum mips_fp_condition cond;
 
-/* Advance simulation state STATE until INSN is ready to issue.  */
+  /* The name of the built-in function.  */
+  const char *name;
 
-static void
-mips_sim_wait_insn (struct mips_sim *state, rtx insn)
-{
-  mips_sim_wait_regs (state, insn);
-  mips_sim_wait_units (state, insn);
-}
+  /* Specifies how the function should be expanded.  */
+  enum mips_builtin_type builtin_type;
 
-/* mips_sim_insn has just set X.  Update the LAST_SET array
-   in simulation state DATA.  */
+  /* The function's prototype.  */
+  enum mips_function_type function_type;
 
-static void
-mips_sim_record_set (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
-{
-  struct mips_sim *state;
-  unsigned int i;
+  /* The target flags required for this function.  */
+  int target_flags;
+};
 
-  state = data;
-  if (REG_P (x))
-    for (i = 0; i < HARD_REGNO_NREGS (REGNO (x), GET_MODE (x)); i++)
-      {
-       state->last_set[REGNO (x) + i].insn = mips_sim_insn;
-       state->last_set[REGNO (x) + i].time = state->time;
-      }
-}
+/* Define a MIPS_BUILTIN_DIRECT function for instruction CODE_FOR_mips_<INSN>.
+   FUNCTION_TYPE and TARGET_FLAGS are mips_builtin_description fields.  */
+#define DIRECT_BUILTIN(INSN, FUNCTION_TYPE, TARGET_FLAGS)              \
+  { CODE_FOR_mips_ ## INSN, 0, "__builtin_mips_" #INSN,                        \
+    MIPS_BUILTIN_DIRECT, FUNCTION_TYPE, TARGET_FLAGS }
 
-/* Issue instruction INSN in scheduler state STATE.  Assume that INSN
-   can issue immediately (i.e., that mips_sim_wait_insn has already
-   been called).  */
+/* Define __builtin_mips_<INSN>_<COND>_{s,d} functions, both of which
+   require TARGET_FLAGS.  */
+#define CMP_SCALAR_BUILTINS(INSN, COND, TARGET_FLAGS)                  \
+  { CODE_FOR_mips_ ## INSN ## _cond_s, MIPS_FP_COND_ ## COND,          \
+    "__builtin_mips_" #INSN "_" #COND "_s",                            \
+    MIPS_BUILTIN_CMP_SINGLE, MIPS_INT_FTYPE_SF_SF, TARGET_FLAGS },     \
+  { CODE_FOR_mips_ ## INSN ## _cond_d, MIPS_FP_COND_ ## COND,          \
+    "__builtin_mips_" #INSN "_" #COND "_d",                            \
+    MIPS_BUILTIN_CMP_SINGLE, MIPS_INT_FTYPE_DF_DF, TARGET_FLAGS }
 
-static void
-mips_sim_issue_insn (struct mips_sim *state, rtx insn)
-{
-  state_transition (state->dfa_state, insn);
-  state->insns_left--;
+/* Define __builtin_mips_{any,all,upper,lower}_<INSN>_<COND>_ps.
+   The lower and upper forms require TARGET_FLAGS while the any and all
+   forms require MASK_MIPS3D.  */
+#define CMP_PS_BUILTINS(INSN, COND, TARGET_FLAGS)                      \
+  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
+    "__builtin_mips_any_" #INSN "_" #COND "_ps",                       \
+    MIPS_BUILTIN_CMP_ANY, MIPS_INT_FTYPE_V2SF_V2SF, MASK_MIPS3D },     \
+  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
+    "__builtin_mips_all_" #INSN "_" #COND "_ps",                       \
+    MIPS_BUILTIN_CMP_ALL, MIPS_INT_FTYPE_V2SF_V2SF, MASK_MIPS3D },     \
+  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
+    "__builtin_mips_lower_" #INSN "_" #COND "_ps",                     \
+    MIPS_BUILTIN_CMP_LOWER, MIPS_INT_FTYPE_V2SF_V2SF, TARGET_FLAGS },  \
+  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
+    "__builtin_mips_upper_" #INSN "_" #COND "_ps",                     \
+    MIPS_BUILTIN_CMP_UPPER, MIPS_INT_FTYPE_V2SF_V2SF, TARGET_FLAGS }
 
-  mips_sim_insn = insn;
-  note_stores (PATTERN (insn), mips_sim_record_set, state);
+/* Define __builtin_mips_{any,all}_<INSN>_<COND>_4s.  The functions
+   require MASK_MIPS3D.  */
+#define CMP_4S_BUILTINS(INSN, COND)                                    \
+  { CODE_FOR_mips_ ## INSN ## _cond_4s, MIPS_FP_COND_ ## COND,         \
+    "__builtin_mips_any_" #INSN "_" #COND "_4s",                       \
+    MIPS_BUILTIN_CMP_ANY, MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF,          \
+    MASK_MIPS3D },                                                     \
+  { CODE_FOR_mips_ ## INSN ## _cond_4s, MIPS_FP_COND_ ## COND,         \
+    "__builtin_mips_all_" #INSN "_" #COND "_4s",                       \
+    MIPS_BUILTIN_CMP_ALL, MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF,          \
+    MASK_MIPS3D }
+
+/* Define __builtin_mips_mov{t,f}_<INSN>_<COND>_ps.  The comparison
+   instruction requires TARGET_FLAGS.  */
+#define MOVTF_BUILTINS(INSN, COND, TARGET_FLAGS)                       \
+  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
+    "__builtin_mips_movt_" #INSN "_" #COND "_ps",                      \
+    MIPS_BUILTIN_MOVT, MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF,            \
+    TARGET_FLAGS },                                                    \
+  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
+    "__builtin_mips_movf_" #INSN "_" #COND "_ps",                      \
+    MIPS_BUILTIN_MOVF, MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF,            \
+    TARGET_FLAGS }
+
+/* Define all the built-in functions related to C.cond.fmt condition COND.  */
+#define CMP_BUILTINS(COND)                                             \
+  MOVTF_BUILTINS (c, COND, MASK_PAIRED_SINGLE_FLOAT),                  \
+  MOVTF_BUILTINS (cabs, COND, MASK_MIPS3D),                            \
+  CMP_SCALAR_BUILTINS (cabs, COND, MASK_MIPS3D),                       \
+  CMP_PS_BUILTINS (c, COND, MASK_PAIRED_SINGLE_FLOAT),                 \
+  CMP_PS_BUILTINS (cabs, COND, MASK_MIPS3D),                           \
+  CMP_4S_BUILTINS (c, COND),                                           \
+  CMP_4S_BUILTINS (cabs, COND)
+
+static const struct mips_builtin_description mips_ps_bdesc[] = {
+  DIRECT_BUILTIN (pll_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
+  DIRECT_BUILTIN (pul_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
+  DIRECT_BUILTIN (plu_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
+  DIRECT_BUILTIN (puu_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
+  DIRECT_BUILTIN (cvt_ps_s, MIPS_V2SF_FTYPE_SF_SF, MASK_PAIRED_SINGLE_FLOAT),
+  DIRECT_BUILTIN (cvt_s_pl, MIPS_SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT),
+  DIRECT_BUILTIN (cvt_s_pu, MIPS_SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT),
+  DIRECT_BUILTIN (abs_ps, MIPS_V2SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT),
+
+  DIRECT_BUILTIN (alnv_ps, MIPS_V2SF_FTYPE_V2SF_V2SF_INT,
+                 MASK_PAIRED_SINGLE_FLOAT),
+  DIRECT_BUILTIN (addr_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
+  DIRECT_BUILTIN (mulr_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
+  DIRECT_BUILTIN (cvt_pw_ps, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
+  DIRECT_BUILTIN (cvt_ps_pw, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
+
+  DIRECT_BUILTIN (recip1_s, MIPS_SF_FTYPE_SF, MASK_MIPS3D),
+  DIRECT_BUILTIN (recip1_d, MIPS_DF_FTYPE_DF, MASK_MIPS3D),
+  DIRECT_BUILTIN (recip1_ps, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
+  DIRECT_BUILTIN (recip2_s, MIPS_SF_FTYPE_SF_SF, MASK_MIPS3D),
+  DIRECT_BUILTIN (recip2_d, MIPS_DF_FTYPE_DF_DF, MASK_MIPS3D),
+  DIRECT_BUILTIN (recip2_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
+
+  DIRECT_BUILTIN (rsqrt1_s, MIPS_SF_FTYPE_SF, MASK_MIPS3D),
+  DIRECT_BUILTIN (rsqrt1_d, MIPS_DF_FTYPE_DF, MASK_MIPS3D),
+  DIRECT_BUILTIN (rsqrt1_ps, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
+  DIRECT_BUILTIN (rsqrt2_s, MIPS_SF_FTYPE_SF_SF, MASK_MIPS3D),
+  DIRECT_BUILTIN (rsqrt2_d, MIPS_DF_FTYPE_DF_DF, MASK_MIPS3D),
+  DIRECT_BUILTIN (rsqrt2_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
+
+  MIPS_FP_CONDITIONS (CMP_BUILTINS)
+};
+
+/* Built-in functions for the SB-1 processor.  */
+
+#define CODE_FOR_mips_sqrt_ps CODE_FOR_sqrtv2sf2
+
+static const struct mips_builtin_description mips_sb1_bdesc[] = {
+  DIRECT_BUILTIN (sqrt_ps, MIPS_V2SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT)
+};
+
+/* Built-in functions for the DSP ASE.  */
+
+#define CODE_FOR_mips_addq_ph CODE_FOR_addv2hi3
+#define CODE_FOR_mips_addu_qb CODE_FOR_addv4qi3
+#define CODE_FOR_mips_subq_ph CODE_FOR_subv2hi3
+#define CODE_FOR_mips_subu_qb CODE_FOR_subv4qi3
+#define CODE_FOR_mips_mul_ph CODE_FOR_mulv2hi3
+
+/* Define a MIPS_BUILTIN_DIRECT_NO_TARGET function for instruction
+   CODE_FOR_mips_<INSN>.  FUNCTION_TYPE and TARGET_FLAGS are
+   mips_builtin_description fields.  */
+#define DIRECT_NO_TARGET_BUILTIN(INSN, FUNCTION_TYPE, TARGET_FLAGS)    \
+  { CODE_FOR_mips_ ## INSN, 0, "__builtin_mips_" #INSN,                        \
+    MIPS_BUILTIN_DIRECT_NO_TARGET, FUNCTION_TYPE, TARGET_FLAGS }
+
+/* Define __builtin_mips_bposge<VALUE>.  <VALUE> is 32 for the MIPS32 DSP
+   branch instruction.  TARGET_FLAGS is a mips_builtin_description field.  */
+#define BPOSGE_BUILTIN(VALUE, TARGET_FLAGS)                            \
+  { CODE_FOR_mips_bposge, 0, "__builtin_mips_bposge" #VALUE,           \
+    MIPS_BUILTIN_BPOSGE ## VALUE, MIPS_SI_FTYPE_VOID, TARGET_FLAGS }
+
+static const struct mips_builtin_description mips_dsp_bdesc[] = {
+  DIRECT_BUILTIN (addq_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (addq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (addq_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (addu_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (addu_s_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (subq_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (subq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (subq_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (subu_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (subu_s_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (addsc, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (addwc, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (modsub, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (raddu_w_qb, MIPS_SI_FTYPE_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (absq_s_ph, MIPS_V2HI_FTYPE_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (absq_s_w, MIPS_SI_FTYPE_SI, MASK_DSP),
+  DIRECT_BUILTIN (precrq_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (precrq_ph_w, MIPS_V2HI_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (precrq_rs_ph_w, MIPS_V2HI_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (precrqu_s_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (preceq_w_phl, MIPS_SI_FTYPE_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (preceq_w_phr, MIPS_SI_FTYPE_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (precequ_ph_qbl, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (precequ_ph_qbr, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (precequ_ph_qbla, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (precequ_ph_qbra, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (preceu_ph_qbl, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (preceu_ph_qbr, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (preceu_ph_qbla, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (preceu_ph_qbra, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (shll_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSP),
+  DIRECT_BUILTIN (shll_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
+  DIRECT_BUILTIN (shll_s_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
+  DIRECT_BUILTIN (shll_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (shrl_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSP),
+  DIRECT_BUILTIN (shra_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
+  DIRECT_BUILTIN (shra_r_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
+  DIRECT_BUILTIN (shra_r_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (muleu_s_ph_qbl, MIPS_V2HI_FTYPE_V4QI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (muleu_s_ph_qbr, MIPS_V2HI_FTYPE_V4QI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (mulq_rs_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (muleq_s_w_phl, MIPS_SI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (muleq_s_w_phr, MIPS_SI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (bitrev, MIPS_SI_FTYPE_SI, MASK_DSP),
+  DIRECT_BUILTIN (insv, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (repl_qb, MIPS_V4QI_FTYPE_SI, MASK_DSP),
+  DIRECT_BUILTIN (repl_ph, MIPS_V2HI_FTYPE_SI, MASK_DSP),
+  DIRECT_NO_TARGET_BUILTIN (cmpu_eq_qb, MIPS_VOID_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_NO_TARGET_BUILTIN (cmpu_lt_qb, MIPS_VOID_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_NO_TARGET_BUILTIN (cmpu_le_qb, MIPS_VOID_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (cmpgu_eq_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (cmpgu_lt_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (cmpgu_le_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_NO_TARGET_BUILTIN (cmp_eq_ph, MIPS_VOID_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_NO_TARGET_BUILTIN (cmp_lt_ph, MIPS_VOID_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_NO_TARGET_BUILTIN (cmp_le_ph, MIPS_VOID_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (pick_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (pick_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (packrl_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
+  DIRECT_NO_TARGET_BUILTIN (wrdsp, MIPS_VOID_FTYPE_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (rddsp, MIPS_SI_FTYPE_SI, MASK_DSP),
+  DIRECT_BUILTIN (lbux, MIPS_SI_FTYPE_POINTER_SI, MASK_DSP),
+  DIRECT_BUILTIN (lhx, MIPS_SI_FTYPE_POINTER_SI, MASK_DSP),
+  DIRECT_BUILTIN (lwx, MIPS_SI_FTYPE_POINTER_SI, MASK_DSP),
+  BPOSGE_BUILTIN (32, MASK_DSP),
+
+  /* The following are for the MIPS DSP ASE REV 2.  */
+  DIRECT_BUILTIN (absq_s_qb, MIPS_V4QI_FTYPE_V4QI, MASK_DSPR2),
+  DIRECT_BUILTIN (addu_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (addu_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (adduh_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
+  DIRECT_BUILTIN (adduh_r_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
+  DIRECT_BUILTIN (append, MIPS_SI_FTYPE_SI_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (balign, MIPS_SI_FTYPE_SI_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (cmpgdu_eq_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSPR2),
+  DIRECT_BUILTIN (cmpgdu_lt_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSPR2),
+  DIRECT_BUILTIN (cmpgdu_le_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSPR2),
+  DIRECT_BUILTIN (mul_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (mul_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (mulq_rs_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (mulq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (mulq_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (precr_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (precr_sra_ph_w, MIPS_V2HI_FTYPE_SI_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (precr_sra_r_ph_w, MIPS_V2HI_FTYPE_SI_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (prepend, MIPS_SI_FTYPE_SI_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (shra_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (shra_r_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (shrl_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (subu_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (subu_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (subuh_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
+  DIRECT_BUILTIN (subuh_r_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
+  DIRECT_BUILTIN (addqh_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (addqh_r_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (addqh_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (addqh_r_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (subqh_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (subqh_r_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (subqh_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (subqh_r_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2)
+};
+
+static const struct mips_builtin_description mips_dsp_32only_bdesc[] = {
+  DIRECT_BUILTIN (dpau_h_qbl, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (dpau_h_qbr, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (dpsu_h_qbl, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (dpsu_h_qbr, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
+  DIRECT_BUILTIN (dpaq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (dpsq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (mulsaq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (dpaq_sa_l_w, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (dpsq_sa_l_w, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSP),
+  DIRECT_BUILTIN (maq_s_w_phl, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (maq_s_w_phr, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (maq_sa_w_phl, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (maq_sa_w_phr, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
+  DIRECT_BUILTIN (extr_w, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
+  DIRECT_BUILTIN (extr_r_w, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
+  DIRECT_BUILTIN (extr_rs_w, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
+  DIRECT_BUILTIN (extr_s_h, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
+  DIRECT_BUILTIN (extp, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
+  DIRECT_BUILTIN (extpdp, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
+  DIRECT_BUILTIN (shilo, MIPS_DI_FTYPE_DI_SI, MASK_DSP),
+  DIRECT_BUILTIN (mthlip, MIPS_DI_FTYPE_DI_SI, MASK_DSP),
+
+  /* The following are for the MIPS DSP ASE REV 2.  */
+  DIRECT_BUILTIN (dpa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (dps_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (madd, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (maddu, MIPS_DI_FTYPE_DI_USI_USI, MASK_DSPR2),
+  DIRECT_BUILTIN (msub, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (msubu, MIPS_DI_FTYPE_DI_USI_USI, MASK_DSPR2),
+  DIRECT_BUILTIN (mulsa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (mult, MIPS_DI_FTYPE_SI_SI, MASK_DSPR2),
+  DIRECT_BUILTIN (multu, MIPS_DI_FTYPE_USI_USI, MASK_DSPR2),
+  DIRECT_BUILTIN (dpax_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (dpsx_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (dpaqx_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (dpaqx_sa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (dpsqx_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
+  DIRECT_BUILTIN (dpsqx_sa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2)
+};
+
+/* This structure describes an array of mips_builtin_description entries.  */
+struct mips_bdesc_map {
+  /* The array that this entry describes.  */
+  const struct mips_builtin_description *bdesc;
+
+  /* The number of entries in BDESC.  */
+  unsigned int size;
+
+  /* The target processor that supports the functions in BDESC.
+     PROCESSOR_MAX means we enable them for all processors.  */
+  enum processor_type proc;
+
+  /* The functions in BDESC are not supported if any of these
+     target flags are set.  */
+  int unsupported_target_flags;
+};
+
+/* All MIPS-specific built-in functions.  */
+static const struct mips_bdesc_map mips_bdesc_arrays[] = {
+  { mips_ps_bdesc, ARRAY_SIZE (mips_ps_bdesc), PROCESSOR_MAX, 0 },
+  { mips_sb1_bdesc, ARRAY_SIZE (mips_sb1_bdesc), PROCESSOR_SB1, 0 },
+  { mips_dsp_bdesc, ARRAY_SIZE (mips_dsp_bdesc), PROCESSOR_MAX, 0 },
+  { mips_dsp_32only_bdesc, ARRAY_SIZE (mips_dsp_32only_bdesc),
+    PROCESSOR_MAX, MASK_64BIT }
+};
+
+/* MODE is a vector mode whose elements have type TYPE.  Return the type
+   of the vector itself.  */
+
+static tree
+mips_builtin_vector_type (tree type, enum machine_mode mode)
+{
+  static tree types[(int) MAX_MACHINE_MODE];
+
+  if (types[(int) mode] == NULL_TREE)
+    types[(int) mode] = build_vector_type_for_mode (type, mode);
+  return types[(int) mode];
 }
 
-/* Simulate issuing a NOP in state STATE.  */
+/* Source-level argument types.  */
+#define MIPS_ATYPE_VOID void_type_node
+#define MIPS_ATYPE_INT integer_type_node
+#define MIPS_ATYPE_POINTER ptr_type_node
 
-static void
-mips_sim_issue_nop (struct mips_sim *state)
+/* Standard mode-based argument types.  */
+#define MIPS_ATYPE_SI intSI_type_node
+#define MIPS_ATYPE_USI unsigned_intSI_type_node
+#define MIPS_ATYPE_DI intDI_type_node
+#define MIPS_ATYPE_SF float_type_node
+#define MIPS_ATYPE_DF double_type_node
+
+/* Vector argument types.  */
+#define MIPS_ATYPE_V2SF mips_builtin_vector_type (float_type_node, V2SFmode)
+#define MIPS_ATYPE_V2HI mips_builtin_vector_type (intHI_type_node, V2HImode)
+#define MIPS_ATYPE_V4QI mips_builtin_vector_type (intQI_type_node, V4QImode)
+
+/* MIPS_FTYPE_ATYPESN takes N MIPS_FTYPES-like type codes and lists
+   their associated MIPS_ATYPEs.  */
+#define MIPS_FTYPE_ATYPES1(A, B) \
+  MIPS_ATYPE_##A, MIPS_ATYPE_##B
+
+#define MIPS_FTYPE_ATYPES2(A, B, C) \
+  MIPS_ATYPE_##A, MIPS_ATYPE_##B, MIPS_ATYPE_##C
+
+#define MIPS_FTYPE_ATYPES3(A, B, C, D) \
+  MIPS_ATYPE_##A, MIPS_ATYPE_##B, MIPS_ATYPE_##C, MIPS_ATYPE_##D
+
+#define MIPS_FTYPE_ATYPES4(A, B, C, D, E) \
+  MIPS_ATYPE_##A, MIPS_ATYPE_##B, MIPS_ATYPE_##C, MIPS_ATYPE_##D, \
+  MIPS_ATYPE_##E
+
+/* Return the function type associated with function prototype TYPE.  */
+
+static tree
+mips_build_function_type (enum mips_function_type type)
 {
-  if (state->insns_left == 0)
-    mips_sim_next_cycle (state);
-  state->insns_left--;
+  static tree types[(int) MIPS_MAX_FTYPE_MAX];
+
+  if (types[(int) type] == NULL_TREE)
+    switch (type)
+      {
+#define DEF_MIPS_FTYPE(NUM, ARGS)                                      \
+  case MIPS_FTYPE_NAME##NUM ARGS:                                      \
+    types[(int) type]                                                  \
+      = build_function_type_list (MIPS_FTYPE_ATYPES##NUM ARGS,         \
+                                 NULL_TREE);                           \
+    break;
+#include "config/mips/mips-ftypes.def"
+#undef DEF_MIPS_FTYPE
+      default:
+       gcc_unreachable ();
+      }
+
+  return types[(int) type];
 }
 
-/* Update simulation state STATE so that it's ready to accept the instruction
-   after INSN.  INSN should be part of the main rtl chain, not a member of a
-   SEQUENCE.  */
+/* Implement TARGET_INIT_BUILTINS.  */
 
 static void
-mips_sim_finish_insn (struct mips_sim *state, rtx insn)
+mips_init_builtins (void)
 {
-  /* If INSN is a jump with an implicit delay slot, simulate a nop.  */
-  if (JUMP_P (insn))
-    mips_sim_issue_nop (state);
+  const struct mips_builtin_description *d;
+  const struct mips_bdesc_map *m;
+  unsigned int offset;
 
-  switch (GET_CODE (SEQ_BEGIN (insn)))
+  /* Iterate through all of the bdesc arrays, initializing all of the
+     builtin functions.  */
+  offset = 0;
+  for (m = mips_bdesc_arrays;
+       m < &mips_bdesc_arrays[ARRAY_SIZE (mips_bdesc_arrays)];
+       m++)
     {
-    case CODE_LABEL:
-    case CALL_INSN:
-      /* We can't predict the processor state after a call or label.  */
-      mips_sim_reset (state);
+      if ((m->proc == PROCESSOR_MAX || m->proc == mips_arch)
+         && (m->unsupported_target_flags & target_flags) == 0)
+       for (d = m->bdesc; d < &m->bdesc[m->size]; d++)
+         if ((d->target_flags & target_flags) == d->target_flags)
+           add_builtin_function (d->name,
+                                 mips_build_function_type (d->function_type),
+                                 d - m->bdesc + offset,
+                                 BUILT_IN_MD, NULL, NULL);
+      offset += m->size;
+    }
+}
+
+/* Take argument ARGNO from EXP's argument list and convert it into a
+   form suitable for input operand OPNO of instruction ICODE.  Return the
+   value.  */
+
+static rtx
+mips_prepare_builtin_arg (enum insn_code icode,
+                         unsigned int opno, tree exp, unsigned int argno)
+{
+  rtx value;
+  enum machine_mode mode;
+
+  value = expand_normal (CALL_EXPR_ARG (exp, argno));
+  mode = insn_data[icode].operand[opno].mode;
+  if (!insn_data[icode].operand[opno].predicate (value, mode))
+    {
+      value = copy_to_mode_reg (mode, value);
+      /* Check the predicate again.  */
+      if (!insn_data[icode].operand[opno].predicate (value, mode))
+       {
+         error ("invalid argument to built-in function");
+         return const0_rtx;
+       }
+    }
+
+  return value;
+}
+
+/* Return an rtx suitable for output operand OP of instruction ICODE.
+   If TARGET is non-null, try to use it where possible.  */
+
+static rtx
+mips_prepare_builtin_target (enum insn_code icode, unsigned int op, rtx target)
+{
+  enum machine_mode mode;
+
+  mode = insn_data[icode].operand[op].mode;
+  if (target == 0 || !insn_data[icode].operand[op].predicate (target, mode))
+    target = gen_reg_rtx (mode);
+
+  return target;
+}
+
+/* Expand a MIPS_BUILTIN_DIRECT or MIPS_BUILTIN_DIRECT_NO_TARGET function;
+   HAS_TARGET_P says which.  EXP is the CALL_EXPR that calls the function
+   and ICODE is the code of the associated .md pattern.  TARGET, if nonnull,
+   suggests a good place to put the result.  */
+
+static rtx
+mips_expand_builtin_direct (enum insn_code icode, rtx target, tree exp,
+                           bool has_target_p)
+{
+  rtx ops[MAX_RECOG_OPERANDS];
+  int opno, argno;
+
+  /* Map any target to operand 0.  */
+  opno = 0;
+  if (has_target_p)
+    {
+      ops[opno] = mips_prepare_builtin_target (icode, opno, target);
+      opno++;
+    }
+
+  /* Map the arguments to the other operands.  The n_operands value
+     for an expander includes match_dups and match_scratches as well as
+     match_operands, so n_operands is only an upper bound on the number
+     of arguments to the expander function.  */
+  gcc_assert (opno + call_expr_nargs (exp) <= insn_data[icode].n_operands);
+  for (argno = 0; argno < call_expr_nargs (exp); argno++, opno++)
+    ops[opno] = mips_prepare_builtin_arg (icode, opno, exp, argno);
+
+  switch (opno)
+    {
+    case 2:
+      emit_insn (GEN_FCN (icode) (ops[0], ops[1]));
       break;
 
-    case JUMP_INSN:
-      /* The delay slots of branch likely instructions are only executed
-        when the branch is taken.  Therefore, if the caller has simulated
-        the delay slot instruction, STATE does not really reflect the state
-        of the pipeline for the instruction after the delay slot.  Also,
-        branch likely instructions tend to incur a penalty when not taken,
-        so there will probably be an extra delay between the branch and
-        the instruction after the delay slot.  */
-      if (INSN_ANNULLED_BRANCH_P (SEQ_BEGIN (insn)))
-       mips_sim_reset (state);
+    case 3:
+      emit_insn (GEN_FCN (icode) (ops[0], ops[1], ops[2]));
       break;
 
-    default:
+    case 4:
+      emit_insn (GEN_FCN (icode) (ops[0], ops[1], ops[2], ops[3]));
       break;
+
+    default:
+      gcc_unreachable ();
     }
+  return target;
 }
-\f
-/* The VR4130 pipeline issues aligned pairs of instructions together,
-   but it stalls the second instruction if it depends on the first.
-   In order to cut down the amount of logic required, this dependence
-   check is not based on a full instruction decode.  Instead, any non-SPECIAL
-   instruction is assumed to modify the register specified by bits 20-16
-   (which is usually the "rt" field).
 
-   In beq, beql, bne and bnel instructions, the rt field is actually an
-   input, so we can end up with a false dependence between the branch
-   and its delay slot.  If this situation occurs in instruction INSN,
-   try to avoid it by swapping rs and rt.  */
+/* Expand a __builtin_mips_movt_*_ps or __builtin_mips_movf_*_ps
+   function; TYPE says which.  EXP is the CALL_EXPR that calls the
+   function, ICODE is the instruction that should be used to compare
+   the first two arguments, and COND is the condition it should test.
+   TARGET, if nonnull, suggests a good place to put the result.  */
 
-static void
-vr4130_avoid_branch_rt_conflict (rtx insn)
+static rtx
+mips_expand_builtin_movtf (enum mips_builtin_type type,
+                          enum insn_code icode, enum mips_fp_condition cond,
+                          rtx target, tree exp)
 {
-  rtx first, second;
+  rtx cmp_result, op0, op1;
 
-  first = SEQ_BEGIN (insn);
-  second = SEQ_END (insn);
-  if (JUMP_P (first)
-      && NONJUMP_INSN_P (second)
-      && GET_CODE (PATTERN (first)) == SET
-      && GET_CODE (SET_DEST (PATTERN (first))) == PC
-      && GET_CODE (SET_SRC (PATTERN (first))) == IF_THEN_ELSE)
+  cmp_result = mips_prepare_builtin_target (icode, 0, 0);
+  op0 = mips_prepare_builtin_arg (icode, 1, exp, 0);
+  op1 = mips_prepare_builtin_arg (icode, 2, exp, 1);
+  emit_insn (GEN_FCN (icode) (cmp_result, op0, op1, GEN_INT (cond)));
+
+  icode = CODE_FOR_mips_cond_move_tf_ps;
+  target = mips_prepare_builtin_target (icode, 0, target);
+  if (type == MIPS_BUILTIN_MOVT)
     {
-      /* Check for the right kind of condition.  */
-      rtx cond = XEXP (SET_SRC (PATTERN (first)), 0);
-      if ((GET_CODE (cond) == EQ || GET_CODE (cond) == NE)
-         && REG_P (XEXP (cond, 0))
-         && REG_P (XEXP (cond, 1))
-         && reg_referenced_p (XEXP (cond, 1), PATTERN (second))
-         && !reg_referenced_p (XEXP (cond, 0), PATTERN (second)))
-       {
-         /* SECOND mentions the rt register but not the rs register.  */
-         rtx tmp = XEXP (cond, 0);
-         XEXP (cond, 0) = XEXP (cond, 1);
-         XEXP (cond, 1) = tmp;
-       }
+      op1 = mips_prepare_builtin_arg (icode, 2, exp, 2);
+      op0 = mips_prepare_builtin_arg (icode, 1, exp, 3);
+    }
+  else
+    {
+      op0 = mips_prepare_builtin_arg (icode, 1, exp, 2);
+      op1 = mips_prepare_builtin_arg (icode, 2, exp, 3);
+    }
+  emit_insn (gen_mips_cond_move_tf_ps (target, op0, op1, cmp_result));
+  return target;
+}
+
+/* Move VALUE_IF_TRUE into TARGET if CONDITION is true; move VALUE_IF_FALSE
+   into TARGET otherwise.  Return TARGET.  */
+
+static rtx
+mips_builtin_branch_and_move (rtx condition, rtx target,
+                             rtx value_if_true, rtx value_if_false)
+{
+  rtx true_label, done_label;
+
+  true_label = gen_label_rtx ();
+  done_label = gen_label_rtx ();
+
+  /* First assume that CONDITION is false.  */
+  mips_emit_move (target, value_if_false);
+
+  /* Branch to TRUE_LABEL if CONDITION is true and DONE_LABEL otherwise.  */
+  emit_jump_insn (gen_condjump (condition, true_label));
+  emit_jump_insn (gen_jump (done_label));
+  emit_barrier ();
+
+  /* Fix TARGET if CONDITION is true.  */
+  emit_label (true_label);
+  mips_emit_move (target, value_if_true);
+
+  emit_label (done_label);
+  return target;
+}
+
+/* Expand a comparison built-in function of type BUILTIN_TYPE.  EXP is
+   the CALL_EXPR that calls the function, ICODE is the code of the
+   comparison instruction, and COND is the condition it should test.
+   TARGET, if nonnull, suggests a good place to put the boolean result.  */
+
+static rtx
+mips_expand_builtin_compare (enum mips_builtin_type builtin_type,
+                            enum insn_code icode, enum mips_fp_condition cond,
+                            rtx target, tree exp)
+{
+  rtx offset, condition, cmp_result, args[MAX_RECOG_OPERANDS];
+  int argno;
+
+  if (target == 0 || GET_MODE (target) != SImode)
+    target = gen_reg_rtx (SImode);
+
+  /* The instruction should have a target operand, an operand for each
+     argument, and an operand for COND.  */
+  gcc_assert (call_expr_nargs (exp) + 2 == insn_data[icode].n_operands);
+
+  /* Prepare the operands to the comparison.  */
+  cmp_result = mips_prepare_builtin_target (icode, 0, 0);
+  for (argno = 0; argno < call_expr_nargs (exp); argno++)
+    args[argno] = mips_prepare_builtin_arg (icode, argno + 1, exp, argno);
+
+  switch (insn_data[icode].n_operands)
+    {
+    case 4:
+      emit_insn (GEN_FCN (icode) (cmp_result, args[0], args[1],
+                                 GEN_INT (cond)));
+      break;
+
+    case 6:
+      emit_insn (GEN_FCN (icode) (cmp_result, args[0], args[1],
+                                 args[2], args[3], GEN_INT (cond)));
+      break;
+
+    default:
+      gcc_unreachable ();
+    }
+
+  /* If the comparison sets more than one register, we define the result
+     to be 0 if all registers are false and -1 if all registers are true.
+     The value of the complete result is indeterminate otherwise.  */
+  switch (builtin_type)
+    {
+    case MIPS_BUILTIN_CMP_ALL:
+      condition = gen_rtx_NE (VOIDmode, cmp_result, constm1_rtx);
+      return mips_builtin_branch_and_move (condition, target,
+                                          const0_rtx, const1_rtx);
+
+    case MIPS_BUILTIN_CMP_UPPER:
+    case MIPS_BUILTIN_CMP_LOWER:
+      offset = GEN_INT (builtin_type == MIPS_BUILTIN_CMP_UPPER);
+      condition = gen_single_cc (cmp_result, offset);
+      return mips_builtin_branch_and_move (condition, target,
+                                          const1_rtx, const0_rtx);
+
+    default:
+      condition = gen_rtx_NE (VOIDmode, cmp_result, const0_rtx);
+      return mips_builtin_branch_and_move (condition, target,
+                                          const1_rtx, const0_rtx);
     }
 }
 
-/* Implement -mvr4130-align.  Go through each basic block and simulate the
-   processor pipeline.  If we find that a pair of instructions could execute
-   in parallel, and the first of those instruction is not 8-byte aligned,
-   insert a nop to make it aligned.  */
+/* Expand a bposge built-in function of type BUILTIN_TYPE.  TARGET,
+   if nonnull, suggests a good place to put the boolean result.  */
 
-static void
-vr4130_align_insns (void)
+static rtx
+mips_expand_builtin_bposge (enum mips_builtin_type builtin_type, rtx target)
 {
-  struct mips_sim state;
-  rtx insn, subinsn, last, last2, next;
-  bool aligned_p;
+  rtx condition, cmp_result;
+  int cmp_value;
 
-  dfa_start ();
+  if (target == 0 || GET_MODE (target) != SImode)
+    target = gen_reg_rtx (SImode);
 
-  /* LAST is the last instruction before INSN to have a nonzero length.
-     LAST2 is the last such instruction before LAST.  */
-  last = 0;
-  last2 = 0;
+  cmp_result = gen_rtx_REG (CCDSPmode, CCDSP_PO_REGNUM);
 
-  /* ALIGNED_P is true if INSN is known to be at an aligned address.  */
-  aligned_p = true;
+  if (builtin_type == MIPS_BUILTIN_BPOSGE32)
+    cmp_value = 32;
+  else
+    gcc_assert (0);
 
-  mips_sim_init (&state, alloca (state_size ()));
-  for (insn = get_insns (); insn != 0; insn = next)
-    {
-      unsigned int length;
+  condition = gen_rtx_GE (VOIDmode, cmp_result, GEN_INT (cmp_value));
+  return mips_builtin_branch_and_move (condition, target,
+                                      const1_rtx, const0_rtx);
+}
 
-      next = NEXT_INSN (insn);
+/* EXP is a CALL_EXPR that calls the function described by BDESC.
+   Expand the call and return an rtx for its return value.
+   TARGET, if nonnull, suggests a good place to put this value.  */
 
-      /* See the comment above vr4130_avoid_branch_rt_conflict for details.
-        This isn't really related to the alignment pass, but we do it on
-        the fly to avoid a separate instruction walk.  */
-      vr4130_avoid_branch_rt_conflict (insn);
+static rtx
+mips_expand_builtin_1 (const struct mips_builtin_description *bdesc,
+                      tree exp, rtx target)
+{
+  switch (bdesc->builtin_type)
+    {
+    case MIPS_BUILTIN_DIRECT:
+      return mips_expand_builtin_direct (bdesc->icode, target, exp, true);
 
-      if (USEFUL_INSN_P (insn))
-       FOR_EACH_SUBINSN (subinsn, insn)
-         {
-           mips_sim_wait_insn (&state, subinsn);
+    case MIPS_BUILTIN_DIRECT_NO_TARGET:
+      return mips_expand_builtin_direct (bdesc->icode, target, exp, false);
 
-           /* If we want this instruction to issue in parallel with the
-              previous one, make sure that the previous instruction is
-              aligned.  There are several reasons why this isn't worthwhile
-              when the second instruction is a call:
+    case MIPS_BUILTIN_MOVT:
+    case MIPS_BUILTIN_MOVF:
+      return mips_expand_builtin_movtf (bdesc->builtin_type, bdesc->icode,
+                                       bdesc->cond, target, exp);
 
-                 - Calls are less likely to be performance critical,
-                 - There's a good chance that the delay slot can execute
-                   in parallel with the call.
-                 - The return address would then be unaligned.
+    case MIPS_BUILTIN_CMP_ANY:
+    case MIPS_BUILTIN_CMP_ALL:
+    case MIPS_BUILTIN_CMP_UPPER:
+    case MIPS_BUILTIN_CMP_LOWER:
+    case MIPS_BUILTIN_CMP_SINGLE:
+      return mips_expand_builtin_compare (bdesc->builtin_type, bdesc->icode,
+                                         bdesc->cond, target, exp);
 
-              In general, if we're going to insert a nop between instructions
-              X and Y, it's better to insert it immediately after X.  That
-              way, if the nop makes Y aligned, it will also align any labels
-              between X and Y.  */
-           if (state.insns_left != state.issue_rate
-               && !CALL_P (subinsn))
-             {
-               if (subinsn == SEQ_BEGIN (insn) && aligned_p)
-                 {
-                   /* SUBINSN is the first instruction in INSN and INSN is
-                      aligned.  We want to align the previous instruction
-                      instead, so insert a nop between LAST2 and LAST.
+    case MIPS_BUILTIN_BPOSGE32:
+      return mips_expand_builtin_bposge (bdesc->builtin_type, target);
+    }
+  gcc_unreachable ();
+}
 
-                      Note that LAST could be either a single instruction
-                      or a branch with a delay slot.  In the latter case,
-                      LAST, like INSN, is already aligned, but the delay
-                      slot must have some extra delay that stops it from
-                      issuing at the same time as the branch.  We therefore
-                      insert a nop before the branch in order to align its
-                      delay slot.  */
-                   emit_insn_after (gen_nop (), last2);
-                   aligned_p = false;
-                 }
-               else if (subinsn != SEQ_BEGIN (insn) && !aligned_p)
-                 {
-                   /* SUBINSN is the delay slot of INSN, but INSN is
-                      currently unaligned.  Insert a nop between
-                      LAST and INSN to align it.  */
-                   emit_insn_after (gen_nop (), last);
-                   aligned_p = true;
-                 }
-             }
-           mips_sim_issue_insn (&state, subinsn);
-         }
-      mips_sim_finish_insn (&state, insn);
+/* Implement TARGET_EXPAND_BUILTIN.  */
 
-      /* Update LAST, LAST2 and ALIGNED_P for the next instruction.  */
-      length = get_attr_length (insn);
-      if (length > 0)
-       {
-         /* If the instruction is an asm statement or multi-instruction
-            mips.md patern, the length is only an estimate.  Insert an
-            8 byte alignment after it so that the following instructions
-            can be handled correctly.  */
-         if (NONJUMP_INSN_P (SEQ_BEGIN (insn))
-             && (recog_memoized (insn) < 0 || length >= 8))
-           {
-             next = emit_insn_after (gen_align (GEN_INT (3)), insn);
-             next = NEXT_INSN (next);
-             mips_sim_next_cycle (&state);
-             aligned_p = true;
-           }
-         else if (length & 4)
-           aligned_p = !aligned_p;
-         last2 = last;
-         last = insn;
-       }
+static rtx
+mips_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
+                    enum machine_mode mode ATTRIBUTE_UNUSED,
+                    int ignore ATTRIBUTE_UNUSED)
+{
+  tree fndecl;
+  unsigned int fcode;
+  const struct mips_bdesc_map *m;
 
-      /* See whether INSN is an aligned label.  */
-      if (LABEL_P (insn) && label_to_alignment (insn) >= 3)
-       aligned_p = true;
+  fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
+  fcode = DECL_FUNCTION_CODE (fndecl);
+  if (TARGET_MIPS16)
+    {
+      error ("built-in function %qs not supported for MIPS16",
+            IDENTIFIER_POINTER (DECL_NAME (fndecl)));
+      return const0_rtx;
     }
-  dfa_finish ();
+
+  for (m = mips_bdesc_arrays;
+       m < &mips_bdesc_arrays[ARRAY_SIZE (mips_bdesc_arrays)];
+       m++)
+    {
+      if (fcode < m->size)
+       return mips_expand_builtin_1 (m->bdesc + fcode, exp, target);
+      fcode -= m->size;
+    }
+  gcc_unreachable ();
 }
 \f
-/* Subroutine of mips_reorg.  If there is a hazard between INSN
-   and a previous instruction, avoid it by inserting nops after
-   instruction AFTER.
-
-   *DELAYED_REG and *HILO_DELAY describe the hazards that apply at
-   this point.  If *DELAYED_REG is non-null, INSN must wait a cycle
-   before using the value of that register.  *HILO_DELAY counts the
-   number of instructions since the last hilo hazard (that is,
-   the number of instructions since the last mflo or mfhi).
+/* An entry in the MIPS16 constant pool.  VALUE is the pool constant,
+   MODE is its mode, and LABEL is the CODE_LABEL associated with it.  */
+struct mips16_constant {
+  struct mips16_constant *next;
+  rtx value;
+  rtx label;
+  enum machine_mode mode;
+};
 
-   After inserting nops for INSN, update *DELAYED_REG and *HILO_DELAY
-   for the next instruction.
+/* Information about an incomplete MIPS16 constant pool.  FIRST is the
+   first constant, HIGHEST_ADDRESS is the highest address that the first
+   byte of the pool can have, and INSN_ADDRESS is the current instruction
+   address.  */
+struct mips16_constant_pool {
+  struct mips16_constant *first;
+  int highest_address;
+  int insn_address;
+};
 
-   LO_REG is an rtx for the LO register, used in dependence checking.  */
+/* Add constant VALUE to POOL and return its label.  MODE is the
+   value's mode (used for CONST_INTs, etc.).  */
 
-static void
-mips_avoid_hazard (rtx after, rtx insn, int *hilo_delay,
-                  rtx *delayed_reg, rtx lo_reg)
+static rtx
+mips16_add_constant (struct mips16_constant_pool *pool,
+                    rtx value, enum machine_mode mode)
 {
-  rtx pattern, set;
-  int nops, ninsns;
+  struct mips16_constant **p, *c;
+  bool first_of_size_p;
 
-  if (!INSN_P (insn))
-    return;
+  /* See whether the constant is already in the pool.  If so, return the
+     existing label, otherwise leave P pointing to the place where the
+     constant should be added.
 
-  pattern = PATTERN (insn);
+     Keep the pool sorted in increasing order of mode size so that we can
+     reduce the number of alignments needed.  */
+  first_of_size_p = true;
+  for (p = &pool->first; *p != 0; p = &(*p)->next)
+    {
+      if (mode == (*p)->mode && rtx_equal_p (value, (*p)->value))
+       return (*p)->label;
+      if (GET_MODE_SIZE (mode) < GET_MODE_SIZE ((*p)->mode))
+       break;
+      if (GET_MODE_SIZE (mode) == GET_MODE_SIZE ((*p)->mode))
+       first_of_size_p = false;
+    }
 
-  /* Do not put the whole function in .set noreorder if it contains
-     an asm statement.  We don't know whether there will be hazards
-     between the asm statement and the gcc-generated code.  */
-  if (GET_CODE (pattern) == ASM_INPUT || asm_noperands (pattern) >= 0)
-    cfun->machine->all_noreorder_p = false;
+  /* In the worst case, the constant needed by the earliest instruction
+     will end up at the end of the pool.  The entire pool must then be
+     accessible from that instruction.
 
-  /* Ignore zero-length instructions (barriers and the like).  */
-  ninsns = get_attr_length (insn) / 4;
-  if (ninsns == 0)
-    return;
+     When adding the first constant, set the pool's highest address to
+     the address of the first out-of-range byte.  Adjust this address
+     downwards each time a new constant is added.  */
+  if (pool->first == 0)
+    /* For LWPC, ADDIUPC and DADDIUPC, the base PC value is the address
+       of the instruction with the lowest two bits clear.  The base PC
+       value for LDPC has the lowest three bits clear.  Assume the worst
+       case here; namely that the PC-relative instruction occupies the
+       last 2 bytes in an aligned word.  */
+    pool->highest_address = pool->insn_address - (UNITS_PER_WORD - 2) + 0x8000;
+  pool->highest_address -= GET_MODE_SIZE (mode);
+  if (first_of_size_p)
+    /* Take into account the worst possible padding due to alignment.  */
+    pool->highest_address -= GET_MODE_SIZE (mode) - 1;
 
-  /* Work out how many nops are needed.  Note that we only care about
-     registers that are explicitly mentioned in the instruction's pattern.
-     It doesn't matter that calls use the argument registers or that they
-     clobber hi and lo.  */
-  if (*hilo_delay < 2 && reg_set_p (lo_reg, pattern))
-    nops = 2 - *hilo_delay;
-  else if (*delayed_reg != 0 && reg_referenced_p (*delayed_reg, pattern))
-    nops = 1;
-  else
-    nops = 0;
+  /* Create a new entry.  */
+  c = XNEW (struct mips16_constant);
+  c->value = value;
+  c->mode = mode;
+  c->label = gen_label_rtx ();
+  c->next = *p;
+  *p = c;
+
+  return c->label;
+}
+
+/* Output constant VALUE after instruction INSN and return the last
+   instruction emitted.  MODE is the mode of the constant.  */
+
+static rtx
+mips16_emit_constants_1 (enum machine_mode mode, rtx value, rtx insn)
+{
+  if (SCALAR_INT_MODE_P (mode) || ALL_SCALAR_FIXED_POINT_MODE_P (mode))
+    {
+      rtx size = GEN_INT (GET_MODE_SIZE (mode));
+      return emit_insn_after (gen_consttable_int (value, size), insn);
+    }
 
-  /* Insert the nops between this instruction and the previous one.
-     Each new nop takes us further from the last hilo hazard.  */
-  *hilo_delay += nops;
-  while (nops-- > 0)
-    emit_insn_after (gen_hazard_nop (), after);
+  if (SCALAR_FLOAT_MODE_P (mode))
+    return emit_insn_after (gen_consttable_float (value), insn);
 
-  /* Set up the state for the next instruction.  */
-  *hilo_delay += ninsns;
-  *delayed_reg = 0;
-  if (INSN_CODE (insn) >= 0)
-    switch (get_attr_hazard (insn))
-      {
-      case HAZARD_NONE:
-       break;
+  if (VECTOR_MODE_P (mode))
+    {
+      int i;
 
-      case HAZARD_HILO:
-       *hilo_delay = 0;
-       break;
+      for (i = 0; i < CONST_VECTOR_NUNITS (value); i++)
+       insn = mips16_emit_constants_1 (GET_MODE_INNER (mode),
+                                       CONST_VECTOR_ELT (value, i), insn);
+      return insn;
+    }
 
-      case HAZARD_DELAY:
-       set = single_set (insn);
-       gcc_assert (set != 0);
-       *delayed_reg = SET_DEST (set);
-       break;
-      }
+  gcc_unreachable ();
 }
 
-
-/* Go through the instruction stream and insert nops where necessary.
-   See if the whole function can then be put into .set noreorder &
-   .set nomacro.  */
+/* Dump out the constants in CONSTANTS after INSN.  */
 
 static void
-mips_avoid_hazards (void)
+mips16_emit_constants (struct mips16_constant *constants, rtx insn)
 {
-  rtx insn, last_insn, lo_reg, delayed_reg;
-  int hilo_delay, i;
-
-  /* Force all instructions to be split into their final form.  */
-  split_all_insns_noflow ();
-
-  /* Recalculate instruction lengths without taking nops into account.  */
-  cfun->machine->ignore_hazard_length_p = true;
-  shorten_branches (get_insns ());
+  struct mips16_constant *c, *next;
+  int align;
 
-  cfun->machine->all_noreorder_p = true;
+  align = 0;
+  for (c = constants; c != NULL; c = next)
+    {
+      /* If necessary, increase the alignment of PC.  */
+      if (align < GET_MODE_SIZE (c->mode))
+       {
+         int align_log = floor_log2 (GET_MODE_SIZE (c->mode));
+         insn = emit_insn_after (gen_align (GEN_INT (align_log)), insn);
+       }
+      align = GET_MODE_SIZE (c->mode);
 
-  /* Profiled functions can't be all noreorder because the profiler
-     support uses assembler macros.  */
-  if (current_function_profile)
-    cfun->machine->all_noreorder_p = false;
+      insn = emit_label_after (c->label, insn);
+      insn = mips16_emit_constants_1 (c->mode, c->value, insn);
 
-  /* Code compiled with -mfix-vr4120 can't be all noreorder because
-     we rely on the assembler to work around some errata.  */
-  if (TARGET_FIX_VR4120)
-    cfun->machine->all_noreorder_p = false;
+      next = c->next;
+      free (c);
+    }
 
-  /* The same is true for -mfix-vr4130 if we might generate mflo or
-     mfhi instructions.  Note that we avoid using mflo and mfhi if
-     the VR4130 macc and dmacc instructions are available instead;
-     see the *mfhilo_{si,di}_macc patterns.  */
-  if (TARGET_FIX_VR4130 && !ISA_HAS_MACCHI)
-    cfun->machine->all_noreorder_p = false;
+  emit_barrier_after (insn);
+}
 
-  last_insn = 0;
-  hilo_delay = 2;
-  delayed_reg = 0;
-  lo_reg = gen_rtx_REG (SImode, LO_REGNUM);
+/* Return the length of instruction INSN.  */
 
-  for (insn = get_insns (); insn != 0; insn = NEXT_INSN (insn))
-    if (INSN_P (insn))
-      {
-       if (GET_CODE (PATTERN (insn)) == SEQUENCE)
-         for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
-           mips_avoid_hazard (last_insn, XVECEXP (PATTERN (insn), 0, i),
-                              &hilo_delay, &delayed_reg, lo_reg);
-       else
-         mips_avoid_hazard (last_insn, insn, &hilo_delay,
-                            &delayed_reg, lo_reg);
-
-       last_insn = insn;
-      }
+static int
+mips16_insn_length (rtx insn)
+{
+  if (JUMP_P (insn))
+    {
+      rtx body = PATTERN (insn);
+      if (GET_CODE (body) == ADDR_VEC)
+       return GET_MODE_SIZE (GET_MODE (body)) * XVECLEN (body, 0);
+      if (GET_CODE (body) == ADDR_DIFF_VEC)
+       return GET_MODE_SIZE (GET_MODE (body)) * XVECLEN (body, 1);
+    }
+  return get_attr_length (insn);
 }
 
-
-/* Implement TARGET_MACHINE_DEPENDENT_REORG.  */
+/* If *X is a symbolic constant that refers to the constant pool, add
+   the constant to POOL and rewrite *X to use the constant's label.  */
 
 static void
-mips_reorg (void)
+mips16_rewrite_pool_constant (struct mips16_constant_pool *pool, rtx *x)
 {
-  mips16_lay_out_constants ();
-  if (TARGET_EXPLICIT_RELOCS)
+  rtx base, offset, label;
+
+  split_const (*x, &base, &offset);
+  if (GET_CODE (base) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (base))
     {
-      if (mips_flag_delayed_branch)
-       dbr_schedule (get_insns ());
-      mips_avoid_hazards ();
-      if (TUNE_MIPS4130 && TARGET_VR4130_ALIGN)
-       vr4130_align_insns ();
+      label = mips16_add_constant (pool, get_pool_constant (base),
+                                  get_pool_mode (base));
+      base = gen_rtx_LABEL_REF (Pmode, label);
+      *x = mips_unspec_address_offset (base, offset, SYMBOL_PC_RELATIVE);
     }
 }
 
-/* This function does three things:
-
-   - Register the special divsi3 and modsi3 functions if -mfix-vr4120.
-   - Register the mips16 hardware floating point stubs.
-   - Register the gofast functions if selected using --enable-gofast.  */
+/* This structure is used to communicate with mips16_rewrite_pool_refs.
+   INSN is the instruction we're rewriting and POOL points to the current
+   constant pool.  */
+struct mips16_rewrite_pool_refs_info {
+  rtx insn;
+  struct mips16_constant_pool *pool;
+};
 
-#include "config/gofast.h"
+/* Rewrite *X so that constant pool references refer to the constant's
+   label instead.  DATA points to a mips16_rewrite_pool_refs_info
+   structure.  */
 
-static void
-mips_init_libfuncs (void)
+static int
+mips16_rewrite_pool_refs (rtx *x, void *data)
 {
-  if (TARGET_FIX_VR4120)
+  struct mips16_rewrite_pool_refs_info *info = data;
+
+  if (force_to_mem_operand (*x, Pmode))
     {
-      set_optab_libfunc (sdiv_optab, SImode, "__vr4120_divsi3");
-      set_optab_libfunc (smod_optab, SImode, "__vr4120_modsi3");
+      rtx mem = force_const_mem (GET_MODE (*x), *x);
+      validate_change (info->insn, x, mem, false);
     }
 
-  if (TARGET_MIPS16 && TARGET_HARD_FLOAT_ABI)
+  if (MEM_P (*x))
     {
-      set_optab_libfunc (add_optab, SFmode, "__mips16_addsf3");
-      set_optab_libfunc (sub_optab, SFmode, "__mips16_subsf3");
-      set_optab_libfunc (smul_optab, SFmode, "__mips16_mulsf3");
-      set_optab_libfunc (sdiv_optab, SFmode, "__mips16_divsf3");
+      mips16_rewrite_pool_constant (info->pool, &XEXP (*x, 0));
+      return -1;
+    }
 
-      set_optab_libfunc (eq_optab, SFmode, "__mips16_eqsf2");
-      set_optab_libfunc (ne_optab, SFmode, "__mips16_nesf2");
-      set_optab_libfunc (gt_optab, SFmode, "__mips16_gtsf2");
-      set_optab_libfunc (ge_optab, SFmode, "__mips16_gesf2");
-      set_optab_libfunc (lt_optab, SFmode, "__mips16_ltsf2");
-      set_optab_libfunc (le_optab, SFmode, "__mips16_lesf2");
-      set_optab_libfunc (unord_optab, SFmode, "__mips16_unordsf2");
+  if (TARGET_MIPS16_TEXT_LOADS)
+    mips16_rewrite_pool_constant (info->pool, x);
 
-      set_conv_libfunc (sfix_optab, SImode, SFmode, "__mips16_fix_truncsfsi");
-      set_conv_libfunc (sfloat_optab, SFmode, SImode, "__mips16_floatsisf");
-      set_conv_libfunc (ufloat_optab, SFmode, SImode, "__mips16_floatunsisf");
+  return GET_CODE (*x) == CONST ? -1 : 0;
+}
 
-      if (TARGET_DOUBLE_FLOAT)
+/* Build MIPS16 constant pools.  */
+
+static void
+mips16_lay_out_constants (void)
+{
+  struct mips16_constant_pool pool;
+  struct mips16_rewrite_pool_refs_info info;
+  rtx insn, barrier;
+
+  if (!TARGET_MIPS16_PCREL_LOADS)
+    return;
+
+  barrier = 0;
+  memset (&pool, 0, sizeof (pool));
+  for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
+    {
+      /* Rewrite constant pool references in INSN.  */
+      if (INSN_P (insn))
        {
-         set_optab_libfunc (add_optab, DFmode, "__mips16_adddf3");
-         set_optab_libfunc (sub_optab, DFmode, "__mips16_subdf3");
-         set_optab_libfunc (smul_optab, DFmode, "__mips16_muldf3");
-         set_optab_libfunc (sdiv_optab, DFmode, "__mips16_divdf3");
+         info.insn = insn;
+         info.pool = &pool;
+         for_each_rtx (&PATTERN (insn), mips16_rewrite_pool_refs, &info);
+       }
 
-         set_optab_libfunc (eq_optab, DFmode, "__mips16_eqdf2");
-         set_optab_libfunc (ne_optab, DFmode, "__mips16_nedf2");
-         set_optab_libfunc (gt_optab, DFmode, "__mips16_gtdf2");
-         set_optab_libfunc (ge_optab, DFmode, "__mips16_gedf2");
-         set_optab_libfunc (lt_optab, DFmode, "__mips16_ltdf2");
-         set_optab_libfunc (le_optab, DFmode, "__mips16_ledf2");
-         set_optab_libfunc (unord_optab, DFmode, "__mips16_unorddf2");
+      pool.insn_address += mips16_insn_length (insn);
+
+      if (pool.first != NULL)
+       {
+         /* If there are no natural barriers between the first user of
+            the pool and the highest acceptable address, we'll need to
+            create a new instruction to jump around the constant pool.
+            In the worst case, this instruction will be 4 bytes long.
+
+            If it's too late to do this transformation after INSN,
+            do it immediately before INSN.  */
+         if (barrier == 0 && pool.insn_address + 4 > pool.highest_address)
+           {
+             rtx label, jump;
+
+             label = gen_label_rtx ();
+
+             jump = emit_jump_insn_before (gen_jump (label), insn);
+             JUMP_LABEL (jump) = label;
+             LABEL_NUSES (label) = 1;
+             barrier = emit_barrier_after (jump);
 
-         set_conv_libfunc (sext_optab, DFmode, SFmode, "__mips16_extendsfdf2");
-         set_conv_libfunc (trunc_optab, SFmode, DFmode, "__mips16_truncdfsf2");
+             emit_label_after (label, barrier);
+             pool.insn_address += 4;
+           }
 
-         set_conv_libfunc (sfix_optab, SImode, DFmode, "__mips16_fix_truncdfsi");
-         set_conv_libfunc (sfloat_optab, DFmode, SImode, "__mips16_floatsidf");
-         set_conv_libfunc (ufloat_optab, DFmode, SImode, "__mips16_floatunsidf");
+         /* See whether the constant pool is now out of range of the first
+            user.  If so, output the constants after the previous barrier.
+            Note that any instructions between BARRIER and INSN (inclusive)
+            will use negative offsets to refer to the pool.  */
+         if (pool.insn_address > pool.highest_address)
+           {
+             mips16_emit_constants (pool.first, barrier);
+             pool.first = NULL;
+             barrier = 0;
+           }
+         else if (BARRIER_P (insn))
+           barrier = insn;
        }
     }
-  else
-    gofast_maybe_init_libfuncs ();
+  mips16_emit_constants (pool.first, get_last_insn ());
+}
+\f
+/* A temporary variable used by for_each_rtx callbacks, etc.  */
+static rtx mips_sim_insn;
+
+/* A structure representing the state of the processor pipeline.
+   Used by the mips_sim_* family of functions.  */
+struct mips_sim {
+  /* The maximum number of instructions that can be issued in a cycle.
+     (Caches mips_issue_rate.)  */
+  unsigned int issue_rate;
+
+  /* The current simulation time.  */
+  unsigned int time;
+
+  /* How many more instructions can be issued in the current cycle.  */
+  unsigned int insns_left;
+
+  /* LAST_SET[X].INSN is the last instruction to set register X.
+     LAST_SET[X].TIME is the time at which that instruction was issued.
+     INSN is null if no instruction has yet set register X.  */
+  struct {
+    rtx insn;
+    unsigned int time;
+  } last_set[FIRST_PSEUDO_REGISTER];
+
+  /* The pipeline's current DFA state.  */
+  state_t dfa_state;
+};
+
+/* Reset STATE to the initial simulation state.  */
+
+static void
+mips_sim_reset (struct mips_sim *state)
+{
+  state->time = 0;
+  state->insns_left = state->issue_rate;
+  memset (&state->last_set, 0, sizeof (state->last_set));
+  state_reset (state->dfa_state);
 }
 
-/* Return a number assessing the cost of moving a register in class
-   FROM to class TO.  The classes are expressed using the enumeration
-   values such as `GENERAL_REGS'.  A value of 2 is the default; other
-   values are interpreted relative to that.
-
-   It is not required that the cost always equal 2 when FROM is the
-   same as TO; on some machines it is expensive to move between
-   registers if they are not general registers.
-
-   If reload sees an insn consisting of a single `set' between two
-   hard registers, and if `REGISTER_MOVE_COST' applied to their
-   classes returns a value of 2, reload does not check to ensure that
-   the constraints of the insn are met.  Setting a cost of other than
-   2 will allow reload to verify that the constraints are met.  You
-   should do this if the `movM' pattern's constraints do not allow
-   such copying.
-
-   ??? We make the cost of moving from HI/LO into general
-   registers the same as for one of moving general registers to
-   HI/LO for TARGET_MIPS16 in order to prevent allocating a
-   pseudo to HI/LO.  This might hurt optimizations though, it
-   isn't clear if it is wise.  And it might not work in all cases.  We
-   could solve the DImode LO reg problem by using a multiply, just
-   like reload_{in,out}si.  We could solve the SImode/HImode HI reg
-   problem by using divide instructions.  divu puts the remainder in
-   the HI reg, so doing a divide by -1 will move the value in the HI
-   reg for all values except -1.  We could handle that case by using a
-   signed divide, e.g.  -1 / 2 (or maybe 1 / -2?).  We'd have to emit
-   a compare/branch to test the input value to see which instruction
-   we need to use.  This gets pretty messy, but it is feasible.  */
+/* Initialize STATE before its first use.  DFA_STATE points to an
+   allocated but uninitialized DFA state.  */
 
-int
-mips_register_move_cost (enum machine_mode mode ATTRIBUTE_UNUSED,
-                        enum reg_class to, enum reg_class from)
+static void
+mips_sim_init (struct mips_sim *state, state_t dfa_state)
 {
-  if (from == M16_REGS && reg_class_subset_p (to, GENERAL_REGS))
-    return 2;
-  else if (from == M16_NA_REGS && reg_class_subset_p (to, GENERAL_REGS))
-    return 2;
-  else if (reg_class_subset_p (from, GENERAL_REGS))
-    {
-      if (to == M16_REGS)
-       return 2;
-      else if (to == M16_NA_REGS)
-       return 2;
-      else if (reg_class_subset_p (to, GENERAL_REGS))
-       {
-         if (TARGET_MIPS16)
-           return 4;
-         else
-           return 2;
-       }
-      else if (to == FP_REGS)
-       return 4;
-      else if (reg_class_subset_p (to, ACC_REGS))
-       {
-         if (TARGET_MIPS16)
-           return 12;
-         else
-           return 6;
-       }
-      else if (reg_class_subset_p (to, ALL_COP_REGS))
-       {
-         return 5;
-       }
-    }
-  else if (from == FP_REGS)
-    {
-      if (reg_class_subset_p (to, GENERAL_REGS))
-       return 4;
-      else if (to == FP_REGS)
-       return 2;
-      else if (to == ST_REGS)
-       return 8;
-    }
-  else if (reg_class_subset_p (from, ACC_REGS))
-    {
-      if (reg_class_subset_p (to, GENERAL_REGS))
-       {
-         if (TARGET_MIPS16)
-           return 12;
-         else
-           return 6;
-       }
-    }
-  else if (from == ST_REGS && reg_class_subset_p (to, GENERAL_REGS))
-    return 4;
-  else if (reg_class_subset_p (from, ALL_COP_REGS))
-    {
-      return 5;
-    }
+  state->issue_rate = mips_issue_rate ();
+  state->dfa_state = dfa_state;
+  mips_sim_reset (state);
+}
 
-  /* Fall through.
-     ??? What cases are these? Shouldn't we return 2 here?  */
+/* Advance STATE by one clock cycle.  */
 
-  return 12;
+static void
+mips_sim_next_cycle (struct mips_sim *state)
+{
+  state->time++;
+  state->insns_left = state->issue_rate;
+  state_transition (state->dfa_state, 0);
 }
 
-/* Return the length of INSN.  LENGTH is the initial length computed by
-   attributes in the machine-description file.  */
+/* Advance simulation state STATE until instruction INSN can read
+   register REG.  */
 
-int
-mips_adjust_insn_length (rtx insn, int length)
+static void
+mips_sim_wait_reg (struct mips_sim *state, rtx insn, rtx reg)
 {
-  /* A unconditional jump has an unfilled delay slot if it is not part
-     of a sequence.  A conditional jump normally has a delay slot, but
-     does not on MIPS16.  */
-  if (CALL_P (insn) || (TARGET_MIPS16 ? simplejump_p (insn) : JUMP_P (insn)))
-    length += 4;
+  unsigned int regno, end_regno;
 
-  /* See how many nops might be needed to avoid hardware hazards.  */
-  if (!cfun->machine->ignore_hazard_length_p && INSN_CODE (insn) >= 0)
-    switch (get_attr_hazard (insn))
+  end_regno = END_REGNO (reg);
+  for (regno = REGNO (reg); regno < end_regno; regno++)
+    if (state->last_set[regno].insn != 0)
       {
-      case HAZARD_NONE:
-       break;
-
-      case HAZARD_DELAY:
-       length += 4;
-       break;
+       unsigned int t;
 
-      case HAZARD_HILO:
-       length += 8;
-       break;
-      }
+       t = (state->last_set[regno].time
+            + insn_latency (state->last_set[regno].insn, insn));
+       while (state->time < t)
+         mips_sim_next_cycle (state);
+    }
+}
 
-  /* All MIPS16 instructions are a measly two bytes.  */
-  if (TARGET_MIPS16)
-    length /= 2;
+/* A for_each_rtx callback.  If *X is a register, advance simulation state
+   DATA until mips_sim_insn can read the register's value.  */
 
-  return length;
+static int
+mips_sim_wait_regs_2 (rtx *x, void *data)
+{
+  if (REG_P (*x))
+    mips_sim_wait_reg (data, mips_sim_insn, *x);
+  return 0;
 }
 
+/* Call mips_sim_wait_regs_2 (R, DATA) for each register R mentioned in *X.  */
 
-/* Return an asm sequence to start a noat block and load the address
-   of a label into $1.  */
-
-const char *
-mips_output_load_label (void)
+static void
+mips_sim_wait_regs_1 (rtx *x, void *data)
 {
-  if (TARGET_EXPLICIT_RELOCS)
-    switch (mips_abi)
-      {
-      case ABI_N32:
-       return "%[lw\t%@,%%got_page(%0)(%+)\n\taddiu\t%@,%@,%%got_ofst(%0)";
+  for_each_rtx (x, mips_sim_wait_regs_2, data);
+}
 
-      case ABI_64:
-       return "%[ld\t%@,%%got_page(%0)(%+)\n\tdaddiu\t%@,%@,%%got_ofst(%0)";
+/* Advance simulation state STATE until all of INSN's register
+   dependencies are satisfied.  */
 
-      default:
-       if (ISA_HAS_LOAD_DELAY)
-         return "%[lw\t%@,%%got(%0)(%+)%#\n\taddiu\t%@,%@,%%lo(%0)";
-       return "%[lw\t%@,%%got(%0)(%+)\n\taddiu\t%@,%@,%%lo(%0)";
-      }
-  else
-    {
-      if (Pmode == DImode)
-       return "%[dla\t%@,%0";
-      else
-       return "%[la\t%@,%0";
-    }
+static void
+mips_sim_wait_regs (struct mips_sim *state, rtx insn)
+{
+  mips_sim_insn = insn;
+  note_uses (&PATTERN (insn), mips_sim_wait_regs_1, state);
 }
 
-/* Return the assembly code for INSN, which has the operands given by
-   OPERANDS, and which branches to OPERANDS[1] if some condition is true.
-   BRANCH_IF_TRUE is the asm template that should be used if OPERANDS[1]
-   is in range of a direct branch.  BRANCH_IF_FALSE is an inverted
-   version of BRANCH_IF_TRUE.  */
+/* Advance simulation state STATE until the units required by
+   instruction INSN are available.  */
 
-const char *
-mips_output_conditional_branch (rtx insn, rtx *operands,
-                               const char *branch_if_true,
-                               const char *branch_if_false)
+static void
+mips_sim_wait_units (struct mips_sim *state, rtx insn)
 {
-  unsigned int length;
-  rtx taken, not_taken;
+  state_t tmp_state;
 
-  length = get_attr_length (insn);
-  if (length <= 8)
-    {
-      /* Just a simple conditional branch.  */
-      mips_branch_likely = (final_sequence && INSN_ANNULLED_BRANCH_P (insn));
-      return branch_if_true;
-    }
+  tmp_state = alloca (state_size ());
+  while (state->insns_left == 0
+        || (memcpy (tmp_state, state->dfa_state, state_size ()),
+            state_transition (tmp_state, insn) >= 0))
+    mips_sim_next_cycle (state);
+}
 
-  /* Generate a reversed branch around a direct jump.  This fallback does
-     not use branch-likely instructions.  */
-  mips_branch_likely = false;
-  not_taken = gen_label_rtx ();
-  taken = operands[1];
+/* Advance simulation state STATE until INSN is ready to issue.  */
 
-  /* Generate the reversed branch to NOT_TAKEN.  */
-  operands[1] = not_taken;
-  output_asm_insn (branch_if_false, operands);
+static void
+mips_sim_wait_insn (struct mips_sim *state, rtx insn)
+{
+  mips_sim_wait_regs (state, insn);
+  mips_sim_wait_units (state, insn);
+}
 
-  /* If INSN has a delay slot, we must provide delay slots for both the
-     branch to NOT_TAKEN and the conditional jump.  We must also ensure
-     that INSN's delay slot is executed in the appropriate cases.  */
-  if (final_sequence)
-    {
-      /* This first delay slot will always be executed, so use INSN's
-        delay slot if is not annulled.  */
-      if (!INSN_ANNULLED_BRANCH_P (insn))
-       {
-         final_scan_insn (XVECEXP (final_sequence, 0, 1),
-                          asm_out_file, optimize, 1, NULL);
-         INSN_DELETED_P (XVECEXP (final_sequence, 0, 1)) = 1;
-       }
-      else
-       output_asm_insn ("nop", 0);
-      fprintf (asm_out_file, "\n");
-    }
+/* mips_sim_insn has just set X.  Update the LAST_SET array
+   in simulation state DATA.  */
 
-  /* Output the unconditional branch to TAKEN.  */
-  if (length <= 16)
-    output_asm_insn ("j\t%0%/", &taken);
-  else
-    {
-      output_asm_insn (mips_output_load_label (), &taken);
-      output_asm_insn ("jr\t%@%]%/", 0);
-    }
+static void
+mips_sim_record_set (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
+{
+  struct mips_sim *state;
 
-  /* Now deal with its delay slot; see above.  */
-  if (final_sequence)
+  state = data;
+  if (REG_P (x))
     {
-      /* This delay slot will only be executed if the branch is taken.
-        Use INSN's delay slot if is annulled.  */
-      if (INSN_ANNULLED_BRANCH_P (insn))
+      unsigned int regno, end_regno;
+
+      end_regno = END_REGNO (x);
+      for (regno = REGNO (x); regno < end_regno; regno++)
        {
-         final_scan_insn (XVECEXP (final_sequence, 0, 1),
-                          asm_out_file, optimize, 1, NULL);
-         INSN_DELETED_P (XVECEXP (final_sequence, 0, 1)) = 1;
+         state->last_set[regno].insn = mips_sim_insn;
+         state->last_set[regno].time = state->time;
        }
-      else
-       output_asm_insn ("nop", 0);
-      fprintf (asm_out_file, "\n");
     }
+}
 
-  /* Output NOT_TAKEN.  */
-  (*targetm.asm_out.internal_label) (asm_out_file, "L",
-                                    CODE_LABEL_NUMBER (not_taken));
-  return "";
+/* Issue instruction INSN in scheduler state STATE.  Assume that INSN
+   can issue immediately (i.e., that mips_sim_wait_insn has already
+   been called).  */
+
+static void
+mips_sim_issue_insn (struct mips_sim *state, rtx insn)
+{
+  state_transition (state->dfa_state, insn);
+  state->insns_left--;
+
+  mips_sim_insn = insn;
+  note_stores (PATTERN (insn), mips_sim_record_set, state);
 }
 
-/* Return the assembly code for INSN, which branches to OPERANDS[1]
-   if some ordered condition is true.  The condition is given by
-   OPERANDS[0] if !INVERTED_P, otherwise it is the inverse of
-   OPERANDS[0].  OPERANDS[2] is the comparison's first operand;
-   its second is always zero.  */
+/* Simulate issuing a NOP in state STATE.  */
+
+static void
+mips_sim_issue_nop (struct mips_sim *state)
+{
+  if (state->insns_left == 0)
+    mips_sim_next_cycle (state);
+  state->insns_left--;
+}
+
+/* Update simulation state STATE so that it's ready to accept the instruction
+   after INSN.  INSN should be part of the main rtl chain, not a member of a
+   SEQUENCE.  */
 
-const char *
-mips_output_order_conditional_branch (rtx insn, rtx *operands, bool inverted_p)
+static void
+mips_sim_finish_insn (struct mips_sim *state, rtx insn)
 {
-  const char *branch[2];
+  /* If INSN is a jump with an implicit delay slot, simulate a nop.  */
+  if (JUMP_P (insn))
+    mips_sim_issue_nop (state);
 
-  /* Make BRANCH[1] branch to OPERANDS[1] when the condition is true.
-     Make BRANCH[0] branch on the inverse condition.  */
-  switch (GET_CODE (operands[0]))
+  switch (GET_CODE (SEQ_BEGIN (insn)))
     {
-      /* These cases are equivalent to comparisons against zero.  */
-    case LEU:
-      inverted_p = !inverted_p;
-      /* Fall through.  */
-    case GTU:
-      branch[!inverted_p] = MIPS_BRANCH ("bne", "%2,%.,%1");
-      branch[inverted_p] = MIPS_BRANCH ("beq", "%2,%.,%1");
+    case CODE_LABEL:
+    case CALL_INSN:
+      /* We can't predict the processor state after a call or label.  */
+      mips_sim_reset (state);
       break;
 
-      /* These cases are always true or always false.  */
-    case LTU:
-      inverted_p = !inverted_p;
-      /* Fall through.  */
-    case GEU:
-      branch[!inverted_p] = MIPS_BRANCH ("beq", "%.,%.,%1");
-      branch[inverted_p] = MIPS_BRANCH ("bne", "%.,%.,%1");
+    case JUMP_INSN:
+      /* The delay slots of branch likely instructions are only executed
+        when the branch is taken.  Therefore, if the caller has simulated
+        the delay slot instruction, STATE does not really reflect the state
+        of the pipeline for the instruction after the delay slot.  Also,
+        branch likely instructions tend to incur a penalty when not taken,
+        so there will probably be an extra delay between the branch and
+        the instruction after the delay slot.  */
+      if (INSN_ANNULLED_BRANCH_P (SEQ_BEGIN (insn)))
+       mips_sim_reset (state);
       break;
 
     default:
-      branch[!inverted_p] = MIPS_BRANCH ("b%C0z", "%2,%1");
-      branch[inverted_p] = MIPS_BRANCH ("b%N0z", "%2,%1");
       break;
     }
-  return mips_output_conditional_branch (insn, operands, branch[1], branch[0]);
 }
 \f
-/* Used to output div or ddiv instruction DIVISION, which has the operands
-   given by OPERANDS.  Add in a divide-by-zero check if needed.
-
-   When working around R4000 and R4400 errata, we need to make sure that
-   the division is not immediately followed by a shift[1][2].  We also
-   need to stop the division from being put into a branch delay slot[3].
-   The easiest way to avoid both problems is to add a nop after the
-   division.  When a divide-by-zero check is needed, this nop can be
-   used to fill the branch delay slot.
-
-   [1] If a double-word or a variable shift executes immediately
-       after starting an integer division, the shift may give an
-       incorrect result.  See quotations of errata #16 and #28 from
-       "MIPS R4000PC/SC Errata, Processor Revision 2.2 and 3.0"
-       in mips.md for details.
-
-   [2] A similar bug to [1] exists for all revisions of the
-       R4000 and the R4400 when run in an MC configuration.
-       From "MIPS R4000MC Errata, Processor Revision 2.2 and 3.0":
-
-       "19. In this following sequence:
+/* The VR4130 pipeline issues aligned pairs of instructions together,
+   but it stalls the second instruction if it depends on the first.
+   In order to cut down the amount of logic required, this dependence
+   check is not based on a full instruction decode.  Instead, any non-SPECIAL
+   instruction is assumed to modify the register specified by bits 20-16
+   (which is usually the "rt" field).
 
-                   ddiv                (or ddivu or div or divu)
-                   dsll32              (or dsrl32, dsra32)
+   In BEQ, BEQL, BNE and BNEL instructions, the rt field is actually an
+   input, so we can end up with a false dependence between the branch
+   and its delay slot.  If this situation occurs in instruction INSN,
+   try to avoid it by swapping rs and rt.  */
 
-           if an MPT stall occurs, while the divide is slipping the cpu
-           pipeline, then the following double shift would end up with an
-           incorrect result.
+static void
+vr4130_avoid_branch_rt_conflict (rtx insn)
+{
+  rtx first, second;
 
-           Workaround: The compiler needs to avoid generating any
-           sequence with divide followed by extended double shift."
+  first = SEQ_BEGIN (insn);
+  second = SEQ_END (insn);
+  if (JUMP_P (first)
+      && NONJUMP_INSN_P (second)
+      && GET_CODE (PATTERN (first)) == SET
+      && GET_CODE (SET_DEST (PATTERN (first))) == PC
+      && GET_CODE (SET_SRC (PATTERN (first))) == IF_THEN_ELSE)
+    {
+      /* Check for the right kind of condition.  */
+      rtx cond = XEXP (SET_SRC (PATTERN (first)), 0);
+      if ((GET_CODE (cond) == EQ || GET_CODE (cond) == NE)
+         && REG_P (XEXP (cond, 0))
+         && REG_P (XEXP (cond, 1))
+         && reg_referenced_p (XEXP (cond, 1), PATTERN (second))
+         && !reg_referenced_p (XEXP (cond, 0), PATTERN (second)))
+       {
+         /* SECOND mentions the rt register but not the rs register.  */
+         rtx tmp = XEXP (cond, 0);
+         XEXP (cond, 0) = XEXP (cond, 1);
+         XEXP (cond, 1) = tmp;
+       }
+    }
+}
 
-       This erratum is also present in "MIPS R4400MC Errata, Processor
-       Revision 1.0" and "MIPS R4400MC Errata, Processor Revision 2.0
-       & 3.0" as errata #10 and #4, respectively.
+/* Implement -mvr4130-align.  Go through each basic block and simulate the
+   processor pipeline.  If we find that a pair of instructions could execute
+   in parallel, and the first of those instructions is not 8-byte aligned,
+   insert a nop to make it aligned.  */
 
-   [3] From "MIPS R4000PC/SC Errata, Processor Revision 2.2 and 3.0"
-       (also valid for MIPS R4000MC processors):
+static void
+vr4130_align_insns (void)
+{
+  struct mips_sim state;
+  rtx insn, subinsn, last, last2, next;
+  bool aligned_p;
 
-       "52. R4000SC: This bug does not apply for the R4000PC.
+  dfa_start ();
 
-           There are two flavors of this bug:
+  /* LAST is the last instruction before INSN to have a nonzero length.
+     LAST2 is the last such instruction before LAST.  */
+  last = 0;
+  last2 = 0;
 
-           1) If the instruction just after divide takes an RF exception
-              (tlb-refill, tlb-invalid) and gets an instruction cache
-              miss (both primary and secondary) and the line which is
-              currently in secondary cache at this index had the first
-              data word, where the bits 5..2 are set, then R4000 would
-              get a wrong result for the div.
+  /* ALIGNED_P is true if INSN is known to be at an aligned address.  */
+  aligned_p = true;
 
-           ##1
-                   nop
-                   div r8, r9
-                   -------------------         # end-of page. -tlb-refill
-                   nop
-           ##2
-                   nop
-                   div r8, r9
-                   -------------------         # end-of page. -tlb-invalid
-                   nop
+  mips_sim_init (&state, alloca (state_size ()));
+  for (insn = get_insns (); insn != 0; insn = next)
+    {
+      unsigned int length;
 
-           2) If the divide is in the taken branch delay slot, where the
-              target takes RF exception and gets an I-cache miss for the
-              exception vector or where I-cache miss occurs for the
-              target address, under the above mentioned scenarios, the
-              div would get wrong results.
+      next = NEXT_INSN (insn);
 
-           ##1
-                   j   r2              # to next page mapped or unmapped
-                   div r8,r9           # this bug would be there as long
-                                       # as there is an ICache miss and
-                   nop                 # the "data pattern" is present
+      /* See the comment above vr4130_avoid_branch_rt_conflict for details.
+        This isn't really related to the alignment pass, but we do it on
+        the fly to avoid a separate instruction walk.  */
+      vr4130_avoid_branch_rt_conflict (insn);
 
-           ##2
-                   beq r0, r0, NextPage        # to Next page
-                   div r8,r9
-                   nop
+      if (USEFUL_INSN_P (insn))
+       FOR_EACH_SUBINSN (subinsn, insn)
+         {
+           mips_sim_wait_insn (&state, subinsn);
 
-           This bug is present for div, divu, ddiv, and ddivu
-           instructions.
+           /* If we want this instruction to issue in parallel with the
+              previous one, make sure that the previous instruction is
+              aligned.  There are several reasons why this isn't worthwhile
+              when the second instruction is a call:
 
-           Workaround: For item 1), OS could make sure that the next page
-           after the divide instruction is also mapped.  For item 2), the
-           compiler could make sure that the divide instruction is not in
-           the branch delay slot."
+                 - Calls are less likely to be performance critical,
+                 - There's a good chance that the delay slot can execute
+                   in parallel with the call.
+                 - The return address would then be unaligned.
 
-       These processors have PRId values of 0x00004220 and 0x00004300 for
-       the R4000 and 0x00004400, 0x00004500 and 0x00004600 for the R4400.  */
+              In general, if we're going to insert a nop between instructions
+              X and Y, it's better to insert it immediately after X.  That
+              way, if the nop makes Y aligned, it will also align any labels
+              between X and Y.  */
+           if (state.insns_left != state.issue_rate
+               && !CALL_P (subinsn))
+             {
+               if (subinsn == SEQ_BEGIN (insn) && aligned_p)
+                 {
+                   /* SUBINSN is the first instruction in INSN and INSN is
+                      aligned.  We want to align the previous instruction
+                      instead, so insert a nop between LAST2 and LAST.
 
-const char *
-mips_output_division (const char *division, rtx *operands)
-{
-  const char *s;
+                      Note that LAST could be either a single instruction
+                      or a branch with a delay slot.  In the latter case,
+                      LAST, like INSN, is already aligned, but the delay
+                      slot must have some extra delay that stops it from
+                      issuing at the same time as the branch.  We therefore
+                      insert a nop before the branch in order to align its
+                      delay slot.  */
+                   emit_insn_after (gen_nop (), last2);
+                   aligned_p = false;
+                 }
+               else if (subinsn != SEQ_BEGIN (insn) && !aligned_p)
+                 {
+                   /* SUBINSN is the delay slot of INSN, but INSN is
+                      currently unaligned.  Insert a nop between
+                      LAST and INSN to align it.  */
+                   emit_insn_after (gen_nop (), last);
+                   aligned_p = true;
+                 }
+             }
+           mips_sim_issue_insn (&state, subinsn);
+         }
+      mips_sim_finish_insn (&state, insn);
 
-  s = division;
-  if (TARGET_FIX_R4000 || TARGET_FIX_R4400)
-    {
-      output_asm_insn (s, operands);
-      s = "nop";
-    }
-  if (TARGET_CHECK_ZERO_DIV)
-    {
-      if (TARGET_MIPS16)
-       {
-         output_asm_insn (s, operands);
-         s = "bnez\t%2,1f\n\tbreak\t7\n1:";
-       }
-      else if (GENERATE_DIVIDE_TRAPS)
-        {
-         output_asm_insn (s, operands);
-         s = "teq\t%2,%.,7";
-        }
-      else
+      /* Update LAST, LAST2 and ALIGNED_P for the next instruction.  */
+      length = get_attr_length (insn);
+      if (length > 0)
        {
-         output_asm_insn ("%(bne\t%2,%.,1f", operands);
-         output_asm_insn (s, operands);
-         s = "break\t7%)\n1:";
+         /* If the instruction is an asm statement or multi-instruction
+            mips.md patern, the length is only an estimate.  Insert an
+            8 byte alignment after it so that the following instructions
+            can be handled correctly.  */
+         if (NONJUMP_INSN_P (SEQ_BEGIN (insn))
+             && (recog_memoized (insn) < 0 || length >= 8))
+           {
+             next = emit_insn_after (gen_align (GEN_INT (3)), insn);
+             next = NEXT_INSN (next);
+             mips_sim_next_cycle (&state);
+             aligned_p = true;
+           }
+         else if (length & 4)
+           aligned_p = !aligned_p;
+         last2 = last;
+         last = insn;
        }
+
+      /* See whether INSN is an aligned label.  */
+      if (LABEL_P (insn) && label_to_alignment (insn) >= 3)
+       aligned_p = true;
     }
-  return s;
+  dfa_finish ();
 }
 \f
-/* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
-   with a final "000" replaced by "k".  Ignore case.
+/* This structure records that the current function has a LO_SUM
+   involving SYMBOL_REF or LABEL_REF BASE and that MAX_OFFSET is
+   the largest offset applied to BASE by all such LO_SUMs.  */
+struct mips_lo_sum_offset {
+  rtx base;
+  HOST_WIDE_INT offset;
+};
 
-   Note: this function is shared between GCC and GAS.  */
+/* Return a hash value for SYMBOL_REF or LABEL_REF BASE.  */
 
-static bool
-mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
+static hashval_t
+mips_hash_base (rtx base)
 {
-  while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
-    given++, canonical++;
+  int do_not_record_p;
 
-  return ((*given == 0 && *canonical == 0)
-         || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
+  return hash_rtx (base, GET_MODE (base), &do_not_record_p, NULL, false);
 }
 
+/* Hash-table callbacks for mips_lo_sum_offsets.  */
 
-/* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
-   CPU name.  We've traditionally allowed a lot of variation here.
-
-   Note: this function is shared between GCC and GAS.  */
-
-static bool
-mips_matching_cpu_name_p (const char *canonical, const char *given)
+static hashval_t
+mips_lo_sum_offset_hash (const void *entry)
 {
-  /* First see if the name matches exactly, or with a final "000"
-     turned into "k".  */
-  if (mips_strict_matching_cpu_name_p (canonical, given))
-    return true;
-
-  /* If not, try comparing based on numerical designation alone.
-     See if GIVEN is an unadorned number, or 'r' followed by a number.  */
-  if (TOLOWER (*given) == 'r')
-    given++;
-  if (!ISDIGIT (*given))
-    return false;
-
-  /* Skip over some well-known prefixes in the canonical name,
-     hoping to find a number there too.  */
-  if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
-    canonical += 2;
-  else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
-    canonical += 2;
-  else if (TOLOWER (canonical[0]) == 'r')
-    canonical += 1;
-
-  return mips_strict_matching_cpu_name_p (canonical, given);
+  return mips_hash_base (((const struct mips_lo_sum_offset *) entry)->base);
 }
 
-
-/* Return the mips_cpu_info entry for the processor or ISA given
-   by CPU_STRING.  Return null if the string isn't recognized.
-
-   A similar function exists in GAS.  */
-
-static const struct mips_cpu_info *
-mips_parse_cpu (const char *cpu_string)
+static int
+mips_lo_sum_offset_eq (const void *entry, const void *value)
 {
-  const struct mips_cpu_info *p;
-  const char *s;
-
-  /* In the past, we allowed upper-case CPU names, but it doesn't
-     work well with the multilib machinery.  */
-  for (s = cpu_string; *s != 0; s++)
-    if (ISUPPER (*s))
-      {
-       warning (0, "the cpu name must be lower case");
-       break;
-      }
-
-  /* 'from-abi' selects the most compatible architecture for the given
-     ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
-     EABIs, we have to decide whether we're using the 32-bit or 64-bit
-     version.  Look first at the -mgp options, if given, otherwise base
-     the choice on MASK_64BIT in TARGET_DEFAULT.  */
-  if (strcasecmp (cpu_string, "from-abi") == 0)
-    return mips_cpu_info_from_isa (ABI_NEEDS_32BIT_REGS ? 1
-                                  : ABI_NEEDS_64BIT_REGS ? 3
-                                  : (TARGET_64BIT ? 3 : 1));
-
-  /* 'default' has traditionally been a no-op.  Probably not very useful.  */
-  if (strcasecmp (cpu_string, "default") == 0)
-    return 0;
-
-  for (p = mips_cpu_info_table; p->name != 0; p++)
-    if (mips_matching_cpu_name_p (p->name, cpu_string))
-      return p;
-
-  return 0;
+  return rtx_equal_p (((const struct mips_lo_sum_offset *) entry)->base,
+                     (const_rtx) value);
 }
 
+/* Look up symbolic constant X in HTAB, which is a hash table of
+   mips_lo_sum_offsets.  If OPTION is NO_INSERT, return true if X can be
+   paired with a recorded LO_SUM, otherwise record X in the table.  */
 
-/* Return the processor associated with the given ISA level, or null
-   if the ISA isn't valid.  */
-
-static const struct mips_cpu_info *
-mips_cpu_info_from_isa (int isa)
+static bool
+mips_lo_sum_offset_lookup (htab_t htab, rtx x, enum insert_option option)
 {
-  const struct mips_cpu_info *p;
+  rtx base, offset;
+  void **slot;
+  struct mips_lo_sum_offset *entry;
 
-  for (p = mips_cpu_info_table; p->name != 0; p++)
-    if (p->isa == isa)
-      return p;
+  /* Split X into a base and offset.  */
+  split_const (x, &base, &offset);
+  if (UNSPEC_ADDRESS_P (base))
+    base = UNSPEC_ADDRESS (base);
 
-  return 0;
-}
-\f
-/* Implement HARD_REGNO_NREGS.  The size of FP registers is controlled
-   by UNITS_PER_FPREG.  The size of FP status registers is always 4, because
-   they only hold condition code modes, and CCmode is always considered to
-   be 4 bytes wide.  All other registers are word sized.  */
+  /* Look up the base in the hash table.  */
+  slot = htab_find_slot_with_hash (htab, base, mips_hash_base (base), option);
+  if (slot == NULL)
+    return false;
 
-unsigned int
-mips_hard_regno_nregs (int regno, enum machine_mode mode)
-{
-  if (ST_REG_P (regno))
-    return ((GET_MODE_SIZE (mode) + 3) / 4);
-  else if (! FP_REG_P (regno))
-    return ((GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD);
-  else
-    return ((GET_MODE_SIZE (mode) + UNITS_PER_FPREG - 1) / UNITS_PER_FPREG);
+  entry = (struct mips_lo_sum_offset *) *slot;
+  if (option == INSERT)
+    {
+      if (entry == NULL)
+       {
+         entry = XNEW (struct mips_lo_sum_offset);
+         entry->base = base;
+         entry->offset = INTVAL (offset);
+         *slot = entry;
+       }
+      else
+       {
+         if (INTVAL (offset) > entry->offset)
+           entry->offset = INTVAL (offset);
+       }
+    }
+  return INTVAL (offset) <= entry->offset;
 }
 
-/* Implement TARGET_RETURN_IN_MEMORY.  Under the old (i.e., 32 and O64 ABIs)
-   all BLKmode objects are returned in memory.  Under the new (N32 and
-   64-bit MIPS ABIs) small structures are returned in a register.
-   Objects with varying size must still be returned in memory, of
-   course.  */
+/* A for_each_rtx callback for which DATA is a mips_lo_sum_offset hash table.
+   Record every LO_SUM in *LOC.  */
 
-static bool
-mips_return_in_memory (const_tree type, const_tree fndecl ATTRIBUTE_UNUSED)
+static int
+mips_record_lo_sum (rtx *loc, void *data)
 {
-  if (TARGET_OLDABI)
-    return (TYPE_MODE (type) == BLKmode);
-  else
-    return ((int_size_in_bytes (type) > (2 * UNITS_PER_WORD))
-           || (int_size_in_bytes (type) == -1));
+  if (GET_CODE (*loc) == LO_SUM)
+    mips_lo_sum_offset_lookup ((htab_t) data, XEXP (*loc, 1), INSERT);
+  return 0;
 }
 
-static bool
-mips_strict_argument_naming (CUMULATIVE_ARGS *ca ATTRIBUTE_UNUSED)
-{
-  return !TARGET_OLDABI;
-}
-\f
-/* Return true if INSN is a multiply-add or multiply-subtract
-   instruction and PREV assigns to the accumulator operand.  */
+/* Return true if INSN is a SET of an orphaned high-part relocation.
+   HTAB is a hash table of mips_lo_sum_offsets that describes all the
+   LO_SUMs in the current function.  */
 
-bool
-mips_linked_madd_p (rtx prev, rtx insn)
+static bool
+mips_orphaned_high_part_p (htab_t htab, rtx insn)
 {
-  rtx x;
-
-  x = single_set (insn);
-  if (x == 0)
-    return false;
-
-  x = SET_SRC (x);
-
-  if (GET_CODE (x) == PLUS
-      && GET_CODE (XEXP (x, 0)) == MULT
-      && reg_set_p (XEXP (x, 1), prev))
-    return true;
+  enum mips_symbol_type type;
+  rtx x, set;
 
-  if (GET_CODE (x) == MINUS
-      && GET_CODE (XEXP (x, 1)) == MULT
-      && reg_set_p (XEXP (x, 0), prev))
-    return true;
+  set = single_set (insn);
+  if (set)
+    {
+      /* Check for %his.  */
+      x = SET_SRC (set);
+      if (GET_CODE (x) == HIGH
+         && absolute_symbolic_operand (XEXP (x, 0), VOIDmode))
+       return !mips_lo_sum_offset_lookup (htab, XEXP (x, 0), NO_INSERT);
 
+      /* Check for local %gots (and %got_pages, which is redundant but OK).  */
+      if (GET_CODE (x) == UNSPEC
+         && XINT (x, 1) == UNSPEC_LOAD_GOT
+         && mips_symbolic_constant_p (XVECEXP (x, 0, 1),
+                                      SYMBOL_CONTEXT_LEA, &type)
+         && type == SYMBOL_GOTOFF_PAGE)
+       return !mips_lo_sum_offset_lookup (htab, XVECEXP (x, 0, 1), NO_INSERT);
+    }
   return false;
 }
-\f
-/* Used by TUNE_MACC_CHAINS to record the last scheduled instruction
-   that may clobber hi or lo.  */
 
-static rtx mips_macc_chains_last_hilo;
+/* Subroutine of mips_reorg_process_insns.  If there is a hazard between
+   INSN and a previous instruction, avoid it by inserting nops after
+   instruction AFTER.
 
-/* A TUNE_MACC_CHAINS helper function.  Record that instruction INSN has
-   been scheduled, updating mips_macc_chains_last_hilo appropriately.  */
+   *DELAYED_REG and *HILO_DELAY describe the hazards that apply at
+   this point.  If *DELAYED_REG is non-null, INSN must wait a cycle
+   before using the value of that register.  *HILO_DELAY counts the
+   number of instructions since the last hilo hazard (that is,
+   the number of instructions since the last MFLO or MFHI).
 
-static void
-mips_macc_chains_record (rtx insn)
-{
-  if (get_attr_may_clobber_hilo (insn))
-    mips_macc_chains_last_hilo = insn;
-}
+   After inserting nops for INSN, update *DELAYED_REG and *HILO_DELAY
+   for the next instruction.
 
-/* A TUNE_MACC_CHAINS helper function.  Search ready queue READY, which
-   has NREADY elements, looking for a multiply-add or multiply-subtract
-   instruction that is cumulative with mips_macc_chains_last_hilo.
-   If there is one, promote it ahead of anything else that might
-   clobber hi or lo.  */
+   LO_REG is an rtx for the LO register, used in dependence checking.  */
 
 static void
-mips_macc_chains_reorder (rtx *ready, int nready)
+mips_avoid_hazard (rtx after, rtx insn, int *hilo_delay,
+                  rtx *delayed_reg, rtx lo_reg)
 {
-  int i, j;
+  rtx pattern, set;
+  int nops, ninsns;
 
-  if (mips_macc_chains_last_hilo != 0)
-    for (i = nready - 1; i >= 0; i--)
-      if (mips_linked_madd_p (mips_macc_chains_last_hilo, ready[i]))
-       {
-         for (j = nready - 1; j > i; j--)
-           if (recog_memoized (ready[j]) >= 0
-               && get_attr_may_clobber_hilo (ready[j]))
-             {
-               mips_promote_ready (ready, i, j);
-               break;
-             }
-         break;
-       }
-}
-\f
-/* The last instruction to be scheduled.  */
+  pattern = PATTERN (insn);
 
-static rtx vr4130_last_insn;
+  /* Do not put the whole function in .set noreorder if it contains
+     an asm statement.  We don't know whether there will be hazards
+     between the asm statement and the gcc-generated code.  */
+  if (GET_CODE (pattern) == ASM_INPUT || asm_noperands (pattern) >= 0)
+    cfun->machine->all_noreorder_p = false;
 
-/* A note_stores callback used by vr4130_true_reg_dependence_p.  DATA
-   points to an rtx that is initially an instruction.  Nullify the rtx
-   if the instruction uses the value of register X.  */
+  /* Ignore zero-length instructions (barriers and the like).  */
+  ninsns = get_attr_length (insn) / 4;
+  if (ninsns == 0)
+    return;
 
-static void
-vr4130_true_reg_dependence_p_1 (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
-{
-  rtx *insn_ptr = data;
-  if (REG_P (x)
-      && *insn_ptr != 0
-      && reg_referenced_p (x, PATTERN (*insn_ptr)))
-    *insn_ptr = 0;
-}
+  /* Work out how many nops are needed.  Note that we only care about
+     registers that are explicitly mentioned in the instruction's pattern.
+     It doesn't matter that calls use the argument registers or that they
+     clobber hi and lo.  */
+  if (*hilo_delay < 2 && reg_set_p (lo_reg, pattern))
+    nops = 2 - *hilo_delay;
+  else if (*delayed_reg != 0 && reg_referenced_p (*delayed_reg, pattern))
+    nops = 1;
+  else
+    nops = 0;
 
-/* Return true if there is true register dependence between vr4130_last_insn
-   and INSN.  */
+  /* Insert the nops between this instruction and the previous one.
+     Each new nop takes us further from the last hilo hazard.  */
+  *hilo_delay += nops;
+  while (nops-- > 0)
+    emit_insn_after (gen_hazard_nop (), after);
 
-static bool
-vr4130_true_reg_dependence_p (rtx insn)
-{
-  note_stores (PATTERN (vr4130_last_insn),
-              vr4130_true_reg_dependence_p_1, &insn);
-  return insn == 0;
+  /* Set up the state for the next instruction.  */
+  *hilo_delay += ninsns;
+  *delayed_reg = 0;
+  if (INSN_CODE (insn) >= 0)
+    switch (get_attr_hazard (insn))
+      {
+      case HAZARD_NONE:
+       break;
+
+      case HAZARD_HILO:
+       *hilo_delay = 0;
+       break;
+
+      case HAZARD_DELAY:
+       set = single_set (insn);
+       gcc_assert (set);
+       *delayed_reg = SET_DEST (set);
+       break;
+      }
 }
 
-/* A TUNE_MIPS4130 helper function.  Given that INSN1 is at the head of
-   the ready queue and that INSN2 is the instruction after it, return
-   true if it is worth promoting INSN2 ahead of INSN1.  Look for cases
-   in which INSN1 and INSN2 can probably issue in parallel, but for
-   which (INSN2, INSN1) should be less sensitive to instruction
-   alignment than (INSN1, INSN2).  See 4130.md for more details.  */
+/* Go through the instruction stream and insert nops where necessary.
+   Also delete any high-part relocations whose partnering low parts
+   are now all dead.  See if the whole function can then be put into
+   .set noreorder and .set nomacro.  */
 
-static bool
-vr4130_swap_insns_p (rtx insn1, rtx insn2)
+static void
+mips_reorg_process_insns (void)
 {
-  sd_iterator_def sd_it;
-  dep_t dep;
+  rtx insn, last_insn, subinsn, next_insn, lo_reg, delayed_reg;
+  int hilo_delay;
+  htab_t htab;
 
-  /* Check for the following case:
+  /* Force all instructions to be split into their final form.  */
+  split_all_insns_noflow ();
 
-     1) there is some other instruction X with an anti dependence on INSN1;
-     2) X has a higher priority than INSN2; and
-     3) X is an arithmetic instruction (and thus has no unit restrictions).
+  /* Recalculate instruction lengths without taking nops into account.  */
+  cfun->machine->ignore_hazard_length_p = true;
+  shorten_branches (get_insns ());
 
-     If INSN1 is the last instruction blocking X, it would better to
-     choose (INSN1, X) over (INSN2, INSN1).  */
-  FOR_EACH_DEP (insn1, SD_LIST_FORW, sd_it, dep)
-    if (DEP_TYPE (dep) == REG_DEP_ANTI
-       && INSN_PRIORITY (DEP_CON (dep)) > INSN_PRIORITY (insn2)
-       && recog_memoized (DEP_CON (dep)) >= 0
-       && get_attr_vr4130_class (DEP_CON (dep)) == VR4130_CLASS_ALU)
-      return false;
+  cfun->machine->all_noreorder_p = true;
 
-  if (vr4130_last_insn != 0
-      && recog_memoized (insn1) >= 0
-      && recog_memoized (insn2) >= 0)
-    {
-      /* See whether INSN1 and INSN2 use different execution units,
-        or if they are both ALU-type instructions.  If so, they can
-        probably execute in parallel.  */
-      enum attr_vr4130_class class1 = get_attr_vr4130_class (insn1);
-      enum attr_vr4130_class class2 = get_attr_vr4130_class (insn2);
-      if (class1 != class2 || class1 == VR4130_CLASS_ALU)
-       {
-         /* If only one of the instructions has a dependence on
-            vr4130_last_insn, prefer to schedule the other one first.  */
-         bool dep1 = vr4130_true_reg_dependence_p (insn1);
-         bool dep2 = vr4130_true_reg_dependence_p (insn2);
-         if (dep1 != dep2)
-           return dep1;
+  /* Code that doesn't use explicit relocs can't be ".set nomacro".  */
+  if (!TARGET_EXPLICIT_RELOCS)
+    cfun->machine->all_noreorder_p = false;
 
-         /* Prefer to schedule INSN2 ahead of INSN1 if vr4130_last_insn
-            is not an ALU-type instruction and if INSN1 uses the same
-            execution unit.  (Note that if this condition holds, we already
-            know that INSN2 uses a different execution unit.)  */
-         if (class1 != VR4130_CLASS_ALU
-             && recog_memoized (vr4130_last_insn) >= 0
-             && class1 == get_attr_vr4130_class (vr4130_last_insn))
-           return true;
-       }
-    }
-  return false;
-}
+  /* Profiled functions can't be all noreorder because the profiler
+     support uses assembler macros.  */
+  if (current_function_profile)
+    cfun->machine->all_noreorder_p = false;
 
-/* A TUNE_MIPS4130 helper function.  (READY, NREADY) describes a ready
-   queue with at least two instructions.  Swap the first two if
-   vr4130_swap_insns_p says that it could be worthwhile.  */
+  /* Code compiled with -mfix-vr4120 can't be all noreorder because
+     we rely on the assembler to work around some errata.  */
+  if (TARGET_FIX_VR4120)
+    cfun->machine->all_noreorder_p = false;
 
-static void
-vr4130_reorder (rtx *ready, int nready)
-{
-  if (vr4130_swap_insns_p (ready[nready - 1], ready[nready - 2]))
-    mips_promote_ready (ready, nready - 2, nready - 1);
-}
-\f
-/* Remove the instruction at index LOWER from ready queue READY and
-   reinsert it in front of the instruction at index HIGHER.  LOWER must
-   be <= HIGHER.  */
+  /* The same is true for -mfix-vr4130 if we might generate MFLO or
+     MFHI instructions.  Note that we avoid using MFLO and MFHI if
+     the VR4130 MACC and DMACC instructions are available instead;
+     see the *mfhilo_{si,di}_macc patterns.  */
+  if (TARGET_FIX_VR4130 && !ISA_HAS_MACCHI)
+    cfun->machine->all_noreorder_p = false;
 
-static void
-mips_promote_ready (rtx *ready, int lower, int higher)
-{
-  rtx new_head;
-  int i;
+  htab = htab_create (37, mips_lo_sum_offset_hash,
+                     mips_lo_sum_offset_eq, free);
 
-  new_head = ready[lower];
-  for (i = lower; i < higher; i++)
-    ready[i] = ready[i + 1];
-  ready[i] = new_head;
-}
+  /* Make a first pass over the instructions, recording all the LO_SUMs.  */
+  for (insn = get_insns (); insn != 0; insn = NEXT_INSN (insn))
+    FOR_EACH_SUBINSN (subinsn, insn)
+      if (INSN_P (subinsn))
+       for_each_rtx (&PATTERN (subinsn), mips_record_lo_sum, htab);
 
-/* If the priority of the instruction at POS2 in the ready queue READY 
-   is within LIMIT units of that of the instruction at POS1, swap the 
-   instructions if POS2 is not already less than POS1.  */
+  last_insn = 0;
+  hilo_delay = 2;
+  delayed_reg = 0;
+  lo_reg = gen_rtx_REG (SImode, LO_REGNUM);
 
-static void
-mips_maybe_swap_ready (rtx *ready, int pos1, int pos2, int limit)
-{
-  if (pos1 < pos2
-      && INSN_PRIORITY (ready[pos1]) + limit >= INSN_PRIORITY (ready[pos2]))
+  /* Make a second pass over the instructions.  Delete orphaned
+     high-part relocations or turn them into NOPs.  Avoid hazards
+     by inserting NOPs.  */
+  for (insn = get_insns (); insn != 0; insn = next_insn)
     {
-      rtx temp;
-      temp = ready[pos1];
-      ready[pos1] = ready[pos2];
-      ready[pos2] = temp;
+      next_insn = NEXT_INSN (insn);
+      if (INSN_P (insn))
+       {
+         if (GET_CODE (PATTERN (insn)) == SEQUENCE)
+           {
+             /* If we find an orphaned high-part relocation in a delay
+                slot, it's easier to turn that instruction into a NOP than
+                to delete it.  The delay slot will be a NOP either way.  */
+             FOR_EACH_SUBINSN (subinsn, insn)
+               if (INSN_P (subinsn))
+                 {
+                   if (mips_orphaned_high_part_p (htab, subinsn))
+                     {
+                       PATTERN (subinsn) = gen_nop ();
+                       INSN_CODE (subinsn) = CODE_FOR_nop;
+                     }
+                   mips_avoid_hazard (last_insn, subinsn, &hilo_delay,
+                                      &delayed_reg, lo_reg);
+                 }
+             last_insn = insn;
+           }
+         else
+           {
+             /* INSN is a single instruction.  Delete it if it's an
+                orphaned high-part relocation.  */
+             if (mips_orphaned_high_part_p (htab, insn))
+               delete_insn (insn);
+             else
+               {
+                 mips_avoid_hazard (last_insn, insn, &hilo_delay,
+                                    &delayed_reg, lo_reg);
+                 last_insn = insn;
+               }
+           }
+       }
     }
-}
 
-/* Record whether last 74k AGEN instruction was a load or store.  */
-
-static enum attr_type mips_last_74k_agen_insn = TYPE_UNKNOWN;
+  htab_delete (htab);
+}
 
-/* Initialize mips_last_74k_agen_insn from INSN.  A null argument
-   resets to TYPE_UNKNOWN state.  */
+/* Implement TARGET_MACHINE_DEPENDENT_REORG.  */
 
 static void
-mips_74k_agen_init (rtx insn)
+mips_reorg (void)
 {
-  if (!insn || !NONJUMP_INSN_P (insn))
-    mips_last_74k_agen_insn = TYPE_UNKNOWN;
-  else if (USEFUL_INSN_P (insn))
-    {
-      enum attr_type type = get_attr_type (insn);
-      if (type == TYPE_LOAD || type == TYPE_STORE)
-       mips_last_74k_agen_insn = type;
-    }
+  mips16_lay_out_constants ();
+  if (mips_base_delayed_branch)
+    dbr_schedule (get_insns ());
+  mips_reorg_process_insns ();
+  if (TARGET_EXPLICIT_RELOCS && TUNE_MIPS4130 && TARGET_VR4130_ALIGN)
+    vr4130_align_insns ();
 }
-
-/* A TUNE_74K helper function.  The 74K AGEN pipeline likes multiple
-   loads to be grouped together, and multiple stores to be grouped
-   together.  Swap things around in the ready queue to make this happen.  */
+\f
+/* Implement TARGET_ASM_OUTPUT_MI_THUNK.  Generate rtl rather than asm text
+   in order to avoid duplicating too much logic from elsewhere.  */
 
 static void
-mips_74k_agen_reorder (rtx *ready, int nready)
+mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
+                     HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
+                     tree function)
 {
-  int i;
-  int store_pos, load_pos;
+  rtx this, temp1, temp2, insn, fnaddr;
+  bool use_sibcall_p;
 
-  store_pos = -1;
-  load_pos = -1;
+  /* Pretend to be a post-reload pass while generating rtl.  */
+  reload_completed = 1;
 
-  for (i = nready - 1; i >= 0; i--)
-    {
-      rtx insn = ready[i];
-      if (USEFUL_INSN_P (insn))
-       switch (get_attr_type (insn))
-         {
-         case TYPE_STORE:
-           if (store_pos == -1)
-             store_pos = i;
-           break;
-           
-         case TYPE_LOAD:
-           if (load_pos == -1)
-             load_pos = i;
-           break;
-           
-         default:
-           break;
-         }
-    }
-  
-  if (load_pos == -1 || store_pos == -1)
-    return;
-  
-  switch (mips_last_74k_agen_insn)
-    {
-    case TYPE_UNKNOWN:
-      /* Prefer to schedule loads since they have a higher latency.  */
-    case TYPE_LOAD:
-      /* Swap loads to the front of the queue.  */
-      mips_maybe_swap_ready (ready, load_pos, store_pos, 4);
-      break;
-    case TYPE_STORE:
-      /* Swap stores to the front of the queue.  */
-      mips_maybe_swap_ready (ready, store_pos, load_pos, 4);
-      break;
-    default:
-      break;
-    }
-}
+  /* Mark the end of the (empty) prologue.  */
+  emit_note (NOTE_INSN_PROLOGUE_END);
 
-/* Implement TARGET_SCHED_INIT.  */
+  /* Determine if we can use a sibcall to call FUNCTION directly.  */
+  fnaddr = XEXP (DECL_RTL (function), 0);
+  use_sibcall_p = (mips_function_ok_for_sibcall (function, NULL)
+                  && const_call_insn_operand (fnaddr, Pmode));
 
-static void
-mips_sched_init (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
-                int max_ready ATTRIBUTE_UNUSED)
-{
-  mips_macc_chains_last_hilo = 0;
-  vr4130_last_insn = 0;
-  mips_74k_agen_init (NULL_RTX);
-}
+  /* Determine if we need to load FNADDR from the GOT.  */
+  if (!use_sibcall_p)
+    switch (mips_classify_symbol (fnaddr, SYMBOL_CONTEXT_LEA))
+      {
+      case SYMBOL_GOT_PAGE_OFST:
+      case SYMBOL_GOT_DISP:
+       /* Pick a global pointer.  Use a call-clobbered register if
+          TARGET_CALL_SAVED_GP.  */
+       cfun->machine->global_pointer =
+         TARGET_CALL_SAVED_GP ? 15 : GLOBAL_POINTER_REGNUM;
+       SET_REGNO (pic_offset_table_rtx, cfun->machine->global_pointer);
 
-/* Implement TARGET_SCHED_REORDER and TARG_SCHED_REORDER2.  */
+       /* Set up the global pointer for n32 or n64 abicalls.  */
+       mips_emit_loadgp ();
+       break;
 
-static int
-mips_sched_reorder (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
-                   rtx *ready, int *nreadyp, int cycle ATTRIBUTE_UNUSED)
-{
-  if (!reload_completed
-      && TUNE_MACC_CHAINS
-      && *nreadyp > 0)
-    mips_macc_chains_reorder (ready, *nreadyp);
-  if (reload_completed
-      && TUNE_MIPS4130
-      && !TARGET_VR4130_ALIGN
-      && *nreadyp > 1)
-    vr4130_reorder (ready, *nreadyp);
-  if (TUNE_74K)
-    mips_74k_agen_reorder (ready, *nreadyp);
-  return mips_issue_rate ();
-}
+      default:
+       break;
+      }
 
-/* Implement TARGET_SCHED_VARIABLE_ISSUE.  */
+  /* We need two temporary registers in some cases.  */
+  temp1 = gen_rtx_REG (Pmode, 2);
+  temp2 = gen_rtx_REG (Pmode, 3);
+
+  /* Find out which register contains the "this" pointer.  */
+  if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
+    this = gen_rtx_REG (Pmode, GP_ARG_FIRST + 1);
+  else
+    this = gen_rtx_REG (Pmode, GP_ARG_FIRST);
+
+  /* Add DELTA to THIS.  */
+  if (delta != 0)
+    {
+      rtx offset = GEN_INT (delta);
+      if (!SMALL_OPERAND (delta))
+       {
+         mips_emit_move (temp1, offset);
+         offset = temp1;
+       }
+      emit_insn (gen_add3_insn (this, this, offset));
+    }
 
-static int
-mips_variable_issue (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
-                    rtx insn, int more)
-{
-  if (TUNE_74K)
-    mips_74k_agen_init (insn);
-  switch (GET_CODE (PATTERN (insn)))
+  /* If needed, add *(*THIS + VCALL_OFFSET) to THIS.  */
+  if (vcall_offset != 0)
     {
-    case USE:
-    case CLOBBER:
-      /* Don't count USEs and CLOBBERs against the issue rate.  */
-      break;
+      rtx addr;
 
-    default:
-      more--;
-      if (!reload_completed && TUNE_MACC_CHAINS)
-       mips_macc_chains_record (insn);
-      vr4130_last_insn = insn;
-      break;
-    }
-  return more;
-}
-\f
-/* Implement TARGET_SCHED_ADJUST_COST.  We assume that anti and output
-   dependencies have no cost, except on the 20Kc where output-dependence
-   is treated like input-dependence.  */
+      /* Set TEMP1 to *THIS.  */
+      mips_emit_move (temp1, gen_rtx_MEM (Pmode, this));
 
-static int
-mips_adjust_cost (rtx insn ATTRIBUTE_UNUSED, rtx link,
-                 rtx dep ATTRIBUTE_UNUSED, int cost)
-{
-  if (REG_NOTE_KIND (link) == REG_DEP_OUTPUT
-      && TUNE_20KC)
-    return cost;
-  if (REG_NOTE_KIND (link) != 0)
-    return 0;
-  return cost;
-}
+      /* Set ADDR to a legitimate address for *THIS + VCALL_OFFSET.  */
+      addr = mips_add_offset (temp2, temp1, vcall_offset);
 
-/* Return the number of instructions that can be issued per cycle.  */
+      /* Load the offset and add it to THIS.  */
+      mips_emit_move (temp1, gen_rtx_MEM (Pmode, addr));
+      emit_insn (gen_add3_insn (this, this, temp1));
+    }
 
-static int
-mips_issue_rate (void)
-{
-  switch (mips_tune)
+  /* Jump to the target function.  Use a sibcall if direct jumps are
+     allowed, otherwise load the address into a register first.  */
+  if (use_sibcall_p)
     {
-    case PROCESSOR_74KC:
-    case PROCESSOR_74KF2_1:
-    case PROCESSOR_74KF1_1:
-    case PROCESSOR_74KF3_2:
-      /* The 74k is not strictly quad-issue cpu, but can be seen as one
-        by the scheduler.  It can issue 1 ALU, 1 AGEN and 2 FPU insns,
-        but in reality only a maximum of 3 insns can be issued as the
-        floating point load/stores also require a slot in the AGEN pipe.  */
-     return 4;
+      insn = emit_call_insn (gen_sibcall_internal (fnaddr, const0_rtx));
+      SIBLING_CALL_P (insn) = 1;
+    }
+  else
+    {
+      /* This is messy.  GAS treats "la $25,foo" as part of a call
+        sequence and may allow a global "foo" to be lazily bound.
+        The general move patterns therefore reject this combination.
 
-    case PROCESSOR_20KC:
-    case PROCESSOR_R4130:
-    case PROCESSOR_R5400:
-    case PROCESSOR_R5500:
-    case PROCESSOR_R7000:
-    case PROCESSOR_R9000:
-      return 2;
+        In this context, lazy binding would actually be OK
+        for TARGET_CALL_CLOBBERED_GP, but it's still wrong for
+        TARGET_CALL_SAVED_GP; see mips_load_call_address.
+        We must therefore load the address via a temporary
+        register if mips_dangerous_for_la25_p.
 
-    case PROCESSOR_SB1:
-    case PROCESSOR_SB1A:
-      /* This is actually 4, but we get better performance if we claim 3.
-        This is partly because of unwanted speculative code motion with the
-        larger number, and partly because in most common cases we can't
-        reach the theoretical max of 4.  */
-      return 3;
+        If we jump to the temporary register rather than $25, the assembler
+        can use the move insn to fill the jump's delay slot.  */
+      if (TARGET_USE_PIC_FN_ADDR_REG
+         && !mips_dangerous_for_la25_p (fnaddr))
+       temp1 = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
+      mips_load_call_address (temp1, fnaddr, true);
 
-    default:
-      return 1;
+      if (TARGET_USE_PIC_FN_ADDR_REG
+         && REGNO (temp1) != PIC_FUNCTION_ADDR_REGNUM)
+       mips_emit_move (gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM), temp1);
+      emit_jump_insn (gen_indirect_jump (temp1));
     }
-}
-
-/* Implements TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD.  This should
-   be as wide as the scheduling freedom in the DFA.  */
 
-static int
-mips_multipass_dfa_lookahead (void)
-{
-  /* Can schedule up to 4 of the 6 function units in any one cycle.  */
-  if (TUNE_SB1)
-    return 4;
+  /* Run just enough of rest_of_compilation.  This sequence was
+     "borrowed" from alpha.c.  */
+  insn = get_insns ();
+  insn_locators_alloc ();
+  split_all_insns_noflow ();
+  mips16_lay_out_constants ();
+  shorten_branches (insn);
+  final_start_function (insn, file, 1);
+  final (insn, file, 1);
+  final_end_function ();
+  free_after_compilation (cfun);
 
-  return 0;
+  /* Clean up the vars set above.  Note that final_end_function resets
+     the global pointer for us.  */
+  reload_completed = 0;
 }
+\f
+/* The last argument passed to mips_set_mips16_mode, or negative if the
+   function hasn't been called yet.  */
+static GTY(()) int was_mips16_p = -1;
 
-/* Implements a store data bypass check.  We need this because the cprestore
-   pattern is type store, but defined using an UNSPEC.  This UNSPEC causes the
-   default routine to abort.  We just return false for that case.  */
-/* ??? Should try to give a better result here than assuming false.  */
+/* Set up the target-dependent global state so that it matches the
+   current function's ISA mode.  */
 
-int
-mips_store_data_bypass_p (rtx out_insn, rtx in_insn)
+static void
+mips_set_mips16_mode (int mips16_p)
 {
-  if (GET_CODE (PATTERN (in_insn)) == UNSPEC_VOLATILE)
-    return false;
+  if (mips16_p == was_mips16_p)
+    return;
 
-  return ! store_data_bypass_p (out_insn, in_insn);
-}
-\f
-/* Given that we have an rtx of the form (prefetch ... WRITE LOCALITY),
-   return the first operand of the associated "pref" or "prefx" insn.  */
+  /* Restore base settings of various flags.  */
+  target_flags = mips_base_target_flags;
+  flag_schedule_insns = mips_base_schedule_insns;
+  flag_reorder_blocks_and_partition = mips_base_reorder_blocks_and_partition;
+  flag_move_loop_invariants = mips_base_move_loop_invariants;
+  align_loops = mips_base_align_loops;
+  align_jumps = mips_base_align_jumps;
+  align_functions = mips_base_align_functions;
 
-rtx
-mips_prefetch_cookie (rtx write, rtx locality)
-{
-  /* store_streamed / load_streamed.  */
-  if (INTVAL (locality) <= 0)
-    return GEN_INT (INTVAL (write) + 4);
+  if (mips16_p)
+    {
+      /* Switch to MIPS16 mode.  */
+      target_flags |= MASK_MIPS16;
 
-  /* store / load.  */
-  if (INTVAL (locality) <= 2)
-    return write;
+      /* Don't run the scheduler before reload, since it tends to
+         increase register pressure.  */
+      flag_schedule_insns = 0;
 
-  /* store_retained / load_retained.  */
-  return GEN_INT (INTVAL (write) + 6);
-}
-\f
-/* MIPS builtin function support. */
+      /* Don't do hot/cold partitioning.  mips16_lay_out_constants expects
+        the whole function to be in a single section.  */
+      flag_reorder_blocks_and_partition = 0;
 
-struct builtin_description
-{
-  /* The code of the main .md file instruction.  See mips_builtin_type
-     for more information.  */
-  enum insn_code icode;
+      /* Don't move loop invariants, because it tends to increase
+        register pressure.  It also introduces an extra move in cases
+        where the constant is the first operand in a two-operand binary
+        instruction, or when it forms a register argument to a functon
+        call.  */
+      flag_move_loop_invariants = 0;
 
-  /* The floating-point comparison code to use with ICODE, if any.  */
-  enum mips_fp_condition cond;
+      /* Silently disable -mexplicit-relocs since it doesn't apply
+        to MIPS16 code.  Even so, it would overly pedantic to warn
+        about "-mips16 -mexplicit-relocs", especially given that
+        we use a %gprel() operator.  */
+      target_flags &= ~MASK_EXPLICIT_RELOCS;
 
-  /* The name of the builtin function.  */
-  const char *name;
+      /* Experiments suggest we get the best overall section-anchor
+        results from using the range of an unextended LW or SW.  Code
+        that makes heavy use of byte or short accesses can do better
+        with ranges of 0...31 and 0...63 respectively, but most code is
+        sensitive to the range of LW and SW instead.  */
+      targetm.min_anchor_offset = 0;
+      targetm.max_anchor_offset = 127;
 
-  /* Specifies how the function should be expanded.  */
-  enum mips_builtin_type builtin_type;
+      if (flag_pic || TARGET_ABICALLS)
+       sorry ("MIPS16 PIC");
 
-  /* The function's prototype.  */
-  enum mips_function_type function_type;
+      if (TARGET_HARD_FLOAT_ABI && !TARGET_OLDABI)
+       sorry ("hard-float MIPS16 code for ABIs other than o32 and o64");
+    }
+  else
+    {
+      /* Switch to normal (non-MIPS16) mode.  */
+      target_flags &= ~MASK_MIPS16;
 
-  /* The target flags required for this function.  */
-  int target_flags;
-};
+      /* Provide default values for align_* for 64-bit targets.  */
+      if (TARGET_64BIT)
+       {
+         if (align_loops == 0)
+           align_loops = 8;
+         if (align_jumps == 0)
+           align_jumps = 8;
+         if (align_functions == 0)
+           align_functions = 8;
+       }
 
-/* Define a MIPS_BUILTIN_DIRECT function for instruction CODE_FOR_mips_<INSN>.
-   FUNCTION_TYPE and TARGET_FLAGS are builtin_description fields.  */
-#define DIRECT_BUILTIN(INSN, FUNCTION_TYPE, TARGET_FLAGS)              \
-  { CODE_FOR_mips_ ## INSN, 0, "__builtin_mips_" #INSN,                        \
-    MIPS_BUILTIN_DIRECT, FUNCTION_TYPE, TARGET_FLAGS }
+      targetm.min_anchor_offset = -32768;
+      targetm.max_anchor_offset = 32767;
+    }
 
-/* Define __builtin_mips_<INSN>_<COND>_{s,d}, both of which require
-   TARGET_FLAGS.  */
-#define CMP_SCALAR_BUILTINS(INSN, COND, TARGET_FLAGS)                  \
-  { CODE_FOR_mips_ ## INSN ## _cond_s, MIPS_FP_COND_ ## COND,          \
-    "__builtin_mips_" #INSN "_" #COND "_s",                            \
-    MIPS_BUILTIN_CMP_SINGLE, MIPS_INT_FTYPE_SF_SF, TARGET_FLAGS },     \
-  { CODE_FOR_mips_ ## INSN ## _cond_d, MIPS_FP_COND_ ## COND,          \
-    "__builtin_mips_" #INSN "_" #COND "_d",                            \
-    MIPS_BUILTIN_CMP_SINGLE, MIPS_INT_FTYPE_DF_DF, TARGET_FLAGS }
+  /* (Re)initialize MIPS target internals for new ISA.  */
+  mips_init_relocs ();
 
-/* Define __builtin_mips_{any,all,upper,lower}_<INSN>_<COND>_ps.
-   The lower and upper forms require TARGET_FLAGS while the any and all
-   forms require MASK_MIPS3D.  */
-#define CMP_PS_BUILTINS(INSN, COND, TARGET_FLAGS)                      \
-  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
-    "__builtin_mips_any_" #INSN "_" #COND "_ps",                       \
-    MIPS_BUILTIN_CMP_ANY, MIPS_INT_FTYPE_V2SF_V2SF, MASK_MIPS3D },     \
-  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
-    "__builtin_mips_all_" #INSN "_" #COND "_ps",                       \
-    MIPS_BUILTIN_CMP_ALL, MIPS_INT_FTYPE_V2SF_V2SF, MASK_MIPS3D },     \
-  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
-    "__builtin_mips_lower_" #INSN "_" #COND "_ps",                     \
-    MIPS_BUILTIN_CMP_LOWER, MIPS_INT_FTYPE_V2SF_V2SF, TARGET_FLAGS },  \
-  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
-    "__builtin_mips_upper_" #INSN "_" #COND "_ps",                     \
-    MIPS_BUILTIN_CMP_UPPER, MIPS_INT_FTYPE_V2SF_V2SF, TARGET_FLAGS }
+  if (was_mips16_p >= 0)
+    /* Reinitialize target-dependent state.  */
+    target_reinit ();
 
-/* Define __builtin_mips_{any,all}_<INSN>_<COND>_4s.  The functions
-   require MASK_MIPS3D.  */
-#define CMP_4S_BUILTINS(INSN, COND)                                    \
-  { CODE_FOR_mips_ ## INSN ## _cond_4s, MIPS_FP_COND_ ## COND,         \
-    "__builtin_mips_any_" #INSN "_" #COND "_4s",                       \
-    MIPS_BUILTIN_CMP_ANY, MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF,          \
-    MASK_MIPS3D },                                                     \
-  { CODE_FOR_mips_ ## INSN ## _cond_4s, MIPS_FP_COND_ ## COND,         \
-    "__builtin_mips_all_" #INSN "_" #COND "_4s",                       \
-    MIPS_BUILTIN_CMP_ALL, MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF,          \
-    MASK_MIPS3D }
+  was_mips16_p = mips16_p;
+}
+
+/* Implement TARGET_SET_CURRENT_FUNCTION.  Decide whether the current
+   function should use the MIPS16 ISA and switch modes accordingly.  */
+
+static void
+mips_set_current_function (tree fndecl)
+{
+  mips_set_mips16_mode (mips_use_mips16_mode_p (fndecl));
+}
+\f
+/* Allocate a chunk of memory for per-function machine-dependent data.  */
 
-/* Define __builtin_mips_mov{t,f}_<INSN>_<COND>_ps.  The comparison
-   instruction requires TARGET_FLAGS.  */
-#define MOVTF_BUILTINS(INSN, COND, TARGET_FLAGS)                       \
-  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
-    "__builtin_mips_movt_" #INSN "_" #COND "_ps",                      \
-    MIPS_BUILTIN_MOVT, MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF,            \
-    TARGET_FLAGS },                                                    \
-  { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,         \
-    "__builtin_mips_movf_" #INSN "_" #COND "_ps",                      \
-    MIPS_BUILTIN_MOVF, MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF,            \
-    TARGET_FLAGS }
+static struct machine_function *
+mips_init_machine_status (void)
+{
+  return ((struct machine_function *)
+         ggc_alloc_cleared (sizeof (struct machine_function)));
+}
 
-/* Define all the builtins related to c.cond.fmt condition COND.  */
-#define CMP_BUILTINS(COND)                                             \
-  MOVTF_BUILTINS (c, COND, MASK_PAIRED_SINGLE_FLOAT),                  \
-  MOVTF_BUILTINS (cabs, COND, MASK_MIPS3D),                            \
-  CMP_SCALAR_BUILTINS (cabs, COND, MASK_MIPS3D),                       \
-  CMP_PS_BUILTINS (c, COND, MASK_PAIRED_SINGLE_FLOAT),                 \
-  CMP_PS_BUILTINS (cabs, COND, MASK_MIPS3D),                           \
-  CMP_4S_BUILTINS (c, COND),                                           \
-  CMP_4S_BUILTINS (cabs, COND)
+/* Return the processor associated with the given ISA level, or null
+   if the ISA isn't valid.  */
 
-static const struct builtin_description mips_bdesc[] =
+static const struct mips_cpu_info *
+mips_cpu_info_from_isa (int isa)
 {
-  DIRECT_BUILTIN (pll_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
-  DIRECT_BUILTIN (pul_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
-  DIRECT_BUILTIN (plu_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
-  DIRECT_BUILTIN (puu_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
-  DIRECT_BUILTIN (cvt_ps_s, MIPS_V2SF_FTYPE_SF_SF, MASK_PAIRED_SINGLE_FLOAT),
-  DIRECT_BUILTIN (cvt_s_pl, MIPS_SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT),
-  DIRECT_BUILTIN (cvt_s_pu, MIPS_SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT),
-  DIRECT_BUILTIN (abs_ps, MIPS_V2SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT),
+  unsigned int i;
 
-  DIRECT_BUILTIN (alnv_ps, MIPS_V2SF_FTYPE_V2SF_V2SF_INT,
-                 MASK_PAIRED_SINGLE_FLOAT),
-  DIRECT_BUILTIN (addr_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
-  DIRECT_BUILTIN (mulr_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
-  DIRECT_BUILTIN (cvt_pw_ps, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
-  DIRECT_BUILTIN (cvt_ps_pw, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
+  for (i = 0; i < ARRAY_SIZE (mips_cpu_info_table); i++)
+    if (mips_cpu_info_table[i].isa == isa)
+      return mips_cpu_info_table + i;
 
-  DIRECT_BUILTIN (recip1_s, MIPS_SF_FTYPE_SF, MASK_MIPS3D),
-  DIRECT_BUILTIN (recip1_d, MIPS_DF_FTYPE_DF, MASK_MIPS3D),
-  DIRECT_BUILTIN (recip1_ps, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
-  DIRECT_BUILTIN (recip2_s, MIPS_SF_FTYPE_SF_SF, MASK_MIPS3D),
-  DIRECT_BUILTIN (recip2_d, MIPS_DF_FTYPE_DF_DF, MASK_MIPS3D),
-  DIRECT_BUILTIN (recip2_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
+  return NULL;
+}
 
-  DIRECT_BUILTIN (rsqrt1_s, MIPS_SF_FTYPE_SF, MASK_MIPS3D),
-  DIRECT_BUILTIN (rsqrt1_d, MIPS_DF_FTYPE_DF, MASK_MIPS3D),
-  DIRECT_BUILTIN (rsqrt1_ps, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
-  DIRECT_BUILTIN (rsqrt2_s, MIPS_SF_FTYPE_SF_SF, MASK_MIPS3D),
-  DIRECT_BUILTIN (rsqrt2_d, MIPS_DF_FTYPE_DF_DF, MASK_MIPS3D),
-  DIRECT_BUILTIN (rsqrt2_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
+/* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
+   with a final "000" replaced by "k".  Ignore case.
 
-  MIPS_FP_CONDITIONS (CMP_BUILTINS)
-};
+   Note: this function is shared between GCC and GAS.  */
+
+static bool
+mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
+{
+  while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
+    given++, canonical++;
 
-/* Builtin functions for the SB-1 processor.  */
+  return ((*given == 0 && *canonical == 0)
+         || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
+}
 
-#define CODE_FOR_mips_sqrt_ps CODE_FOR_sqrtv2sf2
+/* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
+   CPU name.  We've traditionally allowed a lot of variation here.
+
+   Note: this function is shared between GCC and GAS.  */
 
-static const struct builtin_description sb1_bdesc[] =
+static bool
+mips_matching_cpu_name_p (const char *canonical, const char *given)
 {
-  DIRECT_BUILTIN (sqrt_ps, MIPS_V2SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT)
-};
+  /* First see if the name matches exactly, or with a final "000"
+     turned into "k".  */
+  if (mips_strict_matching_cpu_name_p (canonical, given))
+    return true;
+
+  /* If not, try comparing based on numerical designation alone.
+     See if GIVEN is an unadorned number, or 'r' followed by a number.  */
+  if (TOLOWER (*given) == 'r')
+    given++;
+  if (!ISDIGIT (*given))
+    return false;
 
-/* Builtin functions for DSP ASE.  */
+  /* Skip over some well-known prefixes in the canonical name,
+     hoping to find a number there too.  */
+  if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
+    canonical += 2;
+  else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
+    canonical += 2;
+  else if (TOLOWER (canonical[0]) == 'r')
+    canonical += 1;
 
-#define CODE_FOR_mips_addq_ph CODE_FOR_addv2hi3
-#define CODE_FOR_mips_addu_qb CODE_FOR_addv4qi3
-#define CODE_FOR_mips_subq_ph CODE_FOR_subv2hi3
-#define CODE_FOR_mips_subu_qb CODE_FOR_subv4qi3
-#define CODE_FOR_mips_mul_ph CODE_FOR_mulv2hi3
+  return mips_strict_matching_cpu_name_p (canonical, given);
+}
 
-/* Define a MIPS_BUILTIN_DIRECT_NO_TARGET function for instruction
-   CODE_FOR_mips_<INSN>.  FUNCTION_TYPE and TARGET_FLAGS are
-   builtin_description fields.  */
-#define DIRECT_NO_TARGET_BUILTIN(INSN, FUNCTION_TYPE, TARGET_FLAGS)    \
-  { CODE_FOR_mips_ ## INSN, 0, "__builtin_mips_" #INSN,                        \
-    MIPS_BUILTIN_DIRECT_NO_TARGET, FUNCTION_TYPE, TARGET_FLAGS }
+/* Return the mips_cpu_info entry for the processor or ISA given
+   by CPU_STRING.  Return null if the string isn't recognized.
 
-/* Define __builtin_mips_bposge<VALUE>.  <VALUE> is 32 for the MIPS32 DSP
-   branch instruction.  TARGET_FLAGS is a builtin_description field.  */
-#define BPOSGE_BUILTIN(VALUE, TARGET_FLAGS)                            \
-  { CODE_FOR_mips_bposge, 0, "__builtin_mips_bposge" #VALUE,           \
-    MIPS_BUILTIN_BPOSGE ## VALUE, MIPS_SI_FTYPE_VOID, TARGET_FLAGS }
+   A similar function exists in GAS.  */
 
-static const struct builtin_description dsp_bdesc[] =
+static const struct mips_cpu_info *
+mips_parse_cpu (const char *cpu_string)
 {
-  DIRECT_BUILTIN (addq_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (addq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (addq_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (addu_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (addu_s_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (subq_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (subq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (subq_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (subu_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (subu_s_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (addsc, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (addwc, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (modsub, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (raddu_w_qb, MIPS_SI_FTYPE_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (absq_s_ph, MIPS_V2HI_FTYPE_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (absq_s_w, MIPS_SI_FTYPE_SI, MASK_DSP),
-  DIRECT_BUILTIN (precrq_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (precrq_ph_w, MIPS_V2HI_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (precrq_rs_ph_w, MIPS_V2HI_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (precrqu_s_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (preceq_w_phl, MIPS_SI_FTYPE_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (preceq_w_phr, MIPS_SI_FTYPE_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (precequ_ph_qbl, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (precequ_ph_qbr, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (precequ_ph_qbla, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (precequ_ph_qbra, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (preceu_ph_qbl, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (preceu_ph_qbr, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (preceu_ph_qbla, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (preceu_ph_qbra, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (shll_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSP),
-  DIRECT_BUILTIN (shll_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
-  DIRECT_BUILTIN (shll_s_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
-  DIRECT_BUILTIN (shll_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (shrl_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSP),
-  DIRECT_BUILTIN (shra_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
-  DIRECT_BUILTIN (shra_r_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
-  DIRECT_BUILTIN (shra_r_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (muleu_s_ph_qbl, MIPS_V2HI_FTYPE_V4QI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (muleu_s_ph_qbr, MIPS_V2HI_FTYPE_V4QI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (mulq_rs_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (muleq_s_w_phl, MIPS_SI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (muleq_s_w_phr, MIPS_SI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (bitrev, MIPS_SI_FTYPE_SI, MASK_DSP),
-  DIRECT_BUILTIN (insv, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (repl_qb, MIPS_V4QI_FTYPE_SI, MASK_DSP),
-  DIRECT_BUILTIN (repl_ph, MIPS_V2HI_FTYPE_SI, MASK_DSP),
-  DIRECT_NO_TARGET_BUILTIN (cmpu_eq_qb, MIPS_VOID_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_NO_TARGET_BUILTIN (cmpu_lt_qb, MIPS_VOID_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_NO_TARGET_BUILTIN (cmpu_le_qb, MIPS_VOID_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (cmpgu_eq_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (cmpgu_lt_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (cmpgu_le_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_NO_TARGET_BUILTIN (cmp_eq_ph, MIPS_VOID_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_NO_TARGET_BUILTIN (cmp_lt_ph, MIPS_VOID_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_NO_TARGET_BUILTIN (cmp_le_ph, MIPS_VOID_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (pick_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (pick_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (packrl_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
-  DIRECT_NO_TARGET_BUILTIN (wrdsp, MIPS_VOID_FTYPE_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (rddsp, MIPS_SI_FTYPE_SI, MASK_DSP),
-  DIRECT_BUILTIN (lbux, MIPS_SI_FTYPE_PTR_SI, MASK_DSP),
-  DIRECT_BUILTIN (lhx, MIPS_SI_FTYPE_PTR_SI, MASK_DSP),
-  DIRECT_BUILTIN (lwx, MIPS_SI_FTYPE_PTR_SI, MASK_DSP),
-  BPOSGE_BUILTIN (32, MASK_DSP),
+  unsigned int i;
+  const char *s;
 
-  /* The following are for the MIPS DSP ASE REV 2.  */
-  DIRECT_BUILTIN (absq_s_qb, MIPS_V4QI_FTYPE_V4QI, MASK_DSPR2),
-  DIRECT_BUILTIN (addu_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (addu_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (adduh_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
-  DIRECT_BUILTIN (adduh_r_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
-  DIRECT_BUILTIN (append, MIPS_SI_FTYPE_SI_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (balign, MIPS_SI_FTYPE_SI_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (cmpgdu_eq_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSPR2),
-  DIRECT_BUILTIN (cmpgdu_lt_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSPR2),
-  DIRECT_BUILTIN (cmpgdu_le_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSPR2),
-  DIRECT_BUILTIN (mul_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (mul_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (mulq_rs_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (mulq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (mulq_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (precr_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (precr_sra_ph_w, MIPS_V2HI_FTYPE_SI_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (precr_sra_r_ph_w, MIPS_V2HI_FTYPE_SI_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (prepend, MIPS_SI_FTYPE_SI_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (shra_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (shra_r_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (shrl_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (subu_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (subu_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (subuh_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
-  DIRECT_BUILTIN (subuh_r_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
-  DIRECT_BUILTIN (addqh_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (addqh_r_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (addqh_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (addqh_r_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (subqh_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (subqh_r_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (subqh_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (subqh_r_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2)
-};
+  /* In the past, we allowed upper-case CPU names, but it doesn't
+     work well with the multilib machinery.  */
+  for (s = cpu_string; *s != 0; s++)
+    if (ISUPPER (*s))
+      {
+       warning (0, "CPU names must be lower case");
+       break;
+      }
 
-static const struct builtin_description dsp_32only_bdesc[] =
-{
-  DIRECT_BUILTIN (dpau_h_qbl, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (dpau_h_qbr, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (dpsu_h_qbl, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (dpsu_h_qbr, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
-  DIRECT_BUILTIN (dpaq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (dpsq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (mulsaq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (dpaq_sa_l_w, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (dpsq_sa_l_w, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSP),
-  DIRECT_BUILTIN (maq_s_w_phl, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (maq_s_w_phr, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (maq_sa_w_phl, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (maq_sa_w_phr, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
-  DIRECT_BUILTIN (extr_w, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
-  DIRECT_BUILTIN (extr_r_w, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
-  DIRECT_BUILTIN (extr_rs_w, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
-  DIRECT_BUILTIN (extr_s_h, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
-  DIRECT_BUILTIN (extp, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
-  DIRECT_BUILTIN (extpdp, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
-  DIRECT_BUILTIN (shilo, MIPS_DI_FTYPE_DI_SI, MASK_DSP),
-  DIRECT_BUILTIN (mthlip, MIPS_DI_FTYPE_DI_SI, MASK_DSP),
+  /* 'from-abi' selects the most compatible architecture for the given
+     ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
+     EABIs, we have to decide whether we're using the 32-bit or 64-bit
+     version.  */
+  if (strcasecmp (cpu_string, "from-abi") == 0)
+    return mips_cpu_info_from_isa (ABI_NEEDS_32BIT_REGS ? 1
+                                  : ABI_NEEDS_64BIT_REGS ? 3
+                                  : (TARGET_64BIT ? 3 : 1));
 
-  /* The following are for the MIPS DSP ASE REV 2.  */
-  DIRECT_BUILTIN (dpa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (dps_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (madd, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (maddu, MIPS_DI_FTYPE_DI_USI_USI, MASK_DSPR2),
-  DIRECT_BUILTIN (msub, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (msubu, MIPS_DI_FTYPE_DI_USI_USI, MASK_DSPR2),
-  DIRECT_BUILTIN (mulsa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (mult, MIPS_DI_FTYPE_SI_SI, MASK_DSPR2),
-  DIRECT_BUILTIN (multu, MIPS_DI_FTYPE_USI_USI, MASK_DSPR2),
-  DIRECT_BUILTIN (dpax_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (dpsx_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (dpaqx_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (dpaqx_sa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (dpsqx_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
-  DIRECT_BUILTIN (dpsqx_sa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2)
-};
+  /* 'default' has traditionally been a no-op.  Probably not very useful.  */
+  if (strcasecmp (cpu_string, "default") == 0)
+    return NULL;
+
+  for (i = 0; i < ARRAY_SIZE (mips_cpu_info_table); i++)
+    if (mips_matching_cpu_name_p (mips_cpu_info_table[i].name, cpu_string))
+      return mips_cpu_info_table + i;
+
+  return NULL;
+}
 
-/* This helps provide a mapping from builtin function codes to bdesc
-   arrays.  */
+/* Set up globals to generate code for the ISA or processor
+   described by INFO.  */
 
-struct bdesc_map
+static void
+mips_set_architecture (const struct mips_cpu_info *info)
 {
-  /* The builtin function table that this entry describes.  */
-  const struct builtin_description *bdesc;
+  if (info != 0)
+    {
+      mips_arch_info = info;
+      mips_arch = info->cpu;
+      mips_isa = info->isa;
+    }
+}
 
-  /* The number of entries in the builtin function table.  */
-  unsigned int size;
+/* Likewise for tuning.  */
 
-  /* The target processor that supports these builtin functions.
-     PROCESSOR_MAX means we enable them for all processors.  */
-  enum processor_type proc;
+static void
+mips_set_tune (const struct mips_cpu_info *info)
+{
+  if (info != 0)
+    {
+      mips_tune_info = info;
+      mips_tune = info->cpu;
+    }
+}
 
-  /* If the target has these flags, this builtin function table
-     will not be supported.  */
-  int unsupported_target_flags;
-};
+/* Implement TARGET_HANDLE_OPTION.  */
 
-static const struct bdesc_map bdesc_arrays[] =
+static bool
+mips_handle_option (size_t code, const char *arg, int value ATTRIBUTE_UNUSED)
 {
-  { mips_bdesc, ARRAY_SIZE (mips_bdesc), PROCESSOR_MAX, 0 },
-  { sb1_bdesc, ARRAY_SIZE (sb1_bdesc), PROCESSOR_SB1, 0 },
-  { dsp_bdesc, ARRAY_SIZE (dsp_bdesc), PROCESSOR_MAX, 0 },
-  { dsp_32only_bdesc, ARRAY_SIZE (dsp_32only_bdesc), PROCESSOR_MAX,
-    MASK_64BIT }
-};
+  switch (code)
+    {
+    case OPT_mabi_:
+      if (strcmp (arg, "32") == 0)
+       mips_abi = ABI_32;
+      else if (strcmp (arg, "o64") == 0)
+       mips_abi = ABI_O64;
+      else if (strcmp (arg, "n32") == 0)
+       mips_abi = ABI_N32;
+      else if (strcmp (arg, "64") == 0)
+       mips_abi = ABI_64;
+      else if (strcmp (arg, "eabi") == 0)
+       mips_abi = ABI_EABI;
+      else
+       return false;
+      return true;
 
-/* Take the argument ARGNUM of the arglist of EXP and convert it into a form
-   suitable for input operand OP of instruction ICODE.  Return the value.  */
+    case OPT_march_:
+    case OPT_mtune_:
+      return mips_parse_cpu (arg) != 0;
 
-static rtx
-mips_prepare_builtin_arg (enum insn_code icode,
-                         unsigned int op, tree exp, unsigned int argnum)
+    case OPT_mips:
+      mips_isa_option_info = mips_parse_cpu (ACONCAT (("mips", arg, NULL)));
+      return mips_isa_option_info != 0;
+
+    case OPT_mno_flush_func:
+      mips_cache_flush_func = NULL;
+      return true;
+
+    case OPT_mcode_readable_:
+      if (strcmp (arg, "yes") == 0)
+       mips_code_readable = CODE_READABLE_YES;
+      else if (strcmp (arg, "pcrel") == 0)
+       mips_code_readable = CODE_READABLE_PCREL;
+      else if (strcmp (arg, "no") == 0)
+       mips_code_readable = CODE_READABLE_NO;
+      else
+       return false;
+      return true;
+
+    default:
+      return true;
+    }
+}
+
+/* Implement OVERRIDE_OPTIONS.  */
+
+void
+mips_override_options (void)
 {
-  rtx value;
-  enum machine_mode mode;
+  int i, start, regno, mode;
 
-  value = expand_normal (CALL_EXPR_ARG (exp, argnum));
-  mode = insn_data[icode].operand[op].mode;
-  if (!insn_data[icode].operand[op].predicate (value, mode))
+#ifdef SUBTARGET_OVERRIDE_OPTIONS
+  SUBTARGET_OVERRIDE_OPTIONS;
+#endif
+
+  /* Set the small data limit.  */
+  mips_small_data_threshold = (g_switch_set
+                              ? g_switch_value
+                              : MIPS_DEFAULT_GVALUE);
+
+  /* The following code determines the architecture and register size.
+     Similar code was added to GAS 2.14 (see tc-mips.c:md_after_parse_args()).
+     The GAS and GCC code should be kept in sync as much as possible.  */
+
+  if (mips_arch_string != 0)
+    mips_set_architecture (mips_parse_cpu (mips_arch_string));
+
+  if (mips_isa_option_info != 0)
     {
-      value = copy_to_mode_reg (mode, value);
-      /* Check the predicate again.  */
-      if (!insn_data[icode].operand[op].predicate (value, mode))
+      if (mips_arch_info == 0)
+       mips_set_architecture (mips_isa_option_info);
+      else if (mips_arch_info->isa != mips_isa_option_info->isa)
+       error ("%<-%s%> conflicts with the other architecture options, "
+              "which specify a %s processor",
+              mips_isa_option_info->name,
+              mips_cpu_info_from_isa (mips_arch_info->isa)->name);
+    }
+
+  if (mips_arch_info == 0)
+    {
+#ifdef MIPS_CPU_STRING_DEFAULT
+      mips_set_architecture (mips_parse_cpu (MIPS_CPU_STRING_DEFAULT));
+#else
+      mips_set_architecture (mips_cpu_info_from_isa (MIPS_ISA_DEFAULT));
+#endif
+    }
+
+  if (ABI_NEEDS_64BIT_REGS && !ISA_HAS_64BIT_REGS)
+    error ("%<-march=%s%> is not compatible with the selected ABI",
+          mips_arch_info->name);
+
+  /* Optimize for mips_arch, unless -mtune selects a different processor.  */
+  if (mips_tune_string != 0)
+    mips_set_tune (mips_parse_cpu (mips_tune_string));
+
+  if (mips_tune_info == 0)
+    mips_set_tune (mips_arch_info);
+
+  if ((target_flags_explicit & MASK_64BIT) != 0)
+    {
+      /* The user specified the size of the integer registers.  Make sure
+        it agrees with the ABI and ISA.  */
+      if (TARGET_64BIT && !ISA_HAS_64BIT_REGS)
+       error ("%<-mgp64%> used with a 32-bit processor");
+      else if (!TARGET_64BIT && ABI_NEEDS_64BIT_REGS)
+       error ("%<-mgp32%> used with a 64-bit ABI");
+      else if (TARGET_64BIT && ABI_NEEDS_32BIT_REGS)
+       error ("%<-mgp64%> used with a 32-bit ABI");
+    }
+  else
+    {
+      /* Infer the integer register size from the ABI and processor.
+        Restrict ourselves to 32-bit registers if that's all the
+        processor has, or if the ABI cannot handle 64-bit registers.  */
+      if (ABI_NEEDS_32BIT_REGS || !ISA_HAS_64BIT_REGS)
+       target_flags &= ~MASK_64BIT;
+      else
+       target_flags |= MASK_64BIT;
+    }
+
+  if ((target_flags_explicit & MASK_FLOAT64) != 0)
+    {
+      if (TARGET_SINGLE_FLOAT && TARGET_FLOAT64)
+       error ("unsupported combination: %s", "-mfp64 -msingle-float");
+      else if (TARGET_64BIT && TARGET_DOUBLE_FLOAT && !TARGET_FLOAT64)
+       error ("unsupported combination: %s", "-mgp64 -mfp32 -mdouble-float");
+      else if (!TARGET_64BIT && TARGET_FLOAT64)
        {
-         error ("invalid argument to builtin function");
-         return const0_rtx;
+         if (!ISA_HAS_MXHC1)
+           error ("%<-mgp32%> and %<-mfp64%> can only be combined if"
+                  " the target supports the mfhc1 and mthc1 instructions");
+         else if (mips_abi != ABI_32)
+           error ("%<-mgp32%> and %<-mfp64%> can only be combined when using"
+                  " the o32 ABI");
        }
     }
+  else
+    {
+      /* -msingle-float selects 32-bit float registers.  Otherwise the
+        float registers should be the same size as the integer ones.  */
+      if (TARGET_64BIT && TARGET_DOUBLE_FLOAT)
+       target_flags |= MASK_FLOAT64;
+      else
+       target_flags &= ~MASK_FLOAT64;
+    }
 
-  return value;
-}
+  /* End of code shared with GAS.  */
 
-/* Return an rtx suitable for output operand OP of instruction ICODE.
-   If TARGET is non-null, try to use it where possible.  */
+  /* If no -mlong* option was given, infer it from the other options.  */
+  if ((target_flags_explicit & MASK_LONG64) == 0)
+    {
+      if ((mips_abi == ABI_EABI && TARGET_64BIT) || mips_abi == ABI_64)
+       target_flags |= MASK_LONG64;
+      else
+       target_flags &= ~MASK_LONG64;
+    }
 
-static rtx
-mips_prepare_builtin_target (enum insn_code icode, unsigned int op, rtx target)
-{
-  enum machine_mode mode;
+  if (!TARGET_OLDABI)
+    flag_pcc_struct_return = 0;
 
-  mode = insn_data[icode].operand[op].mode;
-  if (target == 0 || !insn_data[icode].operand[op].predicate (target, mode))
-    target = gen_reg_rtx (mode);
+  /* Decide which rtx_costs structure to use.  */
+  if (optimize_size)
+    mips_cost = &mips_rtx_cost_optimize_size;
+  else
+    mips_cost = &mips_rtx_cost_data[mips_tune];
 
-  return target;
-}
+  /* If the user hasn't specified a branch cost, use the processor's
+     default.  */
+  if (mips_branch_cost == 0)
+    mips_branch_cost = mips_cost->branch_cost;
 
-/* Expand builtin functions.  This is called from TARGET_EXPAND_BUILTIN.  */
+  /* If neither -mbranch-likely nor -mno-branch-likely was given
+     on the command line, set MASK_BRANCHLIKELY based on the target
+     architecture and tuning flags.  Annulled delay slots are a
+     size win, so we only consider the processor-specific tuning
+     for !optimize_size.  */
+  if ((target_flags_explicit & MASK_BRANCHLIKELY) == 0)
+    {
+      if (ISA_HAS_BRANCHLIKELY
+         && (optimize_size
+             || (mips_tune_info->tune_flags & PTF_AVOID_BRANCHLIKELY) == 0))
+       target_flags |= MASK_BRANCHLIKELY;
+      else
+       target_flags &= ~MASK_BRANCHLIKELY;
+    }
+  else if (TARGET_BRANCHLIKELY && !ISA_HAS_BRANCHLIKELY)
+    warning (0, "the %qs architecture does not support branch-likely"
+            " instructions", mips_arch_info->name);
 
-rtx
-mips_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
-                    enum machine_mode mode ATTRIBUTE_UNUSED,
-                    int ignore ATTRIBUTE_UNUSED)
-{
-  enum insn_code icode;
-  enum mips_builtin_type type;
-  tree fndecl;
-  unsigned int fcode;
-  const struct builtin_description *bdesc;
-  const struct bdesc_map *m;
+  /* The effect of -mabicalls isn't defined for the EABI.  */
+  if (mips_abi == ABI_EABI && TARGET_ABICALLS)
+    {
+      error ("unsupported combination: %s", "-mabicalls -mabi=eabi");
+      target_flags &= ~MASK_ABICALLS;
+    }
 
-  fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
-  fcode = DECL_FUNCTION_CODE (fndecl);
+  /* MIPS16 cannot generate PIC yet.  */
+  if (TARGET_MIPS16 && (flag_pic || TARGET_ABICALLS))
+    {
+      sorry ("MIPS16 PIC");
+      target_flags &= ~MASK_ABICALLS;
+      flag_pic = flag_pie = flag_shlib = 0;
+    }
+
+  if (TARGET_ABICALLS)
+    /* We need to set flag_pic for executables as well as DSOs
+       because we may reference symbols that are not defined in
+       the final executable.  (MIPS does not use things like
+       copy relocs, for example.)
+
+       Also, there is a body of code that uses __PIC__ to distinguish
+       between -mabicalls and -mno-abicalls code.  */
+    flag_pic = 1;
+
+  /* -mvr4130-align is a "speed over size" optimization: it usually produces
+     faster code, but at the expense of more nops.  Enable it at -O3 and
+     above.  */
+  if (optimize > 2 && (target_flags_explicit & MASK_VR4130_ALIGN) == 0)
+    target_flags |= MASK_VR4130_ALIGN;
+
+  /* Prefer a call to memcpy over inline code when optimizing for size,
+     though see MOVE_RATIO in mips.h.  */
+  if (optimize_size && (target_flags_explicit & MASK_MEMCPY) == 0)
+    target_flags |= MASK_MEMCPY;
 
-  if (TARGET_MIPS16)
+  /* If we have a nonzero small-data limit, check that the -mgpopt
+     setting is consistent with the other target flags.  */
+  if (mips_small_data_threshold > 0)
     {
-      error ("built-in function %qs not supported for MIPS16",
-            IDENTIFIER_POINTER (DECL_NAME (fndecl)));
-      return const0_rtx;
-    }
+      if (!TARGET_GPOPT)
+       {
+         if (!TARGET_MIPS16 && !TARGET_EXPLICIT_RELOCS)
+           error ("%<-mno-gpopt%> needs %<-mexplicit-relocs%>");
 
-  bdesc = NULL;
-  for (m = bdesc_arrays; m < &bdesc_arrays[ARRAY_SIZE (bdesc_arrays)]; m++)
-    {
-      if (fcode < m->size)
+         TARGET_LOCAL_SDATA = false;
+         TARGET_EXTERN_SDATA = false;
+       }
+      else
        {
-         bdesc = m->bdesc;
-         icode = bdesc[fcode].icode;
-         type = bdesc[fcode].builtin_type;
-         break;
+         if (TARGET_VXWORKS_RTP)
+           warning (0, "cannot use small-data accesses for %qs", "-mrtp");
+
+         if (TARGET_ABICALLS)
+           warning (0, "cannot use small-data accesses for %qs",
+                    "-mabicalls");
        }
-      fcode -= m->size;
     }
-  if (bdesc == NULL)
-    return 0;
-
-  switch (type)
-    {
-    case MIPS_BUILTIN_DIRECT:
-      return mips_expand_builtin_direct (icode, target, exp, true);
 
-    case MIPS_BUILTIN_DIRECT_NO_TARGET:
-      return mips_expand_builtin_direct (icode, target, exp, false);
+#ifdef MIPS_TFMODE_FORMAT
+  REAL_MODE_FORMAT (TFmode) = &MIPS_TFMODE_FORMAT;
+#endif
 
-    case MIPS_BUILTIN_MOVT:
-    case MIPS_BUILTIN_MOVF:
-      return mips_expand_builtin_movtf (type, icode, bdesc[fcode].cond,
-                                       target, exp);
+  /* Make sure that the user didn't turn off paired single support when
+     MIPS-3D support is requested.  */
+  if (TARGET_MIPS3D
+      && (target_flags_explicit & MASK_PAIRED_SINGLE_FLOAT)
+      && !TARGET_PAIRED_SINGLE_FLOAT)
+    error ("%<-mips3d%> requires %<-mpaired-single%>");
 
-    case MIPS_BUILTIN_CMP_ANY:
-    case MIPS_BUILTIN_CMP_ALL:
-    case MIPS_BUILTIN_CMP_UPPER:
-    case MIPS_BUILTIN_CMP_LOWER:
-    case MIPS_BUILTIN_CMP_SINGLE:
-      return mips_expand_builtin_compare (type, icode, bdesc[fcode].cond,
-                                         target, exp);
+  /* If TARGET_MIPS3D, enable MASK_PAIRED_SINGLE_FLOAT.  */
+  if (TARGET_MIPS3D)
+    target_flags |= MASK_PAIRED_SINGLE_FLOAT;
 
-    case MIPS_BUILTIN_BPOSGE32:
-      return mips_expand_builtin_bposge (type, target);
+  /* Make sure that when TARGET_PAIRED_SINGLE_FLOAT is true, TARGET_FLOAT64
+     and TARGET_HARD_FLOAT_ABI are both true.  */
+  if (TARGET_PAIRED_SINGLE_FLOAT && !(TARGET_FLOAT64 && TARGET_HARD_FLOAT_ABI))
+    error ("%qs must be used with %qs",
+          TARGET_MIPS3D ? "-mips3d" : "-mpaired-single",
+          TARGET_HARD_FLOAT_ABI ? "-mfp64" : "-mhard-float");
 
-    default:
-      return 0;
-    }
-}
+  /* Make sure that the ISA supports TARGET_PAIRED_SINGLE_FLOAT when it is
+     enabled.  */
+  if (TARGET_PAIRED_SINGLE_FLOAT && !ISA_HAS_PAIRED_SINGLE)
+    warning (0, "the %qs architecture does not support paired-single"
+            " instructions", mips_arch_info->name);
 
-/* Init builtin functions.  This is called from TARGET_INIT_BUILTIN.  */
+  /* If TARGET_DSPR2, enable MASK_DSP.  */
+  if (TARGET_DSPR2)
+    target_flags |= MASK_DSP;
 
-void
-mips_init_builtins (void)
-{
-  const struct builtin_description *d;
-  const struct bdesc_map *m;
-  tree types[(int) MIPS_MAX_FTYPE_MAX];
-  tree V2SF_type_node;
-  tree V2HI_type_node;
-  tree V4QI_type_node;
-  unsigned int offset;
+  mips_init_print_operand_punct ();
 
-  /* We have only builtins for -mpaired-single, -mips3d and -mdsp.  */
-  if (!TARGET_PAIRED_SINGLE_FLOAT && !TARGET_DSP)
-    return;
+  /* Set up array to map GCC register number to debug register number.
+     Ignore the special purpose register numbers.  */
 
-  if (TARGET_PAIRED_SINGLE_FLOAT)
+  for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
     {
-      V2SF_type_node = build_vector_type_for_mode (float_type_node, V2SFmode);
-
-      types[MIPS_V2SF_FTYPE_V2SF]
-       = build_function_type_list (V2SF_type_node, V2SF_type_node, NULL_TREE);
-
-      types[MIPS_V2SF_FTYPE_V2SF_V2SF]
-       = build_function_type_list (V2SF_type_node,
-                                   V2SF_type_node, V2SF_type_node, NULL_TREE);
-
-      types[MIPS_V2SF_FTYPE_V2SF_V2SF_INT]
-       = build_function_type_list (V2SF_type_node,
-                                   V2SF_type_node, V2SF_type_node,
-                                   integer_type_node, NULL_TREE);
+      mips_dbx_regno[i] = INVALID_REGNUM;
+      if (GP_REG_P (i) || FP_REG_P (i) || ALL_COP_REG_P (i))
+       mips_dwarf_regno[i] = i;
+      else
+       mips_dwarf_regno[i] = INVALID_REGNUM;
+    }
 
-      types[MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF]
-       = build_function_type_list (V2SF_type_node,
-                                   V2SF_type_node, V2SF_type_node,
-                                   V2SF_type_node, V2SF_type_node, NULL_TREE);
+  start = GP_DBX_FIRST - GP_REG_FIRST;
+  for (i = GP_REG_FIRST; i <= GP_REG_LAST; i++)
+    mips_dbx_regno[i] = i + start;
 
-      types[MIPS_V2SF_FTYPE_SF_SF]
-       = build_function_type_list (V2SF_type_node,
-                                   float_type_node, float_type_node, NULL_TREE);
+  start = FP_DBX_FIRST - FP_REG_FIRST;
+  for (i = FP_REG_FIRST; i <= FP_REG_LAST; i++)
+    mips_dbx_regno[i] = i + start;
 
-      types[MIPS_INT_FTYPE_V2SF_V2SF]
-       = build_function_type_list (integer_type_node,
-                                   V2SF_type_node, V2SF_type_node, NULL_TREE);
+  /* Accumulator debug registers use big-endian ordering.  */
+  mips_dbx_regno[HI_REGNUM] = MD_DBX_FIRST + 0;
+  mips_dbx_regno[LO_REGNUM] = MD_DBX_FIRST + 1;
+  mips_dwarf_regno[HI_REGNUM] = MD_REG_FIRST + 0;
+  mips_dwarf_regno[LO_REGNUM] = MD_REG_FIRST + 1;
+  for (i = DSP_ACC_REG_FIRST; i <= DSP_ACC_REG_LAST; i += 2)
+    {
+      mips_dwarf_regno[i + TARGET_LITTLE_ENDIAN] = i;
+      mips_dwarf_regno[i + TARGET_BIG_ENDIAN] = i + 1;
+    }
 
-      types[MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF]
-       = build_function_type_list (integer_type_node,
-                                   V2SF_type_node, V2SF_type_node,
-                                   V2SF_type_node, V2SF_type_node, NULL_TREE);
+  /* Set up mips_hard_regno_mode_ok.  */
+  for (mode = 0; mode < MAX_MACHINE_MODE; mode++)
+    for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
+      mips_hard_regno_mode_ok[(int)mode][regno]
+       = mips_hard_regno_mode_ok_p (regno, mode);
 
-      types[MIPS_INT_FTYPE_SF_SF]
-       = build_function_type_list (integer_type_node,
-                                   float_type_node, float_type_node, NULL_TREE);
+  /* Function to allocate machine-dependent function status.  */
+  init_machine_status = &mips_init_machine_status;
 
-      types[MIPS_INT_FTYPE_DF_DF]
-       = build_function_type_list (integer_type_node,
-                                   double_type_node, double_type_node, NULL_TREE);
+  /* Default to working around R4000 errata only if the processor
+     was selected explicitly.  */
+  if ((target_flags_explicit & MASK_FIX_R4000) == 0
+      && mips_matching_cpu_name_p (mips_arch_info->name, "r4000"))
+    target_flags |= MASK_FIX_R4000;
 
-      types[MIPS_SF_FTYPE_V2SF]
-       = build_function_type_list (float_type_node, V2SF_type_node, NULL_TREE);
-
-      types[MIPS_SF_FTYPE_SF]
-       = build_function_type_list (float_type_node,
-                                   float_type_node, NULL_TREE);
-
-      types[MIPS_SF_FTYPE_SF_SF]
-       = build_function_type_list (float_type_node,
-                                   float_type_node, float_type_node, NULL_TREE);
-
-      types[MIPS_DF_FTYPE_DF]
-       = build_function_type_list (double_type_node,
-                                   double_type_node, NULL_TREE);
-
-      types[MIPS_DF_FTYPE_DF_DF]
-       = build_function_type_list (double_type_node,
-                                   double_type_node, double_type_node, NULL_TREE);
-    }
-
-  if (TARGET_DSP)
-    {
-      V2HI_type_node = build_vector_type_for_mode (intHI_type_node, V2HImode);
-      V4QI_type_node = build_vector_type_for_mode (intQI_type_node, V4QImode);
-
-      types[MIPS_V2HI_FTYPE_V2HI_V2HI]
-       = build_function_type_list (V2HI_type_node,
-                                   V2HI_type_node, V2HI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_SI_FTYPE_SI_SI]
-       = build_function_type_list (intSI_type_node,
-                                   intSI_type_node, intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_V4QI_FTYPE_V4QI_V4QI]
-       = build_function_type_list (V4QI_type_node,
-                                   V4QI_type_node, V4QI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_SI_FTYPE_V4QI]
-       = build_function_type_list (intSI_type_node,
-                                   V4QI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_V2HI_FTYPE_V2HI]
-       = build_function_type_list (V2HI_type_node,
-                                   V2HI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_SI_FTYPE_SI]
-       = build_function_type_list (intSI_type_node,
-                                   intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_V4QI_FTYPE_V2HI_V2HI]
-       = build_function_type_list (V4QI_type_node,
-                                   V2HI_type_node, V2HI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_V2HI_FTYPE_SI_SI]
-       = build_function_type_list (V2HI_type_node,
-                                   intSI_type_node, intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_SI_FTYPE_V2HI]
-       = build_function_type_list (intSI_type_node,
-                                   V2HI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_V2HI_FTYPE_V4QI]
-       = build_function_type_list (V2HI_type_node,
-                                   V4QI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_V4QI_FTYPE_V4QI_SI]
-       = build_function_type_list (V4QI_type_node,
-                                   V4QI_type_node, intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_V2HI_FTYPE_V2HI_SI]
-       = build_function_type_list (V2HI_type_node,
-                                   V2HI_type_node, intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_V2HI_FTYPE_V4QI_V2HI]
-       = build_function_type_list (V2HI_type_node,
-                                   V4QI_type_node, V2HI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_SI_FTYPE_V2HI_V2HI]
-       = build_function_type_list (intSI_type_node,
-                                   V2HI_type_node, V2HI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_DI_FTYPE_DI_V4QI_V4QI]
-       = build_function_type_list (intDI_type_node,
-                                   intDI_type_node, V4QI_type_node, V4QI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_DI_FTYPE_DI_V2HI_V2HI]
-       = build_function_type_list (intDI_type_node,
-                                   intDI_type_node, V2HI_type_node, V2HI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_DI_FTYPE_DI_SI_SI]
-       = build_function_type_list (intDI_type_node,
-                                   intDI_type_node, intSI_type_node, intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_V4QI_FTYPE_SI]
-       = build_function_type_list (V4QI_type_node,
-                                   intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_V2HI_FTYPE_SI]
-       = build_function_type_list (V2HI_type_node,
-                                   intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_VOID_FTYPE_V4QI_V4QI]
-       = build_function_type_list (void_type_node,
-                                   V4QI_type_node, V4QI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_SI_FTYPE_V4QI_V4QI]
-       = build_function_type_list (intSI_type_node,
-                                   V4QI_type_node, V4QI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_VOID_FTYPE_V2HI_V2HI]
-       = build_function_type_list (void_type_node,
-                                   V2HI_type_node, V2HI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_SI_FTYPE_DI_SI]
-       = build_function_type_list (intSI_type_node,
-                                   intDI_type_node, intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_DI_FTYPE_DI_SI]
-       = build_function_type_list (intDI_type_node,
-                                   intDI_type_node, intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_VOID_FTYPE_SI_SI]
-       = build_function_type_list (void_type_node,
-                                   intSI_type_node, intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_SI_FTYPE_PTR_SI]
-       = build_function_type_list (intSI_type_node,
-                                   ptr_type_node, intSI_type_node,
-                                   NULL_TREE);
-
-      types[MIPS_SI_FTYPE_VOID]
-       = build_function_type (intSI_type_node, void_list_node);
-
-      if (TARGET_DSPR2)
-       {
-         types[MIPS_V4QI_FTYPE_V4QI]
-           = build_function_type_list (V4QI_type_node,
-                                       V4QI_type_node,
-                                       NULL_TREE);
-
-         types[MIPS_SI_FTYPE_SI_SI_SI]
-           = build_function_type_list (intSI_type_node,
-                                       intSI_type_node, intSI_type_node,
-                                       intSI_type_node, NULL_TREE);
-
-         types[MIPS_DI_FTYPE_DI_USI_USI]
-           = build_function_type_list (intDI_type_node,
-                                       intDI_type_node,
-                                       unsigned_intSI_type_node,
-                                       unsigned_intSI_type_node, NULL_TREE);
-
-         types[MIPS_DI_FTYPE_SI_SI]
-           = build_function_type_list (intDI_type_node,
-                                       intSI_type_node, intSI_type_node,
-                                       NULL_TREE);
-
-         types[MIPS_DI_FTYPE_USI_USI]
-           = build_function_type_list (intDI_type_node,
-                                       unsigned_intSI_type_node,
-                                       unsigned_intSI_type_node, NULL_TREE);
-
-         types[MIPS_V2HI_FTYPE_SI_SI_SI]
-           = build_function_type_list (V2HI_type_node,
-                                       intSI_type_node, intSI_type_node,
-                                       intSI_type_node, NULL_TREE);
+  /* Default to working around R4400 errata only if the processor
+     was selected explicitly.  */
+  if ((target_flags_explicit & MASK_FIX_R4400) == 0
+      && mips_matching_cpu_name_p (mips_arch_info->name, "r4400"))
+    target_flags |= MASK_FIX_R4400;
 
-       }
-    }
+  /* Save base state of options.  */
+  mips_base_mips16 = TARGET_MIPS16;
+  mips_base_target_flags = target_flags;
+  mips_base_delayed_branch = flag_delayed_branch;
+  mips_base_schedule_insns = flag_schedule_insns;
+  mips_base_reorder_blocks_and_partition = flag_reorder_blocks_and_partition;
+  mips_base_move_loop_invariants = flag_move_loop_invariants;
+  mips_base_align_loops = align_loops;
+  mips_base_align_jumps = align_jumps;
+  mips_base_align_functions = align_functions;
 
-  /* Iterate through all of the bdesc arrays, initializing all of the
-     builtin functions.  */
+  /* Now select the ISA mode.  */
+  mips_set_mips16_mode (mips_base_mips16);
 
-  offset = 0;
-  for (m = bdesc_arrays; m < &bdesc_arrays[ARRAY_SIZE (bdesc_arrays)]; m++)
-    {
-      if ((m->proc == PROCESSOR_MAX || (m->proc == mips_arch))
-         && (m->unsupported_target_flags & target_flags) == 0)
-       for (d = m->bdesc; d < &m->bdesc[m->size]; d++)
-         if ((d->target_flags & target_flags) == d->target_flags)
-           add_builtin_function (d->name, types[d->function_type],
-                                 d - m->bdesc + offset,
-                                 BUILT_IN_MD, NULL, NULL);
-      offset += m->size;
-    }
+  /* We call dbr_schedule from within mips_reorg.  */
+  flag_delayed_branch = 0;
 }
 
-/* Expand a MIPS_BUILTIN_DIRECT function.  ICODE is the code of the
-   .md pattern and CALL is the function expr with arguments.  TARGET,
-   if nonnull, suggests a good place to put the result.
-   HAS_TARGET indicates the function must return something.  */
+/* Swap the register information for registers I and I + 1, which
+   currently have the wrong endianness.  Note that the registers'
+   fixedness and call-clobberedness might have been set on the
+   command line.  */
 
-static rtx
-mips_expand_builtin_direct (enum insn_code icode, rtx target, tree exp,
-                           bool has_target)
+static void
+mips_swap_registers (unsigned int i)
 {
-  rtx ops[MAX_RECOG_OPERANDS];
-  int i = 0;
-  int j = 0;
-
-  if (has_target)
-    {
-      /* We save target to ops[0].  */
-      ops[0] = mips_prepare_builtin_target (icode, 0, target);
-      i = 1;
-    }
-
-  /* We need to test if the arglist is not zero.  Some instructions have extra
-     clobber registers.  */
-  for (; i < insn_data[icode].n_operands && i <= call_expr_nargs (exp); i++, j++)
-    ops[i] = mips_prepare_builtin_arg (icode, i, exp, j);
-
-  switch (i)
-    {
-    case 2:
-      emit_insn (GEN_FCN (icode) (ops[0], ops[1]));
-      break;
+  int tmpi;
+  const char *tmps;
 
-    case 3:
-      emit_insn (GEN_FCN (icode) (ops[0], ops[1], ops[2]));
-      break;
+#define SWAP_INT(X, Y) (tmpi = (X), (X) = (Y), (Y) = tmpi)
+#define SWAP_STRING(X, Y) (tmps = (X), (X) = (Y), (Y) = tmps)
 
-    case 4:
-      emit_insn (GEN_FCN (icode) (ops[0], ops[1], ops[2], ops[3]));
-      break;
+  SWAP_INT (fixed_regs[i], fixed_regs[i + 1]);
+  SWAP_INT (call_used_regs[i], call_used_regs[i + 1]);
+  SWAP_INT (call_really_used_regs[i], call_really_used_regs[i + 1]);
+  SWAP_STRING (reg_names[i], reg_names[i + 1]);
 
-    default:
-      gcc_unreachable ();
-    }
-  return target;
+#undef SWAP_STRING
+#undef SWAP_INT
 }
 
-/* Expand a __builtin_mips_movt_*_ps() or __builtin_mips_movf_*_ps()
-   function (TYPE says which).  EXP is the tree for the function
-   function, ICODE is the instruction that should be used to compare
-   the first two arguments, and COND is the condition it should test.
-   TARGET, if nonnull, suggests a good place to put the result.  */
+/* Implement CONDITIONAL_REGISTER_USAGE.  */
 
-static rtx
-mips_expand_builtin_movtf (enum mips_builtin_type type,
-                          enum insn_code icode, enum mips_fp_condition cond,
-                          rtx target, tree exp)
+void
+mips_conditional_register_usage (void)
 {
-  rtx cmp_result, op0, op1;
+  if (!ISA_HAS_DSP)
+    {
+      int regno;
 
-  cmp_result = mips_prepare_builtin_target (icode, 0, 0);
-  op0 = mips_prepare_builtin_arg (icode, 1, exp, 0);
-  op1 = mips_prepare_builtin_arg (icode, 2, exp, 1);
-  emit_insn (GEN_FCN (icode) (cmp_result, op0, op1, GEN_INT (cond)));
+      for (regno = DSP_ACC_REG_FIRST; regno <= DSP_ACC_REG_LAST; regno++)
+       fixed_regs[regno] = call_used_regs[regno] = 1;
+    }
+  if (!TARGET_HARD_FLOAT)
+    {
+      int regno;
 
-  icode = CODE_FOR_mips_cond_move_tf_ps;
-  target = mips_prepare_builtin_target (icode, 0, target);
-  if (type == MIPS_BUILTIN_MOVT)
+      for (regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
+       fixed_regs[regno] = call_used_regs[regno] = 1;
+      for (regno = ST_REG_FIRST; regno <= ST_REG_LAST; regno++)
+       fixed_regs[regno] = call_used_regs[regno] = 1;
+    }
+  else if (! ISA_HAS_8CC)
     {
-      op1 = mips_prepare_builtin_arg (icode, 2, exp, 2);
-      op0 = mips_prepare_builtin_arg (icode, 1, exp, 3);
+      int regno;
+
+      /* We only have a single condition-code register.  We implement
+        this by fixing all the condition-code registers and generating
+        RTL that refers directly to ST_REG_FIRST.  */
+      for (regno = ST_REG_FIRST; regno <= ST_REG_LAST; regno++)
+       fixed_regs[regno] = call_used_regs[regno] = 1;
     }
-  else
+  /* In MIPS16 mode, we permit the $t temporary registers to be used
+     for reload.  We prohibit the unused $s registers, since they
+     are call-saved, and saving them via a MIPS16 register would
+     probably waste more time than just reloading the value.  */
+  if (TARGET_MIPS16)
     {
-      op0 = mips_prepare_builtin_arg (icode, 1, exp, 2);
-      op1 = mips_prepare_builtin_arg (icode, 2, exp, 3);
+      fixed_regs[18] = call_used_regs[18] = 1;
+      fixed_regs[19] = call_used_regs[19] = 1;
+      fixed_regs[20] = call_used_regs[20] = 1;
+      fixed_regs[21] = call_used_regs[21] = 1;
+      fixed_regs[22] = call_used_regs[22] = 1;
+      fixed_regs[23] = call_used_regs[23] = 1;
+      fixed_regs[26] = call_used_regs[26] = 1;
+      fixed_regs[27] = call_used_regs[27] = 1;
+      fixed_regs[30] = call_used_regs[30] = 1;
     }
-  emit_insn (gen_mips_cond_move_tf_ps (target, op0, op1, cmp_result));
-  return target;
-}
-
-/* Move VALUE_IF_TRUE into TARGET if CONDITION is true; move VALUE_IF_FALSE
-   into TARGET otherwise.  Return TARGET.  */
-
-static rtx
-mips_builtin_branch_and_move (rtx condition, rtx target,
-                             rtx value_if_true, rtx value_if_false)
-{
-  rtx true_label, done_label;
+  /* $f20-$f23 are call-clobbered for n64.  */
+  if (mips_abi == ABI_64)
+    {
+      int regno;
+      for (regno = FP_REG_FIRST + 20; regno < FP_REG_FIRST + 24; regno++)
+       call_really_used_regs[regno] = call_used_regs[regno] = 1;
+    }
+  /* Odd registers in the range $f21-$f31 (inclusive) are call-clobbered
+     for n32.  */
+  if (mips_abi == ABI_N32)
+    {
+      int regno;
+      for (regno = FP_REG_FIRST + 21; regno <= FP_REG_FIRST + 31; regno+=2)
+       call_really_used_regs[regno] = call_used_regs[regno] = 1;
+    }
+  /* Make sure that double-register accumulator values are correctly
+     ordered for the current endianness.  */
+  if (TARGET_LITTLE_ENDIAN)
+    {
+      unsigned int regno;
 
-  true_label = gen_label_rtx ();
-  done_label = gen_label_rtx ();
+      mips_swap_registers (MD_REG_FIRST);
+      for (regno = DSP_ACC_REG_FIRST; regno <= DSP_ACC_REG_LAST; regno += 2)
+       mips_swap_registers (regno);
+    }
+}
 
-  /* First assume that CONDITION is false.  */
-  mips_emit_move (target, value_if_false);
+/* When generating MIPS16 code, we want to allocate $24 (T_REG) before
+   other registers for instructions for which it is possible.  This
+   encourages the compiler to use CMP in cases where an XOR would
+   require some register shuffling.  */
 
-  /* Branch to TRUE_LABEL if CONDITION is true and DONE_LABEL otherwise.  */
-  emit_jump_insn (gen_condjump (condition, true_label));
-  emit_jump_insn (gen_jump (done_label));
-  emit_barrier ();
+void
+mips_order_regs_for_local_alloc (void)
+{
+  int i;
 
-  /* Fix TARGET if CONDITION is true.  */
-  emit_label (true_label);
-  mips_emit_move (target, value_if_true);
+  for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
+    reg_alloc_order[i] = i;
 
-  emit_label (done_label);
-  return target;
+  if (TARGET_MIPS16)
+    {
+      /* It really doesn't matter where we put register 0, since it is
+         a fixed register anyhow.  */
+      reg_alloc_order[0] = 24;
+      reg_alloc_order[24] = 0;
+    }
 }
+\f
+/* Initialize the GCC target structure.  */
+#undef TARGET_ASM_ALIGNED_HI_OP
+#define TARGET_ASM_ALIGNED_HI_OP "\t.half\t"
+#undef TARGET_ASM_ALIGNED_SI_OP
+#define TARGET_ASM_ALIGNED_SI_OP "\t.word\t"
+#undef TARGET_ASM_ALIGNED_DI_OP
+#define TARGET_ASM_ALIGNED_DI_OP "\t.dword\t"
 
-/* Expand a comparison builtin of type BUILTIN_TYPE.  ICODE is the code
-   of the comparison instruction and COND is the condition it should test.
-   EXP is the function call and arguments and TARGET, if nonnull,
-   suggests a good place to put the boolean result.  */
+#undef TARGET_ASM_FUNCTION_PROLOGUE
+#define TARGET_ASM_FUNCTION_PROLOGUE mips_output_function_prologue
+#undef TARGET_ASM_FUNCTION_EPILOGUE
+#define TARGET_ASM_FUNCTION_EPILOGUE mips_output_function_epilogue
+#undef TARGET_ASM_SELECT_RTX_SECTION
+#define TARGET_ASM_SELECT_RTX_SECTION mips_select_rtx_section
+#undef TARGET_ASM_FUNCTION_RODATA_SECTION
+#define TARGET_ASM_FUNCTION_RODATA_SECTION mips_function_rodata_section
 
-static rtx
-mips_expand_builtin_compare (enum mips_builtin_type builtin_type,
-                            enum insn_code icode, enum mips_fp_condition cond,
-                            rtx target, tree exp)
-{
-  rtx offset, condition, cmp_result, ops[MAX_RECOG_OPERANDS];
-  int i;
-  int j = 0;
+#undef TARGET_SCHED_INIT
+#define TARGET_SCHED_INIT mips_sched_init
+#undef TARGET_SCHED_REORDER
+#define TARGET_SCHED_REORDER mips_sched_reorder
+#undef TARGET_SCHED_REORDER2
+#define TARGET_SCHED_REORDER2 mips_sched_reorder
+#undef TARGET_SCHED_VARIABLE_ISSUE
+#define TARGET_SCHED_VARIABLE_ISSUE mips_variable_issue
+#undef TARGET_SCHED_ADJUST_COST
+#define TARGET_SCHED_ADJUST_COST mips_adjust_cost
+#undef TARGET_SCHED_ISSUE_RATE
+#define TARGET_SCHED_ISSUE_RATE mips_issue_rate
+#undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
+#define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD \
+  mips_multipass_dfa_lookahead
 
-  if (target == 0 || GET_MODE (target) != SImode)
-    target = gen_reg_rtx (SImode);
+#undef TARGET_DEFAULT_TARGET_FLAGS
+#define TARGET_DEFAULT_TARGET_FLAGS            \
+  (TARGET_DEFAULT                              \
+   | TARGET_CPU_DEFAULT                                \
+   | TARGET_ENDIAN_DEFAULT                     \
+   | TARGET_FP_EXCEPTIONS_DEFAULT              \
+   | MASK_CHECK_ZERO_DIV                       \
+   | MASK_FUSED_MADD)
+#undef TARGET_HANDLE_OPTION
+#define TARGET_HANDLE_OPTION mips_handle_option
 
-  /* Prepare the operands to the comparison.  */
-  cmp_result = mips_prepare_builtin_target (icode, 0, 0);
-  for (i = 1; i < insn_data[icode].n_operands - 1; i++, j++)
-    ops[i] = mips_prepare_builtin_arg (icode, i, exp, j);
+#undef TARGET_FUNCTION_OK_FOR_SIBCALL
+#define TARGET_FUNCTION_OK_FOR_SIBCALL mips_function_ok_for_sibcall
 
-  switch (insn_data[icode].n_operands)
-    {
-    case 4:
-      emit_insn (GEN_FCN (icode) (cmp_result, ops[1], ops[2], GEN_INT (cond)));
-      break;
+#undef TARGET_INSERT_ATTRIBUTES
+#define TARGET_INSERT_ATTRIBUTES mips_insert_attributes
+#undef TARGET_MERGE_DECL_ATTRIBUTES
+#define TARGET_MERGE_DECL_ATTRIBUTES mips_merge_decl_attributes
+#undef TARGET_SET_CURRENT_FUNCTION
+#define TARGET_SET_CURRENT_FUNCTION mips_set_current_function
 
-    case 6:
-      emit_insn (GEN_FCN (icode) (cmp_result, ops[1], ops[2],
-                                 ops[3], ops[4], GEN_INT (cond)));
-      break;
+#undef TARGET_VALID_POINTER_MODE
+#define TARGET_VALID_POINTER_MODE mips_valid_pointer_mode
+#undef TARGET_RTX_COSTS
+#define TARGET_RTX_COSTS mips_rtx_costs
+#undef TARGET_ADDRESS_COST
+#define TARGET_ADDRESS_COST mips_address_cost
 
-    default:
-      gcc_unreachable ();
-    }
+#undef TARGET_IN_SMALL_DATA_P
+#define TARGET_IN_SMALL_DATA_P mips_in_small_data_p
 
-  /* If the comparison sets more than one register, we define the result
-     to be 0 if all registers are false and -1 if all registers are true.
-     The value of the complete result is indeterminate otherwise.  */
-  switch (builtin_type)
-    {
-    case MIPS_BUILTIN_CMP_ALL:
-      condition = gen_rtx_NE (VOIDmode, cmp_result, constm1_rtx);
-      return mips_builtin_branch_and_move (condition, target,
-                                          const0_rtx, const1_rtx);
+#undef TARGET_MACHINE_DEPENDENT_REORG
+#define TARGET_MACHINE_DEPENDENT_REORG mips_reorg
 
-    case MIPS_BUILTIN_CMP_UPPER:
-    case MIPS_BUILTIN_CMP_LOWER:
-      offset = GEN_INT (builtin_type == MIPS_BUILTIN_CMP_UPPER);
-      condition = gen_single_cc (cmp_result, offset);
-      return mips_builtin_branch_and_move (condition, target,
-                                          const1_rtx, const0_rtx);
+#undef TARGET_ASM_FILE_START
+#define TARGET_ASM_FILE_START mips_file_start
+#undef TARGET_ASM_FILE_START_FILE_DIRECTIVE
+#define TARGET_ASM_FILE_START_FILE_DIRECTIVE true
 
-    default:
-      condition = gen_rtx_NE (VOIDmode, cmp_result, const0_rtx);
-      return mips_builtin_branch_and_move (condition, target,
-                                          const1_rtx, const0_rtx);
-    }
-}
+#undef TARGET_INIT_LIBFUNCS
+#define TARGET_INIT_LIBFUNCS mips_init_libfuncs
 
-/* Expand a bposge builtin of type BUILTIN_TYPE.  TARGET, if nonnull,
-   suggests a good place to put the boolean result.  */
+#undef TARGET_BUILD_BUILTIN_VA_LIST
+#define TARGET_BUILD_BUILTIN_VA_LIST mips_build_builtin_va_list
+#undef TARGET_EXPAND_BUILTIN_VA_START
+#define TARGET_EXPAND_BUILTIN_VA_START mips_va_start
+#undef TARGET_GIMPLIFY_VA_ARG_EXPR
+#define TARGET_GIMPLIFY_VA_ARG_EXPR mips_gimplify_va_arg_expr
 
-static rtx
-mips_expand_builtin_bposge (enum mips_builtin_type builtin_type, rtx target)
-{
-  rtx condition, cmp_result;
-  int cmp_value;
+#undef TARGET_PROMOTE_FUNCTION_ARGS
+#define TARGET_PROMOTE_FUNCTION_ARGS hook_bool_const_tree_true
+#undef TARGET_PROMOTE_FUNCTION_RETURN
+#define TARGET_PROMOTE_FUNCTION_RETURN hook_bool_const_tree_true
+#undef TARGET_PROMOTE_PROTOTYPES
+#define TARGET_PROMOTE_PROTOTYPES hook_bool_const_tree_true
 
-  if (target == 0 || GET_MODE (target) != SImode)
-    target = gen_reg_rtx (SImode);
+#undef TARGET_RETURN_IN_MEMORY
+#define TARGET_RETURN_IN_MEMORY mips_return_in_memory
+#undef TARGET_RETURN_IN_MSB
+#define TARGET_RETURN_IN_MSB mips_return_in_msb
 
-  cmp_result = gen_rtx_REG (CCDSPmode, CCDSP_PO_REGNUM);
+#undef TARGET_ASM_OUTPUT_MI_THUNK
+#define TARGET_ASM_OUTPUT_MI_THUNK mips_output_mi_thunk
+#undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
+#define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
 
-  if (builtin_type == MIPS_BUILTIN_BPOSGE32)
-    cmp_value = 32;
-  else
-    gcc_assert (0);
+#undef TARGET_SETUP_INCOMING_VARARGS
+#define TARGET_SETUP_INCOMING_VARARGS mips_setup_incoming_varargs
+#undef TARGET_STRICT_ARGUMENT_NAMING
+#define TARGET_STRICT_ARGUMENT_NAMING mips_strict_argument_naming
+#undef TARGET_MUST_PASS_IN_STACK
+#define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
+#undef TARGET_PASS_BY_REFERENCE
+#define TARGET_PASS_BY_REFERENCE mips_pass_by_reference
+#undef TARGET_CALLEE_COPIES
+#define TARGET_CALLEE_COPIES mips_callee_copies
+#undef TARGET_ARG_PARTIAL_BYTES
+#define TARGET_ARG_PARTIAL_BYTES mips_arg_partial_bytes
 
-  condition = gen_rtx_GE (VOIDmode, cmp_result, GEN_INT (cmp_value));
-  return mips_builtin_branch_and_move (condition, target,
-                                      const1_rtx, const0_rtx);
-}
-\f
-/* Set SYMBOL_REF_FLAGS for the SYMBOL_REF inside RTL, which belongs to DECL.
-   FIRST is true if this is the first time handling this decl.  */
+#undef TARGET_MODE_REP_EXTENDED
+#define TARGET_MODE_REP_EXTENDED mips_mode_rep_extended
 
-static void
-mips_encode_section_info (tree decl, rtx rtl, int first)
-{
-  default_encode_section_info (decl, rtl, first);
+#undef TARGET_VECTOR_MODE_SUPPORTED_P
+#define TARGET_VECTOR_MODE_SUPPORTED_P mips_vector_mode_supported_p
 
-  if (TREE_CODE (decl) == FUNCTION_DECL)
-    {
-      rtx symbol = XEXP (rtl, 0);
-      tree type = TREE_TYPE (decl);
+#undef TARGET_SCALAR_MODE_SUPPORTED_P
+#define TARGET_SCALAR_MODE_SUPPORTED_P mips_scalar_mode_supported_p
 
-      if ((TARGET_LONG_CALLS && !mips_near_type_p (type))
-         || mips_far_type_p (type))
-       SYMBOL_REF_FLAGS (symbol) |= SYMBOL_FLAG_LONG_CALL;
-    }
-}
+#undef TARGET_INIT_BUILTINS
+#define TARGET_INIT_BUILTINS mips_init_builtins
+#undef TARGET_EXPAND_BUILTIN
+#define TARGET_EXPAND_BUILTIN mips_expand_builtin
 
-/* Implement TARGET_EXTRA_LIVE_ON_ENTRY.  Some code models use the incoming
-   value of PIC_FUNCTION_ADDR_REGNUM to set up the global pointer.  */
+#undef TARGET_HAVE_TLS
+#define TARGET_HAVE_TLS HAVE_AS_TLS
 
-static void
-mips_extra_live_on_entry (bitmap regs)
-{
-  if (TARGET_USE_GOT && !TARGET_ABSOLUTE_ABICALLS)
-    bitmap_set_bit (regs, PIC_FUNCTION_ADDR_REGNUM);
-}
+#undef TARGET_CANNOT_FORCE_CONST_MEM
+#define TARGET_CANNOT_FORCE_CONST_MEM mips_cannot_force_const_mem
 
-/* SImode values are represented as sign-extended to DImode.  */
+#undef TARGET_ENCODE_SECTION_INFO
+#define TARGET_ENCODE_SECTION_INFO mips_encode_section_info
 
-int
-mips_mode_rep_extended (enum machine_mode mode, enum machine_mode mode_rep)
-{
-  if (TARGET_64BIT && mode == SImode && mode_rep == DImode)
-    return SIGN_EXTEND;
+#undef TARGET_ATTRIBUTE_TABLE
+#define TARGET_ATTRIBUTE_TABLE mips_attribute_table
+/* All our function attributes are related to how out-of-line copies should
+   be compiled or called.  They don't in themselves prevent inlining.  */
+#undef TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P
+#define TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P hook_bool_const_tree_true
 
-  return UNKNOWN;
-}
-\f
-/* MIPS implementation of TARGET_ASM_OUTPUT_DWARF_DTPREL.  */
+#undef TARGET_EXTRA_LIVE_ON_ENTRY
+#define TARGET_EXTRA_LIVE_ON_ENTRY mips_extra_live_on_entry
 
-static void
-mips_output_dwarf_dtprel (FILE *file, int size, rtx x)
-{
-  switch (size)
-    {
-    case 4:
-      fputs ("\t.dtprelword\t", file);
-      break;
+#undef TARGET_USE_BLOCKS_FOR_CONSTANT_P
+#define TARGET_USE_BLOCKS_FOR_CONSTANT_P mips_use_blocks_for_constant_p
+#undef TARGET_USE_ANCHORS_FOR_SYMBOL_P
+#define TARGET_USE_ANCHORS_FOR_SYMBOL_P mips_use_anchors_for_symbol_p
 
-    case 8:
-      fputs ("\t.dtpreldword\t", file);
-      break;
+#undef  TARGET_COMP_TYPE_ATTRIBUTES
+#define TARGET_COMP_TYPE_ATTRIBUTES mips_comp_type_attributes
 
-    default:
-      gcc_unreachable ();
-    }
-  output_addr_const (file, x);
-  fputs ("+0x8000", file);
-}
+#ifdef HAVE_AS_DTPRELWORD
+#undef TARGET_ASM_OUTPUT_DWARF_DTPREL
+#define TARGET_ASM_OUTPUT_DWARF_DTPREL mips_output_dwarf_dtprel
+#endif
+#undef TARGET_DWARF_REGISTER_SPAN
+#define TARGET_DWARF_REGISTER_SPAN mips_dwarf_register_span
+
+struct gcc_target targetm = TARGET_INITIALIZER;
 \f
 #include "gt-mips.h"