]> git.ipfire.org Git - thirdparty/gcc.git/blobdiff - gcc/config/mips/mips.c
install.texi (--with-mips-plt): Document.
[thirdparty/gcc.git] / gcc / config / mips / mips.c
index c5b30f7ad9bd8545e7b9d7b247c059be6e078353..e9eb20cc0eec58bb7ef5440ef53775fff17c20b7 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, 2008
    Free Software Foundation, Inc.
    Contributed by A. Lichnewsky, lich@inria.inria.fr.
    Changes by Michael Meissner, meissner@osf.org.
@@ -42,6 +42,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "function.h"
 #include "expr.h"
 #include "optabs.h"
+#include "libfuncs.h"
 #include "flags.h"
 #include "reload.h"
 #include "tm_p.h"
@@ -55,11 +56,11 @@ along with GCC; see the file COPYING3.  If not see
 #include "langhooks.h"
 #include "cfglayout.h"
 #include "sched-int.h"
-#include "tree-gimple.h"
+#include "gimple.h"
 #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 +140,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,
@@ -153,35 +154,33 @@ enum mips_address_type {
 #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 builtin function.  */
-enum mips_function_type
-{
+/* 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
@@ -203,7 +202,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),  \
@@ -234,11 +233,8 @@ static const char *const mips_fp_conditions[] = {
   MIPS_FP_CONDITIONS (STRINGIFY)
 };
 
-/* Structure to be filled in by compute_frame_size with register
-   save masks, and offsets for the current function.  */
-
-struct mips_frame_info GTY(())
-{
+/* Information about a function's frame layout.  */
+struct mips_frame_info GTY(()) {
   /* The size of the frame in bytes.  */
   HOST_WIDE_INT total_size;
 
@@ -252,10 +248,6 @@ struct mips_frame_info GTY(())
      is no such slot.  */
   HOST_WIDE_INT cprestore_size;
 
-  /* The size in bytes of the GPR and FPR save areas.  */
-  HOST_WIDE_INT gp_reg_size;
-  HOST_WIDE_INT fp_reg_size;
-
   /* Bit X is set if the function saves or restores GPR X.  */
   unsigned int mask;
 
@@ -280,24 +272,20 @@ struct mips_frame_info GTY(())
 
   /* The offset of hard_frame_pointer_rtx from frame_pointer_rtx.  */
   HOST_WIDE_INT hard_frame_pointer_offset;
-
-  /* True if this structure has been initialized after reload.  */
-  bool initialized;
 };
 
 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
@@ -317,8 +305,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;
@@ -343,7 +330,6 @@ struct mips_arg_info
   unsigned int stack_offset;
 };
 
-
 /* Information about an address described by mips_address_type.
 
    ADDRESS_CONST_INT
@@ -353,22 +339,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:
 
@@ -378,13 +360,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
@@ -406,64 +387,65 @@ 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;
 
-/* Name of the file containing the current function.  */
+/* 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 = "";
 
-/* Count the number of sdb related labels are generated (to find block
-   start and end boundaries).  */
-int sdb_label_count = 0;
+/* A label counter used by PUT_SDB_BLOCK_START and PUT_SDB_BLOCK_END.  */
+int sdb_label_count;
 
-/* Next label # for each statement for Silicon Graphics IRIS systems.  */
-int sym_lineno = 0;
-
-/* Map GCC register number to debugger register number.  */
+/* 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;
+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.  */
-static const struct mips_cpu_info *mips_isa_info;
+/* 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.  */
-static bool mips_base_mips16;
-/* Similar copies of option settings.  */
-static int mips_flag_delayed_branch; /* flag_delayed_branch */
+
+/* True if MIPS16 is the default mode.  */
+bool mips_base_mips16;
+
+/* 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 */
@@ -471,28 +453,26 @@ static int mips_base_align_loops; /* align_loops */
 static int mips_base_align_jumps; /* align_jumps */
 static int mips_base_align_functions; /* align_functions */
 
-/* The -mtext-loads setting.  */
+/* The -mcode-readable setting.  */
 enum mips_code_readable_setting mips_code_readable = CODE_READABLE_YES;
 
-/* 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];
+/* 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_split_hi_p[X] is true if the high parts of symbols of type X
+   can be split by mips_split_symbol.  */
+bool mips_split_hi_p[NUM_SYMBOL_TYPES];
+
 /* mips_lo_relocs[X] is the relocation to use when a symbol of type X
    appears in a LO_SUM.  It can be null if such LO_SUMs aren't valid or
    if they are matched by a special .md file pattern.  */
@@ -501,14 +481,13 @@ 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[] =
-{
-  LEA_REGS,    LEA_REGS,       M16_NA_REGS,    V1_REG,
+/* 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_REGS,       V1_REG,
   M16_REGS,    M16_REGS,       M16_REGS,       M16_REGS,
   LEA_REGS,    LEA_REGS,       LEA_REGS,       LEA_REGS,
   LEA_REGS,    LEA_REGS,       LEA_REGS,       LEA_REGS,
-  M16_NA_REGS, M16_NA_REGS,    LEA_REGS,       LEA_REGS,
+  M16_REGS,    M16_REGS,       LEA_REGS,       LEA_REGS,
   LEA_REGS,    LEA_REGS,       LEA_REGS,       LEA_REGS,
   T_REG,       PIC_FN_ADDR_REG, LEA_REGS,      LEA_REGS,
   LEA_REGS,    LEA_REGS,       LEA_REGS,       LEA_REGS,
@@ -553,32 +532,31 @@ 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 */
+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 },
@@ -591,28 +569,33 @@ const struct mips_cpu_info mips_cpu_info_table[] = {
   { "mips32", PROCESSOR_4KC, 32, PTF_AVOID_BRANCHLIKELY },
   { "mips32r2", PROCESSOR_M4K, 33, PTF_AVOID_BRANCHLIKELY },
   { "mips64", PROCESSOR_5KC, 64, PTF_AVOID_BRANCHLIKELY },
+  /* ??? For now just tune the generic MIPS64r2 for 5KC as well.   */
+  { "mips64r2", PROCESSOR_5KC, 65, PTF_AVOID_BRANCHLIKELY },
 
-  /* MIPS I */
+  /* MIPS I processors.  */
   { "r3000", PROCESSOR_R3000, 1, 0 },
-  { "r2000", PROCESSOR_R3000, 1, 0 }, /* = r3000 */
+  { "r2000", PROCESSOR_R3000, 1, 0 },
   { "r3900", PROCESSOR_R3900, 1, 0 },
 
-  /* MIPS II */
+  /* MIPS II processors.  */
   { "r6000", PROCESSOR_R6000, 2, 0 },
 
-  /* MIPS III */
+  /* 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 }, /* = r4000 */
+  { "r4400", PROCESSOR_R4000, 3, 0 },
   { "r4600", PROCESSOR_R4600, 3, 0 },
-  { "orion", PROCESSOR_R4600, 3, 0 }, /* = r4600 */
+  { "orion", PROCESSOR_R4600, 3, 0 },
   { "r4650", PROCESSOR_R4650, 3, 0 },
+  /* ST Loongson 2E/2F processors.  */
+  { "loongson2e", PROCESSOR_LOONGSON_2E, 3, PTF_AVOID_BRANCHLIKELY },
+  { "loongson2f", PROCESSOR_LOONGSON_2F, 3, PTF_AVOID_BRANCHLIKELY },
 
-  /* MIPS IV */
+  /* MIPS IV processors. */
   { "r8000", PROCESSOR_R8000, 4, 0 },
   { "vr5000", PROCESSOR_R5000, 4, 0 },
   { "vr5400", PROCESSOR_R5400, 4, 0 },
@@ -620,13 +603,13 @@ const struct mips_cpu_info mips_cpu_info_table[] = {
   { "rm7000", PROCESSOR_R7000, 4, 0 },
   { "rm9000", PROCESSOR_R9000, 4, 0 },
 
-  /* MIPS32 */
+  /* MIPS32 processors.  */
   { "4kc", PROCESSOR_4KC, 32, 0 },
-  { "4km", PROCESSOR_4KC, 32, 0 }, /* = 4kc */
+  { "4km", PROCESSOR_4KC, 32, 0 },
   { "4kp", PROCESSOR_4KP, 32, 0 },
   { "4ksc", PROCESSOR_4KC, 32, 0 },
 
-  /* MIPS32 Release 2 */
+  /* MIPS32 Release 2 processors.  */
   { "m4k", PROCESSOR_M4K, 33, 0 },
   { "4kec", PROCESSOR_4KC, 33, 0 },
   { "4kem", PROCESSOR_4KC, 33, 0 },
@@ -640,21 +623,21 @@ const struct mips_cpu_info mips_cpu_info_table[] = {
   { "24kfx", PROCESSOR_24KF1_1, 33, 0 },
   { "24kx", PROCESSOR_24KF1_1, 33, 0 },
 
-  { "24kec", PROCESSOR_24KC, 33, 0 }, /* 24K with DSP */
+  { "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 */
+  { "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 */
+  { "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 },
@@ -662,16 +645,17 @@ const struct mips_cpu_info mips_cpu_info_table[] = {
   { "74kx", PROCESSOR_74KF1_1, 33, 0 },
   { "74kf3_2", PROCESSOR_74KF3_2, 33, 0 },
 
-  /* MIPS64 */
+  /* 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 },
+  { "xlr", PROCESSOR_XLR, 64, 0 }
 };
 
-/* 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 */   \
@@ -685,360 +669,379 @@ 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
-    },
-  };
+/* 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 */
+};
+
+/* 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 */
+  },
+  { /* Loongson-2E */
+    DEFAULT_COSTS
+  },
+  { /* Loongson-2F */
+    DEFAULT_COSTS
+  },
+  { /* 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
+  },
+  { /* XLR */
+    /* Need to replace first five with the costs of calling the appropriate 
+       libgcc routine.  */
+    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 */
+    COSTS_N_INSNS (8),            /* int_mult_si */
+    COSTS_N_INSNS (8),            /* int_mult_di */
+    COSTS_N_INSNS (72),           /* int_div_si */
+    COSTS_N_INSNS (72),           /* int_div_di */
+                    1,           /* branch_cost */
+                    4            /* memory_latency */
+  }
+};
 \f
-/* Use a hash table to keep track of implicit mips16/nomips16 attributes
+/* 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;
@@ -1060,7 +1063,9 @@ mflip_mips16_htab_eq (const void *entry, const void *name)
                 (const char *) name) == 0;
 }
 
-static GTY(()) int mips16_flipper;
+/* 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;
 
 /* 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
@@ -1113,7 +1118,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)
@@ -1148,23 +1153,16 @@ mips_use_mips16_mode_p (tree decl)
   return mips_base_mips16;
 }
 
-/* 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).  */
+/* Implement TARGET_COMP_TYPE_ATTRIBUTES.  */
 
 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;
-
   /* 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;
 }
 
@@ -1192,7 +1190,7 @@ mips_insert_attributes (tree decl, tree *attributes)
       nomips16_p |= mips_nomips16_decl_p (decl);
       if (mips16_p || nomips16_p)
        {
-         /* DECL cannot be simultaneously mips16 and nomips16.  */
+         /* DECL cannot be simultaneously "mips16" and "nomips16".  */
          if (mips16_p && nomips16_p)
            error ("%qs cannot have both %<mips16%> and "
                   "%<nomips16%> attributes",
@@ -1247,7 +1245,7 @@ mips_split_plus (rtx x, rtx *base_ptr, HOST_WIDE_INT *offset_ptr)
 static unsigned int mips_build_integer (struct mips_integer_op *,
                                        unsigned HOST_WIDE_INT);
 
-/* Subroutine of mips_build_integer (with the same interface).
+/* 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
@@ -1267,7 +1265,6 @@ mips_build_shift (struct mips_integer_op *codes, HOST_WIDE_INT value)
   return i + 1;
 }
 
-
 /* As for mips_build_shift, but assume that the final action will be
    an IOR or PLUS operation.  */
 
@@ -1280,17 +1277,19 @@ mips_build_lower (struct mips_integer_op *codes, unsigned HOST_WIDE_INT value)
   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.  */
+      /* 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;
@@ -1298,7 +1297,6 @@ mips_build_lower (struct mips_integer_op *codes, unsigned HOST_WIDE_INT value)
   return i + 1;
 }
 
-
 /* Fill CODES with a sequence of rtl operations to load VALUE.
    Return the number of operations needed.  */
 
@@ -1348,10 +1346,26 @@ mips_build_integer (struct mips_integer_op *codes,
     }
 }
 \f
+/* Return true if symbols of type TYPE require a GOT access.  */
+
+static bool
+mips_got_symbol_type_p (enum mips_symbol_type type)
+{
+  switch (type)
+    {
+    case SYMBOL_GOT_PAGE_OFST:
+    case SYMBOL_GOT_DISP:
+      return true;
+
+    default:
+      return false;
+    }
+}
+
 /* Return true if X is a thread-local symbol.  */
 
 static bool
-mips_tls_operand_p (rtx x)
+mips_tls_symbol_p (rtx x)
 {
   return GET_CODE (x) == SYMBOL_REF && SYMBOL_REF_TLS_MODEL (x) != 0;
 }
@@ -1362,10 +1376,10 @@ mips_tls_operand_p (rtx x)
 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);
+    return !SYMBOL_REF_LOCAL_P (x) || SYMBOL_REF_EXTERNAL_P (x);
 
   /* Weakref symbols are not TREE_PUBLIC, but their targets are global
      or weak symbols.  Relocations in the object file will be against
@@ -1373,6 +1387,27 @@ mips_global_symbol_p (const_rtx x)
   return DECL_P (decl) && (TREE_PUBLIC (decl) || DECL_WEAK (decl));
 }
 
+/* Return true if function X is a libgcc MIPS16 stub function.  */
+
+static bool
+mips16_stub_function_p (const_rtx x)
+{
+  return (GET_CODE (x) == SYMBOL_REF
+         && strncmp (XSTR (x, 0), "__mips16_", 9) == 0);
+}
+
+/* Return true if function X is a locally-defined and locally-binding
+   MIPS16 function.  */
+
+static bool
+mips16_local_function_p (const_rtx x)
+{
+  return (GET_CODE (x) == SYMBOL_REF
+         && SYMBOL_REF_LOCAL_P (x)
+         && !SYMBOL_REF_EXTERNAL_P (x)
+         && mips_use_mips16_mode_p (SYMBOL_REF_DECL (x)));
+}
+
 /* Return true if SYMBOL_REF X binds locally.  */
 
 static bool
@@ -1391,7 +1426,7 @@ 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.
@@ -1407,6 +1442,36 @@ mips_dangerous_for_la25_p (rtx x)
          && mips_global_symbol_p (x));
 }
 
+/* Return true if calls to X might need $25 to be valid on entry.  */
+
+bool
+mips_use_pic_fn_addr_reg_p (const_rtx x)
+{
+  if (!TARGET_USE_PIC_FN_ADDR_REG)
+    return false;
+
+  /* MIPS16 stub functions are guaranteed not to use $25.  */
+  if (mips16_stub_function_p (x))
+    return false;
+
+  if (GET_CODE (x) == SYMBOL_REF)
+    {
+      /* If PLTs and copy relocations are available, the static linker
+        will make sure that $25 is valid on entry to the target function.  */
+      if (TARGET_ABICALLS_PIC0)
+       return false;
+
+      /* Locally-defined functions use absolute accesses to set up
+        the global pointer.  */
+      if (TARGET_ABSOLUTE_ABICALLS
+         && mips_symbol_binds_local_p (x)
+         && !SYMBOL_REF_EXTERNAL_P (x))
+       return false;
+    }
+
+  return true;
+}
+
 /* Return the method that should be used to access SYMBOL_REF or
    LABEL_REF X in context CONTEXT.  */
 
@@ -1423,8 +1488,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;
     }
 
@@ -1447,14 +1514,12 @@ 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
      is in effect.  */
-  if (TARGET_ABICALLS
+  if (TARGET_ABICALLS_PIC2
       && !(TARGET_ABSOLUTE_ABICALLS && mips_symbol_binds_local_p (x)))
     {
       /* There are three cases to consider:
@@ -1484,11 +1549,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)
@@ -1503,23 +1569,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;
-
-  /* Get the alignment of the symbol we're referring to.  */
-  t = SYMBOL_REF_DECL (x);
-  if (t)
-    align = DECL_ALIGN_UNIT (t);
+  HOST_WIDE_INT align;
 
-  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
@@ -1634,8 +1692,8 @@ mips_symbol_insns_1 (enum mips_symbol_type type, enum machine_mode mode)
             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.  */
+        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;
 
     case SYMBOL_GP_RELATIVE:
@@ -1644,14 +1702,14 @@ mips_symbol_insns_1 (enum mips_symbol_type type, enum machine_mode mode)
       return 1;
 
     case SYMBOL_PC_RELATIVE:
-      /* PC-relative constants can be only be used with addiupc,
-        lwpc and ldpc.  */
+      /* 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;
 
-      /* The constant must be loaded using addiupc first.  */
+      /* The constant must be loaded using ADDIUPC or DADDIUPC first.  */
       return 0;
 
     case SYMBOL_FORCE_TO_MEM:
@@ -1660,7 +1718,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:
@@ -1672,11 +1730,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:
@@ -1710,7 +1765,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:
@@ -1735,42 +1792,57 @@ mips_symbol_insns (enum mips_symbol_type type, enum machine_mode mode)
 {
   return mips_symbol_insns_1 (type, mode) * (TARGET_MIPS16 ? 2 : 1);
 }
-
-/* Return true if X can not be forced into a constant pool.  */
+\f
+/* A for_each_rtx callback.  Stop the search if *X references a
+   thread-local symbol.  */
 
 static int
 mips_tls_symbol_ref_1 (rtx *x, void *data ATTRIBUTE_UNUSED)
 {
-  return mips_tls_operand_p (*x);
+  return mips_tls_symbol_p (*x);
 }
 
-/* Return true if X can not be forced into a constant pool.  */
+/* Implement TARGET_CANNOT_FORCE_CONST_MEM.  */
 
 static bool
 mips_cannot_force_const_mem (rtx x)
 {
+  enum mips_symbol_type type;
   rtx base, offset;
 
-  if (!TARGET_MIPS16)
-    {
-      /* As an optimization, reject constants that mips_legitimize_move
-        can expand inline.
+  /* There is no assembler syntax for expressing an address-sized
+     high part.  */
+  if (GET_CODE (x) == HIGH)
+    return true;
+
+  /* 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 && LEGITIMATE_CONSTANT_P (x))
+    return true;
 
-        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)
+  split_const (x, &base, &offset);
+  if (mips_symbolic_constant_p (base, SYMBOL_CONTEXT_LEA, &type)
+      && type != SYMBOL_FORCE_TO_MEM)
+    {
+      /* The same optimization as for CONST_INT.  */
+      if (SMALL_INT (offset) && mips_symbol_insns (type, MAX_MACHINE_MODE) > 0)
        return true;
 
-      split_const (x, &base, &offset);
-      if (symbolic_operand (base, VOIDmode) && SMALL_INT (offset))
+      /* If MIPS16 constant pools live in the text section, they should
+        not refer to anything that might need run-time relocation.  */
+      if (TARGET_MIPS16_PCREL_LOADS && mips_got_symbol_type_p (type))
        return true;
     }
 
-  if (for_each_rtx (&x, &mips_tls_symbol_ref_1, 0))
+  /* TLS symbols must be computed by mips_legitimize_move.  */
+  if (for_each_rtx (&x, &mips_tls_symbol_ref_1, NULL))
     return true;
 
   return false;
@@ -1786,14 +1858,16 @@ mips_use_blocks_for_constant_p (enum machine_mode mode ATTRIBUTE_UNUSED,
   return !TARGET_MIPS16_PCREL_LOADS;
 }
 \f
-/* This function is used to implement REG_MODE_OK_FOR_BASE_P.  */
+/* 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_regno_mode_ok_for_base_p (int regno, enum machine_mode mode, int strict)
+mips_regno_mode_ok_for_base_p (int regno, enum machine_mode mode,
+                              bool strict_p)
 {
   if (!HARD_REGISTER_NUM_P (regno))
     {
-      if (!strict)
+      if (!strict_p)
        return true;
       regno = reg_renumber[regno];
     }
@@ -1804,7 +1878,7 @@ mips_regno_mode_ok_for_base_p (int regno, enum machine_mode mode, int strict)
   if (regno == ARG_POINTER_REGNUM || regno == FRAME_POINTER_REGNUM)
     return true;
 
-  /* In mips16 mode, the stack pointer can only address word and doubleword
+  /* 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
@@ -1820,33 +1894,76 @@ mips_regno_mode_ok_for_base_p (int regno, enum machine_mode mode, int strict)
      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;
+    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 the given mode.
-   Allow only hard registers if STRICT.  */
+/* Return true if X is a valid base register for mode MODE.
+   STRICT_P is true if REG_OK_STRICT is in effect.  */
 
 static bool
-mips_valid_base_register_p (rtx x, enum machine_mode mode, int strict)
+mips_valid_base_register_p (rtx x, enum machine_mode mode, bool strict_p)
 {
-  if (!strict && GET_CODE (x) == SUBREG)
+  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));
+         && mips_regno_mode_ok_for_base_p (REGNO (x), mode, strict_p));
+}
+
+/* Return true if, for every base register BASE_REG, (plus BASE_REG X)
+   can address a value of mode MODE.  */
+
+static bool
+mips_valid_offset_p (rtx x, enum machine_mode mode)
+{
+  /* Check that X is a signed 16-bit number.  */
+  if (!const_arith_operand (x, Pmode))
+    return false;
+
+  /* We may need to split multiword moves, so make sure that every word
+     is accessible.  */
+  if (GET_MODE_SIZE (mode) > UNITS_PER_WORD
+      && !SMALL_OPERAND (INTVAL (x) + GET_MODE_SIZE (mode) - UNITS_PER_WORD))
+    return false;
+
+  return true;
 }
 
+/* Return true if a LO_SUM can address a value of mode MODE when the
+   LO_SUM symbol has type SYMBOL_TYPE.  */
+
+static bool
+mips_valid_lo_sum_p (enum mips_symbol_type symbol_type, enum machine_mode mode)
+{
+  /* Check that symbols of type SYMBOL_TYPE can be used to access values
+     of mode MODE.  */
+  if (mips_symbol_insns (symbol_type, mode) == 0)
+    return false;
+
+  /* Check that there is a known low-part relocation.  */
+  if (mips_lo_relocs[symbol_type] == NULL)
+    return false;
+
+  /* We may need to split multiword moves, so make sure that each word
+     can be accessed without inducing a carry.  This is mainly needed
+     for o64, which has historically only guaranteed 64-bit alignment
+     for 128-bit types.  */
+  if (GET_MODE_SIZE (mode) > UNITS_PER_WORD
+      && GET_MODE_BITSIZE (mode) > GET_MODE_ALIGNMENT (mode))
+    return false;
+
+  return true;
+}
 
 /* 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.  */
+   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, int strict)
+                      enum machine_mode mode, bool strict_p)
 {
   switch (GET_CODE (x))
     {
@@ -1855,14 +1972,14 @@ mips_classify_address (struct mips_address_info *info, rtx x,
       info->type = ADDRESS_REG;
       info->reg = x;
       info->offset = const0_rtx;
-      return mips_valid_base_register_p (info->reg, mode, strict);
+      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)
-             && const_arith_operand (info->offset, VOIDmode));
+      return (mips_valid_base_register_p (info->reg, mode, strict_p)
+             && mips_valid_offset_p (info->offset, mode));
 
     case LO_SUM:
       info->type = ADDRESS_LO_SUM;
@@ -1879,9 +1996,8 @@ mips_classify_address (struct mips_address_info *info, rtx x,
         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);
+      return (mips_valid_base_register_p (info->reg, mode, strict_p)
+             && mips_valid_lo_sum_p (info->symbol_type, mode));
 
     case CONST_INT:
       /* Small-integer addresses don't occur very often, but they
@@ -1903,17 +2019,15 @@ mips_classify_address (struct mips_address_info *info, rtx x,
     }
 }
 
-/* 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.  */
+/* 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, int strict)
+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);
+  return mips_classify_address (&addr, x, mode, strict_p);
 }
 
 /* Return true if X is a legitimate $sp-based address for mode MDOE.  */
@@ -1928,8 +2042,10 @@ mips_stack_address_p (rtx x, enum machine_mode mode)
          && addr.reg == stack_pointer_rtx);
 }
 
-/* Return true if ADDR matches the pattern for the lwxs load scaled indexed
-   address instruction.  */
+/* 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)
@@ -1947,38 +2063,36 @@ mips_lwxs_address_p (rtx addr)
     }
   return false;
 }
-
-/* 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.
+\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 HIs, twice
-   for SIs, and so on.  An exception is SImode accesses off the
-   stack pointer, which have an 8-bit immediate 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, rtx offset)
+mips16_unextended_reference_p (enum machine_mode mode, rtx base,
+                              unsigned HOST_WIDE_INT offset)
 {
-  if (TARGET_MIPS16
-      && GET_CODE (offset) == CONST_INT
-      && INTVAL (offset) >= 0
-      && (INTVAL (offset) & (GET_MODE_SIZE (mode) - 1)) == 0)
+  if (offset % GET_MODE_SIZE (mode) == 0)
     {
       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);
+       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 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.
+   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.  */
+   For MIPS16 code, count extended instructions as two instructions.  */
 
 int
 mips_address_insns (rtx x, enum machine_mode mode, bool might_split_p)
@@ -2000,12 +2114,13 @@ mips_address_insns (rtx x, enum machine_mode mode, bool might_split_p)
       {
       case ADDRESS_REG:
        if (TARGET_MIPS16
-           && !mips16_unextended_reference_p (mode, addr.reg, addr.offset))
+           && !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);
+       return TARGET_MIPS16 ? factor * 2 : factor;
 
       case ADDRESS_CONST_INT:
        return factor;
@@ -2016,8 +2131,8 @@ mips_address_insns (rtx x, enum machine_mode mode, bool might_split_p)
   return 0;
 }
 
-
-/* Likewise for constant X.  */
+/* 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)
@@ -2034,8 +2149,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:
@@ -2044,9 +2159,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);
 
@@ -2054,7 +2169,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))
@@ -2065,8 +2181,13 @@ 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
-        must be calculated separately and then added to the base.  */
+        If the offset is a 16-bit value, we can load the base address
+        into a register and then use (D)ADDIU to add in the offset.
+        If the offset is larger, we can load the base and offset
+        into separate registers and add them together with (D)ADDU.
+        However, the latter is only possible before reload; during
+        and after reload, we must have the option of forcing the
+        constant into the pool instead.  */
       split_const (x, &x, &offset);
       if (offset != 0)
        {
@@ -2075,7 +2196,7 @@ mips_const_insns (rtx x)
            {
              if (SMALL_INT (offset))
                return n + 1;
-             else
+             else if (!targetm.cannot_force_const_mem (x))
                return n + 1 + mips_build_integer (codes, INTVAL (offset));
            }
        }
@@ -2091,10 +2212,24 @@ mips_const_insns (rtx x)
     }
 }
 
+/* X is a doubleword constant that can be handled by splitting it into
+   two words and loading each word separately.  Return the number of
+   instructions required to do this.  */
+
+int
+mips_split_const_insns (rtx x)
+{
+  unsigned int low, high;
+
+  low = mips_const_insns (mips_subword (x, false));
+  high = mips_const_insns (mips_subword (x, true));
+  gcc_assert (low > 0 && high > 0);
+  return low + high;
+}
 
 /* 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)
@@ -2118,7 +2253,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
@@ -2163,7 +2297,20 @@ mips_emit_binary (enum rtx_code code, rtx target, rtx op0, rtx op1)
                          gen_rtx_fmt_ee (code, GET_MODE (target), op0, op1)));
 }
 
-/* Copy VALUE to a register and return that register.  If new psuedos
+/* Compute (CODE OP0 OP1) and store the result in a new register
+   of mode MODE.  Return that new register.  */
+
+static rtx
+mips_force_binary (enum machine_mode mode, enum rtx_code code, rtx op0, rtx op1)
+{
+  rtx reg;
+
+  reg = gen_reg_rtx (mode);
+  mips_emit_binary (code, reg, op0, op1);
+  return reg;
+}
+
+/* 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
@@ -2173,102 +2320,51 @@ 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;
     }
 }
 
-/* If we can access small data directly (using gp-relative relocation
-   operators) return the small data pointer, otherwise return null.
-
-   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.  */
+/* Emit a call sequence with call pattern PATTERN and return the call
+   instruction itself (which is not necessarily the last instruction
+   emitted).  ORIG_ADDR is the original, unlegitimized address,
+   ADDR is the legitimized form, and LAZY_P is true if the call
+   address is lazily-bound.  */
 
 static rtx
-mips16_gp_pseudo_reg (void)
+mips_emit_call_insn (rtx pattern, rtx orig_addr, rtx addr, bool lazy_p)
 {
-  if (cfun->machine->mips16_gp_pseudo_rtx == NULL_RTX)
-    cfun->machine->mips16_gp_pseudo_rtx = gen_reg_rtx (Pmode);
+  rtx insn, reg;
 
-  /* 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))
-    {
-      rtx insn, scan;
-
-      /* 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);
-
-      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 ();
+  insn = emit_call_insn (pattern);
 
-      cfun->machine->initialized_mips16_gp_pseudo_p = true;
+  if (TARGET_MIPS16 && mips_use_pic_fn_addr_reg_p (orig_addr))
+    {
+      /* MIPS16 JALRs only take MIPS16 registers.  If the target
+        function requires $25 to be valid on entry, we must copy it
+        there separately.  The move instruction can be put in the
+        call's delay slot.  */
+      reg = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
+      emit_insn_before (gen_move_insn (reg, addr), insn);
+      use_reg (&CALL_INSN_FUNCTION_USAGE (insn), reg);
     }
 
-  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
-   constant in that context and can be split into a high part and a LO_SUM.
-   If so, and if LO_SUM_OUT is nonnull, emit the high part and return
-   the LO_SUM in *LO_SUM_OUT.  Leave *LO_SUM_OUT unchanged otherwise.
-
-   TEMP is as for mips_force_temporary and is used to load the high
-   part into a register.  */
-
-bool
-mips_split_symbol (rtx temp, rtx addr, enum machine_mode mode, rtx *lo_sum_out)
-{
-  enum mips_symbol_context context;
-  enum mips_symbol_type symbol_type;
-  rtx high;
-
-  context = (mode == MAX_MACHINE_MODE
-            ? SYMBOL_CONTEXT_LEA
-            : SYMBOL_CONTEXT_MEM);
-  if (!mips_symbolic_constant_p (addr, context, &symbol_type)
-      || mips_symbol_insns (symbol_type, mode) == 0
-      || !mips_split_p[symbol_type])
-    return false;
+  if (lazy_p)
+    /* Lazy-binding stubs require $gp to be valid on entry.  */
+    use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
 
-  if (lo_sum_out)
+  if (TARGET_USE_GOT)
     {
-      if (symbol_type == SYMBOL_GP_RELATIVE)
-       {
-         if (!can_create_pseudo_p ())
-           {
-             emit_insn (gen_load_const_gp (copy_rtx (temp)));
-             high = temp;
-           }
-         else
-           high = mips16_gp_pseudo_reg ();
-       }
-      else
-       {
-         high = gen_rtx_HIGH (Pmode, copy_rtx (addr));
-         high = mips_force_temporary (temp, high);
-       }
-      *lo_sum_out = gen_rtx_LO_SUM (Pmode, high, addr);
+      /* 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 true;
+  return insn;
 }
-
-
-/* Wrap symbol or label BASE in an unspec address of type SYMBOL_TYPE
-   and add CONST_INT OFFSET to the result.  */
+\f
+/* 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,
@@ -2293,10 +2389,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.  */
 
@@ -2308,111 +2403,300 @@ 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.  */
+\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
-mips_add_offset (rtx temp, rtx reg, HOST_WIDE_INT offset)
+gen_load_const_gp (rtx reg)
 {
-  if (!SMALL_OPERAND (offset))
-    {
-      rtx high;
-      if (TARGET_MIPS16)
-       {
-         /* Load the full offset into a register so that we can use
-            an unextended instruction for the address itself.  */
-         high = GEN_INT (offset);
-         offset = 0;
-       }
-      else
-       {
-         /* Leave OFFSET as a 16-bit offset and put the excess in HIGH.  */
-         high = GEN_INT (CONST_HIGH_PART (offset));
-         offset = CONST_LOW_PART (offset);
-       }
-      high = mips_force_temporary (temp, high);
-      reg = mips_force_temporary (temp, gen_rtx_PLUS (Pmode, high, reg));
-    }
-  return plus_constant (reg, offset);
+  return (Pmode == SImode
+         ? gen_load_const_gp_si (reg)
+         : gen_load_const_gp_di (reg));
 }
 
-/* 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.  */
-
-static GTY(()) rtx mips_tls_symbol;
+/* 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
-mips_call_tls_get_addr (rtx sym, enum mips_symbol_type type, rtx v0)
+mips16_gp_pseudo_reg (void)
 {
-  rtx insn, loc, tga, a0;
+  if (cfun->machine->mips16_gp_pseudo_rtx == NULL_RTX)
+    cfun->machine->mips16_gp_pseudo_rtx = gen_reg_rtx (Pmode);
 
-  a0 = gen_rtx_REG (Pmode, GP_ARG_FIRST);
+  /* 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;
 
-  if (!mips_tls_symbol)
-    mips_tls_symbol = init_one_libfunc ("__tls_get_addr");
+      push_topmost_sequence ();
 
-  loc = mips_unspec_address (sym, type);
+      scan = get_insns ();
+      while (NEXT_INSN (scan) && !INSN_P (NEXT_INSN (scan)))
+       scan = NEXT_INSN (scan);
 
-  start_sequence ();
+      insn = gen_load_const_gp (cfun->machine->mips16_gp_pseudo_rtx);
+      emit_insn_after (insn, scan);
 
-  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));
-  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 ();
+      pop_topmost_sequence ();
 
-  end_sequence ();
+      cfun->machine->initialized_mips16_gp_pseudo_p = true;
+    }
 
-  return insn;
+  return cfun->machine->mips16_gp_pseudo_rtx;
 }
 
-/* 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).  */
+/* Return a base register that holds pic_offset_table_rtx.
+   TEMP, if nonnull, is a scratch Pmode base register.  */
 
-static rtx
-mips_legitimize_tls_address (rtx loc)
+rtx
+mips_pic_base_register (rtx temp)
 {
-  rtx dest, insn, v0, v1, tmp1, tmp2, eqv;
-  enum tls_model model;
+  if (!TARGET_MIPS16)
+    return pic_offset_table_rtx;
 
-  if (TARGET_MIPS16)
-    {
-      sorry ("MIPS16 TLS");
-      return gen_reg_rtx (Pmode);
-    }
+  if (can_create_pseudo_p ())
+    return mips16_gp_pseudo_reg ();
 
-  v0 = gen_rtx_REG (Pmode, GP_RETURN);
-  v1 = gen_rtx_REG (Pmode, GP_RETURN + 1);
+  if (TARGET_USE_GOT)
+    /* The first post-reload split exposes all references to $gp
+       (both uses and definitions).  All references must remain
+       explicit after that point.
 
-  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
-     reduce to local exec in this situation.  */
-  if (!TARGET_ABICALLS)
-    model = TLS_MODEL_LOCAL_EXEC;
+       It is safe to introduce uses of $gp at any time, so for
+       simplicity, we do that before the split too.  */
+    mips_emit_move (temp, pic_offset_table_rtx);
+  else
+    emit_insn (gen_load_const_gp (temp));
+  return temp;
+}
 
-  switch (model)
-    {
-    case TLS_MODEL_GLOBAL_DYNAMIC:
-      insn = mips_call_tls_get_addr (loc, SYMBOL_TLSGD, v0);
-      dest = gen_reg_rtx (Pmode);
-      emit_libcall_block (insn, dest, v0, loc);
-      break;
+/* Create and return a GOT reference of type TYPE for address ADDR.
+   TEMP, if nonnull, is a scratch Pmode base register.  */
 
-    case TLS_MODEL_LOCAL_DYNAMIC:
+rtx
+mips_got_load (rtx temp, rtx addr, enum mips_symbol_type type)
+{
+  rtx base, high, lo_sum_symbol;
+
+  base = mips_pic_base_register (temp);
+
+  /* If we used the temporary register to load $gp, we can't use
+     it for the high part as well.  */
+  if (temp != NULL && reg_overlap_mentioned_p (base, temp))
+    temp = NULL;
+
+  high = mips_unspec_offset_high (temp, base, addr, type);
+  lo_sum_symbol = mips_unspec_address (addr, type);
+
+  if (type == SYMBOL_GOTOFF_CALL)
+    return (Pmode == SImode
+           ? gen_unspec_callsi (high, lo_sum_symbol)
+           : gen_unspec_calldi (high, lo_sum_symbol));
+  else
+    return (Pmode == SImode
+           ? gen_unspec_gotsi (high, lo_sum_symbol)
+           : gen_unspec_gotdi (high, lo_sum_symbol));
+}
+
+/* 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
+   constant in that context and can be split into high and low parts.
+   If so, and if LOW_OUT is nonnull, emit the high part and store the
+   low part in *LOW_OUT.  Leave *LOW_OUT unchanged otherwise.
+
+   TEMP is as for mips_force_temporary and is used to load the high
+   part into a register.
+
+   When MODE is MAX_MACHINE_MODE, the low part is guaranteed to be
+   a legitimize SET_SRC for an .md pattern, otherwise the low part
+   is guaranteed to be a legitimate address for mode MODE.  */
+
+bool
+mips_split_symbol (rtx temp, rtx addr, enum machine_mode mode, rtx *low_out)
+{
+  enum mips_symbol_context context;
+  enum mips_symbol_type symbol_type;
+  rtx high;
+
+  context = (mode == MAX_MACHINE_MODE
+            ? SYMBOL_CONTEXT_LEA
+            : SYMBOL_CONTEXT_MEM);
+  if (GET_CODE (addr) == HIGH && context == SYMBOL_CONTEXT_LEA)
+    {
+      addr = XEXP (addr, 0);
+      if (mips_symbolic_constant_p (addr, context, &symbol_type)
+         && mips_symbol_insns (symbol_type, mode) > 0
+         && mips_split_hi_p[symbol_type])
+       {
+         if (low_out)
+           switch (symbol_type)
+             {
+             case SYMBOL_GOT_PAGE_OFST:
+               /* The high part of a page/ofst pair is loaded from the GOT.  */
+               *low_out = mips_got_load (temp, addr, SYMBOL_GOTOFF_PAGE);
+               break;
+
+             default:
+               gcc_unreachable ();
+             }
+         return true;
+       }
+    }
+  else
+    {
+      if (mips_symbolic_constant_p (addr, context, &symbol_type)
+         && mips_symbol_insns (symbol_type, mode) > 0
+         && mips_split_p[symbol_type])
+       {
+         if (low_out)
+           switch (symbol_type)
+             {
+             case SYMBOL_GOT_DISP:
+               /* SYMBOL_GOT_DISP symbols are loaded from the GOT.  */
+               *low_out = mips_got_load (temp, addr, SYMBOL_GOTOFF_DISP);
+               break;
+
+             case SYMBOL_GP_RELATIVE:
+               high = mips_pic_base_register (temp);
+               *low_out = gen_rtx_LO_SUM (Pmode, high, addr);
+               break;
+
+             default:
+               high = gen_rtx_HIGH (Pmode, copy_rtx (addr));
+               high = mips_force_temporary (temp, high);
+               *low_out = gen_rtx_LO_SUM (Pmode, high, addr);
+               break;
+             }
+         return true;
+       }
+    }
+  return false;
+}
+
+/* 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.  */
+
+static rtx
+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
+            an unextended instruction for the address itself.  */
+         high = GEN_INT (offset);
+         offset = 0;
+       }
+      else
+       {
+         /* Leave OFFSET as a 16-bit offset and put the excess in HIGH.  */
+         high = GEN_INT (CONST_HIGH_PART (offset));
+         offset = CONST_LOW_PART (offset);
+       }
+      high = mips_force_temporary (temp, high);
+      reg = mips_force_temporary (temp, gen_rtx_PLUS (Pmode, high, reg));
+    }
+  return plus_constant (reg, offset);
+}
+\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, a0;
+
+  a0 = gen_rtx_REG (Pmode, GP_ARG_FIRST);
+
+  if (!mips_tls_symbol)
+    mips_tls_symbol = init_one_libfunc ("__tls_get_addr");
+
+  loc = mips_unspec_address (sym, type);
+
+  start_sequence ();
+
+  emit_insn (gen_rtx_SET (Pmode, a0,
+                         gen_rtx_LO_SUM (Pmode, pic_offset_table_rtx, loc)));
+  insn = mips_expand_call (MIPS_CALL_NORMAL, v0, mips_tls_symbol,
+                          const0_rtx, NULL_RTX, false);
+  RTL_CONST_CALL_P (insn) = 1;
+  use_reg (&CALL_INSN_FUNCTION_USAGE (insn), a0);
+  insn = get_insns ();
+
+  end_sequence ();
+
+  return insn;
+}
+
+/* Return a pseudo register that contains the current thread pointer.  */
+
+static rtx
+mips_get_tp (void)
+{
+  rtx tp;
+
+  tp = gen_reg_rtx (Pmode);
+  if (Pmode == DImode)
+    emit_insn (gen_tls_get_tp_di (tp));
+  else
+    emit_insn (gen_tls_get_tp_si (tp));
+  return tp;
+}
+
+/* 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)
+{
+  rtx dest, insn, v0, tp, tmp1, tmp2, eqv;
+  enum tls_model model;
+
+  if (TARGET_MIPS16)
+    {
+      sorry ("MIPS16 TLS");
+      return gen_reg_rtx (Pmode);
+    }
+
+  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
+     reduce to local exec in this situation.  */
+  if (!TARGET_ABICALLS)
+    model = TLS_MODEL_LOCAL_EXEC;
+
+  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);
 
@@ -2428,29 +2712,20 @@ mips_legitimize_tls_address (rtx loc)
       break;
 
     case TLS_MODEL_INITIAL_EXEC:
+      tp = mips_get_tp ();
       tmp1 = gen_reg_rtx (Pmode);
       tmp2 = mips_unspec_address (loc, SYMBOL_GOTTPREL);
       if (Pmode == DImode)
-       {
-         emit_insn (gen_tls_get_tp_di (v1));
-         emit_insn (gen_load_gotdi (tmp1, pic_offset_table_rtx, tmp2));
-       }
+       emit_insn (gen_load_gotdi (tmp1, pic_offset_table_rtx, tmp2));
       else
-       {
-         emit_insn (gen_tls_get_tp_si (v1));
-         emit_insn (gen_load_gotsi (tmp1, pic_offset_table_rtx, tmp2));
-       }
+       emit_insn (gen_load_gotsi (tmp1, pic_offset_table_rtx, tmp2));
       dest = gen_reg_rtx (Pmode);
-      emit_insn (gen_add3_insn (dest, tmp1, v1));
+      emit_insn (gen_add3_insn (dest, tmp1, tp));
       break;
 
     case TLS_MODEL_LOCAL_EXEC:
-      if (Pmode == DImode)
-       emit_insn (gen_tls_get_tp_di (v1));
-      else
-       emit_insn (gen_tls_get_tp_si (v1));
-
-      tmp1 = mips_unspec_offset_high (NULL, v1, loc, SYMBOL_TPREL);
+      tp = mips_get_tp ();
+      tmp1 = mips_unspec_offset_high (NULL, tp, loc, SYMBOL_TPREL);
       dest = gen_rtx_LO_SUM (Pmode, tmp1,
                             mips_unspec_address (loc, SYMBOL_TPREL));
       break;
@@ -2458,9 +2733,18 @@ mips_legitimize_tls_address (rtx loc)
     default:
       gcc_unreachable ();
     }
-
   return dest;
 }
+\f
+/* If X is not a valid address for mode MODE, force it into a register.  */
+
+static rtx
+mips_force_address (rtx x, enum machine_mode mode)
+{
+  if (!mips_legitimate_address_p (mode, x, false))
+    x = force_reg (Pmode, x);
+  return x;
+}
 
 /* This function is used to implement LEGITIMIZE_ADDRESS.  If *XLOC can
    be legitimized in a way that the generic machinery might not expect,
@@ -2470,49 +2754,52 @@ mips_legitimize_tls_address (rtx loc)
 bool
 mips_legitimize_address (rtx *xloc, enum machine_mode mode)
 {
-  if (mips_tls_operand_p (*xloc))
+  rtx base, addr;
+  HOST_WIDE_INT offset;
+
+  if (mips_tls_symbol_p (*xloc))
     {
       *xloc = mips_legitimize_tls_address (*xloc);
       return true;
     }
 
   /* See if the address can split into a high part and a LO_SUM.  */
-  if (mips_split_symbol (NULL, *xloc, mode, xloc))
-    return true;
-
-  if (GET_CODE (*xloc) == PLUS && GET_CODE (XEXP (*xloc, 1)) == CONST_INT)
+  if (mips_split_symbol (NULL, *xloc, mode, &addr))
     {
-      /* 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)));
+      *xloc = mips_force_address (addr, mode);
       return true;
     }
 
+  /* Handle BASE + OFFSET using mips_add_offset.  */
+  mips_split_plus (*xloc, &base, &offset);
+  if (offset != 0)
+    {
+      if (!mips_valid_base_register_p (base, mode, false))
+       base = copy_to_mode_reg (Pmode, base);
+      addr = mips_add_offset (NULL, base, offset);
+      *xloc = mips_force_address (addr, mode);
+      return true;
+    }
   return false;
 }
 
-
-/* Load VALUE into DEST, using TEMP as a temporary register if need be.  */
+/* Load VALUE into DEST.  TEMP is as for mips_force_temporary.  */
 
 void
-mips_move_integer (rtx dest, rtx temp, unsigned HOST_WIDE_INT value)
+mips_move_integer (rtx temp, rtx dest, unsigned HOST_WIDE_INT value)
 {
   struct mips_integer_op codes[MIPS_MAX_INTEGER_OPS];
   enum machine_mode mode;
-  unsigned int i, cost;
+  unsigned int i, num_ops;
   rtx x;
 
   mode = GET_MODE (dest);
-  cost = mips_build_integer (codes, value);
+  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 ())
        {
@@ -2527,7 +2814,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.  */
@@ -2551,7 +2837,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;
@@ -2567,7 +2854,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;
     }
 
@@ -2579,8 +2866,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
@@ -2592,25 +2878,8 @@ mips_legitimize_move (enum machine_mode mode, rtx dest, rtx src)
       return true;
     }
 
-  /* Check for individual, fully-reloaded mflo and mfhi instructions.  */
-  if (GET_MODE_SIZE (mode) <= UNITS_PER_WORD
-      && REG_P (src) && MD_REG_P (REGNO (src))
-      && REG_P (dest) && GP_REG_P (REGNO (dest)))
-    {
-      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)),
-                                 gen_rtx_REG (SImode, other_regno)));
-      else
-       emit_insn (gen_mfhilo_di (gen_rtx_REG (DImode, REGNO (dest)),
-                                 gen_rtx_REG (DImode, REGNO (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);
@@ -2620,20 +2889,20 @@ mips_legitimize_move (enum machine_mode mode, rtx dest, rtx src)
   return false;
 }
 \f
-/* Return true if X in context CONTEXT is a small data address that can
-   be rewritten as a LO_SUM.  */
+/* 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
+  return (mips_lo_relocs[SYMBOL_GP_RELATIVE]
+         && !mips_split_p[SYMBOL_GP_RELATIVE]
          && 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.  */
 
@@ -2662,9 +2931,9 @@ mips_small_data_pattern_1 (rtx *loc, void *data)
 bool
 mips_small_data_pattern_p (rtx op)
 {
-  return for_each_rtx (&op, mips_small_data_pattern_1, 0);
+  return for_each_rtx (&op, mips_small_data_pattern_1, NULL);
 }
-\f
+
 /* A for_each_rtx callback, used by mips_rewrite_small_data.
    DATA is the containing MEM, or null if none.  */
 
@@ -2689,28 +2958,25 @@ mips_rewrite_small_data_1 (rtx *loc, void *data)
   return 0;
 }
 
-/* If possible, rewrite OP so that it refers to small data using
-   explicit relocations.  */
+/* Rewrite instruction pattern PATTERN so that it refers to small data
+   using explicit relocations.  */
 
 rtx
-mips_rewrite_small_data (rtx op)
+mips_rewrite_small_data (rtx pattern)
 {
-  op = copy_insn (op);
-  for_each_rtx (&op, mips_rewrite_small_data_1, 0);
-  return op;
+  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 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.  */
+/* 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);
 }
 
@@ -2723,49 +2989,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
@@ -2777,13 +3043,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
@@ -2795,24 +3061,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
 /* 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
@@ -3028,7 +3293,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.  */
@@ -3225,7 +3490,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_NMADD4_NMSUB4 (mode) || ISA_HAS_NMADD3_NMSUB3 (mode))
          && TARGET_FUSED_MADD
          && !HONOR_NANS (mode)
          && !HONOR_SIGNED_ZEROS (mode))
@@ -3256,6 +3521,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)
@@ -3274,7 +3541,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_NMADD4_NMSUB4 (mode) || ISA_HAS_NMADD3_NMSUB3 (mode))
          && TARGET_FUSED_MADD
          && !HONOR_NANS (mode)
          && HONOR_SIGNED_ZEROS (mode))
@@ -3318,22 +3585,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 (float_mode_p
+         && ISA_HAS_FP4
+         && flag_unsafe_math_optimizations
+         && 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 (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.  */
 
@@ -3392,8 +3655,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)
@@ -3406,14 +3668,14 @@ 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, offset;
   enum machine_mode mode;
 
   mode = GET_MODE (op);
   if (mode == VOIDmode)
-    mode = DImode;
+    mode = TARGET_64BIT ? TImode : DImode;
 
   if (TARGET_BIG_ENDIAN ? !high_p : high_p)
     byte = UNITS_PER_WORD;
@@ -3433,7 +3695,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
@@ -3442,13 +3703,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;
@@ -3458,7 +3719,6 @@ mips_split_64bit_move_p (rtx dest, rtx src)
   return true;
 }
 
-
 /* 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.  */
@@ -3466,34 +3726,59 @@ mips_split_64bit_move_p (rtx dest, rtx src)
 void
 mips_split_doubleword_move (rtx dest, rtx src)
 {
+  rtx low_dest;
+
   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) == V2SImode)
+       emit_insn (gen_move_doubleword_fprv2si (dest, src));
+      else if (!TARGET_64BIT && GET_MODE (dest) == V4HImode)
+       emit_insn (gen_move_doubleword_fprv4hi (dest, src));
+      else if (!TARGET_64BIT && GET_MODE (dest) == V8QImode)
+       emit_insn (gen_move_doubleword_fprv8qi (dest, src));
       else if (TARGET_64BIT && GET_MODE (dest) == TFmode)
        emit_insn (gen_move_doubleword_fprtf (dest, src));
       else
        gcc_unreachable ();
     }
+  else if (REG_P (dest) && REGNO (dest) == MD_REG_FIRST)
+    {
+      low_dest = mips_subword (dest, false);
+      mips_emit_move (low_dest, mips_subword (src, false));
+      if (TARGET_64BIT)
+       emit_insn (gen_mthidi_ti (dest, mips_subword (src, true), low_dest));
+      else
+       emit_insn (gen_mthisi_di (dest, mips_subword (src, true), low_dest));
+    }
+  else if (REG_P (src) && REGNO (src) == MD_REG_FIRST)
+    {
+      mips_emit_move (mips_subword (dest, false), mips_subword (src, false));
+      if (TARGET_64BIT)
+       emit_insn (gen_mfhidi_ti (mips_subword (dest, true), src));
+      else
+       emit_insn (gen_mfhisi_di (mips_subword (dest, true), src));
+    }
   else
     {
       /* The operation can be split into two normal moves.  Decide in
         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));
        }
     }
 }
@@ -3505,90 +3790,120 @@ 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)
        {
          if (GP_REG_P (REGNO (dest)))
            return "move\t%0,%z1";
 
-         if (MD_REG_P (REGNO (dest)))
-           return "mt%0\t%z1";
+         /* Moves to HI are handled by special .md insns.  */
+         if (REGNO (dest) == LO_REGNUM)
+           return "mtlo\t%z1";
 
          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");
+       switch (GET_MODE_SIZE (mode))
+         {
+         case 1: return "sb\t%z1,%0";
+         case 2: return "sh\t%z1,%0";
+         case 4: return "sw\t%z1,%0";
+         case 8: return "sd\t%z1,%0";
+         }
     }
   if (dest_code == REG && GP_REG_P (REGNO (dest)))
     {
       if (src_code == REG)
        {
+         /* Moves from HI are handled by special .md insns.  */
+         if (REGNO (src) == LO_REGNUM)
+           {
+             /* When generating VR4120 or VR4130 code, we use MACC and
+                DMACC instead of MFLO.  This avoids both the normal
+                MIPS III HI/LO hazards and the errata related to
+                -mfix-vr4130.  */
+             if (ISA_HAS_MACCHI)
+               return dbl_p ? "dmacc\t%0,%.,%." : "macc\t%0,%.,%.";
+             return "mflo\t%0";
+           }
+
          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");
+       switch (GET_MODE_SIZE (mode))
+         {
+         case 1: return "lbu\t%0,%1";
+         case 2: return "lhu\t%0,%1";
+         case 4: return "lw\t%0,%1";
+         case 8: return "ld\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 "#";
        }
 
@@ -3612,7 +3927,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)))
@@ -3622,16 +3937,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)
     {
@@ -3652,11 +3967,11 @@ mips_output_move (rtx dest, rtx src)
   gcc_unreachable ();
 }
 \f
-/* 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)
     {
@@ -3683,80 +3998,81 @@ 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;
-
-  if (GET_CODE (*cmp1) != CONST_INT)
-    return false;
-
-  original = INTVAL (*cmp1);
-  plus_one = trunc_int_for_mode ((unsigned HOST_WIDE_INT) original + 1, mode);
+  HOST_WIDE_INT plus_one;
 
-  switch (*code)
-    {
-    case LE:
-      if (original < plus_one)
-       {
-         *code = LT;
-         *cmp1 = force_reg (mode, GEN_INT (plus_one));
-         return true;
-       }
-      break;
+  if (mips_int_order_operand_ok_p (*code, *cmp1))
+    return true;
 
-    case LEU:
-      if (plus_one != 0)
-       {
-         *code = LTU;
-         *cmp1 = force_reg (mode, GEN_INT (plus_one));
-         return true;
-       }
-      break;
+  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;
 
-    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.  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 (cmp0);
+  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));
-         mips_emit_binary (inv_code, inv_target, cmp0, cmp1);
+         rtx inv_target;
+
+         inv_target = mips_force_binary (GET_MODE (target),
+                                         inv_code, cmp0, cmp1);
          mips_emit_binary (XOR, target, inv_target, const1_rtx);
        }
       else
@@ -3785,12 +4101,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)
     {
@@ -3810,11 +4126,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
@@ -3846,10 +4162,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])))
@@ -3863,14 +4179,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));
@@ -3882,32 +4198,30 @@ mips_emit_compare (enum rtx_code *code, rtx *op0, rtx *op1, bool need_eq_ne_p)
 /* Try comparing cmp_operands[0] and cmp_operands[1] using rtl code CODE.
    Store the result in TARGET and return true if successful.
 
-   On 64-bit targets, TARGET may be wider than cmp_operands[0].  */
+   On 64-bit targets, TARGET may be narrower 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;
 
-  target = gen_lowpart (GET_MODE (cmp_operands[0]), target);
   if (code == EQ || code == NE)
     {
       rtx zie = mips_zero_if_equal (cmp_operands[0], cmp_operands[1]);
       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;
 
@@ -3928,7 +4242,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)));
@@ -3940,102 +4254,80 @@ 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
-/* Argument support functions.  */
-
-/* Initialize CUMULATIVE_ARGS for a function.  */
+/* Initialize *CUM for a call to a function of type FNTYPE.  */
 
 void
-init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype,
-                     rtx libname ATTRIBUTE_UNUSED)
+mips_init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype)
 {
-  static CUMULATIVE_ARGS zero_cum;
-  tree param, next_param;
-
-  *cum = zero_cum;
-  cum->prototype = (fntype && TYPE_ARG_TYPES (fntype));
-
-  /* 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.  */
-
-  for (param = fntype ? TYPE_ARG_TYPES (fntype) : 0;
-       param != 0; param = next_param)
-    {
-      next_param = TREE_CHAIN (param);
-      if (next_param == 0 && TREE_VALUE (param) != void_type_node)
-       cum->gp_reg_found = 1;
-    }
+  memset (cum, 0, sizeof (*cum));
+  cum->prototype = (fntype && prototype_p (fntype));
+  cum->gp_reg_found = (cum->prototype && stdarg_p (fntype));
 }
 
-
 /* 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)
+mips_get_arg_info (struct mips_arg_info *info, const CUMULATIVE_ARGS *cum,
+                  enum machine_mode mode, tree type, int named)
 {
   bool doubleword_aligned_p;
   unsigned int num_bytes, num_words, max_regs;
@@ -4066,7 +4358,8 @@ mips_arg_info (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
         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)
+                    && (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)
@@ -4075,8 +4368,9 @@ mips_arg_info (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
 
     case ABI_N32:
     case ABI_64:
-      /* Scalar and complex floating-point types are passed in
-        floating-point registers.  */
+      /* 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
@@ -4140,9 +4434,9 @@ mips_arg_info (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
   info->stack_words = num_words - info->reg_words;
 }
 
-/* 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.  */
+/* 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.  */
 
 static unsigned int
 mips_arg_regno (const struct mips_arg_info *info, bool hard_float_p)
@@ -4158,6 +4452,8 @@ mips_arg_regno (const struct mips_arg_info *info, bool hard_float_p)
     return FP_ARG_FIRST + info->reg_offset;
 }
 
+/* Implement TARGET_STRICT_ARGUMENT_NAMING.  */
+
 static bool
 mips_strict_argument_naming (CUMULATIVE_ARGS *ca ATTRIBUTE_UNUSED)
 {
@@ -4166,47 +4462,47 @@ mips_strict_argument_naming (CUMULATIVE_ARGS *ca ATTRIBUTE_UNUSED)
 
 /* Implement FUNCTION_ARG.  */
 
-struct rtx_def *
-function_arg (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
-             tree type, int named)
+rtx
+mips_function_arg (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
+                  tree type, int named)
 {
   struct mips_arg_info info;
 
   /* 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.  */
+     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 0;
+       return NULL;
     }
 
-  mips_arg_info (cum, mode, type, named, &info);
+  mips_get_arg_info (&info, cum, mode, type, named);
 
   /* Return straight away if the whole argument is passed on the stack.  */
   if (info.reg_offset == MAX_ARGS_IN_REGISTERS)
-    return 0;
+    return NULL;
 
-  if (type != 0
+  /* 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
-      && TARGET_NEWABI
       && TYPE_SIZE_UNIT (type)
-      && host_integerp (TYPE_SIZE_UNIT (type), 1)
-      && named)
+      && host_integerp (TYPE_SIZE_UNIT (type), 1))
     {
-      /* 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;
 
       /* 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
+           && 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)
@@ -4238,8 +4534,7 @@ function_arg (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
 
              if (field
                  && int_bit_position (field) == bitpos
-                 && TREE_CODE (TREE_TYPE (field)) == REAL_TYPE
-                 && !TARGET_SOFT_FLOAT
+                 && 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
@@ -4264,25 +4559,25 @@ function_arg (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
     {
       rtx real, imag;
       enum machine_mode inner;
-      int reg;
+      unsigned int regno;
 
       inner = GET_MODE_INNER (mode);
-      reg = FP_ARG_FIRST + info.reg_offset;
+      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, reg);
+         return gen_rtx_REG (inner, regno);
        }
       else
        {
          gcc_assert (info.stack_words == 0);
          real = gen_rtx_EXPR_LIST (VOIDmode,
-                                   gen_rtx_REG (inner, reg),
+                                   gen_rtx_REG (inner, regno),
                                    const0_rtx);
          imag = gen_rtx_EXPR_LIST (VOIDmode,
                                    gen_rtx_REG (inner,
-                                                reg + info.reg_words / 2),
+                                                regno + info.reg_words / 2),
                                    GEN_INT (GET_MODE_SIZE (inner)));
          return gen_rtx_PARALLEL (mode, gen_rtvec (2, real, imag));
        }
@@ -4294,27 +4589,33 @@ function_arg (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
 /* Implement FUNCTION_ARG_ADVANCE.  */
 
 void
-function_arg_advance (CUMULATIVE_ARGS *cum, enum machine_mode mode,
-                     tree type, int named)
+mips_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);
+  mips_get_arg_info (&info, cum, mode, type, named);
 
   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.  */
+  /* 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);
 
+  /* 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;
 
+  /* Advance the stack word count.  */
   if (info.stack_words > 0)
     cum->stack_words = info.stack_offset + info.stack_words;
 
@@ -4329,17 +4630,16 @@ mips_arg_partial_bytes (CUMULATIVE_ARGS *cum,
 {
   struct mips_arg_info info;
 
-  mips_arg_info (cum, mode, type, named, &info);
+  mips_get_arg_info (&info, cum, mode, type, named);
   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)
+mips_function_arg_boundary (enum machine_mode mode, tree type)
 {
   unsigned int alignment;
 
@@ -4370,7 +4670,7 @@ mips_pad_arg_upward (enum machine_mode mode, const_tree type)
       ? (INTEGRAL_TYPE_P (type)
         || POINTER_TYPE_P (type)
         || FIXED_POINT_TYPE_P (type))
-      : (GET_MODE_CLASS (mode) == MODE_INT
+      : (SCALAR_INT_MODE_P (mode)
         || ALL_SCALAR_FIXED_POINT_MODE_P (mode)))
     return false;
 
@@ -4385,12 +4685,11 @@ mips_pad_arg_upward (enum machine_mode mode, const_tree type)
 
   /* Arguments smaller than a stack slot are padded downward.  */
   if (mode != BLKmode)
-    return (GET_MODE_BITSIZE (mode) >= PARM_BOUNDARY);
+    return GET_MODE_BITSIZE (mode) >= PARM_BOUNDARY;
   else
-    return (int_size_in_bytes (type) >= (PARM_BOUNDARY / BITS_PER_UNIT));
+    return int_size_in_bytes (type) >= (PARM_BOUNDARY / BITS_PER_UNIT);
 }
 
-
 /* 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.  */
@@ -4407,7 +4706,6 @@ mips_pad_reg_upward (enum machine_mode mode, tree type)
   return mips_pad_arg_upward (mode, type);
 }
 
-
 /* Return nonzero when an argument must be passed by reference.  */
 
 static bool
@@ -4435,6 +4733,8 @@ mips_pass_by_reference (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
     }
 }
 
+/* Implement TARGET_CALLEE_COPIES.  */
+
 static bool
 mips_callee_copies (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
                    enum machine_mode mode ATTRIBUTE_UNUSED,
@@ -4470,7 +4770,7 @@ mips_fpr_return_fields (const_tree valtype, tree *fields)
       if (TREE_CODE (field) != FIELD_DECL)
        continue;
 
-      if (TREE_CODE (TREE_TYPE (field)) != REAL_TYPE)
+      if (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (field)))
        return 0;
 
       if (i == 2)
@@ -4481,7 +4781,6 @@ mips_fpr_return_fields (const_tree valtype, tree *fields)
   return i;
 }
 
-
 /* Implement TARGET_RETURN_IN_MSB.  For n32 & n64, we should return
    a value in the most significant part of $2/$3 if:
 
@@ -4503,7 +4802,6 @@ mips_return_in_msb (const_tree valtype)
          && mips_fpr_return_fields (valtype, fields) == 0);
 }
 
-
 /* Return true if the function return value MODE will get returned in a
    floating-point register.  */
 
@@ -4516,6 +4814,31 @@ mips_return_mode_in_fpr_p (enum machine_mode mode)
          && GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_HWFPVALUE);
 }
 
+/* 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:
+
+       struct __attribute__((packed)) foo { float f; }
+
+   where we return the SFmode value of "f" in FP_RETURN, but where
+   the structure itself has mode BLKmode.  */
+
+static rtx
+mips_return_fpr_single (enum machine_mode type_mode,
+                       enum machine_mode value_mode)
+{
+  rtx x;
+
+  x = gen_rtx_REG (value_mode, FP_RETURN);
+  if (type_mode != value_mode)
+    {
+      x = gen_rtx_EXPR_LIST (VOIDmode, x, const0_rtx);
+      x = gen_rtx_PARALLEL (type_mode, gen_rtvec (1, x));
+    }
+  return x;
+}
+
 /* 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
@@ -4544,32 +4867,31 @@ mips_return_fpr_pair (enum machine_mode mode,
 
 }
 
-
 /* 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.  */
 
 rtx
-mips_function_value (const_tree valtype, const_tree func ATTRIBUTE_UNUSED,
-                    enum machine_mode mode)
+mips_function_value (const_tree valtype, enum machine_mode mode)
 {
   if (valtype)
     {
       tree fields[2];
-      int unsignedp;
+      int unsigned_p;
 
       mode = TYPE_MODE (valtype);
-      unsignedp = TYPE_UNSIGNED (valtype);
+      unsigned_p = TYPE_UNSIGNED (valtype);
 
-      /* 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);
+      /* 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);
 
       /* 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);
+         return mips_return_fpr_single (mode,
+                                        TYPE_MODE (TREE_TYPE (fields[0])));
 
        case 2:
          return mips_return_fpr_pair (mode,
@@ -4622,22 +4944,22 @@ mips_function_value (const_tree valtype, const_tree func ATTRIBUTE_UNUSED,
   return gen_rtx_REG (mode, GP_RETURN);
 }
 
-/* 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.
+/* 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.  */
 
 static bool
 mips_return_in_memory (const_tree type, const_tree fndecl ATTRIBUTE_UNUSED)
 {
-  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));
+  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,
@@ -4649,9 +4971,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;
@@ -4668,7 +4989,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,
@@ -4684,8 +5005,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;
@@ -4696,7 +5016,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;
@@ -4708,46 +5028,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);
@@ -4780,9 +5098,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)
@@ -4795,7 +5113,7 @@ mips_va_start (tree valist, rtx nextarg)
       int fpr_save_area_size;
       int fpr_offset;
 
-      cum = &current_function_args_info;
+      cum = &crtl->args.info;
       gpr_save_area_size
        = (MAX_ARGS_IN_REGISTERS - cum->num_gprs) * UNITS_PER_WORD;
       fpr_save_area_size
@@ -4825,12 +5143,12 @@ mips_va_start (tree valist, rtx nextarg)
       if (cum->stack_words > 0)
        t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (ovfl), t,
                    size_int (cum->stack_words * UNITS_PER_WORD));
-      t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (ovfl), ovfl, t);
+      t = build2 (MODIFY_EXPR, TREE_TYPE (ovfl), ovfl, t);
       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
 
       /* Emit code to initialize GTOP, the top of the GPR save area.  */
       t = make_tree (TREE_TYPE (gtop), virtual_incoming_args_rtx);
-      t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (gtop), gtop, t);
+      t = build2 (MODIFY_EXPR, TREE_TYPE (gtop), gtop, t);
       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
 
       /* Emit code to initialize FTOP, the top of the FPR save area.
@@ -4838,23 +5156,23 @@ 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));
-      t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (ftop), ftop, t);
+      t = build2 (MODIFY_EXPR, TREE_TYPE (ftop), ftop, t);
       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
 
       /* 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));
+      t = build2 (MODIFY_EXPR, TREE_TYPE (goff), goff,
+                 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));
+      t = build2 (MODIFY_EXPR, TREE_TYPE (foff), foff,
+                 build_int_cst (TREE_TYPE (foff), fpr_save_area_size));
       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
     }
   else
@@ -4863,33 +5181,27 @@ 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)
+mips_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
+                          gimple_seq *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);
@@ -4898,38 +5210,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)
@@ -4939,9 +5250,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
@@ -4957,10 +5268,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
@@ -4969,13 +5279,13 @@ 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.      */
              t = build2 (BIT_AND_EXPR, TREE_TYPE (off), off,
                          build_int_cst (NULL_TREE, -rsize));
-             t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (off), off, t);
-             gimplify_and_add (t, pre_p);
+             gimplify_assign (off, t, pre_p);
            }
          osize = rsize;
        }
@@ -4986,15 +5296,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)
        {
@@ -5005,23 +5314,22 @@ 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);
          u = size_int (-osize);
          t = build2 (BIT_AND_EXPR, sizetype, t, u);
          t = fold_convert (TREE_TYPE (ovfl), t);
-         align = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (ovfl), ovfl, t);
+         align = build2 (MODIFY_EXPR, TREE_TYPE (ovfl), ovfl, t);
        }
       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)
        {
@@ -5029,7 +5337,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;
@@ -5038,26 +5346,183 @@ 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
-/* We keep a list of functions for which we have already built stubs
-   in build_mips16_call_stub.  */
+/* Start a definition of function NAME.  MIPS16_P indicates whether the
+   function contains MIPS16 code.  */
+
+static void
+mips_start_function_definition (const char *name, bool mips16_p)
+{
+  if (mips16_p)
+    fprintf (asm_out_file, "\t.set\tmips16\n");
+  else
+    fprintf (asm_out_file, "\t.set\tnomips16\n");
+
+  if (!flag_inhibit_size_directive)
+    {
+      fputs ("\t.ent\t", asm_out_file);
+      assemble_name (asm_out_file, name);
+      fputs ("\n", asm_out_file);
+    }
+
+  ASM_OUTPUT_TYPE_DIRECTIVE (asm_out_file, name, "function");
+
+  /* Start the definition proper.  */
+  assemble_name (asm_out_file, name);
+  fputs (":\n", asm_out_file);
+}
+
+/* End a function definition started by mips_start_function_definition.  */
+
+static void
+mips_end_function_definition (const char *name)
+{
+  if (!flag_inhibit_size_directive)
+    {
+      fputs ("\t.end\t", asm_out_file);
+      assemble_name (asm_out_file, name);
+      fputs ("\n", asm_out_file);
+    }
+}
+\f
+/* Return true if calls to X can use R_MIPS_CALL* relocations.  */
+
+static bool
+mips_ok_for_lazy_binding_p (rtx x)
+{
+  return (TARGET_USE_GOT
+         && GET_CODE (x) == SYMBOL_REF
+         && !SYMBOL_REF_BIND_NOW_P (x)
+         && !mips_symbol_binds_local_p (x));
+}
+
+/* Load function address ADDR into register DEST.  TYPE is as for
+   mips_expand_call.  Return true if we used an explicit lazy-binding
+   sequence.  */
+
+static bool
+mips_load_call_address (enum mips_call_type type, rtx dest, rtx addr)
+{
+  /* 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
+      && !(type == MIPS_CALL_SIBCALL && TARGET_CALL_SAVED_GP)
+      && mips_ok_for_lazy_binding_p (addr))
+    {
+      addr = mips_got_load (dest, addr, SYMBOL_GOTOFF_CALL);
+      emit_insn (gen_rtx_SET (VOIDmode, dest, addr));
+      return true;
+    }
+  else
+    {
+      mips_emit_move (dest, addr);
+      return false;
+    }
+}
+\f
+/* Each locally-defined hard-float MIPS16 function has a local symbol
+   associated with it.  This hash table maps the function symbol (FUNC)
+   to the local symbol (LOCAL). */
+struct mips16_local_alias GTY(()) {
+  rtx func;
+  rtx local;
+};
+static GTY ((param_is (struct mips16_local_alias))) htab_t mips16_local_aliases;
+
+/* Hash table callbacks for mips16_local_aliases.  */
+
+static hashval_t
+mips16_local_aliases_hash (const void *entry)
+{
+  const struct mips16_local_alias *alias;
+
+  alias = (const struct mips16_local_alias *) entry;
+  return htab_hash_string (XSTR (alias->func, 0));
+}
+
+static int
+mips16_local_aliases_eq (const void *entry1, const void *entry2)
+{
+  const struct mips16_local_alias *alias1, *alias2;
+
+  alias1 = (const struct mips16_local_alias *) entry1;
+  alias2 = (const struct mips16_local_alias *) entry2;
+  return rtx_equal_p (alias1->func, alias2->func);
+}
 
-struct mips16_stub
+/* FUNC is the symbol for a locally-defined hard-float MIPS16 function.
+   Return a local alias for it, creating a new one if necessary.  */
+
+static rtx
+mips16_local_alias (rtx func)
 {
+  struct mips16_local_alias *alias, tmp_alias;
+  void **slot;
+
+  /* Create the hash table if this is the first call.  */
+  if (mips16_local_aliases == NULL)
+    mips16_local_aliases = htab_create_ggc (37, mips16_local_aliases_hash,
+                                           mips16_local_aliases_eq, NULL);
+
+  /* Look up the function symbol, creating a new entry if need be.  */
+  tmp_alias.func = func;
+  slot = htab_find_slot (mips16_local_aliases, &tmp_alias, INSERT);
+  gcc_assert (slot != NULL);
+
+  alias = (struct mips16_local_alias *) *slot;
+  if (alias == NULL)
+    {
+      const char *func_name, *local_name;
+      rtx local;
+
+      /* Create a new SYMBOL_REF for the local symbol.  The choice of
+        __fn_local_* is based on the __fn_stub_* names that we've
+        traditionally used for the non-MIPS16 stub.  */
+      func_name = targetm.strip_name_encoding (XSTR (func, 0));
+      local_name = ACONCAT (("__fn_local_", func_name, NULL));
+      local = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (local_name));
+      SYMBOL_REF_FLAGS (local) = SYMBOL_REF_FLAGS (func) | SYMBOL_FLAG_LOCAL;
+
+      /* Create a new structure to represent the mapping.  */
+      alias = GGC_NEW (struct mips16_local_alias);
+      alias->func = func;
+      alias->local = local;
+      *slot = alias;
+    }
+  return alias->local;
+}
+\f
+/* 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;
-  int fpret;
+  bool fp_ret_p;
 };
-
 static struct mips16_stub *mips16_stubs;
 
-/* Return a two-character string representing a function floating-point
-   return mode, used to name MIPS16 function stubs.  */
+/* Return a SYMBOL_REF for a MIPS16 function called NAME.  */
+
+static rtx
+mips16_stub_function (const char *name)
+{
+  rtx x;
+
+  x = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (name));
+  SYMBOL_REF_FLAGS (x) |= (SYMBOL_FLAG_EXTERNAL | SYMBOL_FLAG_FUNCTION);
+  return x;
+}
+
+/* Return the two-character string that identifies floating-point
+   return mode MODE in the name of a MIPS16 function stub.  */
 
 static const char *
 mips16_call_stub_mode_suffix (enum machine_mode mode)
@@ -5076,29 +5541,58 @@ mips16_call_stub_mode_suffix (enum machine_mode mode)
     gcc_unreachable ();
 }
 
-/* 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.  */
+/* 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.  */
 
 static void
-mips16_fp_args (FILE *file, int fp_code, int from_fp_p)
+mips_output_32bit_xfer (char direction, unsigned int gpreg, unsigned int fpreg)
 {
-  const char *s;
-  int gparg, fparg;
-  unsigned int f;
-  CUMULATIVE_ARGS cum;
+  fprintf (asm_out_file, "\tm%cc1\t%s,%s\n", direction,
+          reg_names[gpreg], reg_names[fpreg]);
+}
 
-  /* This code only works for the original 32-bit ABI and the O64 ABI.  */
-  gcc_assert (TARGET_OLDABI);
+/* Likewise for 64-bit values.  */
 
-  if (from_fp_p)
-    s = "mfc1";
+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)
+    {
+      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
-    s = "mtc1";
+    {
+      /* 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]);
+    }
+}
+
+/* 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.  */
+
+static void
+mips_output_args_xfer (int fp_code, char direction)
+{
+  unsigned int gparg, fparg, f;
+  CUMULATIVE_ARGS cum;
 
-  init_cumulative_args (&cum, NULL, NULL);
+  /* This code only works for o32 and o64.  */
+  gcc_assert (TARGET_OLDABI);
+
+  mips_init_cumulative_args (&cum, NULL);
 
   for (f = (unsigned int) fp_code; f != 0; f >>= 2)
     {
@@ -5112,278 +5606,262 @@ mips16_fp_args (FILE *file, int fp_code, int from_fp_p)
       else
        gcc_unreachable ();
 
-      mips_arg_info (&cum, mode, NULL, true, &info);
+      mips_get_arg_info (&info, &cum, mode, NULL, true);
       gparg = mips_arg_regno (&info, false);
       fparg = mips_arg_regno (&info, true);
 
       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]);
+       mips_output_32bit_xfer (direction, gparg, 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]);
+       mips_output_64bit_xfer (direction, gparg, fparg);
 
-      function_arg_advance (&cum, mode, NULL, true);
+      mips_function_arg_advance (&cum, mode, NULL, true);
     }
 }
 
-/* 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.  */
+/* 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.  */
 
 static void
-build_mips16_function_stub (FILE *file)
+mips16_build_function_stub (void)
 {
-  const char *fnname;
+  const char *fnname, *alias_name, *separator;
   char *secname, *stubname;
-  tree stubid, stubdecl;
-  int need_comma;
+  tree stubdecl;
   unsigned int f;
+  rtx symbol, alias;
 
-  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,
+  /* Create the name of the stub, and its unique section.  */
+  symbol = XEXP (DECL_RTL (current_function_decl), 0);
+  alias = mips16_local_alias (symbol);
+
+  fnname = targetm.strip_name_encoding (XSTR (symbol, 0));
+  alias_name = targetm.strip_name_encoding (XSTR (alias, 0));
+  secname = ACONCAT ((".mips16.fn.", fnname, NULL));
+  stubname = ACONCAT (("__fn_stub_", fnname, NULL));
+
+  /* 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);
 
-  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)
+  /* Output a comment.  */
+  fprintf (asm_out_file, "\t# Stub function for %s (",
+          current_function_name ());
+  separator = "";
+  for (f = (unsigned int) crtl->args.info.fp_code; f != 0; f >>= 2)
     {
-      fprintf (file, "%s%s",
-              need_comma ? ", " : "",
+      fprintf (asm_out_file, "%s%s", separator,
               (f & 3) == 1 ? "float" : "double");
-      need_comma = 1;
+      separator = ", ";
     }
-  fprintf (file, ")\n");
+  fprintf (asm_out_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));
+  /* Start the function definition.  */
+  assemble_start_function (stubdecl, stubname);
+  mips_start_function_definition (stubname, false);
 
-  /* ??? If FUNCTION_NAME_ALREADY_DECLARED is defined, then we are
-     within a .ent, and we cannot emit another .ent.  */
-  if (!FUNCTION_NAME_ALREADY_DECLARED)
+  /* If generating pic2 code, either set up the global pointer or
+     switch to pic0.  */
+  if (TARGET_ABICALLS_PIC2)
     {
-      fputs ("\t.ent\t", file);
-      assemble_name (file, stubname);
-      fputs ("\n", file);
+      if (TARGET_ABSOLUTE_ABICALLS)
+       fprintf (asm_out_file, "\t.option\tpic0\n");
+      else
+       {
+         output_asm_insn ("%(.cpload\t%^%)", NULL);
+         /* Emit an R_MIPS_NONE relocation to tell the linker what the
+            target function is.  Use a local GOT access when loading the
+            symbol, to cut down on the number of unnecessary GOT entries
+            for stubs that aren't needed.  */
+         output_asm_insn (".reloc\t0,R_MIPS_NONE,%0", &symbol);
+         symbol = alias;
+       }
     }
 
-  assemble_name (file, stubname);
-  fputs (":\n", file);
+  /* Load the address of the MIPS16 function into $25.  Do this first so
+     that targets with coprocessor interlocks can use an MFC1 to fill the
+     delay slot.  */
+  output_asm_insn ("la\t%^,%0", &symbol);
 
-  /* We don't want the assembler to insert any nops here.  */
-  fprintf (file, "\t.set\tnoreorder\n");
+  /* Move the arguments from floating-point registers to general registers.  */
+  mips_output_args_xfer (crtl->args.info.fp_code, 'f');
 
-  mips16_fp_args (file, current_function_args_info.fp_code, 1);
+  /* Jump to the MIPS16 function.  */
+  output_asm_insn ("jr\t%^", NULL);
 
-  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");
+  if (TARGET_ABICALLS_PIC2 && TARGET_ABSOLUTE_ABICALLS)
+    fprintf (asm_out_file, "\t.option\tpic2\n");
 
-  /* 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");
+  mips_end_function_definition (stubname);
 
-  fprintf (file, "\t.set\treorder\n");
+  /* If the linker needs to create a dynamic symbol for the target
+     function, it will associate the symbol with the stub (which,
+     unlike the target function, follows the proper calling conventions).
+     It is therefore useful to have a local alias for the target function,
+     so that it can still be identified as MIPS16 code.  As an optimization,
+     this symbol can also be used for indirect MIPS16 references from
+     within this file.  */
+  ASM_OUTPUT_DEF (asm_out_file, alias_name, fnname);
 
-  if (!FUNCTION_NAME_ALREADY_DECLARED)
-    {
-      fputs ("\t.end\t", file);
-      assemble_name (file, stubname);
-      fputs ("\n", file);
-    }
+  switch_to_section (function_section (current_function_decl));
+}
+
+/* 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
+mips16_copy_fpr_return_value (void)
+{
+  rtx fn, insn, retval;
+  tree return_type;
+  enum machine_mode return_mode;
+  const char *name;
+
+  return_type = DECL_RESULT (current_function_decl);
+  return_mode = DECL_MODE (return_type);
+
+  name = ACONCAT (("__mips16_ret_",
+                  mips16_call_stub_mode_suffix (return_mode),
+                  NULL));
+  fn = mips16_stub_function (name);
+
+  /* The function takes arguments in $2 (and possibly $3), so calls
+     to it cannot be lazily bound.  */
+  SYMBOL_REF_FLAGS (fn) |= SYMBOL_FLAG_BIND_NOW;
+
+  /* Model the call as something that takes the GPR return value as
+     argument and returns an "updated" value.  */
+  retval = gen_rtx_REG (return_mode, GP_RETURN);
+  insn = mips_expand_call (MIPS_CALL_EPILOGUE, retval, fn,
+                          const0_rtx, NULL_RTX, false);
+  use_reg (&CALL_INSN_FUNCTION_USAGE (insn), retval);
+}
+
+/* Consider building a stub for a MIPS16 call to function *FN_PTR.
+   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.
 
-  switch_to_section (function_section (current_function_decl));
-}
+   There are three alternatives:
 
-/* 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.  */
+   - If a stub was needed, emit the call and return the call insn itself.
 
-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]);
-       }
-    }
-}
+   - If we can avoid using a stub by redirecting the call, set *FN_PTR
+     to the new target and return null.
 
-/* 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.
+   - If *FN_PTR doesn't need a stub, return null and leave *FN_PTR
+     unmodified.
 
-   Similarly, we need a stub if the return value might come back in a
-   floating point register.
+   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.
 
-   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.  */
+   We can emit a JAL to *FN_PTR even when *FN_PTR might need a stub.
+   If *FN_PTR 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.  */
 
-int
-build_mips16_call_stub (rtx retval, rtx fn, rtx arg_size, int fp_code)
+static rtx
+mips16_build_call_stub (rtx retval, rtx *fn_ptr, rtx args_size, int fp_code)
 {
-  int fpret = 0;
   const char *fnname;
-  char *secname, *stubname;
+  bool fp_ret_p;
   struct mips16_stub *l;
-  tree stubid, stubdecl;
-  int need_comma;
-  unsigned int f;
-  rtx insn;
+  rtx insn, fn;
 
-  /* We don't need to do anything if we aren't in mips16 mode, or if
+  /* 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;
+    return NULL_RTX;
 
-  /* Figure out whether the value might come back in a floating point
+  /* 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));
+  fp_ret_p = retval && mips_return_mode_in_fpr_p (GET_MODE (retval));
 
-  /* 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
+  /* 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 (fp_code == 0 && !fp_ret_p)
+    return NULL_RTX;
 
   /* 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;
+     MIPS16 support function.  */
+  fn = *fn_ptr;
+  if (mips16_stub_function_p (fn))
+    return NULL_RTX;
 
   /* This code will only work for o32 and o64 abis.  The other ABI's
      require more sophisticated support.  */
   gcc_assert (TARGET_OLDABI);
 
-  /* 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.  */
-
-  if (GET_CODE (fn) != SYMBOL_REF)
+  /* 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
+      || !call_insn_operand (fn, VOIDmode))
     {
       char buf[30];
-      tree id;
-      rtx stub_fn, insn;
+      rtx stub_fn, insn, addr;
+      bool lazy_p;
 
-      /* ??? If this code is modified to support other ABI's, we need
-         to handle PARALLEL return values here.  */
+      /* If this is a locally-defined and locally-binding function,
+        avoid the stub by calling the local alias directly.  */
+      if (mips16_local_function_p (fn))
+       {
+         *fn_ptr = mips16_local_alias (fn);
+         return NULL_RTX;
+       }
 
-      if (fpret)
+      /* 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);
+       sprintf (buf, "__mips16_call_stub_%d", fp_code);
+      stub_fn = mips16_stub_function (buf);
 
-      id = get_identifier (buf);
-      stub_fn = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (id));
+      /* The function uses $2 as an argument, so calls to it
+        cannot be lazily bound.  */
+      SYMBOL_REF_FLAGS (stub_fn) |= SYMBOL_FLAG_BIND_NOW;
 
-      mips_emit_move (gen_rtx_REG (Pmode, 2), fn);
+      /* Load the target function into $2.  */
+      addr = gen_rtx_REG (Pmode, GP_REG_FIRST + 2);
+      lazy_p = mips_load_call_address (MIPS_CALL_NORMAL, addr, fn);
 
-      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);
+      /* Emit the call.  */
+      insn = mips_expand_call (MIPS_CALL_NORMAL, retval, stub_fn,
+                              args_size, NULL_RTX, lazy_p);
 
-      /* 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));
+      /* Tell GCC that this call does indeed use the value of $2.  */
+      use_reg (&CALL_INSN_FUNCTION_USAGE (insn), addr);
 
-      /* If we are handling a floating point return value, we need to
+      /* 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)
+      if (fp_ret_p)
        CALL_INSN_FUNCTION_USAGE (insn) =
          gen_rtx_EXPR_LIST (VOIDmode,
-                            gen_rtx_USE (VOIDmode,
-                                         gen_rtx_REG (word_mode, 18)),
+                            gen_rtx_CLOBBER (VOIDmode,
+                                             gen_rtx_REG (word_mode, 18)),
                             CALL_INSN_FUNCTION_USAGE (insn));
 
-      /* Return 1 to tell the caller that we've generated the call
-         insn.  */
-      return 1;
+      return insn;
     }
 
   /* 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)
@@ -5391,297 +5869,267 @@ build_mips16_call_stub (rtx retval, rtx fn, rtx arg_size, int fp_code)
 
   if (l == NULL)
     {
-      /* 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
+      const char *separator;
+      char *secname, *stubname;
+      tree stubid, stubdecl;
+      unsigned int f;
 
-        If the function does return a floating point value, the stub
+      /* If the function does not return in FPRs, the special stub
         section is named
+            .mips16.call.FNNAME
+
+        If the function does return in FPRs, 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);
+        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);
+      DECL_RESULT (stubdecl) = build_decl (RESULT_DECL, NULL_TREE,
+                                          void_type_node);
 
+      /* Output a comment.  */
       fprintf (asm_out_file, "\t# Stub function to call %s%s (",
-              (fpret
+              (fp_ret_p
                ? (GET_MODE (retval) == SFmode ? "float " : "double ")
                : ""),
               fnname);
-      need_comma = 0;
+      separator = "";
       for (f = (unsigned int) fp_code; f != 0; f >>= 2)
        {
-         fprintf (asm_out_file, "%s%s",
-                  need_comma ? ", " : "",
+         fprintf (asm_out_file, "%s%s", separator,
                   (f & 3) == 1 ? "float" : "double");
-         need_comma = 1;
+         separator = ", ";
        }
       fprintf (asm_out_file, ")\n");
 
-      fprintf (asm_out_file, "\t.set\tnomips16\n");
+      /* Start the function definition.  */
       assemble_start_function (stubdecl, stubname);
+      mips_start_function_definition (stubname, false);
 
-      if (!FUNCTION_NAME_ALREADY_DECLARED)
+      if (!fp_ret_p)
        {
-         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);
+         /* Load the address of the MIPS16 function into $25.  Do this
+            first so that targets with coprocessor interlocks can use
+            an MFC1 to fill the delay slot.  */
+         if (TARGET_EXPLICIT_RELOCS)
+           {
+             output_asm_insn ("lui\t%^,%%hi(%0)", &fn);
+             output_asm_insn ("addiu\t%^,%^,%%lo(%0)", &fn);
+           }
+         else
+           output_asm_insn ("la\t%^,%0", &fn);
        }
 
-      /* 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.  */
-
-      /* We don't want the assembler to insert any nops here.  */
-      fprintf (asm_out_file, "\t.set\tnoreorder\n");
+      /* Move the arguments from general registers to floating-point
+        registers.  */
+      mips_output_args_xfer (fp_code, 't');
 
-      mips16_fp_args (asm_out_file, fp_code, 0);
-
-      if (! fpret)
+      if (!fp_ret_p)
        {
-         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");
+         /* Jump to the previously-loaded address.  */
+         output_asm_insn ("jr\t%^", NULL);
        }
       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);
-         /* As above, we can't fill the delay slot.  */
-         fprintf (asm_out_file, "\tnop\n");
+         output_asm_insn (MIPS_CALL ("jal", &fn, 0), &fn);
+
+         /* Move the result from floating-point registers to
+            general registers.  */
          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]);
+             mips_output_32bit_xfer ('f', GP_RETURN + 1,
+                                     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]);
+             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_REG_FIRST + 2 + TARGET_LITTLE_ENDIAN],
-                          reg_names[GP_REG_FIRST + 2 + TARGET_LITTLE_ENDIAN]);
+                          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_REG_FIRST + 2],
-                          reg_names[GP_REG_FIRST + 2],
-                          reg_names[GP_REG_FIRST + 3]);
+                          reg_names[GP_RETURN],
+                          reg_names[GP_RETURN],
+                          reg_names[GP_RETURN + 1]);
                }
              break;
 
            case DCmode:
-             mips16_fpret_double (GP_REG_FIRST + 2 + (8 / UNITS_PER_WORD),
-                                  FP_REG_FIRST + MAX_FPRS_PER_FMT);
+             mips_output_64bit_xfer ('f', GP_RETURN + (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);
+             mips_output_64bit_xfer ('f', GP_RETURN, FP_REG_FIRST);
              break;
 
            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");
+         fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 18]);
        }
 
-      fprintf (asm_out_file, "\t.set\treorder\n");
-
 #ifdef ASM_DECLARE_FUNCTION_SIZE
       ASM_DECLARE_FUNCTION_SIZE (asm_out_file, stubname, stubdecl);
 #endif
 
-      if (!FUNCTION_NAME_ALREADY_DECLARED)
-       {
-         fputs ("\t.end\t", asm_out_file);
-         assemble_name (asm_out_file, stubname);
-         fputs ("\n", asm_out_file);
-       }
+      mips_end_function_definition (stubname);
 
       /* Record this stub.  */
-      l = (struct mips16_stub *) xmalloc (sizeof *l);
+      l = XNEW (struct mips16_stub);
       l->name = xstrdup (fnname);
-      l->fpret = fpret;
+      l->fp_ret_p = fp_ret_p;
       l->next = mips16_stubs;
       mips16_stubs = l;
     }
 
-  /* If we expect a floating point return value, but we've built a
+  /* 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
+     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)
+  if (fp_ret_p && !l->fp_ret_p)
     error ("cannot handle inconsistent calls to %qs", fnname);
 
   if (retval == NULL_RTX)
-    insn = gen_call_internal_direct (fn, arg_size);
+    insn = gen_call_internal_direct (fn, args_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)
+    insn = gen_call_value_internal_direct (retval, fn, args_size);
+  insn = mips_emit_call_insn (insn, fn, fn, 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)),
+                        gen_rtx_CLOBBER (VOIDmode,
+                                         gen_rtx_REG (word_mode, 18)),
                         CALL_INSN_FUNCTION_USAGE (insn));
 
-  /* Return 1 to tell the caller that we've generated the call
-     insn.  */
-  return 1;
+  return insn;
 }
 \f
-/* Return true if calls to X can use R_MIPS_CALL* relocations.  */
-
-static bool
-mips_ok_for_lazy_binding_p (rtx x)
-{
-  return (TARGET_USE_GOT
-         && GET_CODE (x) == SYMBOL_REF
-         && !mips_symbol_binds_local_p (x));
-}
+/* Expand a call of type TYPE.  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.  LAZY_P is true if this call already
+   involves a lazily-bound function address (such as when calling
+   functions through a MIPS16 hard-float stub).
 
-/* 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.  */
+   Return the call itself.  */
 
-static bool
-mips_load_call_address (rtx dest, rtx addr, int sibcall_p)
+rtx
+mips_expand_call (enum mips_call_type type, rtx result, rtx addr,
+                 rtx args_size, rtx aux, bool lazy_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))
-    {
-      rtx high, lo_sum_symbol;
+  rtx orig_addr, pattern, insn;
+  int fp_code;
 
-      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
+  fp_code = aux == 0 ? 0 : (int) GET_MODE (aux);
+  insn = mips16_build_call_stub (result, &addr, args_size, fp_code);
+  if (insn)
     {
-      mips_emit_move (dest, addr);
-      return false;
+      gcc_assert (!lazy_p && type == MIPS_CALL_NORMAL);
+      return insn;
     }
-}
-
-
-/* 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.  */
-
-void
-mips_expand_call (rtx result, rtx addr, rtx args_size, rtx aux, int sibcall_p)
-{
-  rtx orig_addr, pattern, insn;
-  bool lazy_p;
-
+                                ;
   orig_addr = addr;
-  lazy_p = false;
   if (!call_insn_operand (addr, VOIDmode))
     {
-      addr = gen_reg_rtx (Pmode);
-      lazy_p = mips_load_call_address (addr, orig_addr, sibcall_p);
+      if (type == MIPS_CALL_EPILOGUE)
+       addr = MIPS_EPILOGUE_TEMP (Pmode);
+      else
+       addr = gen_reg_rtx (Pmode);
+      lazy_p |= mips_load_call_address (type, addr, orig_addr);
     }
 
-  if (TARGET_MIPS16
-      && TARGET_HARD_FLOAT_ABI
-      && build_mips16_call_stub (result, addr, args_size,
-                                aux == 0 ? 0 : (int) GET_MODE (aux)))
-    return;
-
   if (result == 0)
-    pattern = (sibcall_p
-              ? gen_sibcall_internal (addr, args_size)
-              : gen_call_internal (addr, args_size));
+    {
+      rtx (*fn) (rtx, rtx);
+
+      if (type == MIPS_CALL_EPILOGUE && TARGET_SPLIT_CALLS)
+       fn = gen_call_split;
+      else if (type == MIPS_CALL_SIBCALL)
+       fn = gen_sibcall_internal;
+      else
+       fn = gen_call_internal;
+
+      pattern = fn (addr, args_size);
+    }
   else if (GET_CODE (result) == PARALLEL && XVECLEN (result, 0) == 2)
     {
+      /* Handle return values created by mips_return_fpr_pair.  */
+      rtx (*fn) (rtx, rtx, rtx, rtx);
       rtx reg1, reg2;
 
+      if (type == MIPS_CALL_EPILOGUE && TARGET_SPLIT_CALLS)
+       fn = gen_call_value_multiple_split;
+      else if (type == MIPS_CALL_SIBCALL)
+       fn = gen_sibcall_value_multiple_internal;
+      else
+       fn = gen_call_value_multiple_internal;
+
       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));
+      pattern = fn (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));
+    {
+      rtx (*fn) (rtx, rtx, rtx);
 
-  insn = emit_call_insn (pattern);
+      if (type == MIPS_CALL_EPILOGUE && TARGET_SPLIT_CALLS)
+       fn = gen_call_value_split;
+      else if (type == MIPS_CALL_SIBCALL)
+       fn = gen_sibcall_value_internal;
+      else
+       fn = gen_call_value_internal;
 
-  /* Lazy-binding stubs require $gp to be valid on entry.  We also pretend
-     that they use FAKE_CALL_REGNO; see the load_call<mode> patterns for
-     details.  */
-  if (lazy_p)
-    {
-      use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
-      use_reg (&CALL_INSN_FUNCTION_USAGE (insn),
-              gen_rtx_REG (Pmode, FAKE_CALL_REGNO));
+      /* 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 = fn (result, addr, args_size);
     }
+
+  return mips_emit_call_insn (pattern, orig_addr, addr, lazy_p);
 }
 
+/* Split call instruction INSN into a $gp-clobbering call and
+   (where necessary) an instruction to restore $gp from its save slot.
+   CALL_PATTERN is the pattern of the new call.  */
+
+void
+mips_split_call (rtx insn, rtx call_pattern)
+{
+  rtx new_insn;
+
+  new_insn = emit_call_insn (call_pattern);
+  CALL_INSN_FUNCTION_USAGE (new_insn)
+    = copy_rtx (CALL_INSN_FUNCTION_USAGE (insn));
+  if (!find_reg_note (insn, REG_NORETURN, 0))
+    /* Pick a temporary register that is suitable for both MIPS16 and
+       non-MIPS16 code.  $4 and $5 are used for returning complex double
+       values in soft-float code, so $6 is the first suitable candidate.  */
+    mips_restore_gp (gen_rtx_REG (Pmode, GP_ARG_FIRST + 2));
+}
 
 /* Implement TARGET_FUNCTION_OK_FOR_SIBCALL.  */
 
@@ -5693,17 +6141,18 @@ mips_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
 
   /* 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))
+     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;
 
-  /* ...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.  */
+  /* 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)
+      && (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;
@@ -5713,18 +6162,17 @@ mips_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
 }
 \f
 /* Emit code to move general operand SRC into condition-code
-   register DEST.  SCRATCH is a scratch TFmode float register.
+   register DEST given that SCRATCH is a scratch TFmode FPR.
    The sequence is:
 
        FP1 = SRC
        FP2 = 0.0f
        DEST = FP2 < FP1
 
-   where FP1 and FP2 are single-precision float registers
-   taken from SCRATCH.  */
+   where FP1 and FP2 are single-precision FPRs taken from SCRATCH.  */
 
 void
-mips_emit_fcc_reload (rtx dest, rtx src, rtx scratch)
+mips_expand_fcc_reload (rtx dest, rtx src, rtx scratch)
 {
   rtx fp1, fp2;
 
@@ -5769,7 +6217,7 @@ mips_block_move_straight (rtx dest, rtx src, HOST_WIDE_INT length)
   delta = bits / BITS_PER_UNIT;
 
   /* Allocate a buffer for the temporary registers.  */
-  regs = alloca (sizeof (rtx) * length / delta);
+  regs = XALLOCAVEC (rtx, length / delta);
 
   /* Load as many BITS-sized chunks as possible.  Use a normal load if
      the source has enough alignment, otherwise use left/right pairs.  */
@@ -5781,7 +6229,7 @@ mips_block_move_straight (rtx dest, rtx src, HOST_WIDE_INT length)
       else
        {
          rtx part = adjust_address (src, BLKmode, offset);
-         if (!mips_expand_unaligned_load (regs[i], part, bits, 0))
+         if (!mips_expand_ext_as_unaligned_load (regs[i], part, bits, 0))
            gcc_unreachable ();
        }
     }
@@ -5793,7 +6241,7 @@ mips_block_move_straight (rtx dest, rtx src, HOST_WIDE_INT length)
     else
       {
        rtx part = adjust_address (dest, BLKmode, offset);
-       if (!mips_expand_unaligned_store (part, regs[i], bits, 0))
+       if (!mips_expand_ins_as_unaligned_store (part, regs[i], bits, 0))
          gcc_unreachable ();
       }
 
@@ -5806,10 +6254,6 @@ mips_block_move_straight (rtx dest, rtx src, HOST_WIDE_INT length)
                      MIN (MEM_ALIGN (src), MEM_ALIGN (dest)), 0);
     }
 }
-\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
@@ -5831,23 +6275,23 @@ mips_adjust_block_mem (rtx mem, HOST_WIDE_INT length,
   set_mem_align (*loop_mem, MIN (MEM_ALIGN (mem), length * BITS_PER_UNIT));
 }
 
-
-/* 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.  */
+/* 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.  */
 
 static void
-mips_block_move_loop (rtx dest, rtx src, HOST_WIDE_INT length)
+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;
 
-  leftover = length % MAX_MOVE_BYTES;
+  leftover = length % bytes_per_iter;
   length -= leftover;
 
   /* 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);
+  mips_adjust_block_mem (src, bytes_per_iter, &src_reg, &src);
+  mips_adjust_block_mem (dest, bytes_per_iter, &dest_reg, &dest);
 
   /* Calculate the value that SRC_REG should have after the last iteration
      of the loop.  */
@@ -5859,11 +6303,11 @@ mips_block_move_loop (rtx dest, rtx src, HOST_WIDE_INT length)
   emit_label (label);
 
   /* Emit the loop body.  */
-  mips_block_move_straight (dest, src, MAX_MOVE_BYTES);
+  mips_block_move_straight (dest, src, bytes_per_iter);
 
   /* 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));
+  mips_emit_move (src_reg, plus_constant (src_reg, bytes_per_iter));
+  mips_emit_move (dest_reg, plus_constant (dest_reg, bytes_per_iter));
 
   /* Emit the loop condition.  */
   if (Pmode == DImode)
@@ -5877,28 +6321,29 @@ mips_block_move_loop (rtx dest, rtx src, HOST_WIDE_INT length)
     mips_block_move_straight (dest, src, leftover);
 }
 
-/* Expand a movmemsi instruction.  */
+/* Expand a movmemsi instruction, which copies LENGTH bytes from
+   memory reference SRC to memory reference DEST.  */
 
 bool
 mips_expand_block_move (rtx dest, rtx src, rtx length)
 {
   if (GET_CODE (length) == CONST_INT)
     {
-      if (INTVAL (length) <= 2 * MAX_MOVE_BYTES)
+      if (INTVAL (length) <= MIPS_MAX_MOVE_BYTES_STRAIGHT)
        {
          mips_block_move_straight (dest, src, INTVAL (length));
          return true;
        }
       else if (optimize)
        {
-         mips_block_move_loop (dest, src, INTVAL (length));
+         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).  */
 
 void
@@ -5906,7 +6351,7 @@ mips_expand_synci_loop (rtx begin, rtx end)
 {
   rtx inc, label, cmp, cmp_result;
 
-  /* Load INC with the cache line size (rdhwr INC,$1). */
+  /* Load INC with the cache line size (rdhwr INC,$1).  */
   inc = gen_reg_rtx (SImode);
   emit_insn (gen_rdhwr (inc, const1_rtx));
 
@@ -5916,8 +6361,7 @@ mips_expand_synci_loop (rtx begin, rtx end)
 
   emit_insn (gen_synci (begin));
 
-  cmp = gen_reg_rtx (Pmode);
-  mips_emit_binary (GTU, cmp, begin, end);
+  cmp = mips_force_binary (Pmode, GTU, begin, end);
 
   mips_emit_binary (PLUS, begin, begin, inc);
 
@@ -5925,6 +6369,103 @@ mips_expand_synci_loop (rtx begin, rtx end)
   emit_jump_insn (gen_condjump (cmp_result, label));
 }
 \f
+/* Expand a QI or HI mode atomic memory operation.
+
+   GENERATOR contains a pointer to the gen_* function that generates
+   the SI mode underlying atomic operation using masks that we
+   calculate.
+
+   RESULT is the return register for the operation.  Its value is NULL
+   if unused.
+
+   MEM is the location of the atomic access.
+
+   OLDVAL is the first operand for the operation.
+
+   NEWVAL is the optional second operand for the operation.  Its value
+   is NULL if unused.  */
+
+void
+mips_expand_atomic_qihi (union mips_gen_fn_ptrs generator,
+                         rtx result, rtx mem, rtx oldval, rtx newval)
+{
+  rtx orig_addr, memsi_addr, memsi, shift, shiftsi, unshifted_mask;
+  rtx unshifted_mask_reg, mask, inverted_mask, si_op;
+  rtx res = NULL;
+  enum machine_mode mode;
+
+  mode = GET_MODE (mem);
+
+  /* Compute the address of the containing SImode value.  */
+  orig_addr = force_reg (Pmode, XEXP (mem, 0));
+  memsi_addr = mips_force_binary (Pmode, AND, orig_addr,
+                                 force_reg (Pmode, GEN_INT (-4)));
+
+  /* Create a memory reference for it.  */
+  memsi = gen_rtx_MEM (SImode, memsi_addr);
+  set_mem_alias_set (memsi, ALIAS_SET_MEMORY_BARRIER);
+  MEM_VOLATILE_P (memsi) = MEM_VOLATILE_P (mem);
+
+  /* Work out the byte offset of the QImode or HImode value,
+     counting from the least significant byte.  */
+  shift = mips_force_binary (Pmode, AND, orig_addr, GEN_INT (3));
+  if (TARGET_BIG_ENDIAN)
+    mips_emit_binary (XOR, shift, shift, GEN_INT (mode == QImode ? 3 : 2));
+
+  /* Multiply by eight to convert the shift value from bytes to bits.  */
+  mips_emit_binary (ASHIFT, shift, shift, GEN_INT (3));
+
+  /* Make the final shift an SImode value, so that it can be used in
+     SImode operations.  */
+  shiftsi = force_reg (SImode, gen_lowpart (SImode, shift));
+
+  /* Set MASK to an inclusive mask of the QImode or HImode value.  */
+  unshifted_mask = GEN_INT (GET_MODE_MASK (mode));
+  unshifted_mask_reg = force_reg (SImode, unshifted_mask);
+  mask = mips_force_binary (SImode, ASHIFT, unshifted_mask_reg, shiftsi);
+
+  /* Compute the equivalent exclusive mask.  */
+  inverted_mask = gen_reg_rtx (SImode);
+  emit_insn (gen_rtx_SET (VOIDmode, inverted_mask,
+                         gen_rtx_NOT (SImode, mask)));
+
+  /* Shift the old value into place.  */
+  if (oldval != const0_rtx)
+    {
+      oldval = convert_modes (SImode, mode, oldval, true);
+      oldval = force_reg (SImode, oldval);
+      oldval = mips_force_binary (SImode, ASHIFT, oldval, shiftsi);
+    }
+
+  /* Do the same for the new value.  */
+  if (newval && newval != const0_rtx)
+    {
+      newval = convert_modes (SImode, mode, newval, true);
+      newval = force_reg (SImode, newval);
+      newval = mips_force_binary (SImode, ASHIFT, newval, shiftsi);
+    }
+
+  /* Do the SImode atomic access.  */
+  if (result)
+    res = gen_reg_rtx (SImode);
+  if (newval)
+    si_op = generator.fn_6 (res, memsi, mask, inverted_mask, oldval, newval);
+  else if (result)
+    si_op = generator.fn_5 (res, memsi, mask, inverted_mask, oldval);
+  else
+    si_op = generator.fn_4 (memsi, mask, inverted_mask, oldval);
+
+  emit_insn (si_op);
+
+  if (result)
+    {
+      /* Shift and convert the result.  */
+      mips_emit_binary (AND, res, res, mask);
+      mips_emit_binary (LSHIFTRT, res, res, shiftsi);
+      mips_emit_move (result, gen_lowpart (GET_MODE (result), res));
+    }
+}
+
 /* 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:
@@ -5933,13 +6474,13 @@ mips_expand_synci_loop (rtx begin, rtx end)
 
    *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).
+   left-side instructions (LWL, SWL, LDL, SDL).
 
    *RIGHT is a QImode reference to the opposite end of the field and
    can be used in the patterning right-side instruction.  */
 
 static bool
-mips_get_unaligned_mem (rtx *op, unsigned int width, int bitpos,
+mips_get_unaligned_mem (rtx *op, HOST_WIDE_INT width, HOST_WIDE_INT bitpos,
                        rtx *left, rtx *right)
 {
   rtx first, last;
@@ -5976,7 +6517,7 @@ mips_get_unaligned_mem (rtx *op, unsigned int width, int bitpos,
   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.  */
+     correspond to the MSB and RIGHT to the LSB.  */
   if (TARGET_BIG_ENDIAN)
     *left = first, *right = last;
   else
@@ -5985,22 +6526,25 @@ mips_get_unaligned_mem (rtx *op, unsigned int width, int bitpos,
   return true;
 }
 
+/* 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:
 
-/* 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.  */
+      (set DEST (*_extract SRC WIDTH BITPOS))
+
+   Return true on success.  */
 
 bool
-mips_expand_unaligned_load (rtx dest, rtx src, unsigned int width, int bitpos)
+mips_expand_ext_as_unaligned_load (rtx dest, rtx src, HOST_WIDE_INT width,
+                                  HOST_WIDE_INT bitpos)
 {
   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
+  /* 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
-      && SUBREG_BYTE (dest) == 0
       && GET_MODE (SUBREG_REG (dest)) == SImode)
     dest = SUBREG_REG (dest);
 
@@ -6026,12 +6570,17 @@ mips_expand_unaligned_load (rtx dest, rtx src, unsigned int width, int bitpos)
   return true;
 }
 
+/* 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:
+
+       (set (zero_extract DEST WIDTH BITPOS) SRC)
 
-/* Try to expand (set (zero_extract DEST WIDTH BITPOS) SRC).  Return
-   true on success.  */
+   Return true on success.  */
 
 bool
-mips_expand_unaligned_store (rtx dest, rtx src, unsigned int width, int bitpos)
+mips_expand_ins_as_unaligned_store (rtx dest, rtx src, HOST_WIDE_INT width,
+                                   HOST_WIDE_INT bitpos)
 {
   rtx left, right;
   enum machine_mode mode;
@@ -6041,7 +6590,6 @@ mips_expand_unaligned_store (rtx dest, rtx src, unsigned int width, int bitpos)
 
   mode = mode_for_size (width, MODE_INT, 0);
   src = gen_lowpart (mode, src);
-
   if (mode == DImode)
     {
       emit_insn (gen_mov_sdl (dest, src, left));
@@ -6069,45 +6617,41 @@ mips_mem_fits_mode_p (enum machine_mode mode, rtx x)
   return size && INTVAL (size) == GET_MODE_SIZE (mode);
 }
 
-/* Return true if (zero_extract OP SIZE POSITION) can be used as the
+/* 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:
 
-     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))
+     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))
 
    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)
+mips_use_ins_ext_p (rtx op, HOST_WIDE_INT width, HOST_WIDE_INT bitpos)
 {
-  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;
 
-  len = INTVAL (size);
-  pos = INTVAL (position);
+  if (!IN_RANGE (width, 1, GET_MODE_BITSIZE (GET_MODE (op)) - 1))
+    return false;
 
-  if (len <= 0 || len >= GET_MODE_BITSIZE (GET_MODE (op))
-      || pos < 0 || pos + len > GET_MODE_BITSIZE (GET_MODE (op)))
+  if (bitpos < 0 || bitpos + width > GET_MODE_BITSIZE (GET_MODE (op)))
     return false;
 
   return true;
 }
 \f
-/* Initialize mips_split_addresses from the associated command-line
-   settings.
+/* Return true if -msplit-addresses is selected and should be honored.
 
-   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.
+   -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.
 
    Like explicit relocation support for REL targets, it relies
    on GNU extensions in the assembler and the linker.
@@ -6115,23 +6659,23 @@ mips_use_ins_ext_p (rtx op, rtx size, rtx position)
    Although this code should work for -O0, it has traditionally
    been treated as an optimization.  */
 
-static void
-mips_init_split_addresses (void)
+static bool
+mips_split_addresses_p (void)
 {
-  if (!TARGET_MIPS16 && TARGET_SPLIT_ADDRESSES
-      && optimize && !flag_pic
-      && !ABI_HAS_64BIT_SYMBOLS)
-    mips_split_addresses = 1;
-  else
-    mips_split_addresses = 0;
+  return (TARGET_SPLIT_ADDRESSES
+         && optimize
+         && !TARGET_MIPS16
+         && !flag_pic
+         && !ABI_HAS_64BIT_SYMBOLS);
 }
 
-/* (Re-)Initialize information about relocs.  */
+/* (Re-)Initialize mips_split_p, mips_lo_relocs and mips_hi_relocs.  */
 
 static void
 mips_init_relocs (void)
 {
   memset (mips_split_p, '\0', sizeof (mips_split_p));
+  memset (mips_split_hi_p, '\0', sizeof (mips_split_hi_p));
   memset (mips_hi_relocs, '\0', sizeof (mips_hi_relocs));
   memset (mips_lo_relocs, '\0', sizeof (mips_lo_relocs));
 
@@ -6157,7 +6701,7 @@ mips_init_relocs (void)
     }
   else
     {
-      if (TARGET_EXPLICIT_RELOCS || mips_split_addresses || TARGET_MIPS16)
+      if (TARGET_EXPLICIT_RELOCS || mips_split_addresses_p () || TARGET_MIPS16)
        {
          mips_split_p[SYMBOL_ABSOLUTE] = true;
          mips_hi_relocs[SYMBOL_ABSOLUTE] = "%hi(";
@@ -6173,13 +6717,13 @@ mips_init_relocs (void)
       mips_split_p[SYMBOL_GP_RELATIVE] = true;
       mips_lo_relocs[SYMBOL_GP_RELATIVE] = "%gprel(";
     }
+  else 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(";
 
   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(";
-
       mips_split_p[SYMBOL_GOT_PAGE_OFST] = true;
       if (TARGET_NEWABI)
        {
@@ -6191,6 +6735,9 @@ mips_init_relocs (void)
          mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got(";
          mips_lo_relocs[SYMBOL_GOT_PAGE_OFST] = "%lo(";
        }
+      if (TARGET_MIPS16)
+       /* Expose the use of $28 as soon as possible.  */
+       mips_split_hi_p[SYMBOL_GOT_PAGE_OFST] = true;
 
       if (TARGET_XGOT)
        {
@@ -6212,6 +6759,9 @@ mips_init_relocs (void)
          else
            mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got(";
          mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call16(";
+         if (TARGET_MIPS16)
+           /* Expose the use of $28 as soon as possible.  */
+           mips_split_p[SYMBOL_GOT_DISP] = true;
        }
     }
 
@@ -6222,14 +6772,16 @@ mips_init_relocs (void)
       mips_lo_relocs[SYMBOL_GOTOFF_LOADGP] = "%lo(%neg(%gp_rel(";
     }
 
-  /* Thread-local relocation operators.  */
   mips_lo_relocs[SYMBOL_TLSGD] = "%tlsgd(";
   mips_lo_relocs[SYMBOL_TLSLDM] = "%tlsldm(";
-  mips_split_p[SYMBOL_DTPREL] = 1;
+
+  mips_split_p[SYMBOL_DTPREL] = true;
   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_split_p[SYMBOL_TPREL] = true;
   mips_hi_relocs[SYMBOL_TPREL] = "%tprel_hi(";
   mips_lo_relocs[SYMBOL_TPREL] = "%tprel_lo(";
 
@@ -6254,15 +6806,14 @@ mips_strip_unspec_address (rtx op)
    in context CONTEXT.  RELOCS is the array of relocations to use.  */
 
 static void
-print_operand_reloc (FILE *file, rtx op, enum mips_symbol_context context,
-                    const char **relocs)
+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;
 
   symbol_type = mips_classify_symbolic_expression (op, context);
-  if (relocs[symbol_type] == 0)
-    fatal_insn ("PRINT_OPERAND, invalid operand for relocation", op);
+  gcc_assert (relocs[symbol_type]);
 
   fputs (relocs[symbol_type], file);
   output_addr_const (file, mips_strip_unspec_address (op));
@@ -6480,7 +7031,7 @@ mips_print_float_branch_condition (FILE *file, enum rtx_code code, int letter)
    'z' Print $0 if OP is zero, otherwise print OP normally.  */
 
 void
-print_operand (FILE *file, rtx op, int letter)
+mips_print_operand (FILE *file, rtx op, int letter)
 {
   enum rtx_code code;
 
@@ -6519,11 +7070,11 @@ print_operand (FILE *file, rtx op, int letter)
     case 'h':
       if (code == HIGH)
        op = XEXP (op, 0);
-      print_operand_reloc (file, op, SYMBOL_CONTEXT_LEA, mips_hi_relocs);
+      mips_print_operand_reloc (file, op, SYMBOL_CONTEXT_LEA, mips_hi_relocs);
       break;
 
     case 'R':
-      print_operand_reloc (file, op, SYMBOL_CONTEXT_LEA, mips_lo_relocs);
+      mips_print_operand_reloc (file, op, SYMBOL_CONTEXT_LEA, mips_lo_relocs);
       break;
 
     case 'C':
@@ -6562,7 +7113,7 @@ print_operand (FILE *file, rtx op, int letter)
     case 'Z':
       if (ISA_HAS_8CC)
        {
-         print_operand (file, op, 0);
+         mips_print_operand (file, op, 0);
          fputc (',', file);
        }
       break;
@@ -6612,7 +7163,7 @@ print_operand (FILE *file, rtx op, int letter)
 /* Output address operand X to FILE.  */
 
 void
-print_operand_address (FILE *file, rtx x)
+mips_print_operand_address (FILE *file, rtx x)
 {
   struct mips_address_info addr;
 
@@ -6620,19 +7171,19 @@ print_operand_address (FILE *file, rtx x)
     switch (addr.type)
       {
       case ADDRESS_REG:
-       print_operand (file, addr.offset, 0);
+       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:
@@ -6642,8 +7193,7 @@ print_operand_address (FILE *file, rtx x)
   gcc_unreachable ();
 }
 \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.  */
+/* Implement TARGET_ENCODE_SECTION_INFO.  */
 
 static void
 mips_encode_section_info (tree decl, rtx rtl, int first)
@@ -6655,6 +7205,7 @@ mips_encode_section_info (tree decl, rtx rtl, int first)
       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;
@@ -6677,15 +7228,16 @@ mips_select_rtx_section (enum machine_mode mode, rtx x,
 /* 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.  */
+   && !TARGET_ABSOLUTE_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)
+  if (!TARGET_ABICALLS || TARGET_ABSOLUTE_ABICALLS || TARGET_GPWORD)
     return default_function_rodata_section (decl);
 
   if (decl && DECL_SECTION_NAME (decl))
@@ -6697,7 +7249,8 @@ mips_function_rodata_section (tree decl)
          rname[14] = 'd';
          return get_section (rname, SECTION_LINKONCE | SECTION_WRITE, decl);
        }
-      else if (flag_function_sections && flag_data_sections
+      else if (flag_function_sections
+              && flag_data_sections
               && strncmp (name, ".text.", 6) == 0)
        {
          char *rname = ASTRDUP (name);
@@ -6708,21 +7261,19 @@ mips_function_rodata_section (tree decl)
   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.  */
+/* Implement TARGET_IN_SMALL_DATA_P.  */
 
 static bool
 mips_in_small_data_p (const_tree decl)
 {
-  HOST_WIDE_INT size;
+  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 override_options.  */
+  /* 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;
 
@@ -6766,8 +7317,10 @@ mips_in_small_data_p (const_tree decl)
        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_section_threshold);
+  return size > 0 && size <= mips_small_data_threshold;
 }
 
 /* Implement TARGET_USE_ANCHORS_FOR_SYMBOL_P.  We don't want to use
@@ -6807,7 +7360,8 @@ mips_debugger_offset (rtx addr, HOST_WIDE_INT offset)
   if (offset == 0)
     offset = INTVAL (offset2);
 
-  if (reg == stack_pointer_rtx || reg == frame_pointer_rtx
+  if (reg == stack_pointer_rtx
+      || reg == frame_pointer_rtx
       || reg == hard_frame_pointer_rtx)
     {
       offset -= cfun->machine->frame.total_size;
@@ -6825,13 +7379,7 @@ mips_debugger_offset (rtx addr, HOST_WIDE_INT offset)
   return offset;
 }
 \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.
-
-   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.  */
+/* Implement ASM_OUTPUT_EXTERNAL.  */
 
 void
 mips_output_external (FILE *file, tree decl, const char *name)
@@ -6845,6 +7393,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",
@@ -6865,14 +7421,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)
@@ -6886,12 +7440,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)
     {
@@ -6903,9 +7455,9 @@ mips_output_filename (FILE *stream, const char *name)
     }
 }
 
-/* MIPS implementation of TARGET_ASM_OUTPUT_DWARF_DTPREL.  */
+/* Implement TARGET_ASM_OUTPUT_DWARF_DTPREL.  */
 
-static void
+static void ATTRIBUTE_UNUSED
 mips_output_dwarf_dtprel (FILE *file, int size, rtx x)
 {
   switch (size)
@@ -6950,25 +7502,22 @@ mips_dwarf_register_span (rtx reg)
 
   return NULL_RTX;
 }
-\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.  */
+
+/* Implement ASM_OUTPUT_ASCII.  */
 
 void
-mips_output_ascii (FILE *stream, const char *string_param, size_t len,
-                  const char *prefix)
+mips_output_ascii (FILE *stream, const char *string, size_t len)
 {
   size_t i;
-  int cur_pos = 17;
-  register const unsigned char *string =
-    (const unsigned char *)string_param;
+  int cur_pos;
 
-  fprintf (stream, "%s\"", prefix);
+  cur_pos = 17;
+  fprintf (stream, "\t.ascii\t\"");
   for (i = 0; i < len; i++)
     {
-      register int c = string[i];
+      int c;
 
+      c = (unsigned char) string[i];
       if (ISPRINT (c))
        {
          if (c == '\\' || c == '\"')
@@ -6988,39 +7537,19 @@ 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");
 }
 
-#ifdef BSS_SECTION_ASM_OP
-/* Implement ASM_OUTPUT_ALIGNED_BSS.  This differs from the default only
-   in the use of sbss.  */
-
-void
-mips_output_aligned_bss (FILE *stream, tree decl, const char *name,
-                        unsigned HOST_WIDE_INT size, int align)
-{
-  extern tree last_assemble_variable_decl;
-
-  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
 /* 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.  */
+   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_declare_object (FILE *stream, const char *name, const char *init_string,
@@ -7075,8 +7604,10 @@ mips_output_aligned_decl_common (FILE *stream, tree decl, const char *name,
 {
   /* 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)
+  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 (TREE_PUBLIC (decl) && DECL_NAME (decl))
@@ -7097,7 +7628,7 @@ mips_output_aligned_decl_common (FILE *stream, tree decl, const char *name,
 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,
@@ -7130,7 +7661,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)
     {
@@ -7143,6 +7675,29 @@ mips_finish_declare_object (FILE *stream, tree decl, int top_level, int at_end)
 }
 #endif
 \f
+/* Return the FOO in the name of the ".mdebug.FOO" section associated
+   with the current ABI.  */
+
+static const char *
+mips_mdebug_abi_name (void)
+{
+  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.  */
 
 static void
@@ -7150,33 +7705,18 @@ mips_file_start (void)
 {
   default_file_start ();
 
+  /* 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)
     {
-      /* 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.  */
+      /* 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",
-              abi_string);
+              mips_mdebug_abi_name ());
 
       /* There is no ELF header flag to distinguish long32 forms of the
         EABI from long64 forms.  Emit a special section to help tools
@@ -7188,22 +7728,27 @@ mips_file_start (void)
 
 #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);
+              (TARGET_HARD_FLOAT_ABI
+               ? (TARGET_DOUBLE_FLOAT
+                  ? ((!TARGET_64BIT && TARGET_FLOAT64) ? 4 : 1) : 2) : 3));
 #endif
     }
 
-  /* Generate the pseudo ops that System V.4 wants.  */
+  /* If TARGET_ABICALLS, tell GAS to generate -KPIC code.  */
   if (TARGET_ABICALLS)
-    fprintf (asm_out_file, "\t.abicalls\n");
+    {
+      fprintf (asm_out_file, "\t.abicalls\n");
+      if (TARGET_ABICALLS_PIC0)
+       fprintf (asm_out_file, "\t.option\tpic0\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);
+            mips_small_data_threshold, mips_arch_info->name, mips_isa);
 }
 \f
-\f
-/* Make the last instruction frame related and note that it performs
+/* Make the last instruction frame-related and note that it performs
    the operation described by FRAME_PATTERN.  */
 
 static void
@@ -7218,7 +7763,6 @@ mips_set_frame_expr (rtx frame_pattern)
                                      REG_NOTES (insn));
 }
 
-
 /* Return a frame-related rtx that stores REG at MEM.
    REG must be a single register.  */
 
@@ -7227,7 +7771,7 @@ mips_frame_set (rtx mem, rtx reg)
 {
   rtx set;
 
-  /* If we're saving the return address register and the dwarf return
+  /* 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
@@ -7301,21 +7845,19 @@ mips16e_mask_registers (unsigned int *mask_ptr, const unsigned char *regs,
 static rtx
 mips16e_collect_propagate_value (rtx x, rtx *reg_values)
 {
-  rtx x0, x1;
-
   x = avoid_constant_pool_reference (x);
 
   if (UNARY_P (x))
     {
-      x0 = mips16e_collect_propagate_value (XEXP (x, 0), reg_values);
+      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)));
     }
 
   if (ARITHMETIC_P (x))
     {
-      x0 = mips16e_collect_propagate_value (XEXP (x, 0), reg_values);
-      x1 = mips16e_collect_propagate_value (XEXP (x, 1), reg_values);
+      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);
     }
 
@@ -7347,12 +7889,12 @@ mips16e_collect_argument_save_p (rtx dest, rtx src, rtx *reg_values,
   /* 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])
+  if (!IN_RANGE (regno, GP_ARG_FIRST, GP_ARG_LAST) || reg_values[regno])
     return false;
   argno = regno - GP_ARG_FIRST;
 
-  /* Check whether the address is an appropriate stack pointer or
-     frame pointer access.  */
+  /* 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;
@@ -7466,7 +8008,7 @@ mips16e_build_save_restore (bool restore_p, unsigned int *mask_ptr,
   unsigned int i, regno;
   int n;
 
-  gcc_assert (cfun->machine->frame.fp_reg_size == 0);
+  gcc_assert (cfun->machine->frame.num_fp == 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
@@ -7493,7 +8035,7 @@ mips16e_build_save_restore (bool restore_p, unsigned int *mask_ptr,
   /* Save the arguments.  */
   for (i = 0; i < nargs; i++)
     {
-      offset = top_offset + i * GET_MODE_SIZE (gpr_mode);
+      offset = top_offset + i * UNITS_PER_WORD;
       set = mips16e_save_restore_reg (restore_p, offset, GP_ARG_FIRST + i);
       XVECEXP (pattern, 0, n++) = set;
     }
@@ -7513,7 +8055,7 @@ mips16e_build_save_restore (bool restore_p, unsigned int *mask_ptr,
     }
 
   /* Tell the caller what offset it should use for the remaining registers.  */
-  *offset_ptr = size + (offset - top_offset) + size;
+  *offset_ptr = size + (offset - top_offset);
 
   gcc_assert (n == XVECLEN (pattern, 0));
 
@@ -7541,7 +8083,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;
@@ -7570,7 +8112,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)
@@ -7580,7 +8122,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;
@@ -7702,19 +8244,30 @@ mips_function_has_gp_insn (void)
 
       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
+       if (USEFUL_INSN_P (insn)
            && (get_attr_got (insn) != GOT_UNSET
-               || small_data_pattern (PATTERN (insn), VOIDmode)))
-         break;
+               || mips_small_data_pattern_p (PATTERN (insn))))
+         {
+           cfun->machine->has_gp_insn_p = true;
+           break;
+         }
       pop_topmost_sequence ();
-
-      cfun->machine->has_gp_insn_p = (insn != 0);
     }
   return cfun->machine->has_gp_insn_p;
 }
 
+/* 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 the register that should be used as the global pointer
    within this function.  Return 0 if the function doesn't need
@@ -7735,71 +8288,76 @@ mips_global_pointer (void)
 
   /* FUNCTION_PROFILER includes a jal macro, so we need to give it
      a valid gp.  */
-  if (current_function_profile)
+  if (crtl->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)
+  if (crtl->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:
+  /* There's no need to initialize $gp if it isn't referenced now,
+     and if we can be sure that no new references will be added during
+     or after reload.  */
+  if (!df_regs_ever_live_p (GLOBAL_POINTER_REGNUM)
+      && !mips_function_has_gp_insn ())
+    {
+      /* The function doesn't use $gp at the moment.  If we're generating
+        -call_nonpic code, no new uses will be introduced during or after
+        reload.  */
+      if (TARGET_ABICALLS_PIC0)
+       return 0;
 
-         (set (reg:DF R1) (float:DF (reg:SI R2)))
+      /* We need to handle the following implicit gp references:
 
-     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.
+        - Reload can sometimes introduce constant pool references
+          into a function that otherwise didn't need them.  For example,
+          suppose we have an instruction like:
 
-     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;
+              (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.
+
+        - MIPS16 functions that return in FPRs need to call an
+          external libgcc routine.  */
+      if (!crtl->uses_const_pool
+         && !mips16_cfun_returns_in_fpr_p ())
+       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 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)));
-}
+         && call_really_used_regs[regno]
+         && !fixed_regs[regno]
+         && regno != PIC_FUNCTION_ADDR_REGNUM)
+       return regno;
 
+  return GLOBAL_POINTER_REGNUM;
+}
 
-/* Return true if the current function must save REGNO.  */
+/* Return true if the current function must save register 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;
+  /* We need to save $gp if TARGET_CALL_SAVED_GP and if we have not
+     chosen a call-clobbered substitute.  */
+  if (TARGET_CALL_SAVED_GP
+      && regno == GLOBAL_POINTER_REGNUM
+      && cfun->machine->global_pointer == regno)
+    return true;
 
   /* Check call-saved registers.  */
-  if ((current_function_saves_all_registers || df_regs_ever_live_p (regno))
+  if ((crtl->saves_all_registers || df_regs_ever_live_p (regno))
       && !call_really_used_regs[regno])
     return true;
 
@@ -7817,7 +8375,7 @@ mips_save_reg_p (unsigned int regno)
     return true;
 
   /* Check for registers that must be saved for FUNCTION_PROFILER.  */
-  if (current_function_profile && MIPS_SAVE_REG_FOR_PROFILING_P (regno))
+  if (crtl->profile && MIPS_SAVE_REG_FOR_PROFILING_P (regno))
     return true;
 
   /* We need to save the incoming return address if it is ever clobbered
@@ -7826,15 +8384,14 @@ mips_save_reg_p (unsigned int regno)
      value in FPRs.  */
   if (regno == GP_REG_FIRST + 31
       && (df_regs_ever_live_p (regno)
-         || current_function_calls_eh_return
+         || crtl->calls_eh_return
          || mips16_cfun_returns_in_fpr_p ()))
     return true;
 
   return false;
 }
 
-/* Return the bytes needed to compute the frame pointer from the current
-   stack pointer.  SIZE is the size (in bytes) of the local variables.
+/* Populate the current function's mips_frame_info structure.
 
    MIPS stack frames look like:
 
@@ -7895,15 +8452,16 @@ mips_save_reg_p (unsigned int regno)
    They decrease stack_pointer_rtx but leave frame_pointer_rtx and
    hard_frame_pointer_rtx unchanged.  */
 
-HOST_WIDE_INT
-compute_frame_size (HOST_WIDE_INT size)
+static void
+mips_compute_frame_info (void)
 {
   struct mips_frame_info *frame;
-  HOST_WIDE_INT offset;
+  HOST_WIDE_INT offset, size;
   unsigned int regno, i;
 
   frame = &cfun->machine->frame;
   memset (frame, 0, sizeof (*frame));
+  size = get_frame_size ();
 
   cfun->machine->global_pointer = mips_global_pointer ();
 
@@ -7917,7 +8475,7 @@ compute_frame_size (HOST_WIDE_INT size)
         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)
+      if (cfun->calls_alloca)
        frame->args_size = REG_PARM_STACK_SPACE (cfun->decl);
       else
        frame->args_size = 0;
@@ -7925,7 +8483,7 @@ compute_frame_size (HOST_WIDE_INT size)
     }
   else
     {
-      frame->args_size = current_function_outgoing_args_size;
+      frame->args_size = crtl->outgoing_args_size;
       frame->cprestore_size = STARTING_FRAME_OFFSET - frame->args_size;
     }
   offset = frame->args_size + frame->cprestore_size;
@@ -7944,7 +8502,7 @@ compute_frame_size (HOST_WIDE_INT size)
 
   /* If this function calls eh_return, we must also save and restore the
      EH data registers.  */
-  if (current_function_calls_eh_return)
+  if (crtl->calls_eh_return)
     for (i = 0; EH_RETURN_DATA_REGNO (i) != INVALID_REGNUM; i++)
       {
        frame->num_gp++;
@@ -7965,8 +8523,7 @@ compute_frame_size (HOST_WIDE_INT size)
   /* Move above the GPR save area.  */
   if (frame->num_gp > 0)
     {
-      frame->gp_reg_size = frame->num_gp * UNITS_PER_WORD;
-      offset += MIPS_STACK_ALIGN (frame->gp_reg_size);
+      offset += MIPS_STACK_ALIGN (frame->num_gp * UNITS_PER_WORD);
       frame->gp_sp_offset = offset - UNITS_PER_WORD;
     }
 
@@ -7983,8 +8540,7 @@ compute_frame_size (HOST_WIDE_INT size)
   /* Move above the FPR save area.  */
   if (frame->num_fp > 0)
     {
-      frame->fp_reg_size = frame->num_fp * UNITS_PER_FPREG;
-      offset += MIPS_STACK_ALIGN (frame->fp_reg_size);
+      offset += MIPS_STACK_ALIGN (frame->num_fp * UNITS_PER_FPREG);
       frame->fp_sp_offset = offset - UNITS_PER_HWFPVALUE;
     }
 
@@ -7993,7 +8549,7 @@ compute_frame_size (HOST_WIDE_INT size)
   frame->arg_pointer_offset = offset;
 
   /* Move above the callee-allocated area for pretend stack arguments.  */
-  offset += current_function_pretend_args_size;
+  offset += crtl->args.pretend_args_size;
   frame->total_size = offset;
 
   /* Work out the offsets of the save areas from the top of the frame.  */
@@ -8007,9 +8563,6 @@ compute_frame_size (HOST_WIDE_INT size)
      instructions for local variables and incoming arguments.  */
   if (TARGET_MIPS16)
     frame->hard_frame_pointer_offset = frame->args_size;
-
-  frame->initialized = reload_completed;
-  return frame->total_size;
 }
 
 /* Return the style of GP load sequence that is being used for the
@@ -8029,7 +8582,7 @@ mips_current_loadgp_style (void)
 
   return TARGET_NEWABI ? LOADGP_NEWABI : LOADGP_OLDABI;
 }
-\f
+
 /* Implement FRAME_POINTER_REQUIRED.  */
 
 bool
@@ -8037,7 +8590,7 @@ 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)
+  if (cfun->calls_alloca)
     return true;
 
   /* In MIPS16 mode, we need a frame pointer for a large frame; otherwise,
@@ -8046,7 +8599,7 @@ mips_frame_pointer_required (void)
      without using a second temporary register.  */
   if (TARGET_MIPS16)
     {
-      compute_frame_size (get_frame_size ());
+      mips_compute_frame_info ();
       if (!SMALL_OPERAND (cfun->machine->frame.total_size))
        return true;
     }
@@ -8054,16 +8607,16 @@ mips_frame_pointer_required (void)
   return false;
 }
 
-/* Implement INITIAL_ELIMINATION_OFFSET.  FROM is either the frame
-   pointer or argument pointer.  TO is either the stack pointer or
-   hard frame pointer.  */
+/* 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)
 {
   HOST_WIDE_INT offset;
 
-  compute_frame_size (get_frame_size ());
+  mips_compute_frame_info ();
 
   /* Set OFFSET to the offset from the soft frame pointer, which is also
      the offset from the end-of-prologue stack pointer.  */
@@ -8087,18 +8640,30 @@ mips_initial_elimination_offset (int from, int to)
   return offset;
 }
 \f
-/* Implement TARGET_EXTRA_LIVE_ON_ENTRY.  Some code models use the incoming
-   value of PIC_FUNCTION_ADDR_REGNUM to set up the global pointer.  */
+/* Implement TARGET_EXTRA_LIVE_ON_ENTRY.  */
 
 static void
 mips_extra_live_on_entry (bitmap regs)
 {
-  if (TARGET_USE_GOT && !TARGET_ABSOLUTE_ABICALLS)
-    bitmap_set_bit (regs, PIC_FUNCTION_ADDR_REGNUM);
+  if (TARGET_USE_GOT)
+    {
+      /* 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);
+
+      /* The prologue may set MIPS16_PIC_TEMP_REGNUM to the value of
+        the global pointer.  */
+      if (TARGET_MIPS16)
+       bitmap_set_bit (regs, MIPS16_PIC_TEMP_REGNUM);
+
+      /* See the comment above load_call<mode> for details.  */
+      bitmap_set_bit (regs, GOT_VERSION_REGNUM);
+    }
 }
 
-/* Implement RETURN_ADDR_RTX.  Note, we do not support moving
-   back to a previous frame.  */
+/* Implement RETURN_ADDR_RTX.  We do not support moving back to a
+   previous frame.  */
 
 rtx
 mips_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
@@ -8118,32 +8683,54 @@ mips_set_return_address (rtx address, rtx scratch)
 {
   rtx slot_address;
 
-  compute_frame_size (get_frame_size ());
-  gcc_assert ((cfun->machine->frame.mask >> 31) & 1);
+  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);
+}
+
+/* Return a MEM rtx for the cprestore slot, using TEMP as a temporary base
+   register if need be.  */
+
+static rtx
+mips_cprestore_slot (rtx temp)
+{
+  const struct mips_frame_info *frame;
+  rtx base;
+  HOST_WIDE_INT offset;
 
-  mips_emit_move (gen_rtx_MEM (GET_MODE (address), slot_address), address);
+  frame = &cfun->machine->frame;
+  if (frame_pointer_needed)
+    {
+      base = hard_frame_pointer_rtx;
+      offset = frame->args_size - frame->hard_frame_pointer_offset;
+    }
+  else
+    {
+      base = stack_pointer_rtx;
+      offset = frame->args_size;
+    }
+  return gen_frame_mem (Pmode, mips_add_offset (temp, base, offset));
 }
 
-/* Restore $gp from its save slot.  Valid only when using o32 or
-   o64 abicalls.  */
+/* Restore $gp from its save slot, using TEMP as a temporary base register
+   if need be.  This function is for o32 and o64 abicalls only.  */
 
 void
-mips_restore_gp (void)
+mips_restore_gp (rtx temp)
 {
-  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);
+  if (cfun->machine->global_pointer == 0)
+    return;
 
-  mips_emit_move (pic_offset_table_rtx, slot);
+  if (TARGET_MIPS16)
+    {
+      mips_emit_move (temp, mips_cprestore_slot (temp));
+      mips_emit_move (pic_offset_table_rtx, temp);
+    }
+  else
+    mips_emit_move (pic_offset_table_rtx, mips_cprestore_slot (temp));
   if (!TARGET_EXPLICIT_RELOCS)
     emit_insn (gen_blockage ());
 }
@@ -8163,11 +8750,9 @@ mips_save_restore_reg (enum machine_mode mode, int regno,
   rtx mem;
 
   mem = gen_frame_mem (mode, plus_constant (stack_pointer_rtx, offset));
-
   fn (gen_rtx_REG (mode, regno), mem);
 }
 
-
 /* 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.  */
@@ -8187,15 +8772,15 @@ mips_for_each_saved_reg (HOST_WIDE_INT sp_offset, mips_save_restore_fn fn)
   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);
+       mips_save_restore_reg (word_mode, regno, offset, fn);
+       offset -= UNITS_PER_WORD;
       }
 
   /* This loop must iterate over the same space as its companion in
-     compute_frame_size.  */
+     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);
+  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))
@@ -8218,93 +8803,87 @@ mips_output_cplocal (void)
     output_asm_insn (".cplocal %+", 0);
 }
 
-/* Set up the stack and frame (if desired) for the function.  */
+/* Implement TARGET_OUTPUT_FUNCTION_PROLOGUE.  */
 
 static void
 mips_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
 {
   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.  */
+  /* 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)
-    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);
-       }
+      && crtl->args.info.fp_code != 0)
+    mips16_build_function_stub ();
 
-      assemble_name (file, fnname);
-      fputs (":\n", file);
-    }
+  /* 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);
+  mips_start_function_definition (fnname, TARGET_MIPS16);
 
   /* 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)
     {
-      /* .frame FRAMEREG, FRAMESIZE, RETREG */
+      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"
+              "# 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]),
+              reg_names[frame_pointer_needed
+                        ? HARD_FRAME_POINTER_REGNUM
+                        : STACK_POINTER_REGNUM],
               (frame_pointer_needed
-               ? tsize - cfun->machine->frame.hard_frame_pointer_offset
-               : tsize),
+               ? frame->total_size - frame->hard_frame_pointer_offset
+               : frame->total_size),
               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);
+              frame->var_size,
+              frame->num_gp, frame->num_fp,
+              frame->args_size,
+              frame->cprestore_size);
 
-      /* .mask MASK, GPOFFSET; .fmask FPOFFSET */
+      /* .mask MASK, OFFSET.  */
       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);
+              frame->mask, frame->gp_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.  */
+      /* .fmask MASK, OFFSET.  */
+      fprintf (file, "\t.fmask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
+              frame->fmask, frame->fp_save_offset);
     }
 
+  /* 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)
     {
-      /* Handle the initialization of $gp for SVR4 PIC.  */
-      if (!cfun->machine->all_noreorder_p)
+      if (TARGET_MIPS16)
+       {
+         /* This is a fixed-form sequence.  The position of the
+            first two instructions is important because of the
+            way _gp_disp is defined.  */
+         output_asm_insn ("li\t$2,%%hi(_gp_disp)", 0);
+         output_asm_insn ("addiu\t$3,$pc,%%lo(_gp_disp)", 0);
+         output_asm_insn ("sll\t$2,16", 0);
+         output_asm_insn ("addu\t$2,$3", 0);
+       }
+      /* .cpload must be in a .set noreorder but not a .set nomacro block.  */
+      else if (!cfun->machine->all_noreorder_p)
        output_asm_insn ("%(.cpload\t%^%)", 0);
       else
        output_asm_insn ("%(.cpload\t%^\n\t%<", 0);
@@ -8318,15 +8897,14 @@ mips_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
   mips_output_cplocal ();
 }
 
-/* Do any necessary cleanup after a function to restore stack, frame,
-   and regs.  */
-
-#define RA_MASK BITMASK_HIGH   /* 1 << 31 */
+/* Implement TARGET_OUTPUT_FUNCTION_EPILOGUE.  */
 
 static void
 mips_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
                               HOST_WIDE_INT size ATTRIBUTE_UNUSED)
 {
+  const char *fnname;
+
   /* Reinstate the normal $gp.  */
   SET_REGNO (pic_offset_table_rtx, GLOBAL_POINTER_REGNUM);
   mips_output_cplocal ();
@@ -8339,18 +8917,11 @@ mips_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
       set_noreorder = set_nomacro = 0;
     }
 
-  if (!FUNCTION_NAME_ALREADY_DECLARED && !flag_inhibit_size_directive)
-    {
-      const char *fnname;
-
-      /* 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);
-    }
+  /* 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);
+  mips_end_function_definition (fnname);
 }
 \f
 /* Save register REG to MEM.  Make the instruction frame-related.  */
@@ -8367,8 +8938,10 @@ mips_save_reg (rtx reg, rtx mem)
       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));
+      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
@@ -8377,7 +8950,7 @@ mips_save_reg (rtx reg, rtx mem)
          && REGNO (reg) != GP_REG_FIRST + 31
          && !M16_REG_P (REGNO (reg)))
        {
-         /* Save a non-mips16 register by moving it through a temporary.
+         /* 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);
@@ -8400,8 +8973,9 @@ static GTY(()) rtx mips_gnu_local_gp;
 static void
 mips_emit_loadgp (void)
 {
-  rtx addr, offset, incoming_address, base, index;
+  rtx addr, offset, incoming_address, base, index, pic_reg;
 
+  pic_reg = TARGET_MIPS16 ? MIPS16_PIC_TEMP : pic_offset_table_rtx;
   switch (mips_current_loadgp_style ())
     {
     case LOADGP_ABSOLUTE:
@@ -8410,36 +8984,52 @@ mips_emit_loadgp (void)
          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_loadgp_absolute (mips_gnu_local_gp));
+      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;
+
+    case LOADGP_OLDABI:
+      /* Added by mips_output_function_prologue.  */
       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 ());
+      emit_insn (Pmode == SImode
+                ? gen_loadgp_newabi_si (pic_reg, offset, incoming_address)
+                : gen_loadgp_newabi_di (pic_reg, offset, incoming_address));
       break;
 
     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 ());
+      emit_insn (Pmode == SImode
+                ? gen_loadgp_rtp_si (pic_reg, base, index)
+                : gen_loadgp_rtp_di (pic_reg, base, index));
       break;
 
     default:
-      break;
+      return;
     }
+
+  if (TARGET_MIPS16)
+    emit_insn (gen_copygp_mips16 (pic_offset_table_rtx, pic_reg));
+
+  /* Emit a blockage if there are implicit uses of the GP register.
+     This includes profiled functions, because FUNCTION_PROFILE uses
+     a jal macro.  */
+  if (!TARGET_EXPLICIT_RELOCS || crtl->profile)
+    emit_insn (gen_loadgp_blockage ());
 }
 
-/* Expand the prologue into a bunch of separate insns.  */
+/* Expand the "prologue" pattern.  */
 
 void
 mips_expand_prologue (void)
 {
+  const struct mips_frame_info *frame;
   HOST_WIDE_INT size;
   unsigned int nargs;
   rtx insn;
@@ -8447,17 +9037,17 @@ mips_expand_prologue (void)
   if (cfun->machine->global_pointer > 0)
     SET_REGNO (pic_offset_table_rtx, cfun->machine->global_pointer);
 
-  size = compute_frame_size (get_frame_size ());
+  frame = &cfun->machine->frame;
+  size = frame->total_size;
 
   /* 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)
+  if ((frame->mask | frame->fmask) != 0)
     {
       HOST_WIDE_INT step1;
 
       step1 = MIN (size, MIPS_MAX_FIRST_STACK_STEP);
-
       if (GENERATE_MIPS16E_SAVE_RESTORE)
        {
          HOST_WIDE_INT offset;
@@ -8467,7 +9057,7 @@ mips_expand_prologue (void)
          nargs = mips16e_collect_argument_saves ();
 
          /* Build the save instruction.  */
-         mask = cfun->machine->frame.mask;
+         mask = frame->mask;
          insn = mips16e_build_save_restore (false, &mask, &offset,
                                             nargs, step1);
          RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
@@ -8477,8 +9067,9 @@ mips_expand_prologue (void)
          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);
+               offset -= UNITS_PER_WORD;
+               mips_save_restore_reg (word_mode, regno,
+                                      offset, mips_save_reg);
              }
        }
       else
@@ -8532,7 +9123,7 @@ mips_expand_prologue (void)
     {
       HOST_WIDE_INT offset;
 
-      offset = cfun->machine->frame.hard_frame_pointer_offset;
+      offset = frame->hard_frame_pointer_offset;
       if (offset == 0)
        {
          insn = mips_emit_move (hard_frame_pointer_rtx, stack_pointer_rtx);
@@ -8559,14 +9150,23 @@ mips_expand_prologue (void)
 
   mips_emit_loadgp ();
 
-  /* 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)));
+  /* Initialize the $gp save slot.  */
+  if (frame->cprestore_size > 0
+      && cfun->machine->global_pointer != 0)
+    {
+      if (TARGET_MIPS16)
+       mips_emit_move (mips_cprestore_slot (MIPS_PROLOGUE_TEMP (Pmode)),
+                       MIPS16_PIC_TEMP);
+      else if (TARGET_ABICALLS_PIC2)
+       emit_insn (gen_cprestore (GEN_INT (frame->args_size)));
+      else
+       emit_move_insn (mips_cprestore_slot (MIPS_PROLOGUE_TEMP (Pmode)),
+                       pic_offset_table_rtx);
+    }
 
   /* If we are profiling, make sure no instructions are scheduled before
      the call to mcount.  */
-
-  if (current_function_profile)
+  if (crtl->profile)
     emit_insn (gen_blockage ());
 }
 \f
@@ -8575,10 +9175,10 @@ mips_expand_prologue (void)
 static void
 mips_restore_reg (rtx reg, rtx mem)
 {
-  /* There's no mips16 instruction to load $31 directly.  Load into
+  /* 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);
+    reg = gen_rtx_REG (GET_MODE (reg), GP_REG_FIRST + 7);
 
   if (TARGET_MIPS16 && !M16_REG_P (REGNO (reg)))
     {
@@ -8590,14 +9190,31 @@ mips_restore_reg (rtx reg, rtx mem)
     mips_emit_move (reg, mem);
 }
 
+/* Emit any instructions needed before a return.  */
+
+void
+mips_expand_before_return (void)
+{
+  /* When using a call-clobbered gp, we start out with unified call
+     insns that include instructions to restore the gp.  We then split
+     these unified calls after reload.  These split calls explicitly
+     clobber gp, so there is no need to define
+     PIC_OFFSET_TABLE_REG_CALL_CLOBBERED.
+
+     For consistency, we should also insert an explicit clobber of $28
+     before return insns, so that the post-reload optimizers know that
+     the register is not live on exit.  */
+  if (TARGET_CALL_CLOBBERED_GP)
+    emit_clobber (pic_offset_table_rtx);
+}
 
-/* 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.  */
+/* Expand an "epilogue" or "sibcall_epilogue" pattern; SIBCALL_P
+   says which.  */
 
 void
-mips_expand_epilogue (int sibcall_p)
+mips_expand_epilogue (bool sibcall_p)
 {
+  const struct mips_frame_info *frame;
   HOST_WIDE_INT step1, step2;
   rtx base, target;
 
@@ -8607,39 +9224,18 @@ mips_expand_epilogue (int sibcall_p)
       return;
     }
 
-  /* In mips16 mode, if the return value should go into a floating-point
+  /* 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);
-
-      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);
-    }
+    mips16_copy_fpr_return_value ();
 
   /* 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.
 
      Start off by assuming that no registers need to be restored.  */
-  step1 = cfun->machine->frame.total_size;
+  frame = &cfun->machine->frame;
+  step1 = frame->total_size;
   step2 = 0;
 
   /* Work out which register holds the frame address.  */
@@ -8648,12 +9244,12 @@ mips_expand_epilogue (int sibcall_p)
   else
     {
       base = hard_frame_pointer_rtx;
-      step1 -= cfun->machine->frame.hard_frame_pointer_offset;
+      step1 -= frame->hard_frame_pointer_offset;
     }
 
   /* 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)
+  if ((frame->mask | frame->fmask) != 0)
     {
       step2 = MIN (step1, MIPS_MAX_FIRST_STACK_STEP);
       step1 -= step2;
@@ -8690,22 +9286,22 @@ mips_expand_epilogue (int sibcall_p)
   if (TARGET_CALL_SAVED_GP && !TARGET_EXPLICIT_RELOCS)
     emit_insn (gen_blockage ());
 
-  if (GENERATE_MIPS16E_SAVE_RESTORE && cfun->machine->frame.mask != 0)
+  if (GENERATE_MIPS16E_SAVE_RESTORE && frame->mask != 0)
     {
       unsigned int regno, mask;
       HOST_WIDE_INT offset;
       rtx restore;
 
       /* Generate the restore instruction.  */
-      mask = cfun->machine->frame.mask;
+      mask = frame->mask;
       restore = mips16e_build_save_restore (true, &mask, &offset, 0, step2);
 
       /* 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);
+           offset -= UNITS_PER_WORD;
+           mips_save_restore_reg (word_mode, regno, offset, mips_restore_reg);
          }
 
       /* Restore the remaining registers and deallocate the final bit
@@ -8715,8 +9311,7 @@ mips_expand_epilogue (int sibcall_p)
   else
     {
       /* Restore the registers.  */
-      mips_for_each_saved_reg (cfun->machine->frame.total_size - step2,
-                              mips_restore_reg);
+      mips_for_each_saved_reg (frame->total_size - step2, mips_restore_reg);
 
       /* Deallocate the final bit of the frame.  */
       if (step2 > 0)
@@ -8726,8 +9321,8 @@ mips_expand_epilogue (int sibcall_p)
     }
 
   /* Add in the __builtin_eh_return stack adjustment.  We need to
-     use a temporary in mips16 code.  */
-  if (current_function_calls_eh_return)
+     use a temporary in MIPS16 code.  */
+  if (crtl->calls_eh_return)
     {
       if (TARGET_MIPS16)
        {
@@ -8745,16 +9340,18 @@ mips_expand_epilogue (int sibcall_p)
 
   if (!sibcall_p)
     {
+      unsigned int regno;
+
       /* 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)));
+         && BITSET_P (frame->mask, 31))
+       regno = GP_REG_FIRST + 7;
       else
-       emit_jump_insn (gen_return_internal (gen_rtx_REG (Pmode,
-                                                         GP_REG_FIRST + 31)));
+       regno = GP_REG_FIRST + 31;
+      mips_expand_before_return ();
+      emit_jump_insn (gen_return_internal (gen_rtx_REG (Pmode, regno)));
     }
 }
 \f
@@ -8762,76 +9359,175 @@ mips_expand_epilogue (int sibcall_p)
    This allows the optimizer to omit jumps to jumps if no stack
    was created.  */
 
-int
+bool
 mips_can_use_return_insn (void)
 {
-  if (! reload_completed)
-    return 0;
+  if (!reload_completed)
+    return false;
 
-  if (df_regs_ever_live_p (31) || current_function_profile)
-    return 0;
+  if (crtl->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
+  /* 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->frame.initialized)
-    return cfun->machine->frame.total_size == 0;
+    return false;
 
-  return compute_frame_size (get_frame_size ()) == 0;
+  return cfun->machine->frame.total_size == 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.  */
+/* 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 mclass;
+
+  if (mode == CCV2mode)
+    return (ISA_HAS_8CC
+           && ST_REG_P (regno)
+           && (regno - ST_REG_FIRST) % 2 == 0);
+
+  if (mode == CCV4mode)
+    return (ISA_HAS_8CC
+           && ST_REG_P (regno)
+           && (regno - ST_REG_FIRST) % 4 == 0);
+
+  if (mode == CCmode)
+    {
+      if (!ISA_HAS_8CC)
+       return regno == FPSW_REGNUM;
+
+      return (ST_REG_P (regno)
+             || GP_REG_P (regno)
+             || FP_REG_P (regno));
+    }
+
+  size = GET_MODE_SIZE (mode);
+  mclass = GET_MODE_CLASS (mode);
+
+  if (GP_REG_P (regno))
+    return ((regno - GP_REG_FIRST) & 1) == 0 || size <= UNITS_PER_WORD;
+
+  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;
+
+      /* Allow 64-bit vector modes for Loongson-2E/2F.  */
+      if (TARGET_LOONGSON_VECTORS
+         && (mode == V2SImode
+             || mode == V4HImode
+             || mode == V8QImode
+             || mode == DImode))
+       return true;
+
+      if (mclass == MODE_FLOAT
+         || mclass == MODE_COMPLEX_FLOAT
+         || mclass == MODE_VECTOR_FLOAT)
+       return 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.  There's no point allowing sizes smaller than a word,
+        because the FPU has no appropriate load/store instructions.  */
+      if (mclass == MODE_INT)
+       return size >= MIN_UNITS_PER_WORD && size <= UNITS_PER_FPREG;
+    }
+
+  if (ACC_REG_P (regno)
+      && (INTEGRAL_MODE_P (mode) || ALL_FIXED_POINT_MODE_P (mode)))
+    {
+      if (MD_REG_P (regno))
+       {
+         /* After a multiplication or division, clobbering HI makes
+            the value of LO unpredictable, and vice versa.  This means
+            that, for all interesting cases, HI and LO are effectively
+            a single register.
+
+            We model this by requiring that any value that uses HI
+            also uses LO.  */
+         if (size <= UNITS_PER_WORD * 2)
+           return regno == (size <= UNITS_PER_WORD ? LO_REGNUM : MD_REG_FIRST);
+       }
+      else
+       {
+         /* DSP accumulators do not have the same restrictions as
+            HI and LO, so we can treat them as normal doubleword
+            registers.  */
+         if (size <= UNITS_PER_WORD)
+           return true;
+
+         if (size <= UNITS_PER_WORD * 2
+             && ((regno - DSP_ACC_REG_FIRST) & 1) == 0)
+           return true;
+       }
+    }
+
+  if (ALL_COP_REG_P (regno))
+    return mclass == MODE_INT && size <= UNITS_PER_WORD;
+
+  if (regno == GOT_VERSION_REGNUM)
+    return mode == SImode;
+
+  return false;
+}
+
+/* Implement HARD_REGNO_NREGS.  */
 
 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);
-}
-
-/* Implement CLASS_MAX_NREGS.
+    /* 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;
 
-   - UNITS_PER_FPREG controls the number of registers needed by FP_REGS.
+  if (FP_REG_P (regno))
+    return (GET_MODE_SIZE (mode) + UNITS_PER_FPREG - 1) / UNITS_PER_FPREG;
 
-   - ST_REGS are always hold CCmode values, and CCmode values are
-     considered to be 4 bytes wide.
+  /* All other registers are word-sized.  */
+  return (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
+}
 
-   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 CLASS_MAX_NREGS, taking the maximum of the cases
+   in mips_hard_regno_nregs.  */
 
 int
-mips_class_max_nregs (enum reg_class class ATTRIBUTE_UNUSED,
-                     enum machine_mode mode)
+mips_class_max_nregs (enum reg_class rclass, enum machine_mode mode)
 {
-  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;
+  int size;
+  HARD_REG_SET left;
+
+  size = 0x8000;
+  COPY_HARD_REG_SET (left, reg_class_contents[(int) rclass]);
+  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]);
+    }
+  if (hard_reg_set_intersect_p (left, reg_class_contents[(int) FP_REGS]))
+    {
+      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;
 }
 
-/* Return true if registers of class CLASS cannot change from mode FROM
-   to mode TO.  */
+/* 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)
+                              enum reg_class rclass)
 {
   /* There are several problems with changing the modes of values
      in floating-point registers:
@@ -8853,14 +9549,8 @@ mips_cannot_change_mode_class (enum machine_mode from ATTRIBUTE_UNUSED,
      - 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 only allow changes between 4-byte and smaller integer
-     values, all of which have the "W" format as far as the FPU is
-     concerned.  */
-  return (reg_classes_intersect_p (FP_REGS, class)
-         && (GET_MODE_CLASS (from) != MODE_INT
-             || GET_MODE_CLASS (to) != MODE_INT
-             || GET_MODE_SIZE (from) > 4
-             || GET_MODE_SIZE (to) > 4));
+     We therefore disallow all mode changes involving FPRs.  */
+  return reg_classes_intersect_p (FP_REGS, rclass);
 }
 
 /* Return true if moves in mode MODE can use the FPU's mov.fmt instruction.  */
@@ -8884,57 +9574,40 @@ mips_mode_ok_for_mov_fmt_p (enum machine_mode mode)
     }
 }
 
+/* Implement MODES_TIEABLE_P.  */
+
+bool
+mips_modes_tieable_p (enum machine_mode mode1, enum machine_mode mode2)
+{
+  /* 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.  */
 
 enum reg_class
-mips_preferred_reload_class (rtx x, enum reg_class class)
+mips_preferred_reload_class (rtx x, enum reg_class rclass)
 {
-  if (mips_dangerous_for_la25_p (x) && reg_class_subset_p (LEA_REGS, class))
+  if (mips_dangerous_for_la25_p (x) && reg_class_subset_p (LEA_REGS, rclass))
     return LEA_REGS;
 
-  if (reg_class_subset_p (FP_REGS, class)
+  if (reg_class_subset_p (FP_REGS, rclass)
       && mips_mode_ok_for_mov_fmt_p (GET_MODE (x)))
     return FP_REGS;
 
-  if (reg_class_subset_p (GR_REGS, class))
-    class = GR_REGS;
-
-  if (TARGET_MIPS16 && reg_class_subset_p (M16_REGS, class))
-    class = M16_REGS;
-
-  return class;
-}
-
-/* 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.  */
+  if (reg_class_subset_p (GR_REGS, rclass))
+    rclass = GR_REGS;
+
+  if (TARGET_MIPS16 && reg_class_subset_p (M16_REGS, rclass))
+    rclass = M16_REGS;
+
+  return rclass;
+}
+
+/* Implement REGISTER_MOVE_COST.  */
 
 int
 mips_register_move_cost (enum machine_mode mode,
@@ -8942,6 +9615,10 @@ mips_register_move_cost (enum machine_mode mode,
 {
   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))
        {
@@ -8988,32 +9665,32 @@ mips_register_move_cost (enum machine_mode mode,
   return 12;
 }
 
-/* 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.  */
+/* Return the register class required for a secondary register when
+   copying between one of the registers in RCLASS 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, int in_p)
+mips_secondary_reload_class (enum reg_class rclass,
+                            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;
+    return reg_class_subset_p (rclass, LEA_REGS) ? NO_REGS : LEA_REGS;
 
   regno = true_regnum (x);
   if (TARGET_MIPS16)
     {
       /* In MIPS16 mode, every move must involve a member of M16_REGS.  */
-      if (!reg_class_subset_p (class, M16_REGS) && !M16_REG_P (regno))
+      if (!reg_class_subset_p (rclass, 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))
+      if (in_p ? reg_classes_intersect_p (rclass, ACC_REGS) : ACC_REG_P (regno))
        return M16_REGS;
 
       return NO_REGS;
@@ -9021,16 +9698,16 @@ mips_secondary_reload_class (enum reg_class class,
 
   /* 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 (reg_class_subset_p (rclass, ACC_REGS))
     return GP_REG_P (regno) ? NO_REGS : GR_REGS;
   if (ACC_REG_P (regno))
-    return reg_class_subset_p (class, GR_REGS) ? NO_REGS : GR_REGS;
+    return reg_class_subset_p (rclass, 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 (reg_class_subset_p (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 (rclass, ST_REGS))
     {
       if (in_p)
        return FP_REGS;
@@ -9040,10 +9717,10 @@ mips_secondary_reload_class (enum reg_class class,
     {
       if (!in_p)
        return FP_REGS;
-      return reg_class_subset_p (class, GR_REGS) ? NO_REGS : GR_REGS;
+      return reg_class_subset_p (rclass, GR_REGS) ? NO_REGS : GR_REGS;
     }
 
-  if (reg_class_subset_p (class, FP_REGS))
+  if (reg_class_subset_p (rclass, FP_REGS))
     {
       if (MEM_P (x)
          && (GET_MODE_SIZE (mode) == 4 || GET_MODE_SIZE (mode) == 8))
@@ -9069,29 +9746,32 @@ mips_secondary_reload_class (enum reg_class class,
       return GR_REGS;
     }
   if (FP_REG_P (regno))
-    return reg_class_subset_p (class, GR_REGS) ? NO_REGS : GR_REGS;
+    return reg_class_subset_p (rclass, GR_REGS) ? NO_REGS : GR_REGS;
 
   return NO_REGS;
 }
 
-/* SImode values are represented as sign-extended to DImode.  */
+/* Implement TARGET_MODE_REP_EXTENDED.  */
 
 static int
 mips_mode_rep_extended (enum machine_mode mode, enum machine_mode mode_rep)
 {
+  /* 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)
@@ -9111,6 +9791,11 @@ mips_vector_mode_supported_p (enum machine_mode mode)
     case V4UQQmode:
       return TARGET_DSP;
 
+    case V2SImode:
+    case V4HImode:
+    case V8QImode:
+      return TARGET_LOONGSON_VECTORS;
+
     default:
       return false;
     }
@@ -9127,11 +9812,8 @@ mips_scalar_mode_supported_p (enum machine_mode mode)
 
   return default_scalar_mode_supported_p (mode);
 }
-/* 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.  */
+\f
+/* Implement TARGET_INIT_LIBFUNCS.  */
 
 #include "config/gofast.h"
 
@@ -9140,12 +9822,15 @@ mips_init_libfuncs (void)
 {
   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");
     }
 
   if (TARGET_MIPS16 && TARGET_HARD_FLOAT_ABI)
     {
+      /* 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");
@@ -9178,16 +9863,26 @@ mips_init_libfuncs (void)
          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");
+         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 ();
+
+  /* The MIPS16 ISA does not have an encoding for "sync", so we rely
+     on an external non-MIPS16 routine to implement __sync_synchronize.  */
+  if (TARGET_MIPS16)
+    synchronize_libfunc = init_one_libfunc ("__sync_synchronize");
 }
 
 /* Return the length of INSN.  LENGTH is the initial length computed by
@@ -9218,14 +9913,15 @@ mips_adjust_insn_length (rtx insn, int length)
        break;
       }
 
-  /* All MIPS16 instructions are a measly two bytes.  */
+  /* 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;
 
   return length;
 }
 
-
 /* Return an asm sequence to start a noat block and load the address
    of a label into $1.  */
 
@@ -9331,13 +10027,13 @@ mips_output_conditional_branch (rtx insn, rtx *operands,
     }
 
   /* Output NOT_TAKEN.  */
-  (*targetm.asm_out.internal_label) (asm_out_file, "L",
-                                    CODE_LABEL_NUMBER (not_taken));
+  targetm.asm_out.internal_label (asm_out_file, "L",
+                                 CODE_LABEL_NUMBER (not_taken));
   return "";
 }
 
 /* Return the assembly code for INSN, which branches to OPERANDS[1]
-   if some ordered condition is true.  The condition is given by
+   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.  */
@@ -9377,8 +10073,8 @@ mips_output_order_conditional_branch (rtx insn, rtx *operands, bool inverted_p)
   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.
+/* 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.
 
    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
@@ -9499,15 +10195,15 @@ mips_output_division (const char *division, rtx *operands)
   return s;
 }
 \f
-/* Return true if INSN is a multiply-add or multiply-subtract
-   instruction and PREV assigns to the accumulator operand.  */
+/* Return true if IN_INSN is a multiply-add or multiply-subtract
+   instruction and if OUT_INSN assigns to the accumulator operand.  */
 
 bool
-mips_linked_madd_p (rtx prev, rtx insn)
+mips_linked_madd_p (rtx out_insn, rtx in_insn)
 {
   rtx x;
 
-  x = single_set (insn);
+  x = single_set (in_insn);
   if (x == 0)
     return false;
 
@@ -9515,31 +10211,67 @@ mips_linked_madd_p (rtx prev, rtx insn)
 
   if (GET_CODE (x) == PLUS
       && GET_CODE (XEXP (x, 0)) == MULT
-      && reg_set_p (XEXP (x, 1), prev))
+      && reg_set_p (XEXP (x, 1), out_insn))
     return true;
 
   if (GET_CODE (x) == MINUS
       && GET_CODE (XEXP (x, 1)) == MULT
-      && reg_set_p (XEXP (x, 0), prev))
+      && reg_set_p (XEXP (x, 0), out_insn))
     return true;
 
   return false;
 }
 
-/* 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.  */
+/* 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.  */
 
-int
+bool
 mips_store_data_bypass_p (rtx out_insn, rtx in_insn)
 {
   if (GET_CODE (PATTERN (in_insn)) == UNSPEC_VOLATILE)
     return false;
 
-  return ! store_data_bypass_p (out_insn, in_insn);
+  return !store_data_bypass_p (out_insn, in_insn);
 }
 \f
+
+/* Variables and flags used in scheduler hooks when tuning for
+   Loongson 2E/2F.  */
+static struct
+{
+  /* Variables to support Loongson 2E/2F round-robin [F]ALU1/2 dispatch
+     strategy.  */
+
+  /* If true, then next ALU1/2 instruction will go to ALU1.  */
+  bool alu1_turn_p;
+
+  /* If true, then next FALU1/2 unstruction will go to FALU1.  */
+  bool falu1_turn_p;
+
+  /* Codes to query if [f]alu{1,2}_core units are subscribed or not.  */
+  int alu1_core_unit_code;
+  int alu2_core_unit_code;
+  int falu1_core_unit_code;
+  int falu2_core_unit_code;
+
+  /* True if current cycle has a multi instruction.
+     This flag is used in mips_ls2_dfa_post_advance_cycle.  */
+  bool cycle_has_multi_p;
+
+  /* Instructions to subscribe ls2_[f]alu{1,2}_turn_enabled units.
+     These are used in mips_ls2_dfa_post_advance_cycle to initialize
+     DFA state.
+     E.g., when alu1_turn_enabled_insn is issued it makes next ALU1/2
+     instruction to go ALU1.  */
+  rtx alu1_turn_enabled_insn;
+  rtx alu2_turn_enabled_insn;
+  rtx falu1_turn_enabled_insn;
+  rtx falu2_turn_enabled_insn;
+} mips_ls2;
+
 /* 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.  */
@@ -9569,8 +10301,9 @@ mips_issue_rate (void)
     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.  */
+        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;
 
     case PROCESSOR_20KC:
@@ -9589,12 +10322,125 @@ mips_issue_rate (void)
         reach the theoretical max of 4.  */
       return 3;
 
+    case PROCESSOR_LOONGSON_2E:
+    case PROCESSOR_LOONGSON_2F:
+      return 4;
+
     default:
       return 1;
     }
 }
 
-/* Implements TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD.  This should
+/* Implement TARGET_SCHED_INIT_DFA_POST_CYCLE_INSN hook for Loongson2.  */
+
+static void
+mips_ls2_init_dfa_post_cycle_insn (void)
+{
+  start_sequence ();
+  emit_insn (gen_ls2_alu1_turn_enabled_insn ());
+  mips_ls2.alu1_turn_enabled_insn = get_insns ();
+  end_sequence ();
+
+  start_sequence ();
+  emit_insn (gen_ls2_alu2_turn_enabled_insn ());
+  mips_ls2.alu2_turn_enabled_insn = get_insns ();
+  end_sequence ();
+
+  start_sequence ();
+  emit_insn (gen_ls2_falu1_turn_enabled_insn ());
+  mips_ls2.falu1_turn_enabled_insn = get_insns ();
+  end_sequence ();
+
+  start_sequence ();
+  emit_insn (gen_ls2_falu2_turn_enabled_insn ());
+  mips_ls2.falu2_turn_enabled_insn = get_insns ();
+  end_sequence ();
+
+  mips_ls2.alu1_core_unit_code = get_cpu_unit_code ("ls2_alu1_core");
+  mips_ls2.alu2_core_unit_code = get_cpu_unit_code ("ls2_alu2_core");
+  mips_ls2.falu1_core_unit_code = get_cpu_unit_code ("ls2_falu1_core");
+  mips_ls2.falu2_core_unit_code = get_cpu_unit_code ("ls2_falu2_core");
+}
+
+/* Implement TARGET_SCHED_INIT_DFA_POST_CYCLE_INSN hook.
+   Init data used in mips_dfa_post_advance_cycle.  */
+
+static void
+mips_init_dfa_post_cycle_insn (void)
+{
+  if (TUNE_LOONGSON_2EF)
+    mips_ls2_init_dfa_post_cycle_insn ();
+}
+
+/* Initialize STATE when scheduling for Loongson 2E/2F.
+   Support round-robin dispatch scheme by enabling only one of
+   ALU1/ALU2 and one of FALU1/FALU2 units for ALU1/2 and FALU1/2 instructions
+   respectively.  */
+
+static void
+mips_ls2_dfa_post_advance_cycle (state_t state)
+{
+  if (cpu_unit_reservation_p (state, mips_ls2.alu1_core_unit_code))
+    {
+      /* Though there are no non-pipelined ALU1 insns,
+        we can get an instruction of type 'multi' before reload.  */
+      gcc_assert (mips_ls2.cycle_has_multi_p);
+      mips_ls2.alu1_turn_p = false;
+    }
+
+  mips_ls2.cycle_has_multi_p = false;
+
+  if (cpu_unit_reservation_p (state, mips_ls2.alu2_core_unit_code))
+    /* We have a non-pipelined alu instruction in the core,
+       adjust round-robin counter.  */
+    mips_ls2.alu1_turn_p = true;
+
+  if (mips_ls2.alu1_turn_p)
+    {
+      if (state_transition (state, mips_ls2.alu1_turn_enabled_insn) >= 0)
+       gcc_unreachable ();
+    }
+  else
+    {
+      if (state_transition (state, mips_ls2.alu2_turn_enabled_insn) >= 0)
+       gcc_unreachable ();
+    }
+
+  if (cpu_unit_reservation_p (state, mips_ls2.falu1_core_unit_code))
+    {
+      /* There are no non-pipelined FALU1 insns.  */
+      gcc_unreachable ();
+      mips_ls2.falu1_turn_p = false;
+    }
+
+  if (cpu_unit_reservation_p (state, mips_ls2.falu2_core_unit_code))
+    /* We have a non-pipelined falu instruction in the core,
+       adjust round-robin counter.  */
+    mips_ls2.falu1_turn_p = true;
+
+  if (mips_ls2.falu1_turn_p)
+    {
+      if (state_transition (state, mips_ls2.falu1_turn_enabled_insn) >= 0)
+       gcc_unreachable ();
+    }
+  else
+    {
+      if (state_transition (state, mips_ls2.falu2_turn_enabled_insn) >= 0)
+       gcc_unreachable ();
+    }
+}
+
+/* Implement TARGET_SCHED_DFA_POST_ADVANCE_CYCLE.
+   This hook is being called at the start of each cycle.  */
+
+static void
+mips_dfa_post_advance_cycle (void)
+{
+  if (TUNE_LOONGSON_2EF)
+    mips_ls2_dfa_post_advance_cycle (curr_state);
+}
+
+/* Implement TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD.  This should
    be as wide as the scheduling freedom in the DFA.  */
 
 static int
@@ -9604,6 +10450,9 @@ mips_multipass_dfa_lookahead (void)
   if (TUNE_SB1)
     return 4;
 
+  if (TUNE_LOONGSON_2EF)
+    return 4;
+
   return 0;
 }
 \f
@@ -9634,6 +10483,7 @@ mips_maybe_swap_ready (rtx *ready, int pos1, int pos2, int limit)
       && INSN_PRIORITY (ready[pos1]) + limit >= INSN_PRIORITY (ready[pos2]))
     {
       rtx temp;
+
       temp = ready[pos1];
       ready[pos1] = ready[pos2];
       ready[pos2] = temp;
@@ -9642,7 +10492,6 @@ mips_maybe_swap_ready (rtx *ready, int pos1, int pos2, int limit)
 \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;
 
 /* A TUNE_MACC_CHAINS helper function.  Record that instruction INSN has
@@ -9682,7 +10531,6 @@ mips_macc_chains_reorder (rtx *ready, int nready)
 }
 \f
 /* The last instruction to be scheduled.  */
-
 static rtx vr4130_last_insn;
 
 /* A note_stores callback used by vr4130_true_reg_dependence_p.  DATA
@@ -9690,9 +10538,12 @@ static rtx vr4130_last_insn;
    if the instruction uses the value of register X.  */
 
 static void
-vr4130_true_reg_dependence_p_1 (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
+vr4130_true_reg_dependence_p_1 (rtx x, const_rtx pat ATTRIBUTE_UNUSED,
+                               void *data)
 {
-  rtx *insn_ptr = data;
+  rtx *insn_ptr;
+
+  insn_ptr = (rtx *) data;
   if (REG_P (x)
       && *insn_ptr != 0
       && reg_referenced_p (x, PATTERN (*insn_ptr)))
@@ -9751,10 +10602,10 @@ vr4130_swap_insns_p (rtx insn1, rtx insn2)
        {
          /* 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;
+         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
@@ -9781,7 +10632,6 @@ vr4130_reorder (rtx *ready, int nready)
 }
 \f
 /* Record whether last 74k AGEN instruction was a load or store.  */
-
 static enum attr_type mips_last_74k_agen_insn = TYPE_UNKNOWN;
 
 /* Initialize mips_last_74k_agen_insn from INSN.  A null argument
@@ -9792,7 +10642,7 @@ mips_74k_agen_init (rtx insn)
 {
   if (!insn || !NONJUMP_INSN_P (insn))
     mips_last_74k_agen_insn = TYPE_UNKNOWN;
-  else if (USEFUL_INSN_P (insn))
+  else
     {
       enum attr_type type = get_attr_type (insn);
       if (type == TYPE_LOAD || type == TYPE_STORE)
@@ -9863,9 +10713,15 @@ mips_sched_init (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
   mips_macc_chains_last_hilo = 0;
   vr4130_last_insn = 0;
   mips_74k_agen_init (NULL_RTX);
+
+  /* When scheduling for Loongson2, branch instructions go to ALU1,
+     therefore basic block is most likely to start with round-robin counter
+     pointed to ALU2.  */
+  mips_ls2.alu1_turn_p = false;
+  mips_ls2.falu1_turn_p = true;
 }
 
-/* Implement TARGET_SCHED_REORDER and TARG_SCHED_REORDER2.  */
+/* Implement TARGET_SCHED_REORDER and TARGET_SCHED_REORDER2.  */
 
 static int
 mips_sched_reorder (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
@@ -9875,43 +10731,80 @@ mips_sched_reorder (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
       && 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 ();
 }
 
+/* Update round-robin counters for ALU1/2 and FALU1/2.  */
+
+static void
+mips_ls2_variable_issue (rtx insn)
+{
+  if (mips_ls2.alu1_turn_p)
+    {
+      if (cpu_unit_reservation_p (curr_state, mips_ls2.alu1_core_unit_code))
+       mips_ls2.alu1_turn_p = false;
+    }
+  else
+    {
+      if (cpu_unit_reservation_p (curr_state, mips_ls2.alu2_core_unit_code))
+       mips_ls2.alu1_turn_p = true;
+    }
+
+  if (mips_ls2.falu1_turn_p)
+    {
+      if (cpu_unit_reservation_p (curr_state, mips_ls2.falu1_core_unit_code))
+       mips_ls2.falu1_turn_p = false;
+    }
+  else
+    {
+      if (cpu_unit_reservation_p (curr_state, mips_ls2.falu2_core_unit_code))
+       mips_ls2.falu1_turn_p = true;
+    }
+
+  if (recog_memoized (insn) >= 0)
+    mips_ls2.cycle_has_multi_p |= (get_attr_type (insn) == TYPE_MULTI);
+}
+
 /* Implement TARGET_SCHED_VARIABLE_ISSUE.  */
 
 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)))
+  /* Ignore USEs and CLOBBERs; don't count them against the issue rate.  */
+  if (USEFUL_INSN_P (insn))
     {
-    case USE:
-    case CLOBBER:
-      /* Don't count USEs and CLOBBERs against the issue rate.  */
-      break;
-
-    default:
       more--;
       if (!reload_completed && TUNE_MACC_CHAINS)
        mips_macc_chains_record (insn);
       vr4130_last_insn = insn;
-      break;
+      if (TUNE_74K)
+       mips_74k_agen_init (insn);
+      else if (TUNE_LOONGSON_2EF)
+       mips_ls2_variable_issue (insn);
     }
+
+  /* Instructions of type 'multi' should all be split before
+     the second scheduling pass.  */
+  gcc_assert (!reload_completed
+             || recog_memoized (insn) < 0
+             || get_attr_type (insn) != TYPE_MULTI);
+
   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.  */
+   return the first operand of the associated PREF or PREFX insn.  */
 
 rtx
 mips_prefetch_cookie (rtx write, rtx locality)
@@ -9928,10 +10821,25 @@ mips_prefetch_cookie (rtx write, rtx locality)
   return GEN_INT (INTVAL (write) + 6);
 }
 \f
-/* MIPS builtin function support. */
-
-struct builtin_description
-{
+/* Flags that indicate when a built-in function is available.
+
+   BUILTIN_AVAIL_NON_MIPS16
+       The function is available on the current target, but only
+       in non-MIPS16 mode.  */
+#define BUILTIN_AVAIL_NON_MIPS16 1
+
+/* Declare an availability predicate for built-in functions that
+   require non-MIPS16 mode and also require COND to be true.
+   NAME is the main part of the predicate's name.  */
+#define AVAIL_NON_MIPS16(NAME, COND)                                   \
+ static unsigned int                                                   \
+ mips_builtin_avail_##NAME (void)                                      \
+ {                                                                     \
+   return (COND) ? BUILTIN_AVAIL_NON_MIPS16 : 0;                       \
+ }
+
+/* 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;
@@ -9939,7 +10847,7 @@ struct builtin_description
   /* The floating-point comparison code to use with ICODE, if any.  */
   enum mips_fp_condition cond;
 
-  /* The name of the builtin function.  */
+  /* The name of the built-in function.  */
   const char *name;
 
   /* Specifies how the function should be expanded.  */
@@ -9948,316 +10856,449 @@ struct builtin_description
   /* The function's prototype.  */
   enum mips_function_type function_type;
 
-  /* The target flags required for this function.  */
-  int target_flags;
+  /* Whether the function is available.  */
+  unsigned int (*avail) (void);
 };
 
-/* 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 }
-
-/* 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 }
+AVAIL_NON_MIPS16 (paired_single, TARGET_PAIRED_SINGLE_FLOAT)
+AVAIL_NON_MIPS16 (sb1_paired_single, TARGET_SB1 && TARGET_PAIRED_SINGLE_FLOAT)
+AVAIL_NON_MIPS16 (mips3d, TARGET_MIPS3D)
+AVAIL_NON_MIPS16 (dsp, TARGET_DSP)
+AVAIL_NON_MIPS16 (dspr2, TARGET_DSPR2)
+AVAIL_NON_MIPS16 (dsp_32, !TARGET_64BIT && TARGET_DSP)
+AVAIL_NON_MIPS16 (dspr2_32, !TARGET_64BIT && TARGET_DSPR2)
+AVAIL_NON_MIPS16 (loongson, TARGET_LOONGSON_VECTORS)
+
+/* Construct a mips_builtin_description from the given arguments.
+
+   INSN is the name of the associated instruction pattern, without the
+   leading CODE_FOR_mips_.
+
+   CODE is the floating-point condition code associated with the
+   function.  It can be 'f' if the field is not applicable.
+
+   NAME is the name of the function itself, without the leading
+   "__builtin_mips_".
+
+   BUILTIN_TYPE and FUNCTION_TYPE are mips_builtin_description fields.
+
+   AVAIL is the name of the availability predicate, without the leading
+   mips_builtin_avail_.  */
+#define MIPS_BUILTIN(INSN, COND, NAME, BUILTIN_TYPE,                   \
+                    FUNCTION_TYPE, AVAIL)                              \
+  { CODE_FOR_mips_ ## INSN, MIPS_FP_COND_ ## COND,                     \
+    "__builtin_mips_" NAME, BUILTIN_TYPE, FUNCTION_TYPE,               \
+    mips_builtin_avail_ ## AVAIL }
+
+/* Define __builtin_mips_<INSN>, which is a MIPS_BUILTIN_DIRECT function
+   mapped to instruction CODE_FOR_mips_<INSN>,  FUNCTION_TYPE and AVAIL
+   are as for MIPS_BUILTIN.  */
+#define DIRECT_BUILTIN(INSN, FUNCTION_TYPE, AVAIL)                     \
+  MIPS_BUILTIN (INSN, f, #INSN, MIPS_BUILTIN_DIRECT, FUNCTION_TYPE, AVAIL)
+
+/* Define __builtin_mips_<INSN>_<COND>_{s,d} functions, both of which
+   are subject to mips_builtin_avail_<AVAIL>.  */
+#define CMP_SCALAR_BUILTINS(INSN, COND, AVAIL)                         \
+  MIPS_BUILTIN (INSN ## _cond_s, COND, #INSN "_" #COND "_s",           \
+               MIPS_BUILTIN_CMP_SINGLE, MIPS_INT_FTYPE_SF_SF, AVAIL),  \
+  MIPS_BUILTIN (INSN ## _cond_d, COND, #INSN "_" #COND "_d",           \
+               MIPS_BUILTIN_CMP_SINGLE, MIPS_INT_FTYPE_DF_DF, AVAIL)
 
 /* 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 }
+   The lower and upper forms are subject to mips_builtin_avail_<AVAIL>
+   while the any and all forms are subject to mips_builtin_avail_mips3d.  */
+#define CMP_PS_BUILTINS(INSN, COND, AVAIL)                             \
+  MIPS_BUILTIN (INSN ## _cond_ps, COND, "any_" #INSN "_" #COND "_ps",  \
+               MIPS_BUILTIN_CMP_ANY, MIPS_INT_FTYPE_V2SF_V2SF,         \
+               mips3d),                                                \
+  MIPS_BUILTIN (INSN ## _cond_ps, COND, "all_" #INSN "_" #COND "_ps",  \
+               MIPS_BUILTIN_CMP_ALL, MIPS_INT_FTYPE_V2SF_V2SF,         \
+               mips3d),                                                \
+  MIPS_BUILTIN (INSN ## _cond_ps, COND, "lower_" #INSN "_" #COND "_ps",        \
+               MIPS_BUILTIN_CMP_LOWER, MIPS_INT_FTYPE_V2SF_V2SF,       \
+               AVAIL),                                                 \
+  MIPS_BUILTIN (INSN ## _cond_ps, COND, "upper_" #INSN "_" #COND "_ps",        \
+               MIPS_BUILTIN_CMP_UPPER, MIPS_INT_FTYPE_V2SF_V2SF,       \
+               AVAIL)
 
 /* Define __builtin_mips_{any,all}_<INSN>_<COND>_4s.  The functions
-   require MASK_MIPS3D.  */
+   are subject to mips_builtin_avail_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 }
+  MIPS_BUILTIN (INSN ## _cond_4s, COND, "any_" #INSN "_" #COND "_4s",  \
+               MIPS_BUILTIN_CMP_ANY,                                   \
+               MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF, mips3d),            \
+  MIPS_BUILTIN (INSN ## _cond_4s, COND, "all_" #INSN "_" #COND "_4s",  \
+               MIPS_BUILTIN_CMP_ALL,                                   \
+               MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF, 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 builtins related to c.cond.fmt condition COND.  */
+   instruction requires mips_builtin_avail_<AVAIL>.  */
+#define MOVTF_BUILTINS(INSN, COND, AVAIL)                              \
+  MIPS_BUILTIN (INSN ## _cond_ps, COND, "movt_" #INSN "_" #COND "_ps", \
+               MIPS_BUILTIN_MOVT, MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF, \
+               AVAIL),                                                 \
+  MIPS_BUILTIN (INSN ## _cond_ps, COND, "movf_" #INSN "_" #COND "_ps", \
+               MIPS_BUILTIN_MOVF, MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF, \
+               AVAIL)
+
+/* 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),                           \
+  MOVTF_BUILTINS (c, COND, paired_single),                             \
+  MOVTF_BUILTINS (cabs, COND, mips3d),                                 \
+  CMP_SCALAR_BUILTINS (cabs, COND, mips3d),                            \
+  CMP_PS_BUILTINS (c, COND, paired_single),                            \
+  CMP_PS_BUILTINS (cabs, COND, mips3d),                                        \
   CMP_4S_BUILTINS (c, COND),                                           \
   CMP_4S_BUILTINS (cabs, COND)
 
-static const struct builtin_description mips_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)
-};
+/* Define __builtin_mips_<INSN>, which is a MIPS_BUILTIN_DIRECT_NO_TARGET
+   function mapped to instruction CODE_FOR_mips_<INSN>,  FUNCTION_TYPE
+   and AVAIL are as for MIPS_BUILTIN.  */
+#define DIRECT_NO_TARGET_BUILTIN(INSN, FUNCTION_TYPE, AVAIL)           \
+  MIPS_BUILTIN (INSN, f, #INSN,        MIPS_BUILTIN_DIRECT_NO_TARGET,          \
+               FUNCTION_TYPE, AVAIL)
 
-/* Builtin functions for the SB-1 processor.  */
+/* Define __builtin_mips_bposge<VALUE>.  <VALUE> is 32 for the MIPS32 DSP
+   branch instruction.  AVAIL is as for MIPS_BUILTIN.  */
+#define BPOSGE_BUILTIN(VALUE, AVAIL)                                   \
+  MIPS_BUILTIN (bposge, f, "bposge" #VALUE,                            \
+               MIPS_BUILTIN_BPOSGE ## VALUE, MIPS_SI_FTYPE_VOID, AVAIL)
+
+/* Define a Loongson MIPS_BUILTIN_DIRECT function __builtin_loongson_<FN_NAME>
+   for instruction CODE_FOR_loongson_<INSN>.  FUNCTION_TYPE is a
+   builtin_description field.  */
+#define LOONGSON_BUILTIN_ALIAS(INSN, FN_NAME, FUNCTION_TYPE)           \
+  { CODE_FOR_loongson_ ## INSN, 0, "__builtin_loongson_" #FN_NAME,     \
+    MIPS_BUILTIN_DIRECT, FUNCTION_TYPE, mips_builtin_avail_loongson }
+
+/* Define a Loongson MIPS_BUILTIN_DIRECT function __builtin_loongson_<INSN>
+   for instruction CODE_FOR_loongson_<INSN>.  FUNCTION_TYPE is a
+   builtin_description field.  */
+#define LOONGSON_BUILTIN(INSN, FUNCTION_TYPE)                          \
+  LOONGSON_BUILTIN_ALIAS (INSN, INSN, FUNCTION_TYPE)
+
+/* Like LOONGSON_BUILTIN, but add _<SUFFIX> to the end of the function name.
+   We use functions of this form when the same insn can be usefully applied
+   to more than one datatype.  */
+#define LOONGSON_BUILTIN_SUFFIX(INSN, SUFFIX, FUNCTION_TYPE)           \
+  LOONGSON_BUILTIN_ALIAS (INSN, INSN ## _ ## SUFFIX, FUNCTION_TYPE)
 
 #define CODE_FOR_mips_sqrt_ps CODE_FOR_sqrtv2sf2
-
-static const struct builtin_description sb1_bdesc[] =
-{
-  DIRECT_BUILTIN (sqrt_ps, MIPS_V2SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT)
-};
-
-/* Builtin functions for 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
-   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 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 builtin_description 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 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),
-
-  /* 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 helps provide a mapping from builtin function codes to bdesc
-   arrays.  */
-
-struct bdesc_map
-{
-  /* The builtin function table that this entry describes.  */
-  const struct builtin_description *bdesc;
-
-  /* The number of entries in the builtin function table.  */
-  unsigned int size;
-
-  /* The target processor that supports these builtin functions.
-     PROCESSOR_MAX means we enable them for all processors.  */
-  enum processor_type proc;
-
-  /* If the target has these flags, this builtin function table
-     will not be supported.  */
-  int unsupported_target_flags;
-};
-
-static const struct bdesc_map bdesc_arrays[] =
-{
-  { 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 }
+#define CODE_FOR_loongson_packsswh CODE_FOR_vec_pack_ssat_v2si
+#define CODE_FOR_loongson_packsshb CODE_FOR_vec_pack_ssat_v4hi
+#define CODE_FOR_loongson_packushb CODE_FOR_vec_pack_usat_v4hi
+#define CODE_FOR_loongson_paddw CODE_FOR_addv2si3
+#define CODE_FOR_loongson_paddh CODE_FOR_addv4hi3
+#define CODE_FOR_loongson_paddb CODE_FOR_addv8qi3
+#define CODE_FOR_loongson_paddsh CODE_FOR_ssaddv4hi3
+#define CODE_FOR_loongson_paddsb CODE_FOR_ssaddv8qi3
+#define CODE_FOR_loongson_paddush CODE_FOR_usaddv4hi3
+#define CODE_FOR_loongson_paddusb CODE_FOR_usaddv8qi3
+#define CODE_FOR_loongson_pmaxsh CODE_FOR_smaxv4hi3
+#define CODE_FOR_loongson_pmaxub CODE_FOR_umaxv8qi3
+#define CODE_FOR_loongson_pminsh CODE_FOR_sminv4hi3
+#define CODE_FOR_loongson_pminub CODE_FOR_uminv8qi3
+#define CODE_FOR_loongson_pmulhuh CODE_FOR_umulv4hi3_highpart
+#define CODE_FOR_loongson_pmulhh CODE_FOR_smulv4hi3_highpart
+#define CODE_FOR_loongson_biadd CODE_FOR_reduc_uplus_v8qi
+#define CODE_FOR_loongson_psubw CODE_FOR_subv2si3
+#define CODE_FOR_loongson_psubh CODE_FOR_subv4hi3
+#define CODE_FOR_loongson_psubb CODE_FOR_subv8qi3
+#define CODE_FOR_loongson_psubsh CODE_FOR_sssubv4hi3
+#define CODE_FOR_loongson_psubsb CODE_FOR_sssubv8qi3
+#define CODE_FOR_loongson_psubush CODE_FOR_ussubv4hi3
+#define CODE_FOR_loongson_psubusb CODE_FOR_ussubv8qi3
+#define CODE_FOR_loongson_punpckhbh CODE_FOR_vec_interleave_highv8qi
+#define CODE_FOR_loongson_punpckhhw CODE_FOR_vec_interleave_highv4hi
+#define CODE_FOR_loongson_punpckhwd CODE_FOR_vec_interleave_highv2si
+#define CODE_FOR_loongson_punpcklbh CODE_FOR_vec_interleave_lowv8qi
+#define CODE_FOR_loongson_punpcklhw CODE_FOR_vec_interleave_lowv4hi
+#define CODE_FOR_loongson_punpcklwd CODE_FOR_vec_interleave_lowv2si
+
+static const struct mips_builtin_description mips_builtins[] = {
+  DIRECT_BUILTIN (pll_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, paired_single),
+  DIRECT_BUILTIN (pul_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, paired_single),
+  DIRECT_BUILTIN (plu_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, paired_single),
+  DIRECT_BUILTIN (puu_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, paired_single),
+  DIRECT_BUILTIN (cvt_ps_s, MIPS_V2SF_FTYPE_SF_SF, paired_single),
+  DIRECT_BUILTIN (cvt_s_pl, MIPS_SF_FTYPE_V2SF, paired_single),
+  DIRECT_BUILTIN (cvt_s_pu, MIPS_SF_FTYPE_V2SF, paired_single),
+  DIRECT_BUILTIN (abs_ps, MIPS_V2SF_FTYPE_V2SF, paired_single),
+
+  DIRECT_BUILTIN (alnv_ps, MIPS_V2SF_FTYPE_V2SF_V2SF_INT, paired_single),
+  DIRECT_BUILTIN (addr_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, mips3d),
+  DIRECT_BUILTIN (mulr_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, mips3d),
+  DIRECT_BUILTIN (cvt_pw_ps, MIPS_V2SF_FTYPE_V2SF, mips3d),
+  DIRECT_BUILTIN (cvt_ps_pw, MIPS_V2SF_FTYPE_V2SF, mips3d),
+
+  DIRECT_BUILTIN (recip1_s, MIPS_SF_FTYPE_SF, mips3d),
+  DIRECT_BUILTIN (recip1_d, MIPS_DF_FTYPE_DF, mips3d),
+  DIRECT_BUILTIN (recip1_ps, MIPS_V2SF_FTYPE_V2SF, mips3d),
+  DIRECT_BUILTIN (recip2_s, MIPS_SF_FTYPE_SF_SF, mips3d),
+  DIRECT_BUILTIN (recip2_d, MIPS_DF_FTYPE_DF_DF, mips3d),
+  DIRECT_BUILTIN (recip2_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, mips3d),
+
+  DIRECT_BUILTIN (rsqrt1_s, MIPS_SF_FTYPE_SF, mips3d),
+  DIRECT_BUILTIN (rsqrt1_d, MIPS_DF_FTYPE_DF, mips3d),
+  DIRECT_BUILTIN (rsqrt1_ps, MIPS_V2SF_FTYPE_V2SF, mips3d),
+  DIRECT_BUILTIN (rsqrt2_s, MIPS_SF_FTYPE_SF_SF, mips3d),
+  DIRECT_BUILTIN (rsqrt2_d, MIPS_DF_FTYPE_DF_DF, mips3d),
+  DIRECT_BUILTIN (rsqrt2_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, mips3d),
+
+  MIPS_FP_CONDITIONS (CMP_BUILTINS),
+
+  /* Built-in functions for the SB-1 processor.  */
+  DIRECT_BUILTIN (sqrt_ps, MIPS_V2SF_FTYPE_V2SF, sb1_paired_single),
+
+  /* Built-in functions for the DSP ASE (32-bit and 64-bit).  */
+  DIRECT_BUILTIN (addq_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (addq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (addq_s_w, MIPS_SI_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (addu_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_BUILTIN (addu_s_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_BUILTIN (subq_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (subq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (subq_s_w, MIPS_SI_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (subu_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_BUILTIN (subu_s_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_BUILTIN (addsc, MIPS_SI_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (addwc, MIPS_SI_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (modsub, MIPS_SI_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (raddu_w_qb, MIPS_SI_FTYPE_V4QI, dsp),
+  DIRECT_BUILTIN (absq_s_ph, MIPS_V2HI_FTYPE_V2HI, dsp),
+  DIRECT_BUILTIN (absq_s_w, MIPS_SI_FTYPE_SI, dsp),
+  DIRECT_BUILTIN (precrq_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (precrq_ph_w, MIPS_V2HI_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (precrq_rs_ph_w, MIPS_V2HI_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (precrqu_s_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (preceq_w_phl, MIPS_SI_FTYPE_V2HI, dsp),
+  DIRECT_BUILTIN (preceq_w_phr, MIPS_SI_FTYPE_V2HI, dsp),
+  DIRECT_BUILTIN (precequ_ph_qbl, MIPS_V2HI_FTYPE_V4QI, dsp),
+  DIRECT_BUILTIN (precequ_ph_qbr, MIPS_V2HI_FTYPE_V4QI, dsp),
+  DIRECT_BUILTIN (precequ_ph_qbla, MIPS_V2HI_FTYPE_V4QI, dsp),
+  DIRECT_BUILTIN (precequ_ph_qbra, MIPS_V2HI_FTYPE_V4QI, dsp),
+  DIRECT_BUILTIN (preceu_ph_qbl, MIPS_V2HI_FTYPE_V4QI, dsp),
+  DIRECT_BUILTIN (preceu_ph_qbr, MIPS_V2HI_FTYPE_V4QI, dsp),
+  DIRECT_BUILTIN (preceu_ph_qbla, MIPS_V2HI_FTYPE_V4QI, dsp),
+  DIRECT_BUILTIN (preceu_ph_qbra, MIPS_V2HI_FTYPE_V4QI, dsp),
+  DIRECT_BUILTIN (shll_qb, MIPS_V4QI_FTYPE_V4QI_SI, dsp),
+  DIRECT_BUILTIN (shll_ph, MIPS_V2HI_FTYPE_V2HI_SI, dsp),
+  DIRECT_BUILTIN (shll_s_ph, MIPS_V2HI_FTYPE_V2HI_SI, dsp),
+  DIRECT_BUILTIN (shll_s_w, MIPS_SI_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (shrl_qb, MIPS_V4QI_FTYPE_V4QI_SI, dsp),
+  DIRECT_BUILTIN (shra_ph, MIPS_V2HI_FTYPE_V2HI_SI, dsp),
+  DIRECT_BUILTIN (shra_r_ph, MIPS_V2HI_FTYPE_V2HI_SI, dsp),
+  DIRECT_BUILTIN (shra_r_w, MIPS_SI_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (muleu_s_ph_qbl, MIPS_V2HI_FTYPE_V4QI_V2HI, dsp),
+  DIRECT_BUILTIN (muleu_s_ph_qbr, MIPS_V2HI_FTYPE_V4QI_V2HI, dsp),
+  DIRECT_BUILTIN (mulq_rs_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (muleq_s_w_phl, MIPS_SI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (muleq_s_w_phr, MIPS_SI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (bitrev, MIPS_SI_FTYPE_SI, dsp),
+  DIRECT_BUILTIN (insv, MIPS_SI_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (repl_qb, MIPS_V4QI_FTYPE_SI, dsp),
+  DIRECT_BUILTIN (repl_ph, MIPS_V2HI_FTYPE_SI, dsp),
+  DIRECT_NO_TARGET_BUILTIN (cmpu_eq_qb, MIPS_VOID_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_NO_TARGET_BUILTIN (cmpu_lt_qb, MIPS_VOID_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_NO_TARGET_BUILTIN (cmpu_le_qb, MIPS_VOID_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_BUILTIN (cmpgu_eq_qb, MIPS_SI_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_BUILTIN (cmpgu_lt_qb, MIPS_SI_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_BUILTIN (cmpgu_le_qb, MIPS_SI_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_NO_TARGET_BUILTIN (cmp_eq_ph, MIPS_VOID_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_NO_TARGET_BUILTIN (cmp_lt_ph, MIPS_VOID_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_NO_TARGET_BUILTIN (cmp_le_ph, MIPS_VOID_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (pick_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dsp),
+  DIRECT_BUILTIN (pick_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_BUILTIN (packrl_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
+  DIRECT_NO_TARGET_BUILTIN (wrdsp, MIPS_VOID_FTYPE_SI_SI, dsp),
+  DIRECT_BUILTIN (rddsp, MIPS_SI_FTYPE_SI, dsp),
+  DIRECT_BUILTIN (lbux, MIPS_SI_FTYPE_POINTER_SI, dsp),
+  DIRECT_BUILTIN (lhx, MIPS_SI_FTYPE_POINTER_SI, dsp),
+  DIRECT_BUILTIN (lwx, MIPS_SI_FTYPE_POINTER_SI, dsp),
+  BPOSGE_BUILTIN (32, dsp),
+
+  /* The following are for the MIPS DSP ASE REV 2 (32-bit and 64-bit).  */
+  DIRECT_BUILTIN (absq_s_qb, MIPS_V4QI_FTYPE_V4QI, dspr2),
+  DIRECT_BUILTIN (addu_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (addu_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (adduh_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dspr2),
+  DIRECT_BUILTIN (adduh_r_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dspr2),
+  DIRECT_BUILTIN (append, MIPS_SI_FTYPE_SI_SI_SI, dspr2),
+  DIRECT_BUILTIN (balign, MIPS_SI_FTYPE_SI_SI_SI, dspr2),
+  DIRECT_BUILTIN (cmpgdu_eq_qb, MIPS_SI_FTYPE_V4QI_V4QI, dspr2),
+  DIRECT_BUILTIN (cmpgdu_lt_qb, MIPS_SI_FTYPE_V4QI_V4QI, dspr2),
+  DIRECT_BUILTIN (cmpgdu_le_qb, MIPS_SI_FTYPE_V4QI_V4QI, dspr2),
+  DIRECT_BUILTIN (mul_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (mul_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (mulq_rs_w, MIPS_SI_FTYPE_SI_SI, dspr2),
+  DIRECT_BUILTIN (mulq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (mulq_s_w, MIPS_SI_FTYPE_SI_SI, dspr2),
+  DIRECT_BUILTIN (precr_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (precr_sra_ph_w, MIPS_V2HI_FTYPE_SI_SI_SI, dspr2),
+  DIRECT_BUILTIN (precr_sra_r_ph_w, MIPS_V2HI_FTYPE_SI_SI_SI, dspr2),
+  DIRECT_BUILTIN (prepend, MIPS_SI_FTYPE_SI_SI_SI, dspr2),
+  DIRECT_BUILTIN (shra_qb, MIPS_V4QI_FTYPE_V4QI_SI, dspr2),
+  DIRECT_BUILTIN (shra_r_qb, MIPS_V4QI_FTYPE_V4QI_SI, dspr2),
+  DIRECT_BUILTIN (shrl_ph, MIPS_V2HI_FTYPE_V2HI_SI, dspr2),
+  DIRECT_BUILTIN (subu_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (subu_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (subuh_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dspr2),
+  DIRECT_BUILTIN (subuh_r_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dspr2),
+  DIRECT_BUILTIN (addqh_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (addqh_r_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (addqh_w, MIPS_SI_FTYPE_SI_SI, dspr2),
+  DIRECT_BUILTIN (addqh_r_w, MIPS_SI_FTYPE_SI_SI, dspr2),
+  DIRECT_BUILTIN (subqh_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (subqh_r_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
+  DIRECT_BUILTIN (subqh_w, MIPS_SI_FTYPE_SI_SI, dspr2),
+  DIRECT_BUILTIN (subqh_r_w, MIPS_SI_FTYPE_SI_SI, dspr2),
+
+  /* Built-in functions for the DSP ASE (32-bit only).  */
+  DIRECT_BUILTIN (dpau_h_qbl, MIPS_DI_FTYPE_DI_V4QI_V4QI, dsp_32),
+  DIRECT_BUILTIN (dpau_h_qbr, MIPS_DI_FTYPE_DI_V4QI_V4QI, dsp_32),
+  DIRECT_BUILTIN (dpsu_h_qbl, MIPS_DI_FTYPE_DI_V4QI_V4QI, dsp_32),
+  DIRECT_BUILTIN (dpsu_h_qbr, MIPS_DI_FTYPE_DI_V4QI_V4QI, dsp_32),
+  DIRECT_BUILTIN (dpaq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
+  DIRECT_BUILTIN (dpsq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
+  DIRECT_BUILTIN (mulsaq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
+  DIRECT_BUILTIN (dpaq_sa_l_w, MIPS_DI_FTYPE_DI_SI_SI, dsp_32),
+  DIRECT_BUILTIN (dpsq_sa_l_w, MIPS_DI_FTYPE_DI_SI_SI, dsp_32),
+  DIRECT_BUILTIN (maq_s_w_phl, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
+  DIRECT_BUILTIN (maq_s_w_phr, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
+  DIRECT_BUILTIN (maq_sa_w_phl, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
+  DIRECT_BUILTIN (maq_sa_w_phr, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
+  DIRECT_BUILTIN (extr_w, MIPS_SI_FTYPE_DI_SI, dsp_32),
+  DIRECT_BUILTIN (extr_r_w, MIPS_SI_FTYPE_DI_SI, dsp_32),
+  DIRECT_BUILTIN (extr_rs_w, MIPS_SI_FTYPE_DI_SI, dsp_32),
+  DIRECT_BUILTIN (extr_s_h, MIPS_SI_FTYPE_DI_SI, dsp_32),
+  DIRECT_BUILTIN (extp, MIPS_SI_FTYPE_DI_SI, dsp_32),
+  DIRECT_BUILTIN (extpdp, MIPS_SI_FTYPE_DI_SI, dsp_32),
+  DIRECT_BUILTIN (shilo, MIPS_DI_FTYPE_DI_SI, dsp_32),
+  DIRECT_BUILTIN (mthlip, MIPS_DI_FTYPE_DI_SI, dsp_32),
+
+  /* The following are for the MIPS DSP ASE REV 2 (32-bit only).  */
+  DIRECT_BUILTIN (dpa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
+  DIRECT_BUILTIN (dps_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
+  DIRECT_BUILTIN (madd, MIPS_DI_FTYPE_DI_SI_SI, dspr2_32),
+  DIRECT_BUILTIN (maddu, MIPS_DI_FTYPE_DI_USI_USI, dspr2_32),
+  DIRECT_BUILTIN (msub, MIPS_DI_FTYPE_DI_SI_SI, dspr2_32),
+  DIRECT_BUILTIN (msubu, MIPS_DI_FTYPE_DI_USI_USI, dspr2_32),
+  DIRECT_BUILTIN (mulsa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
+  DIRECT_BUILTIN (mult, MIPS_DI_FTYPE_SI_SI, dspr2_32),
+  DIRECT_BUILTIN (multu, MIPS_DI_FTYPE_USI_USI, dspr2_32),
+  DIRECT_BUILTIN (dpax_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
+  DIRECT_BUILTIN (dpsx_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
+  DIRECT_BUILTIN (dpaqx_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
+  DIRECT_BUILTIN (dpaqx_sa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
+  DIRECT_BUILTIN (dpsqx_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
+  DIRECT_BUILTIN (dpsqx_sa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
+
+  /* Builtin functions for ST Microelectronics Loongson-2E/2F cores.  */
+  LOONGSON_BUILTIN (packsswh, MIPS_V4HI_FTYPE_V2SI_V2SI),
+  LOONGSON_BUILTIN (packsshb, MIPS_V8QI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN (packushb, MIPS_UV8QI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (paddw, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
+  LOONGSON_BUILTIN_SUFFIX (paddh, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (paddb, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (paddw, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
+  LOONGSON_BUILTIN_SUFFIX (paddh, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN_SUFFIX (paddb, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
+  LOONGSON_BUILTIN_SUFFIX (paddd, u, MIPS_UDI_FTYPE_UDI_UDI),
+  LOONGSON_BUILTIN_SUFFIX (paddd, s, MIPS_DI_FTYPE_DI_DI),
+  LOONGSON_BUILTIN (paddsh, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN (paddsb, MIPS_V8QI_FTYPE_V8QI_V8QI),
+  LOONGSON_BUILTIN (paddush, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN (paddusb, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_ALIAS (pandn_d, pandn_ud, MIPS_UDI_FTYPE_UDI_UDI),
+  LOONGSON_BUILTIN_ALIAS (pandn_w, pandn_uw, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
+  LOONGSON_BUILTIN_ALIAS (pandn_h, pandn_uh, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_ALIAS (pandn_b, pandn_ub, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_ALIAS (pandn_d, pandn_sd, MIPS_DI_FTYPE_DI_DI),
+  LOONGSON_BUILTIN_ALIAS (pandn_w, pandn_sw, MIPS_V2SI_FTYPE_V2SI_V2SI),
+  LOONGSON_BUILTIN_ALIAS (pandn_h, pandn_sh, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN_ALIAS (pandn_b, pandn_sb, MIPS_V8QI_FTYPE_V8QI_V8QI),
+  LOONGSON_BUILTIN (pavgh, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN (pavgb, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpeqw, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpeqh, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpeqb, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpeqw, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpeqh, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpeqb, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpgtw, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpgth, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpgtb, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpgtw, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpgth, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN_SUFFIX (pcmpgtb, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
+  LOONGSON_BUILTIN_SUFFIX (pextrh, u, MIPS_UV4HI_FTYPE_UV4HI_USI),
+  LOONGSON_BUILTIN_SUFFIX (pextrh, s, MIPS_V4HI_FTYPE_V4HI_USI),
+  LOONGSON_BUILTIN_SUFFIX (pinsrh_0, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (pinsrh_1, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (pinsrh_2, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (pinsrh_3, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (pinsrh_0, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN_SUFFIX (pinsrh_1, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN_SUFFIX (pinsrh_2, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN_SUFFIX (pinsrh_3, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN (pmaddhw, MIPS_V2SI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN (pmaxsh, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN (pmaxub, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN (pminsh, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN (pminub, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (pmovmskb, u, MIPS_UV8QI_FTYPE_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (pmovmskb, s, MIPS_V8QI_FTYPE_V8QI),
+  LOONGSON_BUILTIN (pmulhuh, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN (pmulhh, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN (pmullh, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN (pmuluw, MIPS_UDI_FTYPE_UV2SI_UV2SI),
+  LOONGSON_BUILTIN (pasubub, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN (biadd, MIPS_UV4HI_FTYPE_UV8QI),
+  LOONGSON_BUILTIN (psadbh, MIPS_UV4HI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (pshufh, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (pshufh, s, MIPS_V4HI_FTYPE_V4HI_V4HI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psllh, u, MIPS_UV4HI_FTYPE_UV4HI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psllh, s, MIPS_V4HI_FTYPE_V4HI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psllw, u, MIPS_UV2SI_FTYPE_UV2SI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psllw, s, MIPS_V2SI_FTYPE_V2SI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psrah, u, MIPS_UV4HI_FTYPE_UV4HI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psrah, s, MIPS_V4HI_FTYPE_V4HI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psraw, u, MIPS_UV2SI_FTYPE_UV2SI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psraw, s, MIPS_V2SI_FTYPE_V2SI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psrlh, u, MIPS_UV4HI_FTYPE_UV4HI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psrlh, s, MIPS_V4HI_FTYPE_V4HI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psrlw, u, MIPS_UV2SI_FTYPE_UV2SI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psrlw, s, MIPS_V2SI_FTYPE_V2SI_UQI),
+  LOONGSON_BUILTIN_SUFFIX (psubw, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
+  LOONGSON_BUILTIN_SUFFIX (psubh, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (psubb, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (psubw, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
+  LOONGSON_BUILTIN_SUFFIX (psubh, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN_SUFFIX (psubb, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
+  LOONGSON_BUILTIN_SUFFIX (psubd, u, MIPS_UDI_FTYPE_UDI_UDI),
+  LOONGSON_BUILTIN_SUFFIX (psubd, s, MIPS_DI_FTYPE_DI_DI),
+  LOONGSON_BUILTIN (psubsh, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN (psubsb, MIPS_V8QI_FTYPE_V8QI_V8QI),
+  LOONGSON_BUILTIN (psubush, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN (psubusb, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (punpckhbh, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (punpckhhw, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (punpckhwd, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
+  LOONGSON_BUILTIN_SUFFIX (punpckhbh, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
+  LOONGSON_BUILTIN_SUFFIX (punpckhhw, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN_SUFFIX (punpckhwd, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
+  LOONGSON_BUILTIN_SUFFIX (punpcklbh, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
+  LOONGSON_BUILTIN_SUFFIX (punpcklhw, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
+  LOONGSON_BUILTIN_SUFFIX (punpcklwd, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
+  LOONGSON_BUILTIN_SUFFIX (punpcklbh, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
+  LOONGSON_BUILTIN_SUFFIX (punpcklhw, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
+  LOONGSON_BUILTIN_SUFFIX (punpcklwd, s, MIPS_V2SI_FTYPE_V2SI_V2SI)
 };
 
 /* MODE is a vector mode whose elements have type TYPE.  Return the type
@@ -10266,11 +11307,17 @@ static const struct bdesc_map bdesc_arrays[] =
 static tree
 mips_builtin_vector_type (tree type, enum machine_mode mode)
 {
-  static tree types[(int) MAX_MACHINE_MODE];
+  static tree types[2 * (int) MAX_MACHINE_MODE];
+  int mode_index;
+
+  mode_index = (int) mode;
 
-  if (types[(int) mode] == NULL_TREE)
-    types[(int) mode] = build_vector_type_for_mode (type, mode);
-  return types[(int) mode];
+  if (TREE_CODE (type) == INTEGER_TYPE && TYPE_UNSIGNED (type))
+    mode_index += MAX_MACHINE_MODE;
+
+  if (types[mode_index] == NULL_TREE)
+    types[mode_index] = build_vector_type_for_mode (type, mode);
+  return types[mode_index];
 }
 
 /* Source-level argument types.  */
@@ -10279,16 +11326,27 @@ mips_builtin_vector_type (tree type, enum machine_mode mode)
 #define MIPS_ATYPE_POINTER ptr_type_node
 
 /* Standard mode-based argument types.  */
+#define MIPS_ATYPE_UQI unsigned_intQI_type_node
 #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_UDI unsigned_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_V2SI mips_builtin_vector_type (intSI_type_node, V2SImode)
 #define MIPS_ATYPE_V4QI mips_builtin_vector_type (intQI_type_node, V4QImode)
+#define MIPS_ATYPE_V4HI mips_builtin_vector_type (intHI_type_node, V4HImode)
+#define MIPS_ATYPE_V8QI mips_builtin_vector_type (intQI_type_node, V8QImode)
+#define MIPS_ATYPE_UV2SI                                       \
+  mips_builtin_vector_type (unsigned_intSI_type_node, V2SImode)
+#define MIPS_ATYPE_UV4HI                                       \
+  mips_builtin_vector_type (unsigned_intHI_type_node, V4HImode)
+#define MIPS_ATYPE_UV8QI                                       \
+  mips_builtin_vector_type (unsigned_intQI_type_node, V8QImode)
 
 /* MIPS_FTYPE_ATYPESN takes N MIPS_FTYPES-like type codes and lists
    their associated MIPS_ATYPEs.  */
@@ -10330,52 +11388,46 @@ mips_build_function_type (enum mips_function_type type)
   return types[(int) type];
 }
 
-/* Init builtin functions.  This is called from TARGET_INIT_BUILTIN.  */
+/* Implement TARGET_INIT_BUILTINS.  */
 
 static void
 mips_init_builtins (void)
 {
-  const struct builtin_description *d;
-  const struct bdesc_map *m;
-  unsigned int offset;
+  const struct mips_builtin_description *d;
+  unsigned int i;
 
   /* Iterate through all of the bdesc arrays, initializing all of the
      builtin functions.  */
-
-  offset = 0;
-  for (m = bdesc_arrays; m < &bdesc_arrays[ARRAY_SIZE (bdesc_arrays)]; m++)
+  for (i = 0; i < ARRAY_SIZE (mips_builtins); i++)
     {
-      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;
+      d = &mips_builtins[i];
+      if (d->avail ())
+       add_builtin_function (d->name,
+                             mips_build_function_type (d->function_type),
+                             i, BUILT_IN_MD, NULL, NULL);
     }
 }
 
-/* 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.  */
+/* 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 op, tree exp, unsigned int argnum)
+                         unsigned int opno, tree exp, unsigned int argno)
 {
   rtx value;
   enum machine_mode 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))
+  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[op].predicate (value, mode))
+      if (!insn_data[icode].operand[opno].predicate (value, mode))
        {
-         error ("invalid argument to builtin function");
+         error ("invalid argument to built-in function");
          return const0_rtx;
        }
     }
@@ -10398,32 +11450,35 @@ mips_prepare_builtin_target (enum insn_code icode, unsigned int op, rtx target)
   return target;
 }
 
-/* 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.  */
+/* 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)
+                           bool has_target_p)
 {
   rtx ops[MAX_RECOG_OPERANDS];
-  int i = 0;
-  int j = 0;
+  int opno, argno;
 
-  if (has_target)
+  /* Map any target to operand 0.  */
+  opno = 0;
+  if (has_target_p)
     {
-      /* We save target to ops[0].  */
-      ops[0] = mips_prepare_builtin_target (icode, 0, target);
-      i = 1;
+      ops[opno] = mips_prepare_builtin_target (icode, opno, target);
+      opno++;
     }
 
-  /* 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);
+  /* 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 (i)
+  switch (opno)
     {
     case 2:
       emit_insn (GEN_FCN (icode) (ops[0], ops[1]));
@@ -10443,8 +11498,8 @@ mips_expand_builtin_direct (enum insn_code icode, rtx target, tree exp,
   return target;
 }
 
-/* Expand a __builtin_mips_movt_*_ps() or __builtin_mips_movf_*_ps()
-   function (TYPE says which).  EXP is the tree for the function
+/* 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.  */
@@ -10505,37 +11560,41 @@ mips_builtin_branch_and_move (rtx condition, rtx target,
   return target;
 }
 
-/* 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.  */
+/* 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, ops[MAX_RECOG_OPERANDS];
-  int i;
-  int j = 0;
+  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 (i = 1; i < insn_data[icode].n_operands - 1; i++, j++)
-    ops[i] = mips_prepare_builtin_arg (icode, i, exp, j);
+  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, ops[1], ops[2], GEN_INT (cond)));
+      emit_insn (GEN_FCN (icode) (cmp_result, args[0], args[1],
+                                 GEN_INT (cond)));
       break;
 
     case 6:
-      emit_insn (GEN_FCN (icode) (cmp_result, ops[1], ops[2],
-                                 ops[3], ops[4], GEN_INT (cond)));
+      emit_insn (GEN_FCN (icode) (cmp_result, args[0], args[1],
+                                 args[2], args[3], GEN_INT (cond)));
       break;
 
     default:
@@ -10566,8 +11625,8 @@ mips_expand_builtin_compare (enum mips_builtin_type builtin_type,
     }
 }
 
-/* Expand a bposge builtin of type BUILTIN_TYPE.  TARGET, if nonnull,
-   suggests a good place to put the boolean result.  */
+/* Expand a bposge built-in function of type BUILTIN_TYPE.  TARGET,
+   if nonnull, suggests a good place to put the boolean result.  */
 
 static rtx
 mips_expand_builtin_bposge (enum mips_builtin_type builtin_type, rtx target)
@@ -10590,77 +11649,58 @@ mips_expand_builtin_bposge (enum mips_builtin_type builtin_type, rtx target)
                                       const1_rtx, const0_rtx);
 }
 
-/* Expand builtin functions.  This is called from TARGET_EXPAND_BUILTIN.  */
+/* Implement TARGET_EXPAND_BUILTIN.  */
 
 static 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;
+  unsigned int fcode, avail;
+  const struct mips_builtin_description *d;
 
   fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
   fcode = DECL_FUNCTION_CODE (fndecl);
-
+  gcc_assert (fcode < ARRAY_SIZE (mips_builtins));
+  d = &mips_builtins[fcode];
+  avail = d->avail ();
+  gcc_assert (avail != 0);
   if (TARGET_MIPS16)
     {
       error ("built-in function %qs not supported for MIPS16",
             IDENTIFIER_POINTER (DECL_NAME (fndecl)));
       return const0_rtx;
     }
-
-  bdesc = NULL;
-  for (m = bdesc_arrays; m < &bdesc_arrays[ARRAY_SIZE (bdesc_arrays)]; m++)
-    {
-      if (fcode < m->size)
-       {
-         bdesc = m->bdesc;
-         icode = bdesc[fcode].icode;
-         type = bdesc[fcode].builtin_type;
-         break;
-       }
-      fcode -= m->size;
-    }
-  if (bdesc == NULL)
-    return 0;
-
-  switch (type)
+  switch (d->builtin_type)
     {
     case MIPS_BUILTIN_DIRECT:
-      return mips_expand_builtin_direct (icode, target, exp, true);
+      return mips_expand_builtin_direct (d->icode, target, exp, true);
 
     case MIPS_BUILTIN_DIRECT_NO_TARGET:
-      return mips_expand_builtin_direct (icode, target, exp, false);
+      return mips_expand_builtin_direct (d->icode, target, exp, false);
 
     case MIPS_BUILTIN_MOVT:
     case MIPS_BUILTIN_MOVF:
-      return mips_expand_builtin_movtf (type, icode, bdesc[fcode].cond,
-                                       target, exp);
+      return mips_expand_builtin_movtf (d->builtin_type, d->icode,
+                                       d->cond, target, exp);
 
     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);
+      return mips_expand_builtin_compare (d->builtin_type, d->icode,
+                                         d->cond, target, exp);
 
     case MIPS_BUILTIN_BPOSGE32:
-      return mips_expand_builtin_bposge (type, target);
-
-    default:
-      return 0;
+      return mips_expand_builtin_bposge (d->builtin_type, target);
     }
+  gcc_unreachable ();
 }
 \f
-/* An entry in the mips16 constant pool.  VALUE is the pool constant,
+/* 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;
@@ -10668,11 +11708,10 @@ struct mips16_constant {
   enum machine_mode mode;
 };
 
-/* Information about an incomplete mips16 constant pool.  FIRST is the
+/* 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;
@@ -10683,8 +11722,8 @@ struct mips16_constant_pool {
    value's mode (used for CONST_INTs, etc.).  */
 
 static rtx
-add_constant (struct mips16_constant_pool *pool,
-             rtx value, enum machine_mode mode)
+mips16_add_constant (struct mips16_constant_pool *pool,
+                    rtx value, enum machine_mode mode)
 {
   struct mips16_constant **p, *c;
   bool first_of_size_p;
@@ -10714,10 +11753,11 @@ add_constant (struct mips16_constant_pool *pool,
      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.  */
+    /* 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)
@@ -10725,7 +11765,7 @@ add_constant (struct mips16_constant_pool *pool,
     pool->highest_address -= GET_MODE_SIZE (mode) - 1;
 
   /* Create a new entry.  */
-  c = (struct mips16_constant *) xmalloc (sizeof *c);
+  c = XNEW (struct mips16_constant);
   c->value = value;
   c->mode = mode;
   c->label = gen_label_rtx ();
@@ -10739,11 +11779,9 @@ add_constant (struct mips16_constant_pool *pool,
    instruction emitted.  MODE is the mode of the constant.  */
 
 static rtx
-dump_constants_1 (enum machine_mode mode, rtx value, rtx insn)
+mips16_emit_constants_1 (enum machine_mode mode, rtx value, rtx insn)
 {
-  if (SCALAR_INT_MODE_P (mode)
-      || ALL_SCALAR_FRACT_MODE_P (mode)
-      || ALL_SCALAR_ACCUM_MODE_P (mode))
+  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);
@@ -10757,19 +11795,18 @@ dump_constants_1 (enum machine_mode mode, rtx value, rtx insn)
       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);
+       insn = mips16_emit_constants_1 (GET_MODE_INNER (mode),
+                                       CONST_VECTOR_ELT (value, i), insn);
       return insn;
     }
 
   gcc_unreachable ();
 }
 
-
 /* Dump out the constants in CONSTANTS after INSN.  */
 
 static void
-dump_constants (struct mips16_constant *constants, rtx insn)
+mips16_emit_constants (struct mips16_constant *constants, rtx insn)
 {
   struct mips16_constant *c, *next;
   int align;
@@ -10786,7 +11823,7 @@ dump_constants (struct mips16_constant *constants, rtx insn)
       align = GET_MODE_SIZE (c->mode);
 
       insn = emit_label_after (c->label, insn);
-      insn = dump_constants_1 (c->mode, c->value, insn);
+      insn = mips16_emit_constants_1 (c->mode, c->value, insn);
 
       next = c->next;
       free (c);
@@ -10822,8 +11859,8 @@ mips16_rewrite_pool_constant (struct mips16_constant_pool *pool, rtx *x)
   split_const (*x, &base, &offset);
   if (GET_CODE (base) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (base))
     {
-      label = add_constant (pool, get_pool_constant (base),
-                           get_pool_mode (base));
+      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);
     }
@@ -10844,7 +11881,8 @@ struct mips16_rewrite_pool_refs_info {
 static int
 mips16_rewrite_pool_refs (rtx *x, void *data)
 {
-  struct mips16_rewrite_pool_refs_info *info = data;
+  struct mips16_rewrite_pool_refs_info *info =
+    (struct mips16_rewrite_pool_refs_info *) data;
 
   if (force_to_mem_operand (*x, Pmode))
     {
@@ -10876,6 +11914,7 @@ mips16_lay_out_constants (void)
   if (!TARGET_MIPS16_PCREL_LOADS)
     return;
 
+  split_all_insns_noflow ();
   barrier = 0;
   memset (&pool, 0, sizeof (pool));
   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
@@ -10920,7 +11959,7 @@ mips16_lay_out_constants (void)
             will use negative offsets to refer to the pool.  */
          if (pool.insn_address > pool.highest_address)
            {
-             dump_constants (pool.first, barrier);
+             mips16_emit_constants (pool.first, barrier);
              pool.first = NULL;
              barrier = 0;
            }
@@ -10928,7 +11967,7 @@ mips16_lay_out_constants (void)
            barrier = insn;
        }
     }
-  dump_constants (pool.first, get_last_insn ());
+  mips16_emit_constants (pool.first, get_last_insn ());
 }
 \f
 /* A temporary variable used by for_each_rtx callbacks, etc.  */
@@ -10997,15 +12036,16 @@ mips_sim_next_cycle (struct mips_sim *state)
 static void
 mips_sim_wait_reg (struct mips_sim *state, rtx insn, rtx reg)
 {
-  unsigned int i;
+  unsigned int regno, end_regno;
 
-  for (i = 0; i < HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg)); i++)
-    if (state->last_set[REGNO (reg) + i].insn != 0)
+  end_regno = END_REGNO (reg);
+  for (regno = REGNO (reg); regno < end_regno; regno++)
+    if (state->last_set[regno].insn != 0)
       {
        unsigned int t;
 
-       t = state->last_set[REGNO (reg) + i].time;
-       t += insn_latency (state->last_set[REGNO (reg) + i].insn, insn);
+       t = (state->last_set[regno].time
+            + insn_latency (state->last_set[regno].insn, insn));
        while (state->time < t)
          mips_sim_next_cycle (state);
     }
@@ -11018,7 +12058,7 @@ static int
 mips_sim_wait_regs_2 (rtx *x, void *data)
 {
   if (REG_P (*x))
-    mips_sim_wait_reg (data, mips_sim_insn, *x);
+    mips_sim_wait_reg ((struct mips_sim *) data, mips_sim_insn, *x);
   return 0;
 }
 
@@ -11071,15 +12111,19 @@ static void
 mips_sim_record_set (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
 {
   struct mips_sim *state;
-  unsigned int i;
 
-  state = data;
+  state = (struct mips_sim *) 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;
-      }
+    {
+      unsigned int regno, end_regno;
+
+      end_regno = END_REGNO (x);
+      for (regno = REGNO (x); regno < end_regno; regno++)
+       {
+         state->last_set[regno].insn = mips_sim_insn;
+         state->last_set[regno].time = state->time;
+       }
+    }
 }
 
 /* Issue instruction INSN in scheduler state STATE.  Assume that INSN
@@ -11149,7 +12193,7 @@ mips_sim_finish_insn (struct mips_sim *state, rtx insn)
    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
+   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.  */
@@ -11185,7 +12229,7 @@ vr4130_avoid_branch_rt_conflict (rtx insn)
 
 /* 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,
+   in parallel, and the first of those instructions is not 8-byte aligned,
    insert a nop to make it aligned.  */
 
 static void
@@ -11297,15 +12341,129 @@ vr4130_align_insns (void)
   dfa_finish ();
 }
 \f
-/* Subroutine of mips_reorg.  If there is a hazard between INSN
-   and a previous instruction, avoid it by inserting nops after
+/* 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;
+};
+
+/* Return a hash value for SYMBOL_REF or LABEL_REF BASE.  */
+
+static hashval_t
+mips_hash_base (rtx base)
+{
+  int do_not_record_p;
+
+  return hash_rtx (base, GET_MODE (base), &do_not_record_p, NULL, false);
+}
+
+/* Hash-table callbacks for mips_lo_sum_offsets.  */
+
+static hashval_t
+mips_lo_sum_offset_hash (const void *entry)
+{
+  return mips_hash_base (((const struct mips_lo_sum_offset *) entry)->base);
+}
+
+static int
+mips_lo_sum_offset_eq (const void *entry, const void *value)
+{
+  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.  */
+
+static bool
+mips_lo_sum_offset_lookup (htab_t htab, rtx x, enum insert_option option)
+{
+  rtx base, offset;
+  void **slot;
+  struct mips_lo_sum_offset *entry;
+
+  /* Split X into a base and offset.  */
+  split_const (x, &base, &offset);
+  if (UNSPEC_ADDRESS_P (base))
+    base = UNSPEC_ADDRESS (base);
+
+  /* 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;
+
+  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;
+}
+
+/* A for_each_rtx callback for which DATA is a mips_lo_sum_offset hash table.
+   Record every LO_SUM in *LOC.  */
+
+static int
+mips_record_lo_sum (rtx *loc, void *data)
+{
+  if (GET_CODE (*loc) == LO_SUM)
+    mips_lo_sum_offset_lookup ((htab_t) data, XEXP (*loc, 1), INSERT);
+  return 0;
+}
+
+/* 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.  */
+
+static bool
+mips_orphaned_high_part_p (htab_t htab, rtx insn)
+{
+  enum mips_symbol_type type;
+  rtx x, set;
+
+  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;
+}
+
+/* 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.
 
    *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).
+   the number of instructions since the last MFLO or MFHI).
 
    After inserting nops for INSN, update *DELAYED_REG and *HILO_DELAY
    for the next instruction.
@@ -11317,10 +12475,7 @@ mips_avoid_hazard (rtx after, rtx insn, int *hilo_delay,
                   rtx *delayed_reg, rtx lo_reg)
 {
   rtx pattern, set;
-  int nops, ninsns, hazard_set;
-
-  if (!INSN_P (insn))
-    return;
+  int nops, ninsns;
 
   pattern = PATTERN (insn);
 
@@ -11366,30 +12521,24 @@ mips_avoid_hazard (rtx after, rtx insn, int *hilo_delay,
        break;
 
       case HAZARD_DELAY:
-       hazard_set = (int) get_attr_hazard_set (insn);
-       if (hazard_set == 0)
-         set = single_set (insn);
-       else
-         {
-           gcc_assert (GET_CODE (PATTERN (insn)) == PARALLEL);
-           set = XVECEXP (PATTERN (insn), 0, hazard_set - 1);
-         }
-       gcc_assert (set && GET_CODE (set) == SET);
+       set = single_set (insn);
+       gcc_assert (set);
        *delayed_reg = SET_DEST (set);
        break;
       }
 }
 
-
 /* Go through the instruction stream and insert nops where necessary.
-   See if the whole function can then be put into .set noreorder &
-   .set nomacro.  */
+   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 void
-mips_avoid_hazards (void)
+mips_reorg_process_insns (void)
 {
-  rtx insn, last_insn, lo_reg, delayed_reg;
-  int hilo_delay, i;
+  rtx insn, last_insn, subinsn, next_insn, lo_reg, delayed_reg;
+  int hilo_delay;
+  htab_t htab;
 
   /* Force all instructions to be split into their final form.  */
   split_all_insns_noflow ();
@@ -11400,9 +12549,18 @@ mips_avoid_hazards (void)
 
   cfun->machine->all_noreorder_p = true;
 
+  /* We don't track MIPS16 PC-relative offsets closely enough to make
+     a good job of "set .noreorder" code in MIPS16 mode.  */
+  if (TARGET_MIPS16)
+    cfun->machine->all_noreorder_p = false;
+
+  /* Code that doesn't use explicit relocs can't be ".set nomacro".  */
+  if (!TARGET_EXPLICIT_RELOCS)
+    cfun->machine->all_noreorder_p = false;
+
   /* Profiled functions can't be all noreorder because the profiler
      support uses assembler macros.  */
-  if (current_function_profile)
+  if (crtl->profile)
     cfun->machine->all_noreorder_p = false;
 
   /* Code compiled with -mfix-vr4120 can't be all noreorder because
@@ -11410,33 +12568,71 @@ mips_avoid_hazards (void)
   if (TARGET_FIX_VR4120)
     cfun->machine->all_noreorder_p = false;
 
-  /* 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;
+  /* 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;
 
+  htab = htab_create (37, mips_lo_sum_offset_hash,
+                     mips_lo_sum_offset_eq, free);
+
+  /* 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);
+
   last_insn = 0;
   hilo_delay = 2;
   delayed_reg = 0;
   lo_reg = gen_rtx_REG (SImode, LO_REGNUM);
 
-  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;
-      }
-}
+  /* 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)
+    {
+      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;
+               }
+           }
+       }
+    }
 
+  htab_delete (htab);
+}
 
 /* Implement TARGET_MACHINE_DEPENDENT_REORG.  */
 
@@ -11444,14 +12640,14 @@ static void
 mips_reorg (void)
 {
   mips16_lay_out_constants ();
-  if (TARGET_EXPLICIT_RELOCS)
-    {
-      if (mips_flag_delayed_branch)
-       dbr_schedule (get_insns ());
-      mips_avoid_hazards ();
-      if (TUNE_MIPS4130 && TARGET_VR4130_ALIGN)
-       vr4130_align_insns ();
-    }
+  if (mips_base_delayed_branch)
+    dbr_schedule (get_insns ());
+  mips_reorg_process_insns ();
+  if (!TARGET_MIPS16
+      && TARGET_EXPLICIT_RELOCS
+      && TUNE_MIPS4130
+      && TARGET_VR4130_ALIGN)
+    vr4130_align_insns ();
 }
 \f
 /* Implement TARGET_ASM_OUTPUT_MI_THUNK.  Generate rtl rather than asm text
@@ -11462,7 +12658,7 @@ mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
                      HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
                      tree function)
 {
-  rtx this, temp1, temp2, insn, fnaddr;
+  rtx this_rtx, temp1, temp2, insn, fnaddr;
   bool use_sibcall_p;
 
   /* Pretend to be a post-reload pass while generating rtl.  */
@@ -11477,24 +12673,19 @@ mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
                   && const_call_insn_operand (fnaddr, Pmode));
 
   /* 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);
-
-       /* Set up the global pointer for n32 or n64 abicalls.  */
-       mips_emit_loadgp ();
-       break;
+  if (!use_sibcall_p
+      && (mips_got_symbol_type_p
+         (mips_classify_symbol (fnaddr, SYMBOL_CONTEXT_LEA))))
+    {
+      /* 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);
 
-      default:
-       break;
-      }
+      /* Set up the global pointer for n32 or n64 abicalls.  */
+      mips_emit_loadgp ();
+    }
 
   /* We need two temporary registers in some cases.  */
   temp1 = gen_rtx_REG (Pmode, 2);
@@ -11502,11 +12693,11 @@ mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
 
   /* 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);
+    this_rtx = gen_rtx_REG (Pmode, GP_ARG_FIRST + 1);
   else
-    this = gen_rtx_REG (Pmode, GP_ARG_FIRST);
+    this_rtx = gen_rtx_REG (Pmode, GP_ARG_FIRST);
 
-  /* Add DELTA to THIS.  */
+  /* Add DELTA to THIS_RTX.  */
   if (delta != 0)
     {
       rtx offset = GEN_INT (delta);
@@ -11515,23 +12706,23 @@ mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
          mips_emit_move (temp1, offset);
          offset = temp1;
        }
-      emit_insn (gen_add3_insn (this, this, offset));
+      emit_insn (gen_add3_insn (this_rtx, this_rtx, offset));
     }
 
-  /* If needed, add *(*THIS + VCALL_OFFSET) to THIS.  */
+  /* If needed, add *(*THIS_RTX + VCALL_OFFSET) to THIS_RTX.  */
   if (vcall_offset != 0)
     {
       rtx addr;
 
-      /* Set TEMP1 to *THIS.  */
-      mips_emit_move (temp1, gen_rtx_MEM (Pmode, this));
+      /* Set TEMP1 to *THIS_RTX.  */
+      mips_emit_move (temp1, gen_rtx_MEM (Pmode, this_rtx));
 
-      /* Set ADDR to a legitimate address for *THIS + VCALL_OFFSET.  */
+      /* Set ADDR to a legitimate address for *THIS_RTX + VCALL_OFFSET.  */
       addr = mips_add_offset (temp2, temp1, vcall_offset);
 
-      /* Load the offset and add it to THIS.  */
+      /* Load the offset and add it to THIS_RTX.  */
       mips_emit_move (temp1, gen_rtx_MEM (Pmode, addr));
-      emit_insn (gen_add3_insn (this, this, temp1));
+      emit_insn (gen_add3_insn (this_rtx, this_rtx, temp1));
     }
 
   /* Jump to the target function.  Use a sibcall if direct jumps are
@@ -11543,7 +12734,7 @@ mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
     }
   else
     {
-      /* This is messy.  gas treats "la $25,foo" as part of a call
+      /* 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.
 
@@ -11553,12 +12744,17 @@ mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
         We must therefore load the address via a temporary
         register if mips_dangerous_for_la25_p.
 
-        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 we jump to the temporary register rather than $25,
+        the assembler can use the move insn to fill the jump's
+        delay slot.
+
+        We can use the same technique for MIPS16 code, where $25
+        is not a valid JR register.  */
       if (TARGET_USE_PIC_FN_ADDR_REG
+         && !TARGET_MIPS16
          && !mips_dangerous_for_la25_p (fnaddr))
        temp1 = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
-      mips_load_call_address (temp1, fnaddr, true);
+      mips_load_call_address (MIPS_CALL_SIBCALL, temp1, fnaddr);
 
       if (TARGET_USE_PIC_FN_ADDR_REG
          && REGNO (temp1) != PIC_FUNCTION_ADDR_REGNUM)
@@ -11576,13 +12772,22 @@ mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
   final_start_function (insn, file, 1);
   final (insn, file, 1);
   final_end_function ();
+  free_after_compilation (cfun);
 
   /* Clean up the vars set above.  Note that final_end_function resets
      the global pointer for us.  */
   reload_completed = 0;
 }
 \f
-static GTY(()) int was_mips16_p = -1;
+/* The last argument passed to mips_set_mips16_mode, or negative if the
+   function hasn't been called yet.
+
+   There are two copies of this information.  One is saved and restored
+   by the PCH process while the other is specific to this compiler
+   invocation.  The information calculated by mips_set_mips16_mode
+   is invalid unless the two variables are the same.  */
+static int was_mips16_p = -1;
+static GTY(()) int was_mips16_pch_p = -1;
 
 /* Set up the target-dependent global state so that it matches the
    current function's ISA mode.  */
@@ -11590,12 +12795,12 @@ static GTY(()) int was_mips16_p = -1;
 static void
 mips_set_mips16_mode (int mips16_p)
 {
-  if (mips16_p == was_mips16_p)
+  if (mips16_p == was_mips16_p
+      && mips16_p == was_mips16_pch_p)
     return;
 
   /* Restore base settings of various flags.  */
   target_flags = mips_base_target_flags;
-  flag_delayed_branch = mips_flag_delayed_branch;
   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;
@@ -11605,14 +12810,14 @@ mips_set_mips16_mode (int mips16_p)
 
   if (mips16_p)
     {
-      /* Select mips16 instruction set.  */
+      /* Switch to MIPS16 mode.  */
       target_flags |= MASK_MIPS16;
 
       /* Don't run the scheduler before reload, since it tends to
          increase register pressure.  */
       flag_schedule_insns = 0;
 
-      /* Don't do hot/cold partitioning.  The constant layout code expects
+      /* 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;
 
@@ -11623,33 +12828,30 @@ mips_set_mips16_mode (int mips16_p)
         call.  */
       flag_move_loop_invariants = 0;
 
-      /* 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;
-
-      /* 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.  */
+      target_flags |= MASK_EXPLICIT_RELOCS;
+
+      /* 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;
 
-      if (flag_pic || TARGET_ABICALLS)
-       sorry ("MIPS16 PIC");
+      if (flag_pic && !TARGET_OLDABI)
+       sorry ("MIPS16 PIC for ABIs other than o32 and o64");
+
+      if (TARGET_XGOT)
+       sorry ("MIPS16 -mxgot code");
+
+      if (TARGET_HARD_FLOAT_ABI && !TARGET_OLDABI)
+       sorry ("hard-float MIPS16 code for ABIs other than o32 and o64");
     }
   else
     {
-      /* Reset to select base non-mips16 ISA.  */
+      /* Switch to normal (non-MIPS16) mode.  */
       target_flags &= ~MASK_MIPS16;
 
-      /* When using explicit relocs, we call dbr_schedule from within
-        mips_reorg.  */
-      if (TARGET_EXPLICIT_RELOCS)
-       flag_delayed_branch = 0;
-
       /* Provide default values for align_* for 64-bit targets.  */
       if (TARGET_64BIT)
        {
@@ -11665,15 +12867,15 @@ mips_set_mips16_mode (int mips16_p)
       targetm.max_anchor_offset = 32767;
     }
 
-  /* (Re)initialize mips target internals for new ISA.  */
-  mips_init_split_addresses ();
+  /* (Re)initialize MIPS target internals for new ISA.  */
   mips_init_relocs ();
 
-  if (was_mips16_p >= 0)
+  if (was_mips16_p >= 0 || was_mips16_pch_p >= 0)
     /* Reinitialize target-dependent state.  */
     target_reinit ();
 
-  was_mips16_p = TARGET_MIPS16;
+  was_mips16_p = mips16_p;
+  was_mips16_pch_p = mips16_p;
 }
 
 /* Implement TARGET_SET_CURRENT_FUNCTION.  Decide whether the current
@@ -11686,6 +12888,7 @@ mips_set_current_function (tree fndecl)
 }
 \f
 /* Allocate a chunk of memory for per-function machine-dependent data.  */
+
 static struct machine_function *
 mips_init_machine_status (void)
 {
@@ -11705,7 +12908,7 @@ mips_cpu_info_from_isa (int isa)
     if (mips_cpu_info_table[i].isa == isa)
       return mips_cpu_info_table + i;
 
-  return 0;
+  return NULL;
 }
 
 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
@@ -11723,7 +12926,6 @@ mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
          || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
 }
 
-
 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
    CPU name.  We've traditionally allowed a lot of variation here.
 
@@ -11756,7 +12958,6 @@ mips_matching_cpu_name_p (const char *canonical, const char *given)
   return mips_strict_matching_cpu_name_p (canonical, given);
 }
 
-
 /* Return the mips_cpu_info entry for the processor or ISA given
    by CPU_STRING.  Return null if the string isn't recognized.
 
@@ -11773,15 +12974,14 @@ mips_parse_cpu (const char *cpu_string)
   for (s = cpu_string; *s != 0; s++)
     if (ISUPPER (*s))
       {
-       warning (0, "the cpu name must be lower case");
+       warning (0, "CPU names 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.  */
+     version.  */
   if (strcasecmp (cpu_string, "from-abi") == 0)
     return mips_cpu_info_from_isa (ABI_NEEDS_32BIT_REGS ? 1
                                   : ABI_NEEDS_64BIT_REGS ? 3
@@ -11789,16 +12989,15 @@ mips_parse_cpu (const char *cpu_string)
 
   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
   if (strcasecmp (cpu_string, "default") == 0)
-    return 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 0;
+  return NULL;
 }
 
-
 /* Set up globals to generate code for the ISA or processor
    described by INFO.  */
 
@@ -11813,7 +13012,6 @@ mips_set_architecture (const struct mips_cpu_info *info)
     }
 }
 
-
 /* Likewise for tuning.  */
 
 static void
@@ -11853,8 +13051,8 @@ mips_handle_option (size_t code, const char *arg, int value ATTRIBUTE_UNUSED)
       return mips_parse_cpu (arg) != 0;
 
     case OPT_mips:
-      mips_isa_info = mips_parse_cpu (ACONCAT (("mips", arg, NULL)));
-      return mips_isa_info != 0;
+      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;
@@ -11876,20 +13074,25 @@ mips_handle_option (size_t code, const char *arg, int value ATTRIBUTE_UNUSED)
     }
 }
 
-/* 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.  */
+/* Implement OVERRIDE_OPTIONS.  */
 
 void
-override_options (void)
+mips_override_options (void)
 {
-  int i, start, regno;
-  enum machine_mode mode;
+  int i, start, regno, mode;
+
+  /* Process flags as though we were generating non-MIPS16 code.  */
+  mips_base_mips16 = TARGET_MIPS16;
+  target_flags &= ~MASK_MIPS16;
 
 #ifdef SUBTARGET_OVERRIDE_OPTIONS
   SUBTARGET_OVERRIDE_OPTIONS;
 #endif
 
-  mips_section_threshold = g_switch_set ? g_switch_value : MIPS_DEFAULT_GVALUE;
+  /* 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()).
@@ -11898,14 +13101,14 @@ override_options (void)
   if (mips_arch_string != 0)
     mips_set_architecture (mips_parse_cpu (mips_arch_string));
 
-  if (mips_isa_info != 0)
+  if (mips_isa_option_info != 0)
     {
       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, "
+       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_info->name,
+              mips_isa_option_info->name,
               mips_cpu_info_from_isa (mips_arch_info->isa)->name);
     }
 
@@ -11919,7 +13122,7 @@ override_options (void)
     }
 
   if (ABI_NEEDS_64BIT_REGS && !ISA_HAS_64BIT_REGS)
-    error ("-march=%s is not compatible with the selected ABI",
+    error ("%<-march=%s%> is not compatible with the selected ABI",
           mips_arch_info->name);
 
   /* Optimize for mips_arch, unless -mtune selects a different processor.  */
@@ -11929,27 +13132,16 @@ override_options (void)
   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;
-
   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");
+       error ("%<-mgp64%> used with a 32-bit processor");
       else if (!TARGET_64BIT && ABI_NEEDS_64BIT_REGS)
-       error ("-mgp32 used with a 64-bit ABI");
+       error ("%<-mgp32%> used with a 64-bit ABI");
       else if (TARGET_64BIT && ABI_NEEDS_32BIT_REGS)
-       error ("-mgp64 used with a 32-bit ABI");
+       error ("%<-mgp64%> used with a 32-bit ABI");
     }
   else
     {
@@ -11964,16 +13156,19 @@ override_options (void)
 
   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)
+      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)
+       {
+         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
     {
@@ -11987,6 +13182,7 @@ override_options (void)
 
   /* End of code shared with GAS.  */
 
+  /* 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)
@@ -11998,13 +13194,24 @@ override_options (void)
   if (!TARGET_OLDABI)
     flag_pcc_struct_return = 0;
 
+  /* 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];
+
+  /* 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;
+
+  /* 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 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 (ISA_HAS_BRANCHLIKELY
          && (optimize_size
              || (mips_tune_info->tune_flags & PTF_AVOID_BRANCHLIKELY) == 0))
@@ -12023,22 +13230,16 @@ override_options (void)
       target_flags &= ~MASK_ABICALLS;
     }
 
-  /* 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)
+  if (TARGET_ABICALLS_PIC2)
     /* 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.  */
+       There is a body of code that uses __PIC__ to distinguish
+       between -mabicalls and -mno-abicalls code.  The non-__PIC__
+       variant is usually appropriate for TARGET_ABICALLS_PIC0, as
+       long as any indirect jumps use $25.  */
     flag_pic = 1;
 
   /* -mvr4130-align is a "speed over size" optimization: it usually produces
@@ -12054,11 +13255,11 @@ override_options (void)
 
   /* 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)
+  if (mips_small_data_threshold > 0)
     {
       if (!TARGET_GPOPT)
        {
-         if (!TARGET_MIPS16 && !TARGET_EXPLICIT_RELOCS)
+         if (!TARGET_EXPLICIT_RELOCS)
            error ("%<-mno-gpopt%> needs %<-mexplicit-relocs%>");
 
          TARGET_LOCAL_SDATA = false;
@@ -12081,9 +13282,10 @@ override_options (void)
 
   /* 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)
+  if (TARGET_MIPS3D
+      && (target_flags_explicit & MASK_PAIRED_SINGLE_FLOAT)
       && !TARGET_PAIRED_SINGLE_FLOAT)
-    error ("-mips3d requires -mpaired-single");
+    error ("%<-mips3d%> requires %<-mpaired-single%>");
 
   /* If TARGET_MIPS3D, enable MASK_PAIRED_SINGLE_FLOAT.  */
   if (TARGET_MIPS3D)
@@ -12092,12 +13294,15 @@ override_options (void)
   /* 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");
+    error ("%qs must be used with %qs",
+          TARGET_MIPS3D ? "-mips3d" : "-mpaired-single",
+          TARGET_HARD_FLOAT_ABI ? "-mfp64" : "-mhard-float");
 
   /* 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");
+  if (TARGET_PAIRED_SINGLE_FLOAT && !ISA_HAS_PAIRED_SINGLE)
+    warning (0, "the %qs architecture does not support paired-single"
+            " instructions", mips_arch_info->name);
 
   /* If TARGET_DSPR2, enable MASK_DSP.  */
   if (TARGET_DSPR2)
@@ -12125,7 +13330,7 @@ override_options (void)
   for (i = FP_REG_FIRST; i <= FP_REG_LAST; i++)
     mips_dbx_regno[i] = i + start;
 
-  /* HI and LO debug registers use big-endian ordering.  */
+  /* 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;
@@ -12136,80 +13341,11 @@ override_options (void)
       mips_dwarf_regno[i + TARGET_BIG_ENDIAN] = i + 1;
     }
 
-  /* Set up array giving whether a given register can hold a given mode.  */
-
-  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);
-
-      for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
-       {
-         register int temp;
-
-         if (mode == CCV2mode)
-           temp = (ISA_HAS_8CC
-                   && ST_REG_P (regno)
-                   && (regno - ST_REG_FIRST) % 2 == 0);
-
-         else if (mode == CCV4mode)
-           temp = (ISA_HAS_8CC
-                   && ST_REG_P (regno)
-                   && (regno - ST_REG_FIRST) % 4 == 0);
-
-         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));
-           }
-
-         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;
-
-         mips_hard_regno_mode_ok[(int)mode][regno] = temp;
-       }
-    }
-
-  /* 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;
+  /* 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);
 
   /* Function to allocate machine-dependent function status.  */
   init_machine_status = &mips_init_machine_status;
@@ -12227,9 +13363,8 @@ override_options (void)
     target_flags |= MASK_FIX_R4400;
 
   /* Save base state of options.  */
-  mips_base_mips16 = TARGET_MIPS16;
   mips_base_target_flags = target_flags;
-  mips_flag_delayed_branch = flag_delayed_branch;
+  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;
@@ -12237,8 +13372,14 @@ override_options (void)
   mips_base_align_jumps = align_jumps;
   mips_base_align_functions = align_functions;
 
-  /* Now select the mips16 or 32-bit instruction set, as requested.  */
-  mips_set_mips16_mode (mips_base_mips16);
+  /* Now select the ISA mode.
+
+     Do all CPP-sensitive stuff in non-MIPS16 mode; we'll switch to
+     MIPS16 mode afterwards if need be.  */
+  mips_set_mips16_mode (false);
+
+  /* We call dbr_schedule from within mips_reorg.  */
+  flag_delayed_branch = 0;
 }
 
 /* Swap the register information for registers I and I + 1, which
@@ -12289,15 +13430,15 @@ mips_conditional_register_usage (void)
     {
       int regno;
 
-      /* 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.  */
+      /* 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;
     }
-  /* In mips16 mode, we permit the $t temporary registers to be used
+  /* 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
+     are call-saved, and saving them via a MIPS16 register would
      probably waste more time than just reloading the value.  */
   if (TARGET_MIPS16)
     {
@@ -12311,14 +13452,15 @@ mips_conditional_register_usage (void)
       fixed_regs[27] = call_used_regs[27] = 1;
       fixed_regs[30] = call_used_regs[30] = 1;
     }
-  /* fp20-23 are now caller saved.  */
+  /* $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 from fp21 to fp31 are now caller saved.  */
+  /* Odd registers in the range $f21-$f31 (inclusive) are call-clobbered
+     for n32.  */
   if (mips_abi == ABI_N32)
     {
       int regno;
@@ -12329,22 +13471,47 @@ mips_conditional_register_usage (void)
      ordered for the current endianness.  */
   if (TARGET_LITTLE_ENDIAN)
     {
-      int regno;
+      unsigned 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);
     }
 }
 
-/* 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.  */
+/* Initialize vector TARGET to VALS.  */
+
+void
+mips_expand_vector_init (rtx target, rtx vals)
+{
+  enum machine_mode mode;
+  enum machine_mode inner;
+  unsigned int i, n_elts;
+  rtx mem;
+
+  mode = GET_MODE (target);
+  inner = GET_MODE_INNER (mode);
+  n_elts = GET_MODE_NUNITS (mode);
+
+  gcc_assert (VECTOR_MODE_P (mode));
+
+  mem = assign_stack_temp (mode, GET_MODE_SIZE (mode), 0);
+  for (i = 0; i < n_elts; i++)
+    emit_move_insn (adjust_address_nv (mem, inner, i * GET_MODE_SIZE (inner)),
+                    XVECEXP (vals, 0, i));
+
+  emit_move_insn (target, mem);
+}
+
+/* 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.  */
 
 void
 mips_order_regs_for_local_alloc (void)
 {
-  register int i;
+  int i;
 
   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
     reg_alloc_order[i] = i;
@@ -12387,6 +13554,10 @@ mips_order_regs_for_local_alloc (void)
 #define TARGET_SCHED_ADJUST_COST mips_adjust_cost
 #undef TARGET_SCHED_ISSUE_RATE
 #define TARGET_SCHED_ISSUE_RATE mips_issue_rate
+#undef TARGET_SCHED_INIT_DFA_POST_CYCLE_INSN
+#define TARGET_SCHED_INIT_DFA_POST_CYCLE_INSN mips_init_dfa_post_cycle_insn
+#undef TARGET_SCHED_DFA_POST_ADVANCE_CYCLE
+#define TARGET_SCHED_DFA_POST_ADVANCE_CYCLE mips_dfa_post_advance_cycle
 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD \
   mips_multipass_dfa_lookahead
@@ -12435,6 +13606,8 @@ mips_order_regs_for_local_alloc (void)
 
 #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