OSDN Git Service

* config/arm/arm.c, config/arm/arm.h, config/arm/arm.md,
[pf3gnuchains/gcc-fork.git] / gcc / config / mips / mips.c
1 /* Subroutines used for MIPS code generation.
2    Copyright (C) 1989, 1990, 1991, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4    Contributed by A. Lichnewsky, lich@inria.inria.fr.
5    Changes by Michael Meissner, meissner@osf.org.
6    64 bit r4000 support by Ian Lance Taylor, ian@cygnus.com, and
7    Brendan Eich, brendan@microunity.com.
8
9 This file is part of GCC.
10
11 GCC is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2, or (at your option)
14 any later version.
15
16 GCC is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with GCC; see the file COPYING.  If not, write to
23 the Free Software Foundation, 59 Temple Place - Suite 330,
24 Boston, MA 02111-1307, USA.  */
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tm.h"
30 #include <signal.h>
31 #include "rtl.h"
32 #include "regs.h"
33 #include "hard-reg-set.h"
34 #include "real.h"
35 #include "insn-config.h"
36 #include "conditions.h"
37 #include "insn-attr.h"
38 #include "recog.h"
39 #include "toplev.h"
40 #include "output.h"
41 #include "tree.h"
42 #include "function.h"
43 #include "expr.h"
44 #include "optabs.h"
45 #include "flags.h"
46 #include "reload.h"
47 #include "tm_p.h"
48 #include "ggc.h"
49 #include "gstab.h"
50 #include "hashtab.h"
51 #include "debug.h"
52 #include "target.h"
53 #include "target-def.h"
54 #include "integrate.h"
55 #include "langhooks.h"
56 #include "cfglayout.h"
57
58 /* Enumeration for all of the relational tests, so that we can build
59    arrays indexed by the test type, and not worry about the order
60    of EQ, NE, etc.  */
61
62 enum internal_test {
63   ITEST_EQ,
64   ITEST_NE,
65   ITEST_GT,
66   ITEST_GE,
67   ITEST_LT,
68   ITEST_LE,
69   ITEST_GTU,
70   ITEST_GEU,
71   ITEST_LTU,
72   ITEST_LEU,
73   ITEST_MAX
74 };
75
76 /* Return true if it is likely that the given mode will be accessed
77    using only a single instruction.  */
78 #define SINGLE_WORD_MODE_P(MODE) \
79   ((MODE) != BLKmode && GET_MODE_SIZE (MODE) <= UNITS_PER_WORD)
80
81 /* True if X is an unspec wrapper around a SYMBOL_REF or LABEL_REF.  */
82 #define UNSPEC_ADDRESS_P(X)                                     \
83   (GET_CODE (X) == UNSPEC                                       \
84    && XINT (X, 1) >= UNSPEC_ADDRESS_FIRST                       \
85    && XINT (X, 1) < UNSPEC_ADDRESS_FIRST + NUM_SYMBOL_TYPES)
86
87 /* Extract the symbol or label from UNSPEC wrapper X.  */
88 #define UNSPEC_ADDRESS(X) \
89   XVECEXP (X, 0, 0)
90
91 /* Extract the symbol type from UNSPEC wrapper X.  */
92 #define UNSPEC_ADDRESS_TYPE(X) \
93   ((enum mips_symbol_type) (XINT (X, 1) - UNSPEC_ADDRESS_FIRST))
94
95 /* True if X is (const $gp).  This is used to initialize the mips16
96    gp pseudo register.  */
97 #define CONST_GP_P(X) \
98   (GET_CODE (X) == CONST && XEXP (X, 0) == pic_offset_table_rtx)
99
100 /* The maximum distance between the top of the stack frame and the
101    value $sp has when we save & restore registers.
102
103    Use a maximum gap of 0x100 in the mips16 case.  We can then use
104    unextended instructions to save and restore registers, and to
105    allocate and deallocate the top part of the frame.
106
107    The value in the !mips16 case must be a SMALL_OPERAND and must
108    preserve the maximum stack alignment.  It could really be 0x7ff0,
109    but SGI's assemblers implement daddiu $sp,$sp,-0x7ff0 as a
110    multi-instruction addu sequence.  Use 0x7fe0 to work around this.  */
111 #define MIPS_MAX_FIRST_STACK_STEP (TARGET_MIPS16 ? 0x100 : 0x7fe0)
112
113 /* Classifies a SYMBOL_REF, LABEL_REF or UNSPEC address.
114
115    SYMBOL_GENERAL
116        Used when none of the below apply.
117
118    SYMBOL_SMALL_DATA
119        The symbol refers to something in a small data section.
120
121    SYMBOL_CONSTANT_POOL
122        The symbol refers to something in the mips16 constant pool.
123
124    SYMBOL_GOT_LOCAL
125        The symbol refers to local data that will be found using
126        the global offset table.
127
128    SYMBOL_GOT_GLOBAL
129        Likewise non-local data.
130
131    SYMBOL_GOTOFF_PAGE
132        An UNSPEC wrapper around a SYMBOL_GOT_LOCAL.  It represents the
133        offset from _gp of a GOT page entry.
134
135    SYMBOL_GOTOFF_GLOBAL
136        An UNSPEC wrapper around a SYMBOL_GOT_GLOBAL.  It represents the
137        the offset from _gp of the symbol's GOT entry.
138
139    SYMBOL_GOTOFF_CALL
140        Like SYMBOL_GOTOFF_GLOBAL, but used when calling a global function.
141        The GOT entry is allowed to point to a stub rather than to the
142        function itself.
143
144    SYMBOL_GOTOFF_LOADGP
145        An UNSPEC wrapper around a function's address.  It represents the
146        offset of _gp from the start of the function.  */
147 enum mips_symbol_type {
148   SYMBOL_GENERAL,
149   SYMBOL_SMALL_DATA,
150   SYMBOL_CONSTANT_POOL,
151   SYMBOL_GOT_LOCAL,
152   SYMBOL_GOT_GLOBAL,
153   SYMBOL_GOTOFF_PAGE,
154   SYMBOL_GOTOFF_GLOBAL,
155   SYMBOL_GOTOFF_CALL,
156   SYMBOL_GOTOFF_LOADGP
157 };
158 #define NUM_SYMBOL_TYPES (SYMBOL_GOTOFF_LOADGP + 1)
159
160
161 /* Classifies an address.
162
163    ADDRESS_REG
164        A natural register + offset address.  The register satisfies
165        mips_valid_base_register_p and the offset is a const_arith_operand.
166
167    ADDRESS_LO_SUM
168        A LO_SUM rtx.  The first operand is a valid base register and
169        the second operand is a symbolic address.
170
171    ADDRESS_CONST_INT
172        A signed 16-bit constant address.
173
174    ADDRESS_SYMBOLIC:
175        A constant symbolic address (equivalent to CONSTANT_SYMBOLIC).  */
176 enum mips_address_type {
177   ADDRESS_REG,
178   ADDRESS_LO_SUM,
179   ADDRESS_CONST_INT,
180   ADDRESS_SYMBOLIC
181 };
182
183 /* A function to save or store a register.  The first argument is the
184    register and the second is the stack slot.  */
185 typedef void (*mips_save_restore_fn) (rtx, rtx);
186
187 struct constant;
188 struct mips_arg_info;
189 struct mips_address_info;
190 struct mips_integer_op;
191
192 static enum mips_symbol_type mips_classify_symbol (rtx);
193 static void mips_split_const (rtx, rtx *, HOST_WIDE_INT *);
194 static bool mips_offset_within_object_p (rtx, HOST_WIDE_INT);
195 static bool mips_symbolic_constant_p (rtx, enum mips_symbol_type *);
196 static bool mips_valid_base_register_p (rtx, enum machine_mode, int);
197 static bool mips_symbolic_address_p (enum mips_symbol_type, enum machine_mode);
198 static bool mips_classify_address (struct mips_address_info *, rtx,
199                                    enum machine_mode, int);
200 static int mips_symbol_insns (enum mips_symbol_type);
201 static bool mips16_unextended_reference_p (enum machine_mode mode, rtx, rtx);
202 static rtx mips_force_temporary (rtx, rtx);
203 static rtx mips_split_symbol (rtx, rtx);
204 static rtx mips_unspec_address (rtx, enum mips_symbol_type);
205 static rtx mips_unspec_offset_high (rtx, rtx, rtx, enum mips_symbol_type);
206 static rtx mips_load_got (rtx, rtx, enum mips_symbol_type);
207 static rtx mips_add_offset (rtx, HOST_WIDE_INT);
208 static unsigned int mips_build_shift (struct mips_integer_op *, HOST_WIDE_INT);
209 static unsigned int mips_build_lower (struct mips_integer_op *,
210                                       unsigned HOST_WIDE_INT);
211 static unsigned int mips_build_integer (struct mips_integer_op *,
212                                         unsigned HOST_WIDE_INT);
213 static void mips_move_integer (rtx, unsigned HOST_WIDE_INT);
214 static void mips_legitimize_const_move (enum machine_mode, rtx, rtx);
215 static int m16_check_op (rtx, int, int, int);
216 static bool mips_rtx_costs (rtx, int, int, int *);
217 static int mips_address_cost (rtx);
218 static enum internal_test map_test_to_internal_test (enum rtx_code);
219 static void get_float_compare_codes (enum rtx_code, enum rtx_code *,
220                                      enum rtx_code *);
221 static void mips_load_call_address (rtx, rtx, int);
222 static bool mips_function_ok_for_sibcall (tree, tree);
223 static void mips_block_move_straight (rtx, rtx, HOST_WIDE_INT);
224 static void mips_adjust_block_mem (rtx, HOST_WIDE_INT, rtx *, rtx *);
225 static void mips_block_move_loop (rtx, rtx, HOST_WIDE_INT);
226 static void mips_arg_info (const CUMULATIVE_ARGS *, enum machine_mode,
227                            tree, int, struct mips_arg_info *);
228 static bool mips_get_unaligned_mem (rtx *, unsigned int, int, rtx *, rtx *);
229 static void mips_set_architecture (const struct mips_cpu_info *);
230 static void mips_set_tune (const struct mips_cpu_info *);
231 static struct machine_function *mips_init_machine_status (void);
232 static void print_operand_reloc (FILE *, rtx, const char **);
233 static bool mips_assemble_integer (rtx, unsigned int, int);
234 static void mips_file_start (void);
235 static void mips_file_end (void);
236 static bool mips_rewrite_small_data_p (rtx);
237 static int small_data_pattern_1 (rtx *, void *);
238 static int mips_rewrite_small_data_1 (rtx *, void *);
239 static bool mips_function_has_gp_insn (void);
240 static unsigned int mips_global_pointer (void);
241 static bool mips_save_reg_p (unsigned int);
242 static void mips_save_restore_reg (enum machine_mode, int, HOST_WIDE_INT,
243                                    mips_save_restore_fn);
244 static void mips_for_each_saved_reg (HOST_WIDE_INT, mips_save_restore_fn);
245 static void mips_output_cplocal (void);
246 static void mips_emit_loadgp (void);
247 static void mips_output_function_prologue (FILE *, HOST_WIDE_INT);
248 static void mips_set_frame_expr (rtx);
249 static rtx mips_frame_set (rtx, rtx);
250 static void mips_save_reg (rtx, rtx);
251 static void mips_output_function_epilogue (FILE *, HOST_WIDE_INT);
252 static void mips_restore_reg (rtx, rtx);
253 static void mips_output_mi_thunk (FILE *, tree, HOST_WIDE_INT,
254                                   HOST_WIDE_INT, tree);
255 static int symbolic_expression_p (rtx);
256 static void mips_select_rtx_section (enum machine_mode, rtx,
257                                      unsigned HOST_WIDE_INT);
258 static void mips_select_section (tree, int, unsigned HOST_WIDE_INT)
259                                   ATTRIBUTE_UNUSED;
260 static bool mips_in_small_data_p (tree);
261 static void mips_encode_section_info (tree, rtx, int);
262 static int mips_fpr_return_fields (tree, tree *);
263 static bool mips_return_in_msb (tree);
264 static rtx mips_return_fpr_pair (enum machine_mode mode,
265                                  enum machine_mode mode1, HOST_WIDE_INT,
266                                  enum machine_mode mode2, HOST_WIDE_INT);
267 static rtx mips16_gp_pseudo_reg (void);
268 static void mips16_fp_args (FILE *, int, int);
269 static void build_mips16_function_stub (FILE *);
270 static rtx add_constant (struct constant **, rtx, enum machine_mode);
271 static void dump_constants (struct constant *, rtx);
272 static rtx mips_find_symbol (rtx);
273 static void mips16_lay_out_constants (void);
274 static void mips_avoid_hazard (rtx, rtx, int *, rtx *, rtx);
275 static void mips_avoid_hazards (void);
276 static void mips_reorg (void);
277 static bool mips_strict_matching_cpu_name_p (const char *, const char *);
278 static bool mips_matching_cpu_name_p (const char *, const char *);
279 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
280 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
281 static int mips_adjust_cost (rtx, rtx, rtx, int);
282 static bool mips_return_in_memory (tree, tree);
283 static bool mips_strict_argument_naming (CUMULATIVE_ARGS *);
284 static int mips_issue_rate (void);
285 static int mips_use_dfa_pipeline_interface (void);
286 static void mips_init_libfuncs (void);
287 static void mips_setup_incoming_varargs (CUMULATIVE_ARGS *, enum machine_mode,
288                                          tree, int *, int);
289 static tree mips_build_builtin_va_list (void);
290
291 #if TARGET_IRIX
292 static void irix_asm_named_section_1 (const char *, unsigned int,
293                                       unsigned int);
294 static void irix_asm_named_section (const char *, unsigned int);
295 static int irix_section_align_entry_eq (const void *, const void *);
296 static hashval_t irix_section_align_entry_hash (const void *);
297 static void irix_file_start (void);
298 static int irix_section_align_1 (void **, void *);
299 static void copy_file_data (FILE *, FILE *);
300 static void irix_file_end (void);
301 static unsigned int irix_section_type_flags (tree, const char *, int);
302 #endif
303
304 /* Structure to be filled in by compute_frame_size with register
305    save masks, and offsets for the current function.  */
306
307 struct mips_frame_info GTY(())
308 {
309   HOST_WIDE_INT total_size;     /* # bytes that the entire frame takes up */
310   HOST_WIDE_INT var_size;       /* # bytes that variables take up */
311   HOST_WIDE_INT args_size;      /* # bytes that outgoing arguments take up */
312   HOST_WIDE_INT cprestore_size; /* # bytes that the .cprestore slot takes up */
313   HOST_WIDE_INT gp_reg_size;    /* # bytes needed to store gp regs */
314   HOST_WIDE_INT fp_reg_size;    /* # bytes needed to store fp regs */
315   unsigned int mask;            /* mask of saved gp registers */
316   unsigned int fmask;           /* mask of saved fp registers */
317   HOST_WIDE_INT gp_save_offset; /* offset from vfp to store gp registers */
318   HOST_WIDE_INT fp_save_offset; /* offset from vfp to store fp registers */
319   HOST_WIDE_INT gp_sp_offset;   /* offset from new sp to store gp registers */
320   HOST_WIDE_INT fp_sp_offset;   /* offset from new sp to store fp registers */
321   bool initialized;             /* true if frame size already calculated */
322   int num_gp;                   /* number of gp registers saved */
323   int num_fp;                   /* number of fp registers saved */
324 };
325
326 struct machine_function GTY(()) {
327   /* Pseudo-reg holding the address of the current function when
328      generating embedded PIC code.  */
329   rtx embedded_pic_fnaddr_rtx;
330
331   /* Pseudo-reg holding the value of $28 in a mips16 function which
332      refers to GP relative global variables.  */
333   rtx mips16_gp_pseudo_rtx;
334
335   /* Current frame information, calculated by compute_frame_size.  */
336   struct mips_frame_info frame;
337
338   /* Length of instructions in function; mips16 only.  */
339   long insns_len;
340
341   /* The register to use as the global pointer within this function.  */
342   unsigned int global_pointer;
343
344   /* True if mips_adjust_insn_length should ignore an instruction's
345      hazard attribute.  */
346   bool ignore_hazard_length_p;
347
348   /* True if the whole function is suitable for .set noreorder and
349      .set nomacro.  */
350   bool all_noreorder_p;
351
352   /* True if the function is known to have an instruction that needs $gp.  */
353   bool has_gp_insn_p;
354 };
355
356 /* Information about a single argument.  */
357 struct mips_arg_info
358 {
359   /* True if the argument is passed in a floating-point register, or
360      would have been if we hadn't run out of registers.  */
361   bool fpr_p;
362
363   /* The argument's size, in bytes.  */
364   unsigned int num_bytes;
365
366   /* The number of words passed in registers, rounded up.  */
367   unsigned int reg_words;
368
369   /* The offset of the first register from GP_ARG_FIRST or FP_ARG_FIRST,
370      or MAX_ARGS_IN_REGISTERS if the argument is passed entirely
371      on the stack.  */
372   unsigned int reg_offset;
373
374   /* The number of words that must be passed on the stack, rounded up.  */
375   unsigned int stack_words;
376
377   /* The offset from the start of the stack overflow area of the argument's
378      first stack word.  Only meaningful when STACK_WORDS is nonzero.  */
379   unsigned int stack_offset;
380 };
381
382
383 /* Information about an address described by mips_address_type.
384
385    ADDRESS_CONST_INT
386        No fields are used.
387
388    ADDRESS_REG
389        REG is the base register and OFFSET is the constant offset.
390
391    ADDRESS_LO_SUM
392        REG is the register that contains the high part of the address,
393        OFFSET is the symbolic address being referenced and SYMBOL_TYPE
394        is the type of OFFSET's symbol.
395
396    ADDRESS_SYMBOLIC
397        SYMBOL_TYPE is the type of symbol being referenced.  */
398
399 struct mips_address_info
400 {
401   enum mips_address_type type;
402   rtx reg;
403   rtx offset;
404   enum mips_symbol_type symbol_type;
405 };
406
407
408 /* One stage in a constant building sequence.  These sequences have
409    the form:
410
411         A = VALUE[0]
412         A = A CODE[1] VALUE[1]
413         A = A CODE[2] VALUE[2]
414         ...
415
416    where A is an accumulator, each CODE[i] is a binary rtl operation
417    and each VALUE[i] is a constant integer.  */
418 struct mips_integer_op {
419   enum rtx_code code;
420   unsigned HOST_WIDE_INT value;
421 };
422
423
424 /* The largest number of operations needed to load an integer constant.
425    The worst accepted case for 64-bit constants is LUI,ORI,SLL,ORI,SLL,ORI.
426    When the lowest bit is clear, we can try, but reject a sequence with
427    an extra SLL at the end.  */
428 #define MIPS_MAX_INTEGER_OPS 7
429
430
431 /* Global variables for machine-dependent things.  */
432
433 /* Threshold for data being put into the small data/bss area, instead
434    of the normal data area.  */
435 int mips_section_threshold = -1;
436
437 /* Count the number of .file directives, so that .loc is up to date.  */
438 int num_source_filenames = 0;
439
440 /* Count the number of sdb related labels are generated (to find block
441    start and end boundaries).  */
442 int sdb_label_count = 0;
443
444 /* Next label # for each statement for Silicon Graphics IRIS systems.  */
445 int sym_lineno = 0;
446
447 /* Linked list of all externals that are to be emitted when optimizing
448    for the global pointer if they haven't been declared by the end of
449    the program with an appropriate .comm or initialization.  */
450
451 struct extern_list GTY (())
452 {
453   struct extern_list *next;     /* next external */
454   const char *name;             /* name of the external */
455   int size;                     /* size in bytes */
456 };
457
458 static GTY (()) struct extern_list *extern_head = 0;
459
460 /* Name of the file containing the current function.  */
461 const char *current_function_file = "";
462
463 /* Number of nested .set noreorder, noat, nomacro, and volatile requests.  */
464 int set_noreorder;
465 int set_noat;
466 int set_nomacro;
467 int set_volatile;
468
469 /* The next branch instruction is a branch likely, not branch normal.  */
470 int mips_branch_likely;
471
472 /* Cached operands, and operator to compare for use in set/branch/trap
473    on condition codes.  */
474 rtx branch_cmp[2];
475
476 /* what type of branch to use */
477 enum cmp_type branch_type;
478
479 /* The target cpu for code generation.  */
480 enum processor_type mips_arch;
481 const struct mips_cpu_info *mips_arch_info;
482
483 /* The target cpu for optimization and scheduling.  */
484 enum processor_type mips_tune;
485 const struct mips_cpu_info *mips_tune_info;
486
487 /* Which instruction set architecture to use.  */
488 int mips_isa;
489
490 /* Which ABI to use.  */
491 int mips_abi;
492
493 /* Strings to hold which cpu and instruction set architecture to use.  */
494 const char *mips_arch_string;   /* for -march=<xxx> */
495 const char *mips_tune_string;   /* for -mtune=<xxx> */
496 const char *mips_isa_string;    /* for -mips{1,2,3,4} */
497 const char *mips_abi_string;    /* for -mabi={32,n32,64,eabi} */
498
499 /* Whether we are generating mips16 hard float code.  In mips16 mode
500    we always set TARGET_SOFT_FLOAT; this variable is nonzero if
501    -msoft-float was not specified by the user, which means that we
502    should arrange to call mips32 hard floating point code.  */
503 int mips16_hard_float;
504
505 const char *mips_cache_flush_func = CACHE_FLUSH_FUNC;
506
507 /* If TRUE, we split addresses into their high and low parts in the RTL.  */
508 int mips_split_addresses;
509
510 /* Mode used for saving/restoring general purpose registers.  */
511 static enum machine_mode gpr_mode;
512
513 /* Array giving truth value on whether or not a given hard register
514    can support a given mode.  */
515 char mips_hard_regno_mode_ok[(int)MAX_MACHINE_MODE][FIRST_PSEUDO_REGISTER];
516
517 /* The length of all strings seen when compiling for the mips16.  This
518    is used to tell how many strings are in the constant pool, so that
519    we can see if we may have an overflow.  This is reset each time the
520    constant pool is output.  */
521 int mips_string_length;
522
523 /* When generating mips16 code, a list of all strings that are to be
524    output after the current function.  */
525
526 static GTY(()) rtx mips16_strings;
527
528 /* In mips16 mode, we build a list of all the string constants we see
529    in a particular function.  */
530
531 struct string_constant
532 {
533   struct string_constant *next;
534   const char *label;
535 };
536
537 static struct string_constant *string_constants;
538
539 /* List of all MIPS punctuation characters used by print_operand.  */
540 char mips_print_operand_punct[256];
541
542 /* Map GCC register number to debugger register number.  */
543 int mips_dbx_regno[FIRST_PSEUDO_REGISTER];
544
545 /* An alias set for the GOT.  */
546 static GTY(()) int mips_got_alias_set;
547
548 /* A copy of the original flag_delayed_branch: see override_options.  */
549 static int mips_flag_delayed_branch;
550
551 static GTY (()) int mips_output_filename_first_time = 1;
552
553 /* mips_split_p[X] is true if symbols of type X can be split by
554    mips_split_symbol().  */
555 static bool mips_split_p[NUM_SYMBOL_TYPES];
556
557 /* mips_lo_relocs[X] is the relocation to use when a symbol of type X
558    appears in a LO_SUM.  It can be null if such LO_SUMs aren't valid or
559    if they are matched by a special .md file pattern.  */
560 static const char *mips_lo_relocs[NUM_SYMBOL_TYPES];
561
562 /* Likewise for HIGHs.  */
563 static const char *mips_hi_relocs[NUM_SYMBOL_TYPES];
564
565 /* Hardware names for the registers.  If -mrnames is used, this
566    will be overwritten with mips_sw_reg_names.  */
567
568 char mips_reg_names[][8] =
569 {
570  "$0",   "$1",   "$2",   "$3",   "$4",   "$5",   "$6",   "$7",
571  "$8",   "$9",   "$10",  "$11",  "$12",  "$13",  "$14",  "$15",
572  "$16",  "$17",  "$18",  "$19",  "$20",  "$21",  "$22",  "$23",
573  "$24",  "$25",  "$26",  "$27",  "$28",  "$sp",  "$fp",  "$31",
574  "$f0",  "$f1",  "$f2",  "$f3",  "$f4",  "$f5",  "$f6",  "$f7",
575  "$f8",  "$f9",  "$f10", "$f11", "$f12", "$f13", "$f14", "$f15",
576  "$f16", "$f17", "$f18", "$f19", "$f20", "$f21", "$f22", "$f23",
577  "$f24", "$f25", "$f26", "$f27", "$f28", "$f29", "$f30", "$f31",
578  "hi",   "lo",   "",     "$fcc0","$fcc1","$fcc2","$fcc3","$fcc4",
579  "$fcc5","$fcc6","$fcc7","", "", "$arg", "$frame", "$fakec",
580  "$c0r0", "$c0r1", "$c0r2", "$c0r3", "$c0r4", "$c0r5", "$c0r6", "$c0r7",
581  "$c0r8", "$c0r9", "$c0r10","$c0r11","$c0r12","$c0r13","$c0r14","$c0r15",
582  "$c0r16","$c0r17","$c0r18","$c0r19","$c0r20","$c0r21","$c0r22","$c0r23",
583  "$c0r24","$c0r25","$c0r26","$c0r27","$c0r28","$c0r29","$c0r30","$c0r31",
584  "$c2r0", "$c2r1", "$c2r2", "$c2r3", "$c2r4", "$c2r5", "$c2r6", "$c2r7",
585  "$c2r8", "$c2r9", "$c2r10","$c2r11","$c2r12","$c2r13","$c2r14","$c2r15",
586  "$c2r16","$c2r17","$c2r18","$c2r19","$c2r20","$c2r21","$c2r22","$c2r23",
587  "$c2r24","$c2r25","$c2r26","$c2r27","$c2r28","$c2r29","$c2r30","$c2r31",
588  "$c3r0", "$c3r1", "$c3r2", "$c3r3", "$c3r4", "$c3r5", "$c3r6", "$c3r7",
589  "$c3r8", "$c3r9", "$c3r10","$c3r11","$c3r12","$c3r13","$c3r14","$c3r15",
590  "$c3r16","$c3r17","$c3r18","$c3r19","$c3r20","$c3r21","$c3r22","$c3r23",
591  "$c3r24","$c3r25","$c3r26","$c3r27","$c3r28","$c3r29","$c3r30","$c3r31"
592 };
593
594 /* Mips software names for the registers, used to overwrite the
595    mips_reg_names array.  */
596
597 char mips_sw_reg_names[][8] =
598 {
599   "$zero","$at",  "$v0",  "$v1",  "$a0",  "$a1",  "$a2",  "$a3",
600   "$t0",  "$t1",  "$t2",  "$t3",  "$t4",  "$t5",  "$t6",  "$t7",
601   "$s0",  "$s1",  "$s2",  "$s3",  "$s4",  "$s5",  "$s6",  "$s7",
602   "$t8",  "$t9",  "$k0",  "$k1",  "$gp",  "$sp",  "$fp",  "$ra",
603   "$f0",  "$f1",  "$f2",  "$f3",  "$f4",  "$f5",  "$f6",  "$f7",
604   "$f8",  "$f9",  "$f10", "$f11", "$f12", "$f13", "$f14", "$f15",
605   "$f16", "$f17", "$f18", "$f19", "$f20", "$f21", "$f22", "$f23",
606   "$f24", "$f25", "$f26", "$f27", "$f28", "$f29", "$f30", "$f31",
607   "hi",   "lo",   "",     "$fcc0","$fcc1","$fcc2","$fcc3","$fcc4",
608   "$fcc5","$fcc6","$fcc7","$rap", "", "$arg", "$frame", "$fakec",
609   "$c0r0", "$c0r1", "$c0r2", "$c0r3", "$c0r4", "$c0r5", "$c0r6", "$c0r7",
610   "$c0r8", "$c0r9", "$c0r10","$c0r11","$c0r12","$c0r13","$c0r14","$c0r15",
611   "$c0r16","$c0r17","$c0r18","$c0r19","$c0r20","$c0r21","$c0r22","$c0r23",
612   "$c0r24","$c0r25","$c0r26","$c0r27","$c0r28","$c0r29","$c0r30","$c0r31",
613   "$c2r0", "$c2r1", "$c2r2", "$c2r3", "$c2r4", "$c2r5", "$c2r6", "$c2r7",
614   "$c2r8", "$c2r9", "$c2r10","$c2r11","$c2r12","$c2r13","$c2r14","$c2r15",
615   "$c2r16","$c2r17","$c2r18","$c2r19","$c2r20","$c2r21","$c2r22","$c2r23",
616   "$c2r24","$c2r25","$c2r26","$c2r27","$c2r28","$c2r29","$c2r30","$c2r31",
617   "$c3r0", "$c3r1", "$c3r2", "$c3r3", "$c3r4", "$c3r5", "$c3r6", "$c3r7",
618   "$c3r8", "$c3r9", "$c3r10","$c3r11","$c3r12","$c3r13","$c3r14","$c3r15",
619   "$c3r16","$c3r17","$c3r18","$c3r19","$c3r20","$c3r21","$c3r22","$c3r23",
620   "$c3r24","$c3r25","$c3r26","$c3r27","$c3r28","$c3r29","$c3r30","$c3r31"
621 };
622
623 /* Map hard register number to register class */
624 const enum reg_class mips_regno_to_class[] =
625 {
626   LEA_REGS,     LEA_REGS,       M16_NA_REGS,    M16_NA_REGS,
627   M16_REGS,     M16_REGS,       M16_REGS,       M16_REGS,
628   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
629   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
630   M16_NA_REGS,  M16_NA_REGS,    LEA_REGS,       LEA_REGS,
631   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
632   T_REG,        PIC_FN_ADDR_REG, LEA_REGS,      LEA_REGS,
633   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
634   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
635   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
636   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
637   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
638   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
639   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
640   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
641   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
642   HI_REG,       LO_REG,         NO_REGS,        ST_REGS,
643   ST_REGS,      ST_REGS,        ST_REGS,        ST_REGS,
644   ST_REGS,      ST_REGS,        ST_REGS,        NO_REGS,
645   NO_REGS,      ALL_REGS,       ALL_REGS,       NO_REGS,
646   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
647   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
648   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
649   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
650   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
651   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
652   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
653   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
654   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
655   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
656   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
657   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
658   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
659   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
660   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
661   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
662   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
663   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
664   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
665   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
666   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
667   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
668   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
669   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS
670 };
671
672 /* Map register constraint character to register class.  */
673 enum reg_class mips_char_to_class[256];
674 \f
675 /* A table describing all the processors gcc knows about.  Names are
676    matched in the order listed.  The first mention of an ISA level is
677    taken as the canonical name for that ISA.
678
679    To ease comparison, please keep this table in the same order as
680    gas's mips_cpu_info_table[].  */
681 const struct mips_cpu_info mips_cpu_info_table[] = {
682   /* Entries for generic ISAs */
683   { "mips1", PROCESSOR_R3000, 1 },
684   { "mips2", PROCESSOR_R6000, 2 },
685   { "mips3", PROCESSOR_R4000, 3 },
686   { "mips4", PROCESSOR_R8000, 4 },
687   { "mips32", PROCESSOR_4KC, 32 },
688   { "mips32r2", PROCESSOR_M4K, 33 },
689   { "mips64", PROCESSOR_5KC, 64 },
690
691   /* MIPS I */
692   { "r3000", PROCESSOR_R3000, 1 },
693   { "r2000", PROCESSOR_R3000, 1 }, /* = r3000 */
694   { "r3900", PROCESSOR_R3900, 1 },
695
696   /* MIPS II */
697   { "r6000", PROCESSOR_R6000, 2 },
698
699   /* MIPS III */
700   { "r4000", PROCESSOR_R4000, 3 },
701   { "vr4100", PROCESSOR_R4100, 3 },
702   { "vr4111", PROCESSOR_R4111, 3 },
703   { "vr4120", PROCESSOR_R4120, 3 },
704   { "vr4300", PROCESSOR_R4300, 3 },
705   { "r4400", PROCESSOR_R4000, 3 }, /* = r4000 */
706   { "r4600", PROCESSOR_R4600, 3 },
707   { "orion", PROCESSOR_R4600, 3 }, /* = r4600 */
708   { "r4650", PROCESSOR_R4650, 3 },
709
710   /* MIPS IV */
711   { "r8000", PROCESSOR_R8000, 4 },
712   { "vr5000", PROCESSOR_R5000, 4 },
713   { "vr5400", PROCESSOR_R5400, 4 },
714   { "vr5500", PROCESSOR_R5500, 4 },
715   { "rm7000", PROCESSOR_R7000, 4 },
716   { "rm9000", PROCESSOR_R9000, 4 },
717
718   /* MIPS32 */
719   { "4kc", PROCESSOR_4KC, 32 },
720   { "4kp", PROCESSOR_4KC, 32 }, /* = 4kc */
721
722   /* MIPS32 Release 2 */
723   { "m4k", PROCESSOR_M4K, 33 },
724
725   /* MIPS64 */
726   { "5kc", PROCESSOR_5KC, 64 },
727   { "20kc", PROCESSOR_20KC, 64 },
728   { "sb1", PROCESSOR_SB1, 64 },
729   { "sr71000", PROCESSOR_SR71000, 64 },
730
731   /* End marker */
732   { 0, 0, 0 }
733 };
734 \f
735 /* Nonzero if -march should decide the default value of MASK_SOFT_FLOAT.  */
736 #ifndef MIPS_MARCH_CONTROLS_SOFT_FLOAT
737 #define MIPS_MARCH_CONTROLS_SOFT_FLOAT 0
738 #endif
739 \f
740 /* Initialize the GCC target structure.  */
741 #undef TARGET_ASM_ALIGNED_HI_OP
742 #define TARGET_ASM_ALIGNED_HI_OP "\t.half\t"
743 #undef TARGET_ASM_ALIGNED_SI_OP
744 #define TARGET_ASM_ALIGNED_SI_OP "\t.word\t"
745 #undef TARGET_ASM_INTEGER
746 #define TARGET_ASM_INTEGER mips_assemble_integer
747
748 #undef TARGET_ASM_FUNCTION_PROLOGUE
749 #define TARGET_ASM_FUNCTION_PROLOGUE mips_output_function_prologue
750 #undef TARGET_ASM_FUNCTION_EPILOGUE
751 #define TARGET_ASM_FUNCTION_EPILOGUE mips_output_function_epilogue
752 #undef TARGET_ASM_SELECT_RTX_SECTION
753 #define TARGET_ASM_SELECT_RTX_SECTION mips_select_rtx_section
754
755 #undef TARGET_SCHED_ADJUST_COST
756 #define TARGET_SCHED_ADJUST_COST mips_adjust_cost
757 #undef TARGET_SCHED_ISSUE_RATE
758 #define TARGET_SCHED_ISSUE_RATE mips_issue_rate
759 #undef TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE
760 #define TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE mips_use_dfa_pipeline_interface
761
762 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
763 #define TARGET_FUNCTION_OK_FOR_SIBCALL mips_function_ok_for_sibcall
764
765 #undef TARGET_VALID_POINTER_MODE
766 #define TARGET_VALID_POINTER_MODE mips_valid_pointer_mode
767 #undef TARGET_RTX_COSTS
768 #define TARGET_RTX_COSTS mips_rtx_costs
769 #undef TARGET_ADDRESS_COST
770 #define TARGET_ADDRESS_COST mips_address_cost
771
772 #undef TARGET_ENCODE_SECTION_INFO
773 #define TARGET_ENCODE_SECTION_INFO mips_encode_section_info
774 #undef TARGET_IN_SMALL_DATA_P
775 #define TARGET_IN_SMALL_DATA_P mips_in_small_data_p
776
777 #undef TARGET_MACHINE_DEPENDENT_REORG
778 #define TARGET_MACHINE_DEPENDENT_REORG mips_reorg
779
780 #undef TARGET_ASM_FILE_START
781 #undef TARGET_ASM_FILE_END
782 #if TARGET_IRIX
783 #define TARGET_ASM_FILE_START irix_file_start
784 #define TARGET_ASM_FILE_END irix_file_end
785 #else
786 #define TARGET_ASM_FILE_START mips_file_start
787 #define TARGET_ASM_FILE_END mips_file_end
788 #endif
789 #undef TARGET_ASM_FILE_START_FILE_DIRECTIVE
790 #define TARGET_ASM_FILE_START_FILE_DIRECTIVE true
791
792 #if TARGET_IRIX
793 #undef TARGET_SECTION_TYPE_FLAGS
794 #define TARGET_SECTION_TYPE_FLAGS irix_section_type_flags
795 #endif
796
797 #undef TARGET_INIT_LIBFUNCS
798 #define TARGET_INIT_LIBFUNCS mips_init_libfuncs
799
800 #undef TARGET_BUILD_BUILTIN_VA_LIST
801 #define TARGET_BUILD_BUILTIN_VA_LIST mips_build_builtin_va_list
802
803 #undef TARGET_PROMOTE_FUNCTION_ARGS
804 #define TARGET_PROMOTE_FUNCTION_ARGS hook_bool_tree_true
805 #undef TARGET_PROMOTE_FUNCTION_RETURN
806 #define TARGET_PROMOTE_FUNCTION_RETURN hook_bool_tree_true
807 #undef TARGET_PROMOTE_PROTOTYPES
808 #define TARGET_PROMOTE_PROTOTYPES hook_bool_tree_true
809
810 #undef TARGET_STRUCT_VALUE_RTX
811 #define TARGET_STRUCT_VALUE_RTX hook_rtx_tree_int_null
812 #undef TARGET_RETURN_IN_MEMORY
813 #define TARGET_RETURN_IN_MEMORY mips_return_in_memory
814 #undef TARGET_RETURN_IN_MSB
815 #define TARGET_RETURN_IN_MSB mips_return_in_msb
816
817 #undef TARGET_ASM_OUTPUT_MI_THUNK
818 #define TARGET_ASM_OUTPUT_MI_THUNK mips_output_mi_thunk
819 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
820 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_tree_hwi_hwi_tree_true
821
822 #undef TARGET_SETUP_INCOMING_VARARGS
823 #define TARGET_SETUP_INCOMING_VARARGS mips_setup_incoming_varargs
824 #undef TARGET_STRICT_ARGUMENT_NAMING
825 #define TARGET_STRICT_ARGUMENT_NAMING mips_strict_argument_naming
826
827 struct gcc_target targetm = TARGET_INITIALIZER;
828 \f
829 /* Classify symbol X, which must be a SYMBOL_REF or a LABEL_REF.  */
830
831 static enum mips_symbol_type
832 mips_classify_symbol (rtx x)
833 {
834   if (GET_CODE (x) == LABEL_REF)
835     return (TARGET_ABICALLS ? SYMBOL_GOT_LOCAL : SYMBOL_GENERAL);
836
837   if (GET_CODE (x) != SYMBOL_REF)
838     abort ();
839
840   if (CONSTANT_POOL_ADDRESS_P (x))
841     {
842       if (TARGET_MIPS16)
843         return SYMBOL_CONSTANT_POOL;
844
845       if (TARGET_ABICALLS)
846         return SYMBOL_GOT_LOCAL;
847
848       if (GET_MODE_SIZE (get_pool_mode (x)) <= mips_section_threshold)
849         return SYMBOL_SMALL_DATA;
850
851       return SYMBOL_GENERAL;
852     }
853
854   if (SYMBOL_REF_SMALL_P (x))
855     return SYMBOL_SMALL_DATA;
856
857   /* When generating mips16 code, SYMBOL_REF_FLAG indicates a string
858      in the current function's constant pool.  */
859   if (TARGET_MIPS16 && SYMBOL_REF_FLAG (x))
860     return SYMBOL_CONSTANT_POOL;
861
862   if (TARGET_ABICALLS)
863     {
864       if (SYMBOL_REF_DECL (x) == 0)
865         return SYMBOL_REF_LOCAL_P (x) ? SYMBOL_GOT_LOCAL : SYMBOL_GOT_GLOBAL;
866
867       /* There are three cases to consider:
868
869             - o32 PIC (either with or without explicit relocs)
870             - n32/n64 PIC without explicit relocs
871             - n32/n64 PIC with explicit relocs
872
873          In the first case, both local and global accesses will use an
874          R_MIPS_GOT16 relocation.  We must correctly predict which of
875          the two semantics (local or global) the assembler and linker
876          will apply.  The choice doesn't depend on the symbol's
877          visibility, so we deliberately ignore decl_visibility and
878          binds_local_p here.
879
880          In the second case, the assembler will not use R_MIPS_GOT16
881          relocations, but it chooses between local and global accesses
882          in the same way as for o32 PIC.
883
884          In the third case we have more freedom since both forms of
885          access will work for any kind of symbol.  However, there seems
886          little point in doing things differently.  */
887       if (DECL_P (SYMBOL_REF_DECL (x)) && TREE_PUBLIC (SYMBOL_REF_DECL (x)))
888         return SYMBOL_GOT_GLOBAL;
889
890       return SYMBOL_GOT_LOCAL;
891     }
892
893   return SYMBOL_GENERAL;
894 }
895
896
897 /* Split X into a base and a constant offset, storing them in *BASE
898    and *OFFSET respectively.  */
899
900 static void
901 mips_split_const (rtx x, rtx *base, HOST_WIDE_INT *offset)
902 {
903   *offset = 0;
904
905   if (GET_CODE (x) == CONST)
906     x = XEXP (x, 0);
907
908   if (GET_CODE (x) == PLUS && GET_CODE (XEXP (x, 1)) == CONST_INT)
909     {
910       *offset += INTVAL (XEXP (x, 1));
911       x = XEXP (x, 0);
912     }
913   *base = x;
914 }
915
916
917 /* Return true if SYMBOL is a SYMBOL_REF and OFFSET + SYMBOL points
918    to the same object as SYMBOL.  */
919
920 static bool
921 mips_offset_within_object_p (rtx symbol, HOST_WIDE_INT offset)
922 {
923   if (GET_CODE (symbol) != SYMBOL_REF)
924     return false;
925
926   if (CONSTANT_POOL_ADDRESS_P (symbol)
927       && offset >= 0
928       && offset < (int) GET_MODE_SIZE (get_pool_mode (symbol)))
929     return true;
930
931   if (SYMBOL_REF_DECL (symbol) != 0
932       && offset >= 0
933       && offset < int_size_in_bytes (TREE_TYPE (SYMBOL_REF_DECL (symbol))))
934     return true;
935
936   return false;
937 }
938
939
940 /* Return true if X is a symbolic constant that can be calculated in
941    the same way as a bare symbol.  If it is, store the type of the
942    symbol in *SYMBOL_TYPE.  */
943
944 static bool
945 mips_symbolic_constant_p (rtx x, enum mips_symbol_type *symbol_type)
946 {
947   HOST_WIDE_INT offset;
948
949   mips_split_const (x, &x, &offset);
950   if (UNSPEC_ADDRESS_P (x))
951     *symbol_type = UNSPEC_ADDRESS_TYPE (x);
952   else if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF)
953     *symbol_type = mips_classify_symbol (x);
954   else
955     return false;
956
957   if (offset == 0)
958     return true;
959
960   /* Check whether a nonzero offset is valid for the underlying
961      relocations.  */
962   switch (*symbol_type)
963     {
964     case SYMBOL_GENERAL:
965       /* If the target has 64-bit pointers and the object file only
966          supports 32-bit symbols, the values of those symbols will be
967          sign-extended.  In this case we can't allow an arbitrary offset
968          in case the 32-bit value X + OFFSET has a different sign from X.  */
969       if (Pmode == DImode && !ABI_HAS_64BIT_SYMBOLS)
970         return mips_offset_within_object_p (x, offset);
971
972       /* In other cases the relocations can handle any offset.  */
973       return true;
974
975     case SYMBOL_SMALL_DATA:
976     case SYMBOL_CONSTANT_POOL:
977       /* Make sure that the offset refers to something within the
978          underlying object.  This should guarantee that the final
979          PC- or GP-relative offset is within the 16-bit limit.  */
980       return mips_offset_within_object_p (x, offset);
981
982     case SYMBOL_GOT_LOCAL:
983     case SYMBOL_GOTOFF_PAGE:
984       /* The linker should provide enough local GOT entries for a
985          16-bit offset.  Larger offsets may lead to GOT overflow.  */
986       return SMALL_OPERAND (offset);
987
988     case SYMBOL_GOT_GLOBAL:
989     case SYMBOL_GOTOFF_GLOBAL:
990     case SYMBOL_GOTOFF_CALL:
991     case SYMBOL_GOTOFF_LOADGP:
992       return false;
993     }
994   abort ();
995 }
996
997
998 /* This function is used to implement REG_MODE_OK_FOR_BASE_P.  */
999
1000 int
1001 mips_regno_mode_ok_for_base_p (int regno, enum machine_mode mode, int strict)
1002 {
1003   if (regno >= FIRST_PSEUDO_REGISTER)
1004     {
1005       if (!strict)
1006         return true;
1007       regno = reg_renumber[regno];
1008     }
1009
1010   /* These fake registers will be eliminated to either the stack or
1011      hard frame pointer, both of which are usually valid base registers.
1012      Reload deals with the cases where the eliminated form isn't valid.  */
1013   if (regno == ARG_POINTER_REGNUM || regno == FRAME_POINTER_REGNUM)
1014     return true;
1015
1016   /* In mips16 mode, the stack pointer can only address word and doubleword
1017      values, nothing smaller.  There are two problems here:
1018
1019        (a) Instantiating virtual registers can introduce new uses of the
1020            stack pointer.  If these virtual registers are valid addresses,
1021            the stack pointer should be too.
1022
1023        (b) Most uses of the stack pointer are not made explicit until
1024            FRAME_POINTER_REGNUM and ARG_POINTER_REGNUM have been eliminated.
1025            We don't know until that stage whether we'll be eliminating to the
1026            stack pointer (which needs the restriction) or the hard frame
1027            pointer (which doesn't).
1028
1029      All in all, it seems more consitent to only enforce this restriction
1030      during and after reload.  */
1031   if (TARGET_MIPS16 && regno == STACK_POINTER_REGNUM)
1032     return !strict || GET_MODE_SIZE (mode) == 4 || GET_MODE_SIZE (mode) == 8;
1033
1034   return TARGET_MIPS16 ? M16_REG_P (regno) : GP_REG_P (regno);
1035 }
1036
1037
1038 /* Return true if X is a valid base register for the given mode.
1039    Allow only hard registers if STRICT.  */
1040
1041 static bool
1042 mips_valid_base_register_p (rtx x, enum machine_mode mode, int strict)
1043 {
1044   if (!strict && GET_CODE (x) == SUBREG)
1045     x = SUBREG_REG (x);
1046
1047   return (GET_CODE (x) == REG
1048           && mips_regno_mode_ok_for_base_p (REGNO (x), mode, strict));
1049 }
1050
1051
1052 /* Return true if symbols of type SYMBOL_TYPE can directly address a value
1053    with mode MODE.  This is used for both symbolic and LO_SUM addresses.  */
1054
1055 static bool
1056 mips_symbolic_address_p (enum mips_symbol_type symbol_type,
1057                          enum machine_mode mode)
1058 {
1059   switch (symbol_type)
1060     {
1061     case SYMBOL_GENERAL:
1062       return !TARGET_MIPS16;
1063
1064     case SYMBOL_SMALL_DATA:
1065       return true;
1066
1067     case SYMBOL_CONSTANT_POOL:
1068       /* PC-relative addressing is only available for lw, sw, ld and sd.  */
1069       return GET_MODE_SIZE (mode) == 4 || GET_MODE_SIZE (mode) == 8;
1070
1071     case SYMBOL_GOT_LOCAL:
1072       return true;
1073
1074     case SYMBOL_GOT_GLOBAL:
1075       /* The address will have to be loaded from the GOT first.  */
1076       return false;
1077
1078     case SYMBOL_GOTOFF_PAGE:
1079     case SYMBOL_GOTOFF_GLOBAL:
1080     case SYMBOL_GOTOFF_CALL:
1081     case SYMBOL_GOTOFF_LOADGP:
1082       return true;
1083     }
1084   abort ();
1085 }
1086
1087
1088 /* Return true if X is a valid address for machine mode MODE.  If it is,
1089    fill in INFO appropriately.  STRICT is true if we should only accept
1090    hard base registers.  */
1091
1092 static bool
1093 mips_classify_address (struct mips_address_info *info, rtx x,
1094                        enum machine_mode mode, int strict)
1095 {
1096   switch (GET_CODE (x))
1097     {
1098     case REG:
1099     case SUBREG:
1100       info->type = ADDRESS_REG;
1101       info->reg = x;
1102       info->offset = const0_rtx;
1103       return mips_valid_base_register_p (info->reg, mode, strict);
1104
1105     case PLUS:
1106       info->type = ADDRESS_REG;
1107       info->reg = XEXP (x, 0);
1108       info->offset = XEXP (x, 1);
1109       return (mips_valid_base_register_p (info->reg, mode, strict)
1110               && const_arith_operand (info->offset, VOIDmode));
1111
1112     case LO_SUM:
1113       info->type = ADDRESS_LO_SUM;
1114       info->reg = XEXP (x, 0);
1115       info->offset = XEXP (x, 1);
1116       return (mips_valid_base_register_p (info->reg, mode, strict)
1117               && mips_symbolic_constant_p (info->offset, &info->symbol_type)
1118               && mips_symbolic_address_p (info->symbol_type, mode)
1119               && mips_lo_relocs[info->symbol_type] != 0);
1120
1121     case CONST_INT:
1122       /* Small-integer addresses don't occur very often, but they
1123          are legitimate if $0 is a valid base register.  */
1124       info->type = ADDRESS_CONST_INT;
1125       return !TARGET_MIPS16 && SMALL_INT (x);
1126
1127     case CONST:
1128     case LABEL_REF:
1129     case SYMBOL_REF:
1130       info->type = ADDRESS_SYMBOLIC;
1131       return (mips_symbolic_constant_p (x, &info->symbol_type)
1132               && mips_symbolic_address_p (info->symbol_type, mode)
1133               && !mips_split_p[info->symbol_type]);
1134
1135     default:
1136       return false;
1137     }
1138 }
1139 \f
1140 /* Return the number of instructions needed to load a symbol of the
1141    given type into a register.  If valid in an address, the same number
1142    of instructions are needed for loads and stores.  Treat extended
1143    mips16 instructions as two instructions.  */
1144
1145 static int
1146 mips_symbol_insns (enum mips_symbol_type type)
1147 {
1148   switch (type)
1149     {
1150     case SYMBOL_GENERAL:
1151       /* In mips16 code, general symbols must be fetched from the
1152          constant pool.  */
1153       if (TARGET_MIPS16)
1154         return 0;
1155
1156       /* When using 64-bit symbols, we need 5 preparatory instructions,
1157          such as:
1158
1159              lui     $at,%highest(symbol)
1160              daddiu  $at,$at,%higher(symbol)
1161              dsll    $at,$at,16
1162              daddiu  $at,$at,%hi(symbol)
1163              dsll    $at,$at,16
1164
1165          The final address is then $at + %lo(symbol).  With 32-bit
1166          symbols we just need a preparatory lui.  */
1167       return (ABI_HAS_64BIT_SYMBOLS ? 6 : 2);
1168
1169     case SYMBOL_SMALL_DATA:
1170       return 1;
1171
1172     case SYMBOL_CONSTANT_POOL:
1173       /* This case is for mips16 only.  Assume we'll need an
1174          extended instruction.  */
1175       return 2;
1176
1177     case SYMBOL_GOT_LOCAL:
1178     case SYMBOL_GOT_GLOBAL:
1179       /* Unless -funit-at-a-time is in effect, we can't be sure whether
1180          the local/global classification is accurate.  See override_options
1181          for details.
1182
1183          The worst cases are:
1184
1185          (1) For local symbols when generating o32 or o64 code.  The assembler
1186              will use:
1187
1188                  lw           $at,%got(symbol)
1189                  nop
1190
1191              ...and the final address will be $at + %lo(symbol).
1192
1193          (2) For global symbols when -mxgot.  The assembler will use:
1194
1195                  lui     $at,%got_hi(symbol)
1196                  (d)addu $at,$at,$gp
1197
1198              ...and the final address will be $at + %got_lo(symbol).  */
1199       return 3;
1200
1201     case SYMBOL_GOTOFF_PAGE:
1202     case SYMBOL_GOTOFF_GLOBAL:
1203     case SYMBOL_GOTOFF_CALL:
1204     case SYMBOL_GOTOFF_LOADGP:
1205       /* Check whether the offset is a 16- or 32-bit value.  */
1206       return mips_split_p[type] ? 2 : 1;
1207     }
1208   abort ();
1209 }
1210
1211
1212 /* Return true if a value at OFFSET bytes from BASE can be accessed
1213    using an unextended mips16 instruction.  MODE is the mode of the
1214    value.
1215
1216    Usually the offset in an unextended instruction is a 5-bit field.
1217    The offset is unsigned and shifted left once for HIs, twice
1218    for SIs, and so on.  An exception is SImode accesses off the
1219    stack pointer, which have an 8-bit immediate field.  */
1220
1221 static bool
1222 mips16_unextended_reference_p (enum machine_mode mode, rtx base, rtx offset)
1223 {
1224   if (TARGET_MIPS16
1225       && GET_CODE (offset) == CONST_INT
1226       && INTVAL (offset) >= 0
1227       && (INTVAL (offset) & (GET_MODE_SIZE (mode) - 1)) == 0)
1228     {
1229       if (GET_MODE_SIZE (mode) == 4 && base == stack_pointer_rtx)
1230         return INTVAL (offset) < 256 * GET_MODE_SIZE (mode);
1231       return INTVAL (offset) < 32 * GET_MODE_SIZE (mode);
1232     }
1233   return false;
1234 }
1235
1236
1237 /* Return the number of instructions needed to load or store a value
1238    of mode MODE at X.  Return 0 if X isn't valid for MODE.
1239
1240    For mips16 code, count extended instructions as two instructions.  */
1241
1242 int
1243 mips_address_insns (rtx x, enum machine_mode mode)
1244 {
1245   struct mips_address_info addr;
1246   int factor;
1247
1248   /* Each word of a multi-word value will be accessed individually.  */
1249   factor = (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
1250   if (mips_classify_address (&addr, x, mode, false))
1251     switch (addr.type)
1252       {
1253       case ADDRESS_REG:
1254         if (TARGET_MIPS16
1255             && !mips16_unextended_reference_p (mode, addr.reg, addr.offset))
1256           return factor * 2;
1257         return factor;
1258
1259       case ADDRESS_LO_SUM:
1260         return (TARGET_MIPS16 ? factor * 2 : factor);
1261
1262       case ADDRESS_CONST_INT:
1263         return factor;
1264
1265       case ADDRESS_SYMBOLIC:
1266         return factor * mips_symbol_insns (addr.symbol_type);
1267       }
1268   return 0;
1269 }
1270
1271
1272 /* Likewise for constant X.  */
1273
1274 int
1275 mips_const_insns (rtx x)
1276 {
1277   struct mips_integer_op codes[MIPS_MAX_INTEGER_OPS];
1278   enum mips_symbol_type symbol_type;
1279   HOST_WIDE_INT offset;
1280
1281   switch (GET_CODE (x))
1282     {
1283     case CONSTANT_P_RTX:
1284       return 1;
1285
1286     case HIGH:
1287       if (TARGET_MIPS16
1288           || !mips_symbolic_constant_p (XEXP (x, 0), &symbol_type)
1289           || !mips_split_p[symbol_type])
1290         return 0;
1291
1292       return 1;
1293
1294     case CONST_INT:
1295       if (TARGET_MIPS16)
1296         /* Unsigned 8-bit constants can be loaded using an unextended
1297            LI instruction.  Unsigned 16-bit constants can be loaded
1298            using an extended LI.  Negative constants must be loaded
1299            using LI and then negated.  */
1300         return (INTVAL (x) >= 0 && INTVAL (x) < 256 ? 1
1301                 : SMALL_OPERAND_UNSIGNED (INTVAL (x)) ? 2
1302                 : INTVAL (x) > -256 && INTVAL (x) < 0 ? 2
1303                 : SMALL_OPERAND_UNSIGNED (-INTVAL (x)) ? 3
1304                 : 0);
1305
1306       return mips_build_integer (codes, INTVAL (x));
1307
1308     case CONST_DOUBLE:
1309       return (!TARGET_MIPS16 && x == CONST0_RTX (GET_MODE (x)) ? 1 : 0);
1310
1311     case CONST:
1312       if (CONST_GP_P (x))
1313         return 1;
1314
1315       /* See if we can refer to X directly.  */
1316       if (mips_symbolic_constant_p (x, &symbol_type))
1317         return mips_symbol_insns (symbol_type);
1318
1319       /* Otherwise try splitting the constant into a base and offset.
1320          16-bit offsets can be added using an extra addiu.  Larger offsets
1321          must be calculated separately and then added to the base.  */
1322       mips_split_const (x, &x, &offset);
1323       if (offset != 0)
1324         {
1325           int n = mips_const_insns (x);
1326           if (n != 0)
1327             {
1328               if (SMALL_OPERAND (offset))
1329                 return n + 1;
1330               else
1331                 return n + 1 + mips_build_integer (codes, offset);
1332             }
1333         }
1334       return 0;
1335
1336     case SYMBOL_REF:
1337     case LABEL_REF:
1338       return mips_symbol_insns (mips_classify_symbol (x));
1339
1340     default:
1341       return 0;
1342     }
1343 }
1344
1345
1346 /* Return the number of instructions needed for memory reference X.
1347    Count extended mips16 instructions as two instructions.  */
1348
1349 int
1350 mips_fetch_insns (rtx x)
1351 {
1352   if (GET_CODE (x) != MEM)
1353     abort ();
1354
1355   return mips_address_insns (XEXP (x, 0), GET_MODE (x));
1356 }
1357
1358
1359 /* Return truth value of whether OP can be used as an operands
1360    where a register or 16 bit unsigned integer is needed.  */
1361
1362 int
1363 uns_arith_operand (rtx op, enum machine_mode mode)
1364 {
1365   if (GET_CODE (op) == CONST_INT && SMALL_INT_UNSIGNED (op))
1366     return 1;
1367
1368   return register_operand (op, mode);
1369 }
1370
1371
1372 /* True if OP can be treated as a signed 16-bit constant.  */
1373
1374 int
1375 const_arith_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
1376 {
1377   return GET_CODE (op) == CONST_INT && SMALL_INT (op);
1378 }
1379
1380
1381 /* Return true if OP is a register operand or a signed 16-bit constant.  */
1382
1383 int
1384 arith_operand (rtx op, enum machine_mode mode)
1385 {
1386   return const_arith_operand (op, mode) || register_operand (op, mode);
1387 }
1388
1389 /* Return truth value of whether OP is an integer which fits in 16 bits.  */
1390
1391 int
1392 small_int (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
1393 {
1394   return (GET_CODE (op) == CONST_INT && SMALL_INT (op));
1395 }
1396
1397 /* Return truth value of whether OP is a register or the constant 0.
1398    Do not accept 0 in mips16 mode since $0 is not one of the core 8
1399    registers.  */
1400
1401 int
1402 reg_or_0_operand (rtx op, enum machine_mode mode)
1403 {
1404   switch (GET_CODE (op))
1405     {
1406     case CONST_INT:
1407       if (TARGET_MIPS16)
1408         return 0;
1409       return INTVAL (op) == 0;
1410
1411     case CONST_DOUBLE:
1412       if (TARGET_MIPS16)
1413         return 0;
1414       return op == CONST0_RTX (mode);
1415
1416     default:
1417       return register_operand (op, mode);
1418     }
1419 }
1420
1421 /* Accept a register or the floating point constant 1 in the appropriate mode.  */
1422
1423 int
1424 reg_or_const_float_1_operand (rtx op, enum machine_mode mode)
1425 {
1426   REAL_VALUE_TYPE d;
1427
1428   switch (GET_CODE (op))
1429     {
1430     case CONST_DOUBLE:
1431       if (mode != GET_MODE (op)
1432           || (mode != DFmode && mode != SFmode))
1433         return 0;
1434
1435       REAL_VALUE_FROM_CONST_DOUBLE (d, op);
1436       return REAL_VALUES_EQUAL (d, dconst1);
1437
1438     default:
1439       return register_operand (op, mode);
1440     }
1441 }
1442
1443 /* Accept the floating point constant 1 in the appropriate mode.  */
1444
1445 int
1446 const_float_1_operand (rtx op, enum machine_mode mode)
1447 {
1448   REAL_VALUE_TYPE d;
1449
1450   if (GET_CODE (op) != CONST_DOUBLE
1451       || mode != GET_MODE (op)
1452       || (mode != DFmode && mode != SFmode))
1453     return 0;
1454
1455   REAL_VALUE_FROM_CONST_DOUBLE (d, op);
1456
1457   return REAL_VALUES_EQUAL (d, dconst1);
1458 }
1459
1460 /* Return true if OP is either the HI or LO register.  */
1461
1462 int
1463 hilo_operand (rtx op, enum machine_mode mode)
1464 {
1465   return ((mode == VOIDmode || mode == GET_MODE (op))
1466           && REG_P (op) && MD_REG_P (REGNO (op)));
1467 }
1468
1469 /* Return true if OP is an extension operator.  */
1470
1471 int
1472 extend_operator (rtx op, enum machine_mode mode)
1473 {
1474   return ((mode == VOIDmode || mode == GET_MODE (op))
1475           && (GET_CODE (op) == ZERO_EXTEND || GET_CODE (op) == SIGN_EXTEND));
1476 }
1477
1478 /* Return nonzero if the code of this rtx pattern is EQ or NE.  */
1479
1480 int
1481 equality_op (rtx op, enum machine_mode mode)
1482 {
1483   if (mode != GET_MODE (op))
1484     return 0;
1485
1486   return GET_CODE (op) == EQ || GET_CODE (op) == NE;
1487 }
1488
1489 /* Return nonzero if the code is a relational operations (EQ, LE, etc.) */
1490
1491 int
1492 cmp_op (rtx op, enum machine_mode mode)
1493 {
1494   if (mode != GET_MODE (op))
1495     return 0;
1496
1497   return GET_RTX_CLASS (GET_CODE (op)) == '<';
1498 }
1499
1500 /* Return nonzero if the code is a relational operation suitable for a
1501    conditional trap instruction (only EQ, NE, LT, LTU, GE, GEU).
1502    We need this in the insn that expands `trap_if' in order to prevent
1503    combine from erroneously altering the condition.  */
1504
1505 int
1506 trap_cmp_op (rtx op, enum machine_mode mode)
1507 {
1508   if (mode != GET_MODE (op))
1509     return 0;
1510
1511   switch (GET_CODE (op))
1512     {
1513     case EQ:
1514     case NE:
1515     case LT:
1516     case LTU:
1517     case GE:
1518     case GEU:
1519       return 1;
1520
1521     default:
1522       return 0;
1523     }
1524 }
1525
1526 /* Return nonzero if the operand is either the PC or a label_ref.  */
1527
1528 int
1529 pc_or_label_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
1530 {
1531   if (op == pc_rtx)
1532     return 1;
1533
1534   if (GET_CODE (op) == LABEL_REF)
1535     return 1;
1536
1537   return 0;
1538 }
1539
1540 /* Test for a valid call address.  */
1541
1542 int
1543 call_insn_operand (rtx op, enum machine_mode mode)
1544 {
1545   enum mips_symbol_type symbol_type;
1546
1547   if (mips_symbolic_constant_p (op, &symbol_type))
1548     switch (symbol_type)
1549       {
1550       case SYMBOL_GENERAL:
1551         /* If -mlong-calls, force all calls to use register addressing.  */
1552         return !TARGET_LONG_CALLS;
1553
1554       case SYMBOL_GOT_GLOBAL:
1555         /* Without explicit relocs, there is no special syntax for
1556            loading the address of a call destination into a register.
1557            Using "la $25,foo; jal $25" would prevent the lazy binding
1558            of "foo", so keep the address of global symbols with the
1559            jal macro.  */
1560         return !TARGET_EXPLICIT_RELOCS;
1561
1562       default:
1563         return false;
1564       }
1565   return register_operand (op, mode);
1566 }
1567
1568
1569 /* Return nonzero if OP is valid as a source operand for a move
1570    instruction.  */
1571
1572 int
1573 move_operand (rtx op, enum machine_mode mode)
1574 {
1575   enum mips_symbol_type symbol_type;
1576
1577   if (!general_operand (op, mode))
1578     return false;
1579
1580   switch (GET_CODE (op))
1581     {
1582     case CONST_INT:
1583       /* When generating mips16 code, LEGITIMATE_CONSTANT_P rejects
1584          CONST_INTs that can't be loaded using simple insns.  */
1585       if (TARGET_MIPS16)
1586         return true;
1587
1588       /* Otherwise check whether the constant can be loaded in a single
1589          instruction.  */
1590       return LUI_INT (op) || SMALL_INT (op) || SMALL_INT_UNSIGNED (op);
1591
1592     case CONST:
1593     case SYMBOL_REF:
1594     case LABEL_REF:
1595       if (CONST_GP_P (op))
1596         return true;
1597
1598       return (mips_symbolic_constant_p (op, &symbol_type)
1599               && !mips_split_p[symbol_type]);
1600
1601     default:
1602       return true;
1603     }
1604 }
1605
1606
1607 /* Accept any operand that can appear in a mips16 constant table
1608    instruction.  We can't use any of the standard operand functions
1609    because for these instructions we accept values that are not
1610    accepted by LEGITIMATE_CONSTANT, such as arbitrary SYMBOL_REFs.  */
1611
1612 int
1613 consttable_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
1614 {
1615   return CONSTANT_P (op);
1616 }
1617
1618 /* Return 1 if OP is a symbolic operand, i.e. a symbol_ref or a label_ref,
1619    possibly with an offset.  */
1620
1621 int
1622 symbolic_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
1623 {
1624   enum mips_symbol_type symbol_type;
1625
1626   return mips_symbolic_constant_p (op, &symbol_type);
1627 }
1628
1629
1630 /* Return true if we're generating PIC and OP is a global symbol.  */
1631
1632 int
1633 global_got_operand (rtx op, enum machine_mode mode)
1634 {
1635   enum mips_symbol_type symbol_type;
1636
1637   return ((mode == VOIDmode || mode == GET_MODE (op))
1638           && mips_symbolic_constant_p (op, &symbol_type)
1639           && symbol_type == SYMBOL_GOT_GLOBAL);
1640 }
1641
1642
1643 /* Likewise for local symbols.  */
1644
1645 int
1646 local_got_operand (rtx op, enum machine_mode mode)
1647 {
1648   enum mips_symbol_type symbol_type;
1649
1650   return ((mode == VOIDmode || mode == GET_MODE (op))
1651           && mips_symbolic_constant_p (op, &symbol_type)
1652           && symbol_type == SYMBOL_GOT_LOCAL);
1653 }
1654
1655
1656 /* Return true if OP is a memory reference that uses the stack pointer
1657    as a base register.  */
1658
1659 int
1660 stack_operand (rtx op, enum machine_mode mode)
1661 {
1662   struct mips_address_info addr;
1663
1664   return ((mode == VOIDmode || mode == GET_MODE (op))
1665           && GET_CODE (op) == MEM
1666           && mips_classify_address (&addr, XEXP (op, 0), GET_MODE (op), false)
1667           && addr.type == ADDRESS_REG
1668           && addr.reg == stack_pointer_rtx);
1669 }
1670
1671
1672 /* This function is used to implement GO_IF_LEGITIMATE_ADDRESS.  It
1673    returns a nonzero value if X is a legitimate address for a memory
1674    operand of the indicated MODE.  STRICT is nonzero if this function
1675    is called during reload.  */
1676
1677 bool
1678 mips_legitimate_address_p (enum machine_mode mode, rtx x, int strict)
1679 {
1680   struct mips_address_info addr;
1681
1682   return mips_classify_address (&addr, x, mode, strict);
1683 }
1684
1685
1686 /* Copy VALUE to a register and return that register.  If new psuedos
1687    are allowed, copy it into a new register, otherwise use DEST.  */
1688
1689 static rtx
1690 mips_force_temporary (rtx dest, rtx value)
1691 {
1692   if (!no_new_pseudos)
1693     return force_reg (Pmode, value);
1694   else
1695     {
1696       emit_move_insn (copy_rtx (dest), value);
1697       return dest;
1698     }
1699 }
1700
1701
1702 /* Return a LO_SUM expression for ADDR.  TEMP is as for mips_force_temporary
1703    and is used to load the high part into a register.  */
1704
1705 static rtx
1706 mips_split_symbol (rtx temp, rtx addr)
1707 {
1708   rtx high;
1709
1710   if (TARGET_MIPS16)
1711     high = mips16_gp_pseudo_reg ();
1712   else
1713     high = mips_force_temporary (temp, gen_rtx_HIGH (Pmode, copy_rtx (addr)));
1714   return gen_rtx_LO_SUM (Pmode, high, addr);
1715 }
1716
1717
1718 /* Return an UNSPEC address with underlying address ADDRESS and symbol
1719    type SYMBOL_TYPE.  */
1720
1721 static rtx
1722 mips_unspec_address (rtx address, enum mips_symbol_type symbol_type)
1723 {
1724   rtx base;
1725   HOST_WIDE_INT offset;
1726
1727   mips_split_const (address, &base, &offset);
1728   base = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, base),
1729                          UNSPEC_ADDRESS_FIRST + symbol_type);
1730   return plus_constant (gen_rtx_CONST (Pmode, base), offset);
1731 }
1732
1733
1734 /* If mips_unspec_address (ADDR, SYMBOL_TYPE) is a 32-bit value, add the
1735    high part to BASE and return the result.  Just return BASE otherwise.
1736    TEMP is available as a temporary register if needed.
1737
1738    The returned expression can be used as the first operand to a LO_SUM.  */
1739
1740 static rtx
1741 mips_unspec_offset_high (rtx temp, rtx base, rtx addr,
1742                          enum mips_symbol_type symbol_type)
1743 {
1744   if (mips_split_p[symbol_type])
1745     {
1746       addr = gen_rtx_HIGH (Pmode, mips_unspec_address (addr, symbol_type));
1747       addr = mips_force_temporary (temp, addr);
1748       return mips_force_temporary (temp, gen_rtx_PLUS (Pmode, addr, base));
1749     }
1750   return base;
1751 }
1752
1753
1754 /* Return a memory reference for the GOT slot whose offset is given by
1755    mips_unspec_address (ADDR, SYMBOL_TYPE).  Register BASE contains the
1756    high part of the offset plus $gp.  */
1757
1758 static rtx
1759 mips_load_got (rtx base, rtx addr, enum mips_symbol_type symbol_type)
1760 {
1761   rtx mem, offset;
1762
1763   offset = mips_unspec_address (addr, symbol_type);
1764   mem = gen_rtx_MEM (ptr_mode, gen_rtx_LO_SUM (Pmode, base, offset));
1765   set_mem_alias_set (mem, mips_got_alias_set);
1766
1767   /* GOT entries are constant and references to them can't trap.  */
1768   RTX_UNCHANGING_P (mem) = 1;
1769   MEM_NOTRAP_P (mem) = 1;
1770
1771   return mem;
1772 }
1773
1774
1775 /* Return the offset of ADDR's GOT entry from _gp.  ADDR is a
1776    global_got_operand.  */
1777
1778 rtx
1779 mips_gotoff_global (rtx addr)
1780 {
1781   return mips_unspec_address (addr, SYMBOL_GOTOFF_GLOBAL);
1782 }
1783
1784
1785 /* Fetch the high part of local_got_operand ADDR from the GOT.  */
1786
1787 rtx
1788 mips_load_got_page (rtx addr)
1789 {
1790   return mips_load_got (pic_offset_table_rtx, addr, SYMBOL_GOTOFF_PAGE);
1791 }
1792
1793
1794 /* Fetch the address of global_got_operand ADDR from the GOT.  BASE is a
1795    register that holds the address _gp + %got_hi(ADDR).  */
1796
1797 rtx
1798 mips_load_got_global (rtx base, rtx addr)
1799 {
1800   return mips_load_got (base, addr, SYMBOL_GOTOFF_GLOBAL);
1801 }
1802
1803
1804 /* Return a legitimate address for REG + OFFSET.  This function will
1805    create a temporary register if OFFSET is not a SMALL_OPERAND.  */
1806
1807 static rtx
1808 mips_add_offset (rtx reg, HOST_WIDE_INT offset)
1809 {
1810   if (!SMALL_OPERAND (offset))
1811     reg = expand_simple_binop (GET_MODE (reg), PLUS,
1812                                GEN_INT (CONST_HIGH_PART (offset)),
1813                                reg, NULL, 0, OPTAB_WIDEN);
1814
1815   return plus_constant (reg, CONST_LOW_PART (offset));
1816 }
1817
1818
1819 /* This function is used to implement LEGITIMIZE_ADDRESS.  If *XLOC can
1820    be legitimized in a way that the generic machinery might not expect,
1821    put the new address in *XLOC and return true.  MODE is the mode of
1822    the memory being accessed.  */
1823
1824 bool
1825 mips_legitimize_address (rtx *xloc, enum machine_mode mode)
1826 {
1827   enum mips_symbol_type symbol_type;
1828
1829   /* See if the address can split into a high part and a LO_SUM.  */
1830   if (mips_symbolic_constant_p (*xloc, &symbol_type)
1831       && mips_symbolic_address_p (symbol_type, mode)
1832       && mips_split_p[symbol_type])
1833     {
1834       *xloc = mips_split_symbol (0, *xloc);
1835       return true;
1836     }
1837
1838   if (GET_CODE (*xloc) == PLUS && GET_CODE (XEXP (*xloc, 1)) == CONST_INT)
1839     {
1840       /* Handle REG + CONSTANT using mips_add_offset.  */
1841       rtx reg;
1842
1843       reg = XEXP (*xloc, 0);
1844       if (!mips_valid_base_register_p (reg, mode, 0))
1845         reg = copy_to_mode_reg (Pmode, reg);
1846       *xloc = mips_add_offset (reg, INTVAL (XEXP (*xloc, 1)));
1847       return true;
1848     }
1849
1850   return false;
1851 }
1852
1853
1854 /* Subroutine of mips_build_integer (with the same interface).
1855    Assume that the final action in the sequence should be a left shift.  */
1856
1857 static unsigned int
1858 mips_build_shift (struct mips_integer_op *codes, HOST_WIDE_INT value)
1859 {
1860   unsigned int i, shift;
1861
1862   /* Shift VALUE right until its lowest bit is set.  Shift arithmetically
1863      since signed numbers are easier to load than unsigned ones.  */
1864   shift = 0;
1865   while ((value & 1) == 0)
1866     value /= 2, shift++;
1867
1868   i = mips_build_integer (codes, value);
1869   codes[i].code = ASHIFT;
1870   codes[i].value = shift;
1871   return i + 1;
1872 }
1873
1874
1875 /* As for mips_build_shift, but assume that the final action will be
1876    an IOR or PLUS operation.  */
1877
1878 static unsigned int
1879 mips_build_lower (struct mips_integer_op *codes, unsigned HOST_WIDE_INT value)
1880 {
1881   unsigned HOST_WIDE_INT high;
1882   unsigned int i;
1883
1884   high = value & ~(unsigned HOST_WIDE_INT) 0xffff;
1885   if (!LUI_OPERAND (high) && (value & 0x18000) == 0x18000)
1886     {
1887       /* The constant is too complex to load with a simple lui/ori pair
1888          so our goal is to clear as many trailing zeros as possible.
1889          In this case, we know bit 16 is set and that the low 16 bits
1890          form a negative number.  If we subtract that number from VALUE,
1891          we will clear at least the lowest 17 bits, maybe more.  */
1892       i = mips_build_integer (codes, CONST_HIGH_PART (value));
1893       codes[i].code = PLUS;
1894       codes[i].value = CONST_LOW_PART (value);
1895     }
1896   else
1897     {
1898       i = mips_build_integer (codes, high);
1899       codes[i].code = IOR;
1900       codes[i].value = value & 0xffff;
1901     }
1902   return i + 1;
1903 }
1904
1905
1906 /* Fill CODES with a sequence of rtl operations to load VALUE.
1907    Return the number of operations needed.  */
1908
1909 static unsigned int
1910 mips_build_integer (struct mips_integer_op *codes,
1911                     unsigned HOST_WIDE_INT value)
1912 {
1913   if (SMALL_OPERAND (value)
1914       || SMALL_OPERAND_UNSIGNED (value)
1915       || LUI_OPERAND (value))
1916     {
1917       /* The value can be loaded with a single instruction.  */
1918       codes[0].code = NIL;
1919       codes[0].value = value;
1920       return 1;
1921     }
1922   else if ((value & 1) != 0 || LUI_OPERAND (CONST_HIGH_PART (value)))
1923     {
1924       /* Either the constant is a simple LUI/ORI combination or its
1925          lowest bit is set.  We don't want to shift in this case.  */
1926       return mips_build_lower (codes, value);
1927     }
1928   else if ((value & 0xffff) == 0)
1929     {
1930       /* The constant will need at least three actions.  The lowest
1931          16 bits are clear, so the final action will be a shift.  */
1932       return mips_build_shift (codes, value);
1933     }
1934   else
1935     {
1936       /* The final action could be a shift, add or inclusive OR.
1937          Rather than use a complex condition to select the best
1938          approach, try both mips_build_shift and mips_build_lower
1939          and pick the one that gives the shortest sequence.
1940          Note that this case is only used once per constant.  */
1941       struct mips_integer_op alt_codes[MIPS_MAX_INTEGER_OPS];
1942       unsigned int cost, alt_cost;
1943
1944       cost = mips_build_shift (codes, value);
1945       alt_cost = mips_build_lower (alt_codes, value);
1946       if (alt_cost < cost)
1947         {
1948           memcpy (codes, alt_codes, alt_cost * sizeof (codes[0]));
1949           cost = alt_cost;
1950         }
1951       return cost;
1952     }
1953 }
1954
1955
1956 /* Move VALUE into register DEST.  */
1957
1958 static void
1959 mips_move_integer (rtx dest, unsigned HOST_WIDE_INT value)
1960 {
1961   struct mips_integer_op codes[MIPS_MAX_INTEGER_OPS];
1962   enum machine_mode mode;
1963   unsigned int i, cost;
1964   rtx x;
1965
1966   mode = GET_MODE (dest);
1967   cost = mips_build_integer (codes, value);
1968
1969   /* Apply each binary operation to X.  Invariant: X is a legitimate
1970      source operand for a SET pattern.  */
1971   x = GEN_INT (codes[0].value);
1972   for (i = 1; i < cost; i++)
1973     {
1974       if (no_new_pseudos)
1975         emit_move_insn (dest, x), x = dest;
1976       else
1977         x = force_reg (mode, x);
1978       x = gen_rtx_fmt_ee (codes[i].code, mode, x, GEN_INT (codes[i].value));
1979     }
1980
1981   emit_insn (gen_rtx_SET (VOIDmode, dest, x));
1982 }
1983
1984
1985 /* Subroutine of mips_legitimize_move.  Move constant SRC into register
1986    DEST given that SRC satisfies immediate_operand but doesn't satisfy
1987    move_operand.  */
1988
1989 static void
1990 mips_legitimize_const_move (enum machine_mode mode, rtx dest, rtx src)
1991 {
1992   rtx base;
1993   HOST_WIDE_INT offset;
1994   enum mips_symbol_type symbol_type;
1995
1996   /* Split moves of big integers into smaller pieces.  In mips16 code,
1997      it's better to force the constant into memory instead.  */
1998   if (GET_CODE (src) == CONST_INT && !TARGET_MIPS16)
1999     {
2000       mips_move_integer (dest, INTVAL (src));
2001       return;
2002     }
2003
2004   /* See if the symbol can be split.  For mips16, this is often worse than
2005      forcing it in the constant pool since it needs the single-register form
2006      of addiu or daddiu.  */
2007   if (!TARGET_MIPS16
2008       && mips_symbolic_constant_p (src, &symbol_type)
2009       && mips_split_p[symbol_type])
2010     {
2011       emit_move_insn (dest, mips_split_symbol (dest, src));
2012       return;
2013     }
2014
2015   /* If we have (const (plus symbol offset)), load the symbol first
2016      and then add in the offset.  This is usually better than forcing
2017      the constant into memory, at least in non-mips16 code.  */
2018   mips_split_const (src, &base, &offset);
2019   if (!TARGET_MIPS16
2020       && offset != 0
2021       && (!no_new_pseudos || SMALL_OPERAND (offset)))
2022     {
2023       base = mips_force_temporary (dest, base);
2024       emit_move_insn (dest, mips_add_offset (base, offset));
2025       return;
2026     }
2027
2028   src = force_const_mem (mode, src);
2029
2030   /* When using explicit relocs, constant pool references are sometimes
2031      not legitimate addresses.  */
2032   if (!memory_operand (src, VOIDmode))
2033     src = replace_equiv_address (src, mips_split_symbol (dest, XEXP (src, 0)));
2034   emit_move_insn (dest, src);
2035 }
2036
2037
2038 /* If (set DEST SRC) is not a valid instruction, emit an equivalent
2039    sequence that is valid.  */
2040
2041 bool
2042 mips_legitimize_move (enum machine_mode mode, rtx dest, rtx src)
2043 {
2044   if (!register_operand (dest, mode) && !reg_or_0_operand (src, mode))
2045     {
2046       emit_move_insn (dest, force_reg (mode, src));
2047       return true;
2048     }
2049
2050   /* The source of an SImode move must be a move_operand.  Likewise
2051      DImode moves on 64-bit targets.  We need to deal with constants
2052      that would be legitimate immediate_operands but not legitimate
2053      move_operands.  */
2054   if (GET_MODE_SIZE (mode) <= UNITS_PER_WORD
2055       && CONSTANT_P (src)
2056       && !move_operand (src, mode))
2057     {
2058       mips_legitimize_const_move (mode, dest, src);
2059       set_unique_reg_note (get_last_insn (), REG_EQUAL, copy_rtx (src));
2060       return true;
2061     }
2062   return false;
2063 }
2064 \f
2065 /* We need a lot of little routines to check constant values on the
2066    mips16.  These are used to figure out how long the instruction will
2067    be.  It would be much better to do this using constraints, but
2068    there aren't nearly enough letters available.  */
2069
2070 static int
2071 m16_check_op (rtx op, int low, int high, int mask)
2072 {
2073   return (GET_CODE (op) == CONST_INT
2074           && INTVAL (op) >= low
2075           && INTVAL (op) <= high
2076           && (INTVAL (op) & mask) == 0);
2077 }
2078
2079 int
2080 m16_uimm3_b (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2081 {
2082   return m16_check_op (op, 0x1, 0x8, 0);
2083 }
2084
2085 int
2086 m16_simm4_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2087 {
2088   return m16_check_op (op, - 0x8, 0x7, 0);
2089 }
2090
2091 int
2092 m16_nsimm4_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2093 {
2094   return m16_check_op (op, - 0x7, 0x8, 0);
2095 }
2096
2097 int
2098 m16_simm5_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2099 {
2100   return m16_check_op (op, - 0x10, 0xf, 0);
2101 }
2102
2103 int
2104 m16_nsimm5_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2105 {
2106   return m16_check_op (op, - 0xf, 0x10, 0);
2107 }
2108
2109 int
2110 m16_uimm5_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2111 {
2112   return m16_check_op (op, (- 0x10) << 2, 0xf << 2, 3);
2113 }
2114
2115 int
2116 m16_nuimm5_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2117 {
2118   return m16_check_op (op, (- 0xf) << 2, 0x10 << 2, 3);
2119 }
2120
2121 int
2122 m16_simm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2123 {
2124   return m16_check_op (op, - 0x80, 0x7f, 0);
2125 }
2126
2127 int
2128 m16_nsimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2129 {
2130   return m16_check_op (op, - 0x7f, 0x80, 0);
2131 }
2132
2133 int
2134 m16_uimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2135 {
2136   return m16_check_op (op, 0x0, 0xff, 0);
2137 }
2138
2139 int
2140 m16_nuimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2141 {
2142   return m16_check_op (op, - 0xff, 0x0, 0);
2143 }
2144
2145 int
2146 m16_uimm8_m1_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2147 {
2148   return m16_check_op (op, - 0x1, 0xfe, 0);
2149 }
2150
2151 int
2152 m16_uimm8_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2153 {
2154   return m16_check_op (op, 0x0, 0xff << 2, 3);
2155 }
2156
2157 int
2158 m16_nuimm8_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2159 {
2160   return m16_check_op (op, (- 0xff) << 2, 0x0, 3);
2161 }
2162
2163 int
2164 m16_simm8_8 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2165 {
2166   return m16_check_op (op, (- 0x80) << 3, 0x7f << 3, 7);
2167 }
2168
2169 int
2170 m16_nsimm8_8 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2171 {
2172   return m16_check_op (op, (- 0x7f) << 3, 0x80 << 3, 7);
2173 }
2174
2175 /* References to the string table on the mips16 only use a small
2176    offset if the function is small.  We can't check for LABEL_REF here,
2177    because the offset is always large if the label is before the
2178    referencing instruction.  */
2179
2180 int
2181 m16_usym8_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2182 {
2183   if (GET_CODE (op) == SYMBOL_REF
2184       && SYMBOL_REF_FLAG (op)
2185       && cfun->machine->insns_len > 0
2186       && (cfun->machine->insns_len + get_pool_size () + mips_string_length
2187           < 4 * 0x100))
2188     {
2189       struct string_constant *l;
2190
2191       /* Make sure this symbol is on thelist of string constants to be
2192          output for this function.  It is possible that it has already
2193          been output, in which case this requires a large offset.  */
2194       for (l = string_constants; l != NULL; l = l->next)
2195         if (strcmp (l->label, XSTR (op, 0)) == 0)
2196           return 1;
2197     }
2198
2199   return 0;
2200 }
2201
2202 int
2203 m16_usym5_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2204 {
2205   if (GET_CODE (op) == SYMBOL_REF
2206       && SYMBOL_REF_FLAG (op)
2207       && cfun->machine->insns_len > 0
2208       && (cfun->machine->insns_len + get_pool_size () + mips_string_length
2209           < 4 * 0x20))
2210     {
2211       struct string_constant *l;
2212
2213       /* Make sure this symbol is on thelist of string constants to be
2214          output for this function.  It is possible that it has already
2215          been output, in which case this requires a large offset.  */
2216       for (l = string_constants; l != NULL; l = l->next)
2217         if (strcmp (l->label, XSTR (op, 0)) == 0)
2218           return 1;
2219     }
2220
2221   return 0;
2222 }
2223 \f
2224 static bool
2225 mips_rtx_costs (rtx x, int code, int outer_code, int *total)
2226 {
2227   enum machine_mode mode = GET_MODE (x);
2228
2229   switch (code)
2230     {
2231     case CONST_INT:
2232       if (!TARGET_MIPS16)
2233         {
2234           /* Always return 0, since we don't have different sized
2235              instructions, hence different costs according to Richard
2236              Kenner */
2237           *total = 0;
2238           return true;
2239         }
2240
2241       /* A number between 1 and 8 inclusive is efficient for a shift.
2242          Otherwise, we will need an extended instruction.  */
2243       if ((outer_code) == ASHIFT || (outer_code) == ASHIFTRT
2244           || (outer_code) == LSHIFTRT)
2245         {
2246           if (INTVAL (x) >= 1 && INTVAL (x) <= 8)
2247             *total = 0;
2248           else
2249             *total = COSTS_N_INSNS (1);
2250           return true;
2251         }
2252
2253       /* We can use cmpi for an xor with an unsigned 16 bit value.  */
2254       if ((outer_code) == XOR
2255           && INTVAL (x) >= 0 && INTVAL (x) < 0x10000)
2256         {
2257           *total = 0;
2258           return true;
2259         }
2260
2261       /* We may be able to use slt or sltu for a comparison with a
2262          signed 16 bit value.  (The boundary conditions aren't quite
2263          right, but this is just a heuristic anyhow.)  */
2264       if (((outer_code) == LT || (outer_code) == LE
2265            || (outer_code) == GE || (outer_code) == GT
2266            || (outer_code) == LTU || (outer_code) == LEU
2267            || (outer_code) == GEU || (outer_code) == GTU)
2268           && INTVAL (x) >= -0x8000 && INTVAL (x) < 0x8000)
2269         {
2270           *total = 0;
2271           return true;
2272         }
2273
2274       /* Equality comparisons with 0 are cheap.  */
2275       if (((outer_code) == EQ || (outer_code) == NE)
2276           && INTVAL (x) == 0)
2277         {
2278           *total = 0;
2279           return true;
2280         }
2281
2282       /* Otherwise fall through to the handling below.  */
2283
2284     case CONST:
2285     case SYMBOL_REF:
2286     case LABEL_REF:
2287     case CONST_DOUBLE:
2288       if (LEGITIMATE_CONSTANT_P (x))
2289         {
2290           *total = COSTS_N_INSNS (1);
2291           return true;
2292         }
2293       else
2294         {
2295           /* The value will need to be fetched from the constant pool.  */
2296           *total = CONSTANT_POOL_COST;
2297           return true;
2298         }
2299
2300     case MEM:
2301       {
2302         /* If the address is legitimate, return the number of
2303            instructions it needs, otherwise use the default handling.  */
2304         int n = mips_address_insns (XEXP (x, 0), GET_MODE (x));
2305         if (n > 0)
2306           {
2307             *total = COSTS_N_INSNS (1 + n);
2308             return true;
2309           }
2310         return false;
2311       }
2312
2313     case FFS:
2314       *total = COSTS_N_INSNS (6);
2315       return true;
2316
2317     case NOT:
2318       *total = COSTS_N_INSNS ((mode == DImode && !TARGET_64BIT) ? 2 : 1);
2319       return true;
2320
2321     case AND:
2322     case IOR:
2323     case XOR:
2324       if (mode == DImode && !TARGET_64BIT)
2325         {
2326           *total = COSTS_N_INSNS (2);
2327           return true;
2328         }
2329       return false;
2330
2331     case ASHIFT:
2332     case ASHIFTRT:
2333     case LSHIFTRT:
2334       if (mode == DImode && !TARGET_64BIT)
2335         {
2336           *total = COSTS_N_INSNS ((GET_CODE (XEXP (x, 1)) == CONST_INT)
2337                                   ? 4 : 12);
2338           return true;
2339         }
2340       return false;
2341
2342     case ABS:
2343       if (mode == SFmode || mode == DFmode)
2344         *total = COSTS_N_INSNS (1);
2345       else
2346         *total = COSTS_N_INSNS (4);
2347       return true;
2348
2349     case LO_SUM:
2350       *total = COSTS_N_INSNS (1);
2351       return true;
2352
2353     case PLUS:
2354     case MINUS:
2355       if (mode == SFmode || mode == DFmode)
2356         {
2357           if (TUNE_MIPS3000 || TUNE_MIPS3900)
2358             *total = COSTS_N_INSNS (2);
2359           else if (TUNE_MIPS6000)
2360             *total = COSTS_N_INSNS (3);
2361           else
2362             *total = COSTS_N_INSNS (6);
2363           return true;
2364         }
2365       if (mode == DImode && !TARGET_64BIT)
2366         {
2367           *total = COSTS_N_INSNS (4);
2368           return true;
2369         }
2370       return false;
2371
2372     case NEG:
2373       if (mode == DImode && !TARGET_64BIT)
2374         {
2375           *total = 4;
2376           return true;
2377         }
2378       return false;
2379
2380     case MULT:
2381       if (mode == SFmode)
2382         {
2383           if (TUNE_MIPS3000
2384               || TUNE_MIPS3900
2385               || TUNE_MIPS5000)
2386             *total = COSTS_N_INSNS (4);
2387           else if (TUNE_MIPS6000
2388                    || TUNE_MIPS5400
2389                    || TUNE_MIPS5500)
2390             *total = COSTS_N_INSNS (5);
2391           else
2392             *total = COSTS_N_INSNS (7);
2393           return true;
2394         }
2395
2396       if (mode == DFmode)
2397         {
2398           if (TUNE_MIPS3000
2399               || TUNE_MIPS3900
2400               || TUNE_MIPS5000)
2401             *total = COSTS_N_INSNS (5);
2402           else if (TUNE_MIPS6000
2403                    || TUNE_MIPS5400
2404                    || TUNE_MIPS5500)
2405             *total = COSTS_N_INSNS (6);
2406           else
2407             *total = COSTS_N_INSNS (8);
2408           return true;
2409         }
2410
2411       if (TUNE_MIPS3000)
2412         *total = COSTS_N_INSNS (12);
2413       else if (TUNE_MIPS3900)
2414         *total = COSTS_N_INSNS (2);
2415       else if (TUNE_MIPS5400 || TUNE_MIPS5500)
2416         *total = COSTS_N_INSNS ((mode == DImode) ? 4 : 3);
2417       else if (TUNE_MIPS7000)
2418         *total = COSTS_N_INSNS (mode == DImode ? 9 : 5);
2419       else if (TUNE_MIPS9000)
2420         *total = COSTS_N_INSNS (mode == DImode ? 8 : 3);
2421       else if (TUNE_MIPS6000)
2422         *total = COSTS_N_INSNS (17);
2423       else if (TUNE_MIPS5000)
2424         *total = COSTS_N_INSNS (5);
2425       else
2426         *total = COSTS_N_INSNS (10);
2427       return true;
2428
2429     case DIV:
2430     case MOD:
2431       if (mode == SFmode)
2432         {
2433           if (TUNE_MIPS3000
2434               || TUNE_MIPS3900)
2435             *total = COSTS_N_INSNS (12);
2436           else if (TUNE_MIPS6000)
2437             *total = COSTS_N_INSNS (15);
2438           else if (TUNE_MIPS5400 || TUNE_MIPS5500)
2439             *total = COSTS_N_INSNS (30);
2440           else
2441             *total = COSTS_N_INSNS (23);
2442           return true;
2443         }
2444
2445       if (mode == DFmode)
2446         {
2447           if (TUNE_MIPS3000
2448               || TUNE_MIPS3900)
2449             *total = COSTS_N_INSNS (19);
2450           else if (TUNE_MIPS5400 || TUNE_MIPS5500)
2451             *total = COSTS_N_INSNS (59);
2452           else if (TUNE_MIPS6000)
2453             *total = COSTS_N_INSNS (16);
2454           else
2455             *total = COSTS_N_INSNS (36);
2456           return true;
2457         }
2458       /* Fall through.  */
2459
2460     case UDIV:
2461     case UMOD:
2462       if (TUNE_MIPS3000
2463           || TUNE_MIPS3900)
2464         *total = COSTS_N_INSNS (35);
2465       else if (TUNE_MIPS6000)
2466         *total = COSTS_N_INSNS (38);
2467       else if (TUNE_MIPS5000)
2468         *total = COSTS_N_INSNS (36);
2469       else if (TUNE_MIPS5400 || TUNE_MIPS5500)
2470         *total = COSTS_N_INSNS ((mode == SImode) ? 42 : 74);
2471       else
2472         *total = COSTS_N_INSNS (69);
2473       return true;
2474
2475     case SIGN_EXTEND:
2476       /* A sign extend from SImode to DImode in 64 bit mode is often
2477          zero instructions, because the result can often be used
2478          directly by another instruction; we'll call it one.  */
2479       if (TARGET_64BIT && mode == DImode
2480           && GET_MODE (XEXP (x, 0)) == SImode)
2481         *total = COSTS_N_INSNS (1);
2482       else
2483         *total = COSTS_N_INSNS (2);
2484       return true;
2485
2486     case ZERO_EXTEND:
2487       if (TARGET_64BIT && mode == DImode
2488           && GET_MODE (XEXP (x, 0)) == SImode)
2489         *total = COSTS_N_INSNS (2);
2490       else
2491         *total = COSTS_N_INSNS (1);
2492       return true;
2493
2494     default:
2495       return false;
2496     }
2497 }
2498
2499 /* Provide the costs of an addressing mode that contains ADDR.
2500    If ADDR is not a valid address, its cost is irrelevant.  */
2501
2502 static int
2503 mips_address_cost (rtx addr)
2504 {
2505   return mips_address_insns (addr, SImode);
2506 }
2507 \f
2508 /* Return a pseudo that points to the address of the current function.
2509    The first time it is called for a function, an initializer for the
2510    pseudo is emitted in the beginning of the function.  */
2511
2512 rtx
2513 embedded_pic_fnaddr_reg (void)
2514 {
2515   if (cfun->machine->embedded_pic_fnaddr_rtx == NULL)
2516     {
2517       rtx seq;
2518
2519       cfun->machine->embedded_pic_fnaddr_rtx = gen_reg_rtx (Pmode);
2520
2521       /* Output code at function start to initialize the pseudo-reg.  */
2522       /* ??? We used to do this in FINALIZE_PIC, but that does not work for
2523          inline functions, because it is called after RTL for the function
2524          has been copied.  The pseudo-reg in embedded_pic_fnaddr_rtx however
2525          does not get copied, and ends up not matching the rest of the RTL.
2526          This solution works, but means that we get unnecessary code to
2527          initialize this value every time a function is inlined into another
2528          function.  */
2529       start_sequence ();
2530       emit_insn (gen_get_fnaddr (cfun->machine->embedded_pic_fnaddr_rtx,
2531                                  XEXP (DECL_RTL (current_function_decl), 0)));
2532       seq = get_insns ();
2533       end_sequence ();
2534       push_topmost_sequence ();
2535       emit_insn_after (seq, get_insns ());
2536       pop_topmost_sequence ();
2537     }
2538
2539   return cfun->machine->embedded_pic_fnaddr_rtx;
2540 }
2541
2542 /* Return RTL for the offset from the current function to the argument.
2543    X is the symbol whose offset from the current function we want.  */
2544
2545 rtx
2546 embedded_pic_offset (rtx x)
2547 {
2548   /* Make sure it is emitted.  */
2549   embedded_pic_fnaddr_reg ();
2550
2551   return
2552     gen_rtx_CONST (Pmode,
2553                    gen_rtx_MINUS (Pmode, x,
2554                                   XEXP (DECL_RTL (current_function_decl), 0)));
2555 }
2556 \f
2557 /* Return one word of double-word value OP, taking into account the fixed
2558    endianness of certain registers.  HIGH_P is true to select the high part,
2559    false to select the low part.  */
2560
2561 rtx
2562 mips_subword (rtx op, int high_p)
2563 {
2564   unsigned int byte;
2565   enum machine_mode mode;
2566
2567   mode = GET_MODE (op);
2568   if (mode == VOIDmode)
2569     mode = DImode;
2570
2571   if (TARGET_BIG_ENDIAN ? !high_p : high_p)
2572     byte = UNITS_PER_WORD;
2573   else
2574     byte = 0;
2575
2576   if (GET_CODE (op) == REG)
2577     {
2578       if (FP_REG_P (REGNO (op)))
2579         return gen_rtx_REG (word_mode, high_p ? REGNO (op) + 1 : REGNO (op));
2580       if (REGNO (op) == HI_REGNUM)
2581         return gen_rtx_REG (word_mode, high_p ? HI_REGNUM : LO_REGNUM);
2582     }
2583
2584   if (GET_CODE (op) == MEM)
2585     return mips_rewrite_small_data (adjust_address (op, word_mode, byte));
2586
2587   return simplify_gen_subreg (word_mode, op, mode, byte);
2588 }
2589
2590
2591 /* Return true if a 64-bit move from SRC to DEST should be split into two.  */
2592
2593 bool
2594 mips_split_64bit_move_p (rtx dest, rtx src)
2595 {
2596   if (TARGET_64BIT)
2597     return false;
2598
2599   /* FP->FP moves can be done in a single instruction.  */
2600   if (FP_REG_RTX_P (src) && FP_REG_RTX_P (dest))
2601     return false;
2602
2603   /* Check for floating-point loads and stores.  They can be done using
2604      ldc1 and sdc1 on MIPS II and above.  */
2605   if (mips_isa > 1)
2606     {
2607       if (FP_REG_RTX_P (dest) && GET_CODE (src) == MEM)
2608         return false;
2609       if (FP_REG_RTX_P (src) && GET_CODE (dest) == MEM)
2610         return false;
2611     }
2612   return true;
2613 }
2614
2615
2616 /* Split a 64-bit move from SRC to DEST assuming that
2617    mips_split_64bit_move_p holds.
2618
2619    Moves into and out of FPRs cause some difficulty here.  Such moves
2620    will always be DFmode, since paired FPRs are not allowed to store
2621    DImode values.  The most natural representation would be two separate
2622    32-bit moves, such as:
2623
2624         (set (reg:SI $f0) (mem:SI ...))
2625         (set (reg:SI $f1) (mem:SI ...))
2626
2627    However, the second insn is invalid because odd-numbered FPRs are
2628    not allowed to store independent values.  Use the patterns load_df_low,
2629    load_df_high and store_df_high instead.  */
2630
2631 void
2632 mips_split_64bit_move (rtx dest, rtx src)
2633 {
2634   if (FP_REG_RTX_P (dest))
2635     {
2636       /* Loading an FPR from memory or from GPRs.  */
2637       emit_insn (gen_load_df_low (copy_rtx (dest), mips_subword (src, 0)));
2638       emit_insn (gen_load_df_high (dest, mips_subword (src, 1),
2639                                    copy_rtx (dest)));
2640     }
2641   else if (FP_REG_RTX_P (src))
2642     {
2643       /* Storing an FPR into memory or GPRs.  */
2644       emit_move_insn (mips_subword (dest, 0), mips_subword (src, 0));
2645       emit_insn (gen_store_df_high (mips_subword (dest, 1), src));
2646     }
2647   else
2648     {
2649       /* The operation can be split into two normal moves.  Decide in
2650          which order to do them.  */
2651       rtx low_dest;
2652
2653       low_dest = mips_subword (dest, 0);
2654       if (GET_CODE (low_dest) == REG
2655           && reg_overlap_mentioned_p (low_dest, src))
2656         {
2657           emit_move_insn (mips_subword (dest, 1), mips_subword (src, 1));
2658           emit_move_insn (low_dest, mips_subword (src, 0));
2659         }
2660       else
2661         {
2662           emit_move_insn (low_dest, mips_subword (src, 0));
2663           emit_move_insn (mips_subword (dest, 1), mips_subword (src, 1));
2664         }
2665     }
2666 }
2667 \f
2668 /* Return the appropriate instructions to move SRC into DEST.  Assume
2669    that SRC is operand 1 and DEST is operand 0.  */
2670
2671 const char *
2672 mips_output_move (rtx dest, rtx src)
2673 {
2674   enum rtx_code dest_code, src_code;
2675   bool dbl_p;
2676
2677   dest_code = GET_CODE (dest);
2678   src_code = GET_CODE (src);
2679   dbl_p = (GET_MODE_SIZE (GET_MODE (dest)) == 8);
2680
2681   if (dbl_p && mips_split_64bit_move_p (dest, src))
2682     return "#";
2683
2684   if ((src_code == REG && GP_REG_P (REGNO (src)))
2685       || (!TARGET_MIPS16 && src == CONST0_RTX (GET_MODE (dest))))
2686     {
2687       if (dest_code == REG)
2688         {
2689           if (GP_REG_P (REGNO (dest)))
2690             return "move\t%0,%z1";
2691
2692           if (MD_REG_P (REGNO (dest)))
2693             return "mt%0\t%z1";
2694
2695           if (FP_REG_P (REGNO (dest)))
2696             return (dbl_p ? "dmtc1\t%z1,%0" : "mtc1\t%z1,%0");
2697
2698           if (ALL_COP_REG_P (REGNO (dest)))
2699             {
2700               static char retval[] = "dmtc_\t%z1,%0";
2701
2702               retval[4] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (dest));
2703               return (dbl_p ? retval : retval + 1);
2704             }
2705         }
2706       if (dest_code == MEM)
2707         return (dbl_p ? "sd\t%z1,%0" : "sw\t%z1,%0");
2708     }
2709   if (dest_code == REG && GP_REG_P (REGNO (dest)))
2710     {
2711       if (src_code == REG)
2712         {
2713           if (MD_REG_P (REGNO (src)))
2714             return "mf%1\t%0";
2715
2716           if (ST_REG_P (REGNO (src)) && ISA_HAS_8CC)
2717             return "lui\t%0,0x3f80\n\tmovf\t%0,%.,%1";
2718
2719           if (FP_REG_P (REGNO (src)))
2720             return (dbl_p ? "dmfc1\t%0,%1" : "mfc1\t%0,%1");
2721
2722           if (ALL_COP_REG_P (REGNO (src)))
2723             {
2724               static char retval[] = "dmfc_\t%0,%1";
2725
2726               retval[4] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (src));
2727               return (dbl_p ? retval : retval + 1);
2728             }
2729         }
2730
2731       if (src_code == MEM)
2732         return (dbl_p ? "ld\t%0,%1" : "lw\t%0,%1");
2733
2734       if (src_code == CONST_INT)
2735         {
2736           /* Don't use the X format, because that will give out of
2737              range numbers for 64 bit hosts and 32 bit targets.  */
2738           if (!TARGET_MIPS16)
2739             return "li\t%0,%1\t\t\t# %X1";
2740
2741           if (INTVAL (src) >= 0 && INTVAL (src) <= 0xffff)
2742             return "li\t%0,%1";
2743
2744           if (INTVAL (src) < 0 && INTVAL (src) >= -0xffff)
2745             return "li\t%0,%n1\n\tneg\t%0";
2746         }
2747
2748       if (src_code == HIGH)
2749         return "lui\t%0,%h1";
2750
2751       if (CONST_GP_P (src))
2752         return "move\t%0,%1";
2753
2754       if (symbolic_operand (src, VOIDmode))
2755         return (dbl_p ? "dla\t%0,%1" : "la\t%0,%1");
2756     }
2757   if (src_code == REG && FP_REG_P (REGNO (src)))
2758     {
2759       if (dest_code == REG && FP_REG_P (REGNO (dest)))
2760         return (dbl_p ? "mov.d\t%0,%1" : "mov.s\t%0,%1");
2761
2762       if (dest_code == MEM)
2763         return (dbl_p ? "sdc1\t%1,%0" : "swc1\t%1,%0");
2764     }
2765   if (dest_code == REG && FP_REG_P (REGNO (dest)))
2766     {
2767       if (src_code == MEM)
2768         return (dbl_p ? "ldc1\t%0,%1" : "lwc1\t%0,%1");
2769     }
2770   if (dest_code == REG && ALL_COP_REG_P (REGNO (dest)) && src_code == MEM)
2771     {
2772       static char retval[] = "l_c_\t%0,%1";
2773
2774       retval[1] = (dbl_p ? 'd' : 'w');
2775       retval[3] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (dest));
2776       return retval;
2777     }
2778   if (dest_code == MEM && src_code == REG && ALL_COP_REG_P (REGNO (src)))
2779     {
2780       static char retval[] = "s_c_\t%1,%0";
2781
2782       retval[1] = (dbl_p ? 'd' : 'w');
2783       retval[3] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (src));
2784       return retval;
2785     }
2786   abort ();
2787 }
2788 \f
2789 /* Return an rtx for the gp save slot.  Valid only when using o32 or
2790    o64 abicalls.  */
2791
2792 rtx
2793 mips_gp_save_slot (void)
2794 {
2795   rtx loc;
2796
2797   if (!TARGET_ABICALLS || TARGET_NEWABI)
2798     abort ();
2799
2800   if (frame_pointer_needed)
2801     loc = hard_frame_pointer_rtx;
2802   else
2803     loc = stack_pointer_rtx;
2804   loc = plus_constant (loc, current_function_outgoing_args_size);
2805   loc = gen_rtx_MEM (Pmode, loc);
2806   RTX_UNCHANGING_P (loc) = 1;
2807   return loc;
2808 }
2809 \f
2810 /* Make normal rtx_code into something we can index from an array */
2811
2812 static enum internal_test
2813 map_test_to_internal_test (enum rtx_code test_code)
2814 {
2815   enum internal_test test = ITEST_MAX;
2816
2817   switch (test_code)
2818     {
2819     case EQ:  test = ITEST_EQ;  break;
2820     case NE:  test = ITEST_NE;  break;
2821     case GT:  test = ITEST_GT;  break;
2822     case GE:  test = ITEST_GE;  break;
2823     case LT:  test = ITEST_LT;  break;
2824     case LE:  test = ITEST_LE;  break;
2825     case GTU: test = ITEST_GTU; break;
2826     case GEU: test = ITEST_GEU; break;
2827     case LTU: test = ITEST_LTU; break;
2828     case LEU: test = ITEST_LEU; break;
2829     default:                    break;
2830     }
2831
2832   return test;
2833 }
2834
2835 \f
2836 /* Generate the code to compare two integer values.  The return value is:
2837    (reg:SI xx)          The pseudo register the comparison is in
2838    0                    No register, generate a simple branch.
2839
2840    ??? This is called with result nonzero by the Scond patterns in
2841    mips.md.  These patterns are called with a target in the mode of
2842    the Scond instruction pattern.  Since this must be a constant, we
2843    must use SImode.  This means that if RESULT is nonzero, it will
2844    always be an SImode register, even if TARGET_64BIT is true.  We
2845    cope with this by calling convert_move rather than emit_move_insn.
2846    This will sometimes lead to an unnecessary extension of the result;
2847    for example:
2848
2849    long long
2850    foo (long long i)
2851    {
2852      return i < 5;
2853    }
2854
2855    TEST_CODE is the rtx code for the comparison.
2856    CMP0 and CMP1 are the two operands to compare.
2857    RESULT is the register in which the result should be stored (null for
2858      branches).
2859    For branches, P_INVERT points to an integer that is nonzero on return
2860      if the branch should be inverted.  */
2861
2862 rtx
2863 gen_int_relational (enum rtx_code test_code, rtx result, rtx cmp0,
2864                     rtx cmp1, int *p_invert)
2865 {
2866   struct cmp_info
2867   {
2868     enum rtx_code test_code;    /* code to use in instruction (LT vs. LTU) */
2869     int const_low;              /* low bound of constant we can accept */
2870     int const_high;             /* high bound of constant we can accept */
2871     int const_add;              /* constant to add (convert LE -> LT) */
2872     int reverse_regs;           /* reverse registers in test */
2873     int invert_const;           /* != 0 if invert value if cmp1 is constant */
2874     int invert_reg;             /* != 0 if invert value if cmp1 is register */
2875     int unsignedp;              /* != 0 for unsigned comparisons.  */
2876   };
2877
2878   static const struct cmp_info info[ (int)ITEST_MAX ] = {
2879
2880     { XOR,       0,  65535,  0,  0,  0,  0, 0 },        /* EQ  */
2881     { XOR,       0,  65535,  0,  0,  1,  1, 0 },        /* NE  */
2882     { LT,   -32769,  32766,  1,  1,  1,  0, 0 },        /* GT  */
2883     { LT,   -32768,  32767,  0,  0,  1,  1, 0 },        /* GE  */
2884     { LT,   -32768,  32767,  0,  0,  0,  0, 0 },        /* LT  */
2885     { LT,   -32769,  32766,  1,  1,  0,  1, 0 },        /* LE  */
2886     { LTU,  -32769,  32766,  1,  1,  1,  0, 1 },        /* GTU */
2887     { LTU,  -32768,  32767,  0,  0,  1,  1, 1 },        /* GEU */
2888     { LTU,  -32768,  32767,  0,  0,  0,  0, 1 },        /* LTU */
2889     { LTU,  -32769,  32766,  1,  1,  0,  1, 1 },        /* LEU */
2890   };
2891
2892   enum internal_test test;
2893   enum machine_mode mode;
2894   const struct cmp_info *p_info;
2895   int branch_p;
2896   int eqne_p;
2897   int invert;
2898   rtx reg;
2899   rtx reg2;
2900
2901   test = map_test_to_internal_test (test_code);
2902   if (test == ITEST_MAX)
2903     abort ();
2904
2905   p_info = &info[(int) test];
2906   eqne_p = (p_info->test_code == XOR);
2907
2908   mode = GET_MODE (cmp0);
2909   if (mode == VOIDmode)
2910     mode = GET_MODE (cmp1);
2911
2912   /* Eliminate simple branches */
2913   branch_p = (result == 0);
2914   if (branch_p)
2915     {
2916       if (GET_CODE (cmp0) == REG || GET_CODE (cmp0) == SUBREG)
2917         {
2918           /* Comparisons against zero are simple branches */
2919           if (GET_CODE (cmp1) == CONST_INT && INTVAL (cmp1) == 0
2920               && (! TARGET_MIPS16 || eqne_p))
2921             return 0;
2922
2923           /* Test for beq/bne.  */
2924           if (eqne_p && ! TARGET_MIPS16)
2925             return 0;
2926         }
2927
2928       /* Allocate a pseudo to calculate the value in.  */
2929       result = gen_reg_rtx (mode);
2930     }
2931
2932   /* Make sure we can handle any constants given to us.  */
2933   if (GET_CODE (cmp0) == CONST_INT)
2934     cmp0 = force_reg (mode, cmp0);
2935
2936   if (GET_CODE (cmp1) == CONST_INT)
2937     {
2938       HOST_WIDE_INT value = INTVAL (cmp1);
2939
2940       if (value < p_info->const_low
2941           || value > p_info->const_high
2942           /* ??? Why?  And why wasn't the similar code below modified too?  */
2943           || (TARGET_64BIT
2944               && HOST_BITS_PER_WIDE_INT < 64
2945               && p_info->const_add != 0
2946               && ((p_info->unsignedp
2947                    ? ((unsigned HOST_WIDE_INT) (value + p_info->const_add)
2948                       > (unsigned HOST_WIDE_INT) INTVAL (cmp1))
2949                    : (value + p_info->const_add) > INTVAL (cmp1))
2950                   != (p_info->const_add > 0))))
2951         cmp1 = force_reg (mode, cmp1);
2952     }
2953
2954   /* See if we need to invert the result.  */
2955   invert = (GET_CODE (cmp1) == CONST_INT
2956             ? p_info->invert_const : p_info->invert_reg);
2957
2958   if (p_invert != (int *)0)
2959     {
2960       *p_invert = invert;
2961       invert = 0;
2962     }
2963
2964   /* Comparison to constants, may involve adding 1 to change a LT into LE.
2965      Comparison between two registers, may involve switching operands.  */
2966   if (GET_CODE (cmp1) == CONST_INT)
2967     {
2968       if (p_info->const_add != 0)
2969         {
2970           HOST_WIDE_INT new = INTVAL (cmp1) + p_info->const_add;
2971
2972           /* If modification of cmp1 caused overflow,
2973              we would get the wrong answer if we follow the usual path;
2974              thus, x > 0xffffffffU would turn into x > 0U.  */
2975           if ((p_info->unsignedp
2976                ? (unsigned HOST_WIDE_INT) new >
2977                (unsigned HOST_WIDE_INT) INTVAL (cmp1)
2978                : new > INTVAL (cmp1))
2979               != (p_info->const_add > 0))
2980             {
2981               /* This test is always true, but if INVERT is true then
2982                  the result of the test needs to be inverted so 0 should
2983                  be returned instead.  */
2984               emit_move_insn (result, invert ? const0_rtx : const_true_rtx);
2985               return result;
2986             }
2987           else
2988             cmp1 = GEN_INT (new);
2989         }
2990     }
2991
2992   else if (p_info->reverse_regs)
2993     {
2994       rtx temp = cmp0;
2995       cmp0 = cmp1;
2996       cmp1 = temp;
2997     }
2998
2999   if (test == ITEST_NE && GET_CODE (cmp1) == CONST_INT && INTVAL (cmp1) == 0)
3000     reg = cmp0;
3001   else
3002     {
3003       reg = (invert || eqne_p) ? gen_reg_rtx (mode) : result;
3004       convert_move (reg, gen_rtx (p_info->test_code, mode, cmp0, cmp1), 0);
3005     }
3006
3007   if (test == ITEST_NE)
3008     {
3009       if (! TARGET_MIPS16)
3010         {
3011           convert_move (result, gen_rtx_GTU (mode, reg, const0_rtx), 0);
3012           if (p_invert != NULL)
3013             *p_invert = 0;
3014           invert = 0;
3015         }
3016       else
3017         {
3018           reg2 = invert ? gen_reg_rtx (mode) : result;
3019           convert_move (reg2, gen_rtx_LTU (mode, reg, const1_rtx), 0);
3020           reg = reg2;
3021         }
3022     }
3023
3024   else if (test == ITEST_EQ)
3025     {
3026       reg2 = invert ? gen_reg_rtx (mode) : result;
3027       convert_move (reg2, gen_rtx_LTU (mode, reg, const1_rtx), 0);
3028       reg = reg2;
3029     }
3030
3031   if (invert)
3032     {
3033       rtx one;
3034
3035       if (! TARGET_MIPS16)
3036         one = const1_rtx;
3037       else
3038         {
3039           /* The value is in $24.  Copy it to another register, so
3040              that reload doesn't think it needs to store the $24 and
3041              the input to the XOR in the same location.  */
3042           reg2 = gen_reg_rtx (mode);
3043           emit_move_insn (reg2, reg);
3044           reg = reg2;
3045           one = force_reg (mode, const1_rtx);
3046         }
3047       convert_move (result, gen_rtx_XOR (mode, reg, one), 0);
3048     }
3049
3050   return result;
3051 }
3052 \f
3053 /* Work out how to check a floating-point condition.  We need a
3054    separate comparison instruction (C.cond.fmt), followed by a
3055    branch or conditional move.  Given that IN_CODE is the
3056    required condition, set *CMP_CODE to the C.cond.fmt code
3057    and *action_code to the branch or move code.  */
3058
3059 static void
3060 get_float_compare_codes (enum rtx_code in_code, enum rtx_code *cmp_code,
3061                          enum rtx_code *action_code)
3062 {
3063   switch (in_code)
3064     {
3065     case NE:
3066     case UNGE:
3067     case UNGT:
3068     case LTGT:
3069     case ORDERED:
3070       *cmp_code = reverse_condition_maybe_unordered (in_code);
3071       *action_code = EQ;
3072       break;
3073
3074     default:
3075       *cmp_code = in_code;
3076       *action_code = NE;
3077       break;
3078     }
3079 }
3080
3081 /* Emit the common code for doing conditional branches.
3082    operand[0] is the label to jump to.
3083    The comparison operands are saved away by cmp{si,di,sf,df}.  */
3084
3085 void
3086 gen_conditional_branch (rtx *operands, enum rtx_code test_code)
3087 {
3088   enum cmp_type type = branch_type;
3089   rtx cmp0 = branch_cmp[0];
3090   rtx cmp1 = branch_cmp[1];
3091   enum machine_mode mode;
3092   enum rtx_code cmp_code;
3093   rtx reg;
3094   int invert;
3095   rtx label1, label2;
3096
3097   switch (type)
3098     {
3099     case CMP_SI:
3100     case CMP_DI:
3101       mode = type == CMP_SI ? SImode : DImode;
3102       invert = 0;
3103       reg = gen_int_relational (test_code, NULL_RTX, cmp0, cmp1, &invert);
3104
3105       if (reg)
3106         {
3107           cmp0 = reg;
3108           cmp1 = const0_rtx;
3109           test_code = NE;
3110         }
3111       else if (GET_CODE (cmp1) == CONST_INT && INTVAL (cmp1) != 0)
3112         /* We don't want to build a comparison against a nonzero
3113            constant.  */
3114         cmp1 = force_reg (mode, cmp1);
3115
3116       break;
3117
3118     case CMP_SF:
3119     case CMP_DF:
3120       if (! ISA_HAS_8CC)
3121         reg = gen_rtx_REG (CCmode, FPSW_REGNUM);
3122       else
3123         reg = gen_reg_rtx (CCmode);
3124
3125       get_float_compare_codes (test_code, &cmp_code, &test_code);
3126       emit_insn (gen_rtx_SET (VOIDmode, reg,
3127                               gen_rtx (cmp_code, CCmode, cmp0, cmp1)));
3128
3129       mode = CCmode;
3130       cmp0 = reg;
3131       cmp1 = const0_rtx;
3132       invert = 0;
3133       break;
3134
3135     default:
3136       fatal_insn ("bad test", gen_rtx (test_code, VOIDmode, cmp0, cmp1));
3137     }
3138
3139   /* Generate the branch.  */
3140
3141   label1 = gen_rtx_LABEL_REF (VOIDmode, operands[0]);
3142   label2 = pc_rtx;
3143
3144   if (invert)
3145     {
3146       label2 = label1;
3147       label1 = pc_rtx;
3148     }
3149
3150   emit_jump_insn (gen_rtx_SET (VOIDmode, pc_rtx,
3151                                gen_rtx_IF_THEN_ELSE (VOIDmode,
3152                                                      gen_rtx (test_code, mode,
3153                                                               cmp0, cmp1),
3154                                                      label1, label2)));
3155 }
3156
3157 /* Emit the common code for conditional moves.  OPERANDS is the array
3158    of operands passed to the conditional move define_expand.  */
3159
3160 void
3161 gen_conditional_move (rtx *operands)
3162 {
3163   rtx op0 = branch_cmp[0];
3164   rtx op1 = branch_cmp[1];
3165   enum machine_mode mode = GET_MODE (branch_cmp[0]);
3166   enum rtx_code cmp_code = GET_CODE (operands[1]);
3167   enum rtx_code move_code = NE;
3168   enum machine_mode op_mode = GET_MODE (operands[0]);
3169   enum machine_mode cmp_mode;
3170   rtx cmp_reg;
3171
3172   if (GET_MODE_CLASS (mode) != MODE_FLOAT)
3173     {
3174       switch (cmp_code)
3175         {
3176         case EQ:
3177           cmp_code = XOR;
3178           move_code = EQ;
3179           break;
3180         case NE:
3181           cmp_code = XOR;
3182           break;
3183         case LT:
3184           break;
3185         case GE:
3186           cmp_code = LT;
3187           move_code = EQ;
3188           break;
3189         case GT:
3190           cmp_code = LT;
3191           op0 = force_reg (mode, branch_cmp[1]);
3192           op1 = branch_cmp[0];
3193           break;
3194         case LE:
3195           cmp_code = LT;
3196           op0 = force_reg (mode, branch_cmp[1]);
3197           op1 = branch_cmp[0];
3198           move_code = EQ;
3199           break;
3200         case LTU:
3201           break;
3202         case GEU:
3203           cmp_code = LTU;
3204           move_code = EQ;
3205           break;
3206         case GTU:
3207           cmp_code = LTU;
3208           op0 = force_reg (mode, branch_cmp[1]);
3209           op1 = branch_cmp[0];
3210           break;
3211         case LEU:
3212           cmp_code = LTU;
3213           op0 = force_reg (mode, branch_cmp[1]);
3214           op1 = branch_cmp[0];
3215           move_code = EQ;
3216           break;
3217         default:
3218           abort ();
3219         }
3220     }
3221   else
3222     get_float_compare_codes (cmp_code, &cmp_code, &move_code);
3223
3224   if (mode == SImode || mode == DImode)
3225     cmp_mode = mode;
3226   else if (mode == SFmode || mode == DFmode)
3227     cmp_mode = CCmode;
3228   else
3229     abort ();
3230
3231   cmp_reg = gen_reg_rtx (cmp_mode);
3232   emit_insn (gen_rtx_SET (cmp_mode, cmp_reg,
3233                           gen_rtx (cmp_code, cmp_mode, op0, op1)));
3234
3235   emit_insn (gen_rtx_SET (op_mode, operands[0],
3236                           gen_rtx_IF_THEN_ELSE (op_mode,
3237                                                 gen_rtx (move_code, VOIDmode,
3238                                                          cmp_reg,
3239                                                          CONST0_RTX (SImode)),
3240                                                 operands[2], operands[3])));
3241 }
3242
3243 /* Emit a conditional trap.  OPERANDS is the array of operands passed to
3244    the conditional_trap expander.  */
3245
3246 void
3247 mips_gen_conditional_trap (rtx *operands)
3248 {
3249   rtx op0, op1;
3250   enum rtx_code cmp_code = GET_CODE (operands[0]);
3251   enum machine_mode mode = GET_MODE (branch_cmp[0]);
3252
3253   /* MIPS conditional trap machine instructions don't have GT or LE
3254      flavors, so we must invert the comparison and convert to LT and
3255      GE, respectively.  */
3256   switch (cmp_code)
3257     {
3258     case GT: cmp_code = LT; break;
3259     case LE: cmp_code = GE; break;
3260     case GTU: cmp_code = LTU; break;
3261     case LEU: cmp_code = GEU; break;
3262     default: break;
3263     }
3264   if (cmp_code == GET_CODE (operands[0]))
3265     {
3266       op0 = force_reg (mode, branch_cmp[0]);
3267       op1 = branch_cmp[1];
3268     }
3269   else
3270     {
3271       op0 = force_reg (mode, branch_cmp[1]);
3272       op1 = branch_cmp[0];
3273     }
3274   if (GET_CODE (op1) == CONST_INT && ! SMALL_INT (op1))
3275     op1 = force_reg (mode, op1);
3276
3277   emit_insn (gen_rtx_TRAP_IF (VOIDmode,
3278                               gen_rtx (cmp_code, GET_MODE (operands[0]), op0, op1),
3279                               operands[1]));
3280 }
3281 \f
3282 /* Load function address ADDR into register DEST.  SIBCALL_P is true
3283    if the address is needed for a sibling call.  */
3284
3285 static void
3286 mips_load_call_address (rtx dest, rtx addr, int sibcall_p)
3287 {
3288   /* If we're generating PIC, and this call is to a global function,
3289      try to allow its address to be resolved lazily.  This isn't
3290      possible for NewABI sibcalls since the value of $gp on entry
3291      to the stub would be our caller's gp, not ours.  */
3292   if (TARGET_EXPLICIT_RELOCS
3293       && !(sibcall_p && TARGET_NEWABI)
3294       && global_got_operand (addr, VOIDmode))
3295     {
3296       rtx high, lo_sum_symbol;
3297
3298       high = mips_unspec_offset_high (dest, pic_offset_table_rtx,
3299                                       addr, SYMBOL_GOTOFF_CALL);
3300       lo_sum_symbol = mips_unspec_address (addr, SYMBOL_GOTOFF_CALL);
3301       if (Pmode == SImode)
3302         emit_insn (gen_load_callsi (dest, high, lo_sum_symbol));
3303       else
3304         emit_insn (gen_load_calldi (dest, high, lo_sum_symbol));
3305     }
3306   else
3307     emit_move_insn (dest, addr);
3308 }
3309
3310
3311 /* Expand a call or call_value instruction.  RESULT is where the
3312    result will go (null for calls), ADDR is the address of the
3313    function, ARGS_SIZE is the size of the arguments and AUX is
3314    the value passed to us by mips_function_arg.  SIBCALL_P is true
3315    if we are expanding a sibling call, false if we're expanding
3316    a normal call.  */
3317
3318 void
3319 mips_expand_call (rtx result, rtx addr, rtx args_size, rtx aux, int sibcall_p)
3320 {
3321   rtx orig_addr, pattern, insn;
3322
3323   orig_addr = addr;
3324   if (!call_insn_operand (addr, VOIDmode))
3325     {
3326       addr = gen_reg_rtx (Pmode);
3327       mips_load_call_address (addr, orig_addr, sibcall_p);
3328     }
3329
3330   if (TARGET_MIPS16
3331       && mips16_hard_float
3332       && build_mips16_call_stub (result, addr, args_size,
3333                                  aux == 0 ? 0 : (int) GET_MODE (aux)))
3334     return;
3335
3336   if (result == 0)
3337     pattern = (sibcall_p
3338                ? gen_sibcall_internal (addr, args_size)
3339                : gen_call_internal (addr, args_size));
3340   else if (GET_CODE (result) == PARALLEL && XVECLEN (result, 0) == 2)
3341     {
3342       rtx reg1, reg2;
3343
3344       reg1 = XEXP (XVECEXP (result, 0, 0), 0);
3345       reg2 = XEXP (XVECEXP (result, 0, 1), 0);
3346       pattern =
3347         (sibcall_p
3348          ? gen_sibcall_value_multiple_internal (reg1, addr, args_size, reg2)
3349          : gen_call_value_multiple_internal (reg1, addr, args_size, reg2));
3350     }
3351   else
3352     pattern = (sibcall_p
3353                ? gen_sibcall_value_internal (result, addr, args_size)
3354                : gen_call_value_internal (result, addr, args_size));
3355
3356   insn = emit_call_insn (pattern);
3357
3358   /* Lazy-binding stubs require $gp to be valid on entry.  */
3359   if (global_got_operand (orig_addr, VOIDmode))
3360     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
3361 }
3362
3363
3364 /* We can handle any sibcall when TARGET_SIBCALLS is true.  */
3365
3366 static bool
3367 mips_function_ok_for_sibcall (tree decl ATTRIBUTE_UNUSED,
3368                               tree exp ATTRIBUTE_UNUSED)
3369 {
3370   return TARGET_SIBCALLS;
3371 }
3372 \f
3373 /* Return true if operand OP is a condition code register.
3374    Only for use during or after reload.  */
3375
3376 int
3377 fcc_register_operand (rtx op, enum machine_mode mode)
3378 {
3379   return ((mode == VOIDmode || mode == GET_MODE (op))
3380           && (reload_in_progress || reload_completed)
3381           && (GET_CODE (op) == REG || GET_CODE (op) == SUBREG)
3382           && ST_REG_P (true_regnum (op)));
3383 }
3384
3385 /* Emit code to move general operand SRC into condition-code
3386    register DEST.  SCRATCH is a scratch TFmode float register.
3387    The sequence is:
3388
3389         FP1 = SRC
3390         FP2 = 0.0f
3391         DEST = FP2 < FP1
3392
3393    where FP1 and FP2 are single-precision float registers
3394    taken from SCRATCH.  */
3395
3396 void
3397 mips_emit_fcc_reload (rtx dest, rtx src, rtx scratch)
3398 {
3399   rtx fp1, fp2;
3400
3401   /* Change the source to SFmode.  */
3402   if (GET_CODE (src) == MEM)
3403     src = adjust_address (src, SFmode, 0);
3404   else if (GET_CODE (src) == REG || GET_CODE (src) == SUBREG)
3405     src = gen_rtx_REG (SFmode, true_regnum (src));
3406
3407   fp1 = gen_rtx_REG (SFmode, REGNO (scratch));
3408   fp2 = gen_rtx_REG (SFmode, REGNO (scratch) + FP_INC);
3409
3410   emit_move_insn (copy_rtx (fp1), src);
3411   emit_move_insn (copy_rtx (fp2), CONST0_RTX (SFmode));
3412   emit_insn (gen_slt_sf (dest, fp2, fp1));
3413 }
3414 \f
3415 /* Emit code to change the current function's return address to
3416    ADDRESS.  SCRATCH is available as a scratch register, if needed.
3417    ADDRESS and SCRATCH are both word-mode GPRs.  */
3418
3419 void
3420 mips_set_return_address (rtx address, rtx scratch)
3421 {
3422   HOST_WIDE_INT gp_offset;
3423
3424   compute_frame_size (get_frame_size ());
3425   if (((cfun->machine->frame.mask >> 31) & 1) == 0)
3426     abort ();
3427   gp_offset = cfun->machine->frame.gp_sp_offset;
3428
3429   /* Reduce SP + GP_OFSET to a legitimate address and put it in SCRATCH.  */
3430   if (gp_offset < 32768)
3431     scratch = plus_constant (stack_pointer_rtx, gp_offset);
3432   else
3433     {
3434       emit_move_insn (scratch, GEN_INT (gp_offset));
3435       if (Pmode == DImode)
3436         emit_insn (gen_adddi3 (scratch, scratch, stack_pointer_rtx));
3437       else
3438         emit_insn (gen_addsi3 (scratch, scratch, stack_pointer_rtx));
3439     }
3440
3441   emit_move_insn (gen_rtx_MEM (GET_MODE (address), scratch), address);
3442 }
3443 \f
3444 /* Emit straight-line code to move LENGTH bytes from SRC to DEST.
3445    Assume that the areas do not overlap.  */
3446
3447 static void
3448 mips_block_move_straight (rtx dest, rtx src, HOST_WIDE_INT length)
3449 {
3450   HOST_WIDE_INT offset, delta;
3451   unsigned HOST_WIDE_INT bits;
3452   int i;
3453   enum machine_mode mode;
3454   rtx *regs;
3455
3456   /* Work out how many bits to move at a time.  If both operands have
3457      half-word alignment, it is usually better to move in half words.
3458      For instance, lh/lh/sh/sh is usually better than lwl/lwr/swl/swr
3459      and lw/lw/sw/sw is usually better than ldl/ldr/sdl/sdr.
3460      Otherwise move word-sized chunks.  */
3461   if (MEM_ALIGN (src) == BITS_PER_WORD / 2
3462       && MEM_ALIGN (dest) == BITS_PER_WORD / 2)
3463     bits = BITS_PER_WORD / 2;
3464   else
3465     bits = BITS_PER_WORD;
3466
3467   mode = mode_for_size (bits, MODE_INT, 0);
3468   delta = bits / BITS_PER_UNIT;
3469
3470   /* Allocate a buffer for the temporary registers.  */
3471   regs = alloca (sizeof (rtx) * length / delta);
3472
3473   /* Load as many BITS-sized chunks as possible.  Use a normal load if
3474      the source has enough alignment, otherwise use left/right pairs.  */
3475   for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
3476     {
3477       rtx part;
3478
3479       regs[i] = gen_reg_rtx (mode);
3480       part = adjust_address (src, mode, offset);
3481       if (MEM_ALIGN (part) >= bits)
3482         emit_move_insn (regs[i], part);
3483       else if (!mips_expand_unaligned_load (regs[i], part, bits, 0))
3484         abort ();
3485     }
3486
3487   /* Copy the chunks to the destination.  */
3488   for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
3489     {
3490       rtx part;
3491
3492       part = adjust_address (dest, mode, offset);
3493       if (MEM_ALIGN (part) >= bits)
3494         emit_move_insn (part, regs[i]);
3495       else if (!mips_expand_unaligned_store (part, regs[i], bits, 0))
3496         abort ();
3497     }
3498
3499   /* Mop up any left-over bytes.  */
3500   if (offset < length)
3501     {
3502       src = adjust_address (src, mode, offset);
3503       dest = adjust_address (dest, mode, offset);
3504       move_by_pieces (dest, src, length - offset,
3505                       MIN (MEM_ALIGN (src), MEM_ALIGN (dest)), 0);
3506     }
3507 }
3508 \f
3509 #define MAX_MOVE_REGS 4
3510 #define MAX_MOVE_BYTES (MAX_MOVE_REGS * UNITS_PER_WORD)
3511
3512
3513 /* Helper function for doing a loop-based block operation on memory
3514    reference MEM.  Each iteration of the loop will operate on LENGTH
3515    bytes of MEM.
3516
3517    Create a new base register for use within the loop and point it to
3518    the start of MEM.  Create a new memory reference that uses this
3519    register.  Store them in *LOOP_REG and *LOOP_MEM respectively.  */
3520
3521 static void
3522 mips_adjust_block_mem (rtx mem, HOST_WIDE_INT length,
3523                        rtx *loop_reg, rtx *loop_mem)
3524 {
3525   *loop_reg = copy_addr_to_reg (XEXP (mem, 0));
3526
3527   /* Although the new mem does not refer to a known location,
3528      it does keep up to LENGTH bytes of alignment.  */
3529   *loop_mem = change_address (mem, BLKmode, *loop_reg);
3530   set_mem_align (*loop_mem, MIN (MEM_ALIGN (mem), length * BITS_PER_UNIT));
3531 }
3532
3533
3534 /* Move LENGTH bytes from SRC to DEST using a loop that moves MAX_MOVE_BYTES
3535    per iteration.  LENGTH must be at least MAX_MOVE_BYTES.  Assume that the
3536    memory regions do not overlap.  */
3537
3538 static void
3539 mips_block_move_loop (rtx dest, rtx src, HOST_WIDE_INT length)
3540 {
3541   rtx label, src_reg, dest_reg, final_src;
3542   HOST_WIDE_INT leftover;
3543
3544   leftover = length % MAX_MOVE_BYTES;
3545   length -= leftover;
3546
3547   /* Create registers and memory references for use within the loop.  */
3548   mips_adjust_block_mem (src, MAX_MOVE_BYTES, &src_reg, &src);
3549   mips_adjust_block_mem (dest, MAX_MOVE_BYTES, &dest_reg, &dest);
3550
3551   /* Calculate the value that SRC_REG should have after the last iteration
3552      of the loop.  */
3553   final_src = expand_simple_binop (Pmode, PLUS, src_reg, GEN_INT (length),
3554                                    0, 0, OPTAB_WIDEN);
3555
3556   /* Emit the start of the loop.  */
3557   label = gen_label_rtx ();
3558   emit_label (label);
3559
3560   /* Emit the loop body.  */
3561   mips_block_move_straight (dest, src, MAX_MOVE_BYTES);
3562
3563   /* Move on to the next block.  */
3564   emit_move_insn (src_reg, plus_constant (src_reg, MAX_MOVE_BYTES));
3565   emit_move_insn (dest_reg, plus_constant (dest_reg, MAX_MOVE_BYTES));
3566
3567   /* Emit the loop condition.  */
3568   if (Pmode == DImode)
3569     emit_insn (gen_cmpdi (src_reg, final_src));
3570   else
3571     emit_insn (gen_cmpsi (src_reg, final_src));
3572   emit_jump_insn (gen_bne (label));
3573
3574   /* Mop up any left-over bytes.  */
3575   if (leftover)
3576     mips_block_move_straight (dest, src, leftover);
3577 }
3578 \f
3579 /* Expand a movstrsi instruction.  */
3580
3581 bool
3582 mips_expand_block_move (rtx dest, rtx src, rtx length)
3583 {
3584   if (GET_CODE (length) == CONST_INT)
3585     {
3586       if (INTVAL (length) <= 2 * MAX_MOVE_BYTES)
3587         {
3588           mips_block_move_straight (dest, src, INTVAL (length));
3589           return true;
3590         }
3591       else if (optimize)
3592         {
3593           mips_block_move_loop (dest, src, INTVAL (length));
3594           return true;
3595         }
3596     }
3597   return false;
3598 }
3599 \f
3600 /* Argument support functions.  */
3601
3602 /* Initialize CUMULATIVE_ARGS for a function.  */
3603
3604 void
3605 init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype,
3606                       rtx libname ATTRIBUTE_UNUSED)
3607 {
3608   static CUMULATIVE_ARGS zero_cum;
3609   tree param, next_param;
3610
3611   if (TARGET_DEBUG_E_MODE)
3612     {
3613       fprintf (stderr,
3614                "\ninit_cumulative_args, fntype = 0x%.8lx", (long)fntype);
3615
3616       if (!fntype)
3617         fputc ('\n', stderr);
3618
3619       else
3620         {
3621           tree ret_type = TREE_TYPE (fntype);
3622           fprintf (stderr, ", fntype code = %s, ret code = %s\n",
3623                    tree_code_name[(int)TREE_CODE (fntype)],
3624                    tree_code_name[(int)TREE_CODE (ret_type)]);
3625         }
3626     }
3627
3628   *cum = zero_cum;
3629   cum->prototype = (fntype && TYPE_ARG_TYPES (fntype));
3630
3631   /* Determine if this function has variable arguments.  This is
3632      indicated by the last argument being 'void_type_mode' if there
3633      are no variable arguments.  The standard MIPS calling sequence
3634      passes all arguments in the general purpose registers in this case.  */
3635
3636   for (param = fntype ? TYPE_ARG_TYPES (fntype) : 0;
3637        param != 0; param = next_param)
3638     {
3639       next_param = TREE_CHAIN (param);
3640       if (next_param == 0 && TREE_VALUE (param) != void_type_node)
3641         cum->gp_reg_found = 1;
3642     }
3643 }
3644
3645
3646 /* Fill INFO with information about a single argument.  CUM is the
3647    cumulative state for earlier arguments.  MODE is the mode of this
3648    argument and TYPE is its type (if known).  NAMED is true if this
3649    is a named (fixed) argument rather than a variable one.  */
3650
3651 static void
3652 mips_arg_info (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
3653                tree type, int named, struct mips_arg_info *info)
3654 {
3655   bool even_reg_p;
3656   unsigned int num_words, max_regs;
3657
3658   /* Decide whether this argument should go in a floating-point register,
3659      assuming one is free.  Later code checks for availability.  */
3660
3661   info->fpr_p = (GET_MODE_CLASS (mode) == MODE_FLOAT
3662                  && GET_MODE_SIZE (mode) <= UNITS_PER_FPVALUE);
3663
3664   if (info->fpr_p)
3665     switch (mips_abi)
3666       {
3667       case ABI_32:
3668       case ABI_O64:
3669         info->fpr_p = (!cum->gp_reg_found
3670                        && cum->arg_number < 2
3671                        && (type == 0 || FLOAT_TYPE_P (type)));
3672         break;
3673
3674       case ABI_N32:
3675       case ABI_64:
3676         info->fpr_p = (named && (type == 0 || FLOAT_TYPE_P (type)));
3677         break;
3678       }
3679
3680   /* Now decide whether the argument must go in an even-numbered register.  */
3681
3682   even_reg_p = false;
3683   if (info->fpr_p)
3684     {
3685       /* Under the O64 ABI, the second float argument goes in $f13 if it
3686          is a double, but $f14 if it is a single.  Otherwise, on a
3687          32-bit double-float machine, each FP argument must start in a
3688          new register pair.  */
3689       even_reg_p = (GET_MODE_SIZE (mode) > UNITS_PER_HWFPVALUE
3690                     || (mips_abi == ABI_O64 && mode == SFmode)
3691                     || FP_INC > 1);
3692     }
3693   else if (!TARGET_64BIT || LONG_DOUBLE_TYPE_SIZE == 128)
3694     {
3695       if (GET_MODE_CLASS (mode) == MODE_INT
3696           || GET_MODE_CLASS (mode) == MODE_FLOAT)
3697         even_reg_p = (GET_MODE_SIZE (mode) > UNITS_PER_WORD);
3698
3699       else if (type != NULL_TREE && TYPE_ALIGN (type) > BITS_PER_WORD)
3700         even_reg_p = true;
3701     }
3702
3703   if (mips_abi != ABI_EABI && MUST_PASS_IN_STACK (mode, type))
3704     /* This argument must be passed on the stack.  Eat up all the
3705        remaining registers.  */
3706     info->reg_offset = MAX_ARGS_IN_REGISTERS;
3707   else
3708     {
3709       /* Set REG_OFFSET to the register count we're interested in.
3710          The EABI allocates the floating-point registers separately,
3711          but the other ABIs allocate them like integer registers.  */
3712       info->reg_offset = (mips_abi == ABI_EABI && info->fpr_p
3713                           ? cum->num_fprs
3714                           : cum->num_gprs);
3715
3716       if (even_reg_p)
3717         info->reg_offset += info->reg_offset & 1;
3718     }
3719
3720   /* The alignment applied to registers is also applied to stack arguments.  */
3721   info->stack_offset = cum->stack_words;
3722   if (even_reg_p)
3723     info->stack_offset += info->stack_offset & 1;
3724
3725   if (mode == BLKmode)
3726     info->num_bytes = int_size_in_bytes (type);
3727   else
3728     info->num_bytes = GET_MODE_SIZE (mode);
3729
3730   num_words = (info->num_bytes + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
3731   max_regs = MAX_ARGS_IN_REGISTERS - info->reg_offset;
3732
3733   /* Partition the argument between registers and stack.  */
3734   info->reg_words = MIN (num_words, max_regs);
3735   info->stack_words = num_words - info->reg_words;
3736 }
3737
3738
3739 /* Implement FUNCTION_ARG_ADVANCE.  */
3740
3741 void
3742 function_arg_advance (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3743                       tree type, int named)
3744 {
3745   struct mips_arg_info info;
3746
3747   mips_arg_info (cum, mode, type, named, &info);
3748
3749   if (!info.fpr_p)
3750     cum->gp_reg_found = true;
3751
3752   /* See the comment above the cumulative args structure in mips.h
3753      for an explanation of what this code does.  It assumes the O32
3754      ABI, which passes at most 2 arguments in float registers.  */
3755   if (cum->arg_number < 2 && info.fpr_p)
3756     cum->fp_code += (mode == SFmode ? 1 : 2) << ((cum->arg_number - 1) * 2);
3757
3758   if (mips_abi != ABI_EABI || !info.fpr_p)
3759     cum->num_gprs = info.reg_offset + info.reg_words;
3760   else if (info.reg_words > 0)
3761     cum->num_fprs += FP_INC;
3762
3763   if (info.stack_words > 0)
3764     cum->stack_words = info.stack_offset + info.stack_words;
3765
3766   cum->arg_number++;
3767 }
3768
3769 /* Implement FUNCTION_ARG.  */
3770
3771 struct rtx_def *
3772 function_arg (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
3773               tree type, int named)
3774 {
3775   struct mips_arg_info info;
3776
3777   /* We will be called with a mode of VOIDmode after the last argument
3778      has been seen.  Whatever we return will be passed to the call
3779      insn.  If we need a mips16 fp_code, return a REG with the code
3780      stored as the mode.  */
3781   if (mode == VOIDmode)
3782     {
3783       if (TARGET_MIPS16 && cum->fp_code != 0)
3784         return gen_rtx_REG ((enum machine_mode) cum->fp_code, 0);
3785
3786       else
3787         return 0;
3788     }
3789
3790   mips_arg_info (cum, mode, type, named, &info);
3791
3792   /* Return straight away if the whole argument is passed on the stack.  */
3793   if (info.reg_offset == MAX_ARGS_IN_REGISTERS)
3794     return 0;
3795
3796   if (type != 0
3797       && TREE_CODE (type) == RECORD_TYPE
3798       && (mips_abi == ABI_N32 || mips_abi == ABI_64)
3799       && TYPE_SIZE_UNIT (type)
3800       && host_integerp (TYPE_SIZE_UNIT (type), 1)
3801       && named)
3802     {
3803       /* The Irix 6 n32/n64 ABIs say that if any 64 bit chunk of the
3804          structure contains a double in its entirety, then that 64 bit
3805          chunk is passed in a floating point register.  */
3806       tree field;
3807
3808       /* First check to see if there is any such field.  */
3809       for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
3810         if (TREE_CODE (field) == FIELD_DECL
3811             && TREE_CODE (TREE_TYPE (field)) == REAL_TYPE
3812             && TYPE_PRECISION (TREE_TYPE (field)) == BITS_PER_WORD
3813             && host_integerp (bit_position (field), 0)
3814             && int_bit_position (field) % BITS_PER_WORD == 0)
3815           break;
3816
3817       if (field != 0)
3818         {
3819           /* Now handle the special case by returning a PARALLEL
3820              indicating where each 64 bit chunk goes.  INFO.REG_WORDS
3821              chunks are passed in registers.  */
3822           unsigned int i;
3823           HOST_WIDE_INT bitpos;
3824           rtx ret;
3825
3826           /* assign_parms checks the mode of ENTRY_PARM, so we must
3827              use the actual mode here.  */
3828           ret = gen_rtx_PARALLEL (mode, rtvec_alloc (info.reg_words));
3829
3830           bitpos = 0;
3831           field = TYPE_FIELDS (type);
3832           for (i = 0; i < info.reg_words; i++)
3833             {
3834               rtx reg;
3835
3836               for (; field; field = TREE_CHAIN (field))
3837                 if (TREE_CODE (field) == FIELD_DECL
3838                     && int_bit_position (field) >= bitpos)
3839                   break;
3840
3841               if (field
3842                   && int_bit_position (field) == bitpos
3843                   && TREE_CODE (TREE_TYPE (field)) == REAL_TYPE
3844                   && !TARGET_SOFT_FLOAT
3845                   && TYPE_PRECISION (TREE_TYPE (field)) == BITS_PER_WORD)
3846                 reg = gen_rtx_REG (DFmode, FP_ARG_FIRST + info.reg_offset + i);
3847               else
3848                 reg = gen_rtx_REG (DImode, GP_ARG_FIRST + info.reg_offset + i);
3849
3850               XVECEXP (ret, 0, i)
3851                 = gen_rtx_EXPR_LIST (VOIDmode, reg,
3852                                      GEN_INT (bitpos / BITS_PER_UNIT));
3853
3854               bitpos += BITS_PER_WORD;
3855             }
3856           return ret;
3857         }
3858     }
3859
3860   if (info.fpr_p)
3861     return gen_rtx_REG (mode, FP_ARG_FIRST + info.reg_offset);
3862   else
3863     return gen_rtx_REG (mode, GP_ARG_FIRST + info.reg_offset);
3864 }
3865
3866
3867 /* Implement FUNCTION_ARG_PARTIAL_NREGS.  */
3868
3869 int
3870 function_arg_partial_nregs (const CUMULATIVE_ARGS *cum,
3871                             enum machine_mode mode, tree type, int named)
3872 {
3873   struct mips_arg_info info;
3874
3875   mips_arg_info (cum, mode, type, named, &info);
3876   return info.stack_words > 0 ? info.reg_words : 0;
3877 }
3878
3879
3880 /* Return true if FUNCTION_ARG_PADDING (MODE, TYPE) should return
3881    upward rather than downward.  In other words, return true if the
3882    first byte of the stack slot has useful data, false if the last
3883    byte does.  */
3884
3885 bool
3886 mips_pad_arg_upward (enum machine_mode mode, tree type)
3887 {
3888   /* On little-endian targets, the first byte of every stack argument
3889      is passed in the first byte of the stack slot.  */
3890   if (!BYTES_BIG_ENDIAN)
3891     return true;
3892
3893   /* Otherwise, integral types are padded downward: the last byte of a
3894      stack argument is passed in the last byte of the stack slot.  */
3895   if (type != 0
3896       ? INTEGRAL_TYPE_P (type) || POINTER_TYPE_P (type)
3897       : GET_MODE_CLASS (mode) == MODE_INT)
3898     return false;
3899
3900   /* Big-endian o64 pads floating-point arguments downward.  */
3901   if (mips_abi == ABI_O64)
3902     if (type != 0 ? FLOAT_TYPE_P (type) : GET_MODE_CLASS (mode) == MODE_FLOAT)
3903       return false;
3904
3905   /* Other types are padded upward for o32, o64, n32 and n64.  */
3906   if (mips_abi != ABI_EABI)
3907     return true;
3908
3909   /* Arguments smaller than a stack slot are padded downward.  */
3910   if (mode != BLKmode)
3911     return (GET_MODE_BITSIZE (mode) >= PARM_BOUNDARY);
3912   else
3913     return (int_size_in_bytes (type) >= (PARM_BOUNDARY / BITS_PER_UNIT));
3914 }
3915
3916
3917 /* Likewise BLOCK_REG_PADDING (MODE, TYPE, ...).  Return !BYTES_BIG_ENDIAN
3918    if the least significant byte of the register has useful data.  Return
3919    the opposite if the most significant byte does.  */
3920
3921 bool
3922 mips_pad_reg_upward (enum machine_mode mode, tree type)
3923 {
3924   /* No shifting is required for floating-point arguments.  */
3925   if (type != 0 ? FLOAT_TYPE_P (type) : GET_MODE_CLASS (mode) == MODE_FLOAT)
3926     return !BYTES_BIG_ENDIAN;
3927
3928   /* Otherwise, apply the same padding to register arguments as we do
3929      to stack arguments.  */
3930   return mips_pad_arg_upward (mode, type);
3931 }
3932 \f
3933 static void
3934 mips_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3935                              tree type, int *pretend_size, int no_rtl)
3936 {
3937   CUMULATIVE_ARGS local_cum;
3938   int gp_saved, fp_saved;
3939
3940   /* The caller has advanced CUM up to, but not beyond, the last named
3941      argument.  Advance a local copy of CUM past the last "real" named
3942      argument, to find out how many registers are left over.  */
3943
3944   local_cum = *cum;
3945   FUNCTION_ARG_ADVANCE (local_cum, mode, type, 1);
3946
3947   /* Found out how many registers we need to save.  */
3948   gp_saved = MAX_ARGS_IN_REGISTERS - local_cum.num_gprs;
3949   fp_saved = (EABI_FLOAT_VARARGS_P
3950               ? MAX_ARGS_IN_REGISTERS - local_cum.num_fprs
3951               : 0);
3952
3953   if (!no_rtl)
3954     {
3955       if (gp_saved > 0)
3956         {
3957           rtx ptr, mem;
3958
3959           ptr = virtual_incoming_args_rtx;
3960           switch (mips_abi)
3961             {
3962             case ABI_32:
3963             case ABI_O64:
3964               ptr = plus_constant (ptr, local_cum.num_gprs * UNITS_PER_WORD);
3965               break;
3966
3967             case ABI_EABI:
3968               ptr = plus_constant (ptr, -gp_saved * UNITS_PER_WORD);
3969               break;
3970             }
3971           mem = gen_rtx_MEM (BLKmode, ptr);
3972           set_mem_alias_set (mem, get_varargs_alias_set ());
3973
3974           move_block_from_reg (local_cum.num_gprs + GP_ARG_FIRST,
3975                                mem, gp_saved);
3976         }
3977       if (fp_saved > 0)
3978         {
3979           /* We can't use move_block_from_reg, because it will use
3980              the wrong mode.  */
3981           enum machine_mode mode;
3982           int off, i;
3983
3984           /* Set OFF to the offset from virtual_incoming_args_rtx of
3985              the first float register.   The FP save area lies below
3986              the integer one, and is aligned to UNITS_PER_FPVALUE bytes.  */
3987           off = -gp_saved * UNITS_PER_WORD;
3988           off &= ~(UNITS_PER_FPVALUE - 1);
3989           off -= fp_saved * UNITS_PER_FPREG;
3990
3991           mode = TARGET_SINGLE_FLOAT ? SFmode : DFmode;
3992
3993           for (i = local_cum.num_fprs; i < MAX_ARGS_IN_REGISTERS; i += FP_INC)
3994             {
3995               rtx ptr, mem;
3996
3997               ptr = plus_constant (virtual_incoming_args_rtx, off);
3998               mem = gen_rtx_MEM (mode, ptr);
3999               set_mem_alias_set (mem, get_varargs_alias_set ());
4000               emit_move_insn (mem, gen_rtx_REG (mode, FP_ARG_FIRST + i));
4001               off += UNITS_PER_HWFPVALUE;
4002             }
4003         }
4004     }
4005   if (mips_abi == ABI_32 || mips_abi == ABI_O64)
4006     {
4007       /* No need for pretend arguments: the register parameter area was
4008          allocated by the caller.  */
4009       *pretend_size = 0;
4010       return;
4011     }
4012   *pretend_size = (gp_saved * UNITS_PER_WORD) + (fp_saved * UNITS_PER_FPREG);
4013 }
4014
4015 /* Create the va_list data type.
4016    We keep 3 pointers, and two offsets.
4017    Two pointers are to the overflow area, which starts at the CFA.
4018      One of these is constant, for addressing into the GPR save area below it.
4019      The other is advanced up the stack through the overflow region.
4020    The third pointer is to the GPR save area.  Since the FPR save area
4021      is just below it, we can address FPR slots off this pointer.
4022    We also keep two one-byte offsets, which are to be subtracted from the
4023      constant pointers to yield addresses in the GPR and FPR save areas.
4024      These are downcounted as float or non-float arguments are used,
4025      and when they get to zero, the argument must be obtained from the
4026      overflow region.
4027    If !EABI_FLOAT_VARARGS_P, then no FPR save area exists, and a single
4028      pointer is enough.  It's started at the GPR save area, and is
4029      advanced, period.
4030    Note that the GPR save area is not constant size, due to optimization
4031      in the prologue.  Hence, we can't use a design with two pointers
4032      and two offsets, although we could have designed this with two pointers
4033      and three offsets.  */
4034
4035 static tree
4036 mips_build_builtin_va_list (void)
4037 {
4038   if (EABI_FLOAT_VARARGS_P)
4039     {
4040       tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff, f_res, record;
4041       tree array, index;
4042
4043       record = (*lang_hooks.types.make_type) (RECORD_TYPE);
4044
4045       f_ovfl = build_decl (FIELD_DECL, get_identifier ("__overflow_argptr"),
4046                           ptr_type_node);
4047       f_gtop = build_decl (FIELD_DECL, get_identifier ("__gpr_top"),
4048                           ptr_type_node);
4049       f_ftop = build_decl (FIELD_DECL, get_identifier ("__fpr_top"),
4050                           ptr_type_node);
4051       f_goff = build_decl (FIELD_DECL, get_identifier ("__gpr_offset"),
4052                           unsigned_char_type_node);
4053       f_foff = build_decl (FIELD_DECL, get_identifier ("__fpr_offset"),
4054                           unsigned_char_type_node);
4055       /* Explicitly pad to the size of a pointer, so that -Wpadded won't
4056          warn on every user file.  */
4057       index = build_int_2 (GET_MODE_SIZE (ptr_mode) - 2 - 1, 0);
4058       array = build_array_type (unsigned_char_type_node,
4059                                 build_index_type (index));
4060       f_res = build_decl (FIELD_DECL, get_identifier ("__reserved"), array);
4061
4062       DECL_FIELD_CONTEXT (f_ovfl) = record;
4063       DECL_FIELD_CONTEXT (f_gtop) = record;
4064       DECL_FIELD_CONTEXT (f_ftop) = record;
4065       DECL_FIELD_CONTEXT (f_goff) = record;
4066       DECL_FIELD_CONTEXT (f_foff) = record;
4067       DECL_FIELD_CONTEXT (f_res) = record;
4068
4069       TYPE_FIELDS (record) = f_ovfl;
4070       TREE_CHAIN (f_ovfl) = f_gtop;
4071       TREE_CHAIN (f_gtop) = f_ftop;
4072       TREE_CHAIN (f_ftop) = f_goff;
4073       TREE_CHAIN (f_goff) = f_foff;
4074       TREE_CHAIN (f_foff) = f_res;
4075
4076       layout_type (record);
4077       return record;
4078     }
4079   else if (TARGET_IRIX && !TARGET_IRIX5)
4080     /* On IRIX 6, this type is 'char *'.  */
4081     return build_pointer_type (char_type_node);
4082   else
4083     /* Otherwise, we use 'void *'.  */
4084     return ptr_type_node;
4085 }
4086
4087 /* Implement va_start.  */
4088
4089 void
4090 mips_va_start (tree valist, rtx nextarg)
4091 {
4092   const CUMULATIVE_ARGS *cum = &current_function_args_info;
4093
4094   /* ARG_POINTER_REGNUM is initialized to STACK_POINTER_BOUNDARY, but
4095      since the stack is aligned for a pair of argument-passing slots,
4096      and the beginning of a variable argument list may be an odd slot,
4097      we have to decrease its alignment.  */
4098   if (cfun && cfun->emit->regno_pointer_align)
4099     while (((current_function_pretend_args_size * BITS_PER_UNIT)
4100             & (REGNO_POINTER_ALIGN (ARG_POINTER_REGNUM) - 1)) != 0)
4101       REGNO_POINTER_ALIGN (ARG_POINTER_REGNUM) /= 2;
4102
4103   if (mips_abi == ABI_EABI)
4104     {
4105       int gpr_save_area_size;
4106
4107       gpr_save_area_size
4108         = (MAX_ARGS_IN_REGISTERS - cum->num_gprs) * UNITS_PER_WORD;
4109
4110       if (EABI_FLOAT_VARARGS_P)
4111         {
4112           tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff;
4113           tree ovfl, gtop, ftop, goff, foff;
4114           tree t;
4115           int fpr_offset;
4116           int fpr_save_area_size;
4117
4118           f_ovfl = TYPE_FIELDS (va_list_type_node);
4119           f_gtop = TREE_CHAIN (f_ovfl);
4120           f_ftop = TREE_CHAIN (f_gtop);
4121           f_goff = TREE_CHAIN (f_ftop);
4122           f_foff = TREE_CHAIN (f_goff);
4123
4124           ovfl = build (COMPONENT_REF, TREE_TYPE (f_ovfl), valist, f_ovfl);
4125           gtop = build (COMPONENT_REF, TREE_TYPE (f_gtop), valist, f_gtop);
4126           ftop = build (COMPONENT_REF, TREE_TYPE (f_ftop), valist, f_ftop);
4127           goff = build (COMPONENT_REF, TREE_TYPE (f_goff), valist, f_goff);
4128           foff = build (COMPONENT_REF, TREE_TYPE (f_foff), valist, f_foff);
4129
4130           /* Emit code to initialize OVFL, which points to the next varargs
4131              stack argument.  CUM->STACK_WORDS gives the number of stack
4132              words used by named arguments.  */
4133           t = make_tree (TREE_TYPE (ovfl), virtual_incoming_args_rtx);
4134           if (cum->stack_words > 0)
4135             t = build (PLUS_EXPR, TREE_TYPE (ovfl), t,
4136                        build_int_2 (cum->stack_words * UNITS_PER_WORD, 0));
4137           t = build (MODIFY_EXPR, TREE_TYPE (ovfl), ovfl, t);
4138           expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4139
4140           /* Emit code to initialize GTOP, the top of the GPR save area.  */
4141           t = make_tree (TREE_TYPE (gtop), virtual_incoming_args_rtx);
4142           t = build (MODIFY_EXPR, TREE_TYPE (gtop), gtop, t);
4143           expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4144
4145           /* Emit code to initialize FTOP, the top of the FPR save area.
4146              This address is gpr_save_area_bytes below GTOP, rounded
4147              down to the next fp-aligned boundary.  */
4148           t = make_tree (TREE_TYPE (ftop), virtual_incoming_args_rtx);
4149           fpr_offset = gpr_save_area_size + UNITS_PER_FPVALUE - 1;
4150           fpr_offset &= ~(UNITS_PER_FPVALUE - 1);
4151           if (fpr_offset)
4152             t = build (PLUS_EXPR, TREE_TYPE (ftop), t,
4153                        build_int_2 (-fpr_offset, -1));
4154           t = build (MODIFY_EXPR, TREE_TYPE (ftop), ftop, t);
4155           expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4156
4157           /* Emit code to initialize GOFF, the offset from GTOP of the
4158              next GPR argument.  */
4159           t = build (MODIFY_EXPR, TREE_TYPE (goff), goff,
4160                      build_int_2 (gpr_save_area_size, 0));
4161           expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4162
4163           /* Likewise emit code to initialize FOFF, the offset from FTOP
4164              of the next FPR argument.  */
4165           fpr_save_area_size
4166             = (MAX_ARGS_IN_REGISTERS - cum->num_fprs) * UNITS_PER_FPREG;
4167           t = build (MODIFY_EXPR, TREE_TYPE (foff), foff,
4168                      build_int_2 (fpr_save_area_size, 0));
4169           expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4170         }
4171       else
4172         {
4173           /* Everything is in the GPR save area, or in the overflow
4174              area which is contiguous with it.  */
4175           nextarg = plus_constant (nextarg, -gpr_save_area_size);
4176           std_expand_builtin_va_start (valist, nextarg);
4177         }
4178     }
4179   else
4180     std_expand_builtin_va_start (valist, nextarg);
4181 }
4182 \f
4183 /* Implement va_arg.  */
4184
4185 rtx
4186 mips_va_arg (tree valist, tree type)
4187 {
4188   HOST_WIDE_INT size, rsize;
4189   rtx addr_rtx;
4190   tree t;
4191
4192   size = int_size_in_bytes (type);
4193   rsize = (size + UNITS_PER_WORD - 1) & -UNITS_PER_WORD;
4194
4195   if (mips_abi == ABI_EABI)
4196     {
4197       bool indirect;
4198       rtx r;
4199
4200       indirect
4201         = function_arg_pass_by_reference (NULL, TYPE_MODE (type), type, 0);
4202
4203       if (indirect)
4204         {
4205           size = POINTER_SIZE / BITS_PER_UNIT;
4206           rsize = UNITS_PER_WORD;
4207         }
4208
4209       addr_rtx = gen_reg_rtx (Pmode);
4210
4211       if (!EABI_FLOAT_VARARGS_P)
4212         {
4213           /* Case of all args in a merged stack.  No need to check bounds,
4214              just advance valist along the stack.  */
4215
4216           tree gpr = valist;
4217           if (!indirect
4218               && !TARGET_64BIT
4219               && TYPE_ALIGN (type) > (unsigned) BITS_PER_WORD)
4220             {
4221               /* Align the pointer using: ap = (ap + align - 1) & -align,
4222                  where align is 2 * UNITS_PER_WORD.  */
4223               t = build (PLUS_EXPR, TREE_TYPE (gpr), gpr,
4224                          build_int_2 (2 * UNITS_PER_WORD - 1, 0));
4225               t = build (BIT_AND_EXPR, TREE_TYPE (t), t,
4226                          build_int_2 (-2 * UNITS_PER_WORD, -1));
4227               t = build (MODIFY_EXPR, TREE_TYPE (gpr), gpr, t);
4228               expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4229             }
4230
4231           /* Emit code to set addr_rtx to the valist, and postincrement
4232              the valist by the size of the argument, rounded up to the
4233              next word.  */
4234           t = build (POSTINCREMENT_EXPR, TREE_TYPE (gpr), gpr,
4235                      size_int (rsize));
4236           r = expand_expr (t, addr_rtx, Pmode, EXPAND_NORMAL);
4237           if (r != addr_rtx)
4238             emit_move_insn (addr_rtx, r);
4239
4240           /* Flush the POSTINCREMENT.  */
4241           emit_queue();
4242         }
4243       else
4244         {
4245           /* Not a simple merged stack.  */
4246
4247           tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff;
4248           tree ovfl, top, off;
4249           rtx lab_over = NULL_RTX, lab_false;
4250           HOST_WIDE_INT osize;
4251
4252           f_ovfl = TYPE_FIELDS (va_list_type_node);
4253           f_gtop = TREE_CHAIN (f_ovfl);
4254           f_ftop = TREE_CHAIN (f_gtop);
4255           f_goff = TREE_CHAIN (f_ftop);
4256           f_foff = TREE_CHAIN (f_goff);
4257
4258           /* We maintain separate pointers and offsets for floating-point
4259              and integer arguments, but we need similar code in both cases.
4260              Let:
4261
4262                  TOP be the top of the register save area;
4263                  OFF be the offset from TOP of the next register;
4264                  ADDR_RTX be the address of the argument;
4265                  RSIZE be the number of bytes used to store the argument
4266                    when it's in the register save area;
4267                  OSIZE be the number of bytes used to store it when it's
4268                    in the stack overflow area; and
4269                  PADDING be (BYTES_BIG_ENDIAN ? OSIZE - RSIZE : 0)
4270
4271              The code we want is:
4272
4273                   1: off &= -rsize;       // round down
4274                   2: if (off != 0)
4275                   3:   {
4276                   4:     addr_rtx = top - off;
4277                   5:     off -= rsize;
4278                   6:   }
4279                   7: else
4280                   8:   {
4281                   9:     ovfl += ((intptr_t) ovfl + osize - 1) & -osize;
4282                  10:     addr_rtx = ovfl + PADDING;
4283                  11:     ovfl += osize;
4284                  14:   }
4285
4286              [1] and [9] can sometimes be optimized away.  */
4287
4288           lab_false = gen_label_rtx ();
4289           lab_over = gen_label_rtx ();
4290
4291           ovfl = build (COMPONENT_REF, TREE_TYPE (f_ovfl), valist, f_ovfl);
4292           if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_FLOAT
4293               && GET_MODE_SIZE (TYPE_MODE (type)) <= UNITS_PER_FPVALUE)
4294             {
4295               top = build (COMPONENT_REF, TREE_TYPE (f_ftop), valist, f_ftop);
4296               off = build (COMPONENT_REF, TREE_TYPE (f_foff), valist, f_foff);
4297
4298               /* When floating-point registers are saved to the stack,
4299                  each one will take up UNITS_PER_HWFPVALUE bytes, regardless
4300                  of the float's precision.  */
4301               rsize = UNITS_PER_HWFPVALUE;
4302             }
4303           else
4304             {
4305               top = build (COMPONENT_REF, TREE_TYPE (f_gtop), valist, f_gtop);
4306               off = build (COMPONENT_REF, TREE_TYPE (f_goff), valist, f_goff);
4307               if (rsize > UNITS_PER_WORD)
4308                 {
4309                   /* [1] Emit code for: off &= -rsize.  */
4310                   t = build (BIT_AND_EXPR, TREE_TYPE (off), off,
4311                              build_int_2 (-rsize, -1));
4312                   t = build (MODIFY_EXPR, TREE_TYPE (off), off, t);
4313                   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4314                 }
4315             }
4316           /* Every overflow argument must take up at least UNITS_PER_WORD
4317              bytes (= PARM_BOUNDARY bits).  RSIZE can sometimes be smaller
4318              than that, such as in the combination -mgp64 -msingle-float
4319              -fshort-double.  Doubles passed in registers will then take
4320              up UNITS_PER_HWFPVALUE bytes, but those passed on the stack
4321              take up UNITS_PER_WORD bytes.  */
4322           osize = MAX (rsize, UNITS_PER_WORD);
4323
4324           /* [2] Emit code to branch if off == 0.  */
4325           r = expand_expr (off, NULL_RTX, TYPE_MODE (TREE_TYPE (off)),
4326                            EXPAND_NORMAL);
4327           emit_cmp_and_jump_insns (r, const0_rtx, EQ, const1_rtx, GET_MODE (r),
4328                                    1, lab_false);
4329
4330           /* [4] Emit code for: addr_rtx = top - off.  */
4331           t = build (MINUS_EXPR, TREE_TYPE (top), top, off);
4332           r = expand_expr (t, addr_rtx, Pmode, EXPAND_NORMAL);
4333           if (r != addr_rtx)
4334             emit_move_insn (addr_rtx, r);
4335
4336           /* [5] Emit code for: off -= rsize.  */
4337           t = build (MINUS_EXPR, TREE_TYPE (off), off, build_int_2 (rsize, 0));
4338           t = build (MODIFY_EXPR, TREE_TYPE (off), off, t);
4339           expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4340
4341           /* [7] Emit code to jump over the else clause, then the label
4342              that starts it.  */
4343           emit_queue();
4344           emit_jump (lab_over);
4345           emit_barrier ();
4346           emit_label (lab_false);
4347
4348           if (osize > UNITS_PER_WORD)
4349             {
4350               /* [9] Emit: ovfl += ((intptr_t) ovfl + osize - 1) & -osize.  */
4351               t = build (PLUS_EXPR, TREE_TYPE (ovfl), ovfl,
4352                          build_int_2 (osize - 1, 0));
4353               t = build (BIT_AND_EXPR, TREE_TYPE (ovfl), t,
4354                          build_int_2 (-osize, -1));
4355               t = build (MODIFY_EXPR, TREE_TYPE (ovfl), ovfl, t);
4356               expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4357             }
4358
4359           /* [10, 11].  Emit code to store ovfl in addr_rtx, then
4360              post-increment ovfl by osize.  On big-endian machines,
4361              the argument has OSIZE - RSIZE bytes of leading padding.  */
4362           t = build (POSTINCREMENT_EXPR, TREE_TYPE (ovfl), ovfl,
4363                      size_int (osize));
4364           if (BYTES_BIG_ENDIAN && osize > rsize)
4365             t = build (PLUS_EXPR, TREE_TYPE (t), t,
4366                        build_int_2 (osize - rsize, 0));
4367           r = expand_expr (t, addr_rtx, Pmode, EXPAND_NORMAL);
4368           if (r != addr_rtx)
4369             emit_move_insn (addr_rtx, r);
4370
4371           emit_queue();
4372           emit_label (lab_over);
4373         }
4374       if (BYTES_BIG_ENDIAN && rsize != size)
4375         addr_rtx = plus_constant (addr_rtx, rsize - size);
4376       if (indirect)
4377         {
4378           addr_rtx = force_reg (Pmode, addr_rtx);
4379           r = gen_rtx_MEM (Pmode, addr_rtx);
4380           set_mem_alias_set (r, get_varargs_alias_set ());
4381           emit_move_insn (addr_rtx, r);
4382         }
4383       return addr_rtx;
4384     }
4385   else
4386     {
4387       /* Not EABI.  */
4388       int align;
4389       HOST_WIDE_INT min_offset;
4390
4391       /* ??? The original va-mips.h did always align, despite the fact
4392          that alignments <= UNITS_PER_WORD are preserved by the va_arg
4393          increment mechanism.  */
4394
4395       if ((mips_abi == ABI_N32 || mips_abi == ABI_64)
4396           && TYPE_ALIGN (type) > 64)
4397         align = 16;
4398       else if (TARGET_64BIT)
4399         align = 8;
4400       else if (TYPE_ALIGN (type) > 32)
4401         align = 8;
4402       else
4403         align = 4;
4404
4405       t = build (PLUS_EXPR, TREE_TYPE (valist), valist,
4406                  build_int_2 (align - 1, 0));
4407       t = build (BIT_AND_EXPR, TREE_TYPE (t), t, build_int_2 (-align, -1));
4408
4409       /* If arguments of type TYPE must be passed on the stack,
4410          set MIN_OFFSET to the offset of the first stack parameter.  */
4411       if (!MUST_PASS_IN_STACK (TYPE_MODE (type), type))
4412         min_offset = 0;
4413       else if (TARGET_NEWABI)
4414         min_offset = current_function_pretend_args_size;
4415       else
4416         min_offset = REG_PARM_STACK_SPACE (current_function_decl);
4417
4418       /* Make sure the new address is at least MIN_OFFSET bytes from
4419          the incoming argument pointer.  */
4420       if (min_offset > 0)
4421         t = build (MAX_EXPR, TREE_TYPE (valist), t,
4422                    make_tree (TREE_TYPE (valist),
4423                               plus_constant (virtual_incoming_args_rtx,
4424                                              min_offset)));
4425
4426       t = build (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4427       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4428
4429       /* Everything past the alignment is standard.  */
4430       return std_expand_builtin_va_arg (valist, type);
4431     }
4432 }
4433 \f
4434 /* Return true if it is possible to use left/right accesses for a
4435    bitfield of WIDTH bits starting BITPOS bits into *OP.  When
4436    returning true, update *OP, *LEFT and *RIGHT as follows:
4437
4438    *OP is a BLKmode reference to the whole field.
4439
4440    *LEFT is a QImode reference to the first byte if big endian or
4441    the last byte if little endian.  This address can be used in the
4442    left-side instructions (lwl, swl, ldl, sdl).
4443
4444    *RIGHT is a QImode reference to the opposite end of the field and
4445    can be used in the parterning right-side instruction.  */
4446
4447 static bool
4448 mips_get_unaligned_mem (rtx *op, unsigned int width, int bitpos,
4449                         rtx *left, rtx *right)
4450 {
4451   rtx first, last;
4452
4453   /* Check that the operand really is a MEM.  Not all the extv and
4454      extzv predicates are checked.  */
4455   if (GET_CODE (*op) != MEM)
4456     return false;
4457
4458   /* Check that the size is valid.  */
4459   if (width != 32 && (!TARGET_64BIT || width != 64))
4460     return false;
4461
4462   /* We can only access byte-aligned values.  Since we are always passed
4463      a reference to the first byte of the field, it is not necessary to
4464      do anything with BITPOS after this check.  */
4465   if (bitpos % BITS_PER_UNIT != 0)
4466     return false;
4467
4468   /* Reject aligned bitfields: we want to use a normal load or store
4469      instead of a left/right pair.  */
4470   if (MEM_ALIGN (*op) >= width)
4471     return false;
4472
4473   /* Adjust *OP to refer to the whole field.  This also has the effect
4474      of legitimizing *OP's address for BLKmode, possibly simplifying it.  */
4475   *op = adjust_address (*op, BLKmode, 0);
4476   set_mem_size (*op, GEN_INT (width / BITS_PER_UNIT));
4477
4478   /* Get references to both ends of the field.  We deliberately don't
4479      use the original QImode *OP for FIRST since the new BLKmode one
4480      might have a simpler address.  */
4481   first = adjust_address (*op, QImode, 0);
4482   last = adjust_address (*op, QImode, width / BITS_PER_UNIT - 1);
4483
4484   /* Allocate to LEFT and RIGHT according to endiannes.  LEFT should
4485      be the upper word and RIGHT the lower word.  */
4486   if (TARGET_BIG_ENDIAN)
4487     *left = first, *right = last;
4488   else
4489     *left = last, *right = first;
4490
4491   return true;
4492 }
4493
4494
4495 /* Try to emit the equivalent of (set DEST (zero_extract SRC WIDTH BITPOS)).
4496    Return true on success.  We only handle cases where zero_extract is
4497    equivalent to sign_extract.  */
4498
4499 bool
4500 mips_expand_unaligned_load (rtx dest, rtx src, unsigned int width, int bitpos)
4501 {
4502   rtx left, right;
4503
4504   /* If TARGET_64BIT, the destination of a 32-bit load will be a
4505      paradoxical word_mode subreg.  This is the only case in which
4506      we allow the destination to be larger than the source.  */
4507   if (GET_CODE (dest) == SUBREG
4508       && GET_MODE (dest) == DImode
4509       && SUBREG_BYTE (dest) == 0
4510       && GET_MODE (SUBREG_REG (dest)) == SImode)
4511     dest = SUBREG_REG (dest);
4512
4513   /* After the above adjustment, the destination must be the same
4514      width as the source.  */
4515   if (GET_MODE_BITSIZE (GET_MODE (dest)) != width)
4516     return false;
4517
4518   if (!mips_get_unaligned_mem (&src, width, bitpos, &left, &right))
4519     return false;
4520
4521   if (GET_MODE (dest) == DImode)
4522     {
4523       emit_insn (gen_mov_ldl (dest, src, left));
4524       emit_insn (gen_mov_ldr (copy_rtx (dest), copy_rtx (src),
4525                               right, copy_rtx (dest)));
4526     }
4527   else
4528     {
4529       emit_insn (gen_mov_lwl (dest, src, left));
4530       emit_insn (gen_mov_lwr (copy_rtx (dest), copy_rtx (src),
4531                               right, copy_rtx (dest)));
4532     }
4533   return true;
4534 }
4535
4536
4537 /* Try to expand (set (zero_extract DEST WIDTH BITPOS) SRC).  Return
4538    true on success.  */
4539
4540 bool
4541 mips_expand_unaligned_store (rtx dest, rtx src, unsigned int width, int bitpos)
4542 {
4543   rtx left, right;
4544
4545   if (!mips_get_unaligned_mem (&dest, width, bitpos, &left, &right))
4546     return false;
4547
4548   src = gen_lowpart (mode_for_size (width, MODE_INT, 0), src);
4549
4550   if (GET_MODE (src) == DImode)
4551     {
4552       emit_insn (gen_mov_sdl (dest, src, left));
4553       emit_insn (gen_mov_sdr (copy_rtx (dest), copy_rtx (src), right));
4554     }
4555   else
4556     {
4557       emit_insn (gen_mov_swl (dest, src, left));
4558       emit_insn (gen_mov_swr (copy_rtx (dest), copy_rtx (src), right));
4559     }
4560   return true;
4561 }
4562 \f
4563 /* Set up globals to generate code for the ISA or processor
4564    described by INFO.  */
4565
4566 static void
4567 mips_set_architecture (const struct mips_cpu_info *info)
4568 {
4569   if (info != 0)
4570     {
4571       mips_arch_info = info;
4572       mips_arch = info->cpu;
4573       mips_isa = info->isa;
4574     }
4575 }
4576
4577
4578 /* Likewise for tuning.  */
4579
4580 static void
4581 mips_set_tune (const struct mips_cpu_info *info)
4582 {
4583   if (info != 0)
4584     {
4585       mips_tune_info = info;
4586       mips_tune = info->cpu;
4587     }
4588 }
4589
4590
4591 /* Set up the threshold for data to go into the small data area, instead
4592    of the normal data area, and detect any conflicts in the switches.  */
4593
4594 void
4595 override_options (void)
4596 {
4597   int i, start, regno;
4598   enum machine_mode mode;
4599
4600   mips_section_threshold = g_switch_set ? g_switch_value : MIPS_DEFAULT_GVALUE;
4601
4602   /* Interpret -mabi.  */
4603   mips_abi = MIPS_ABI_DEFAULT;
4604   if (mips_abi_string != 0)
4605     {
4606       if (strcmp (mips_abi_string, "32") == 0)
4607         mips_abi = ABI_32;
4608       else if (strcmp (mips_abi_string, "o64") == 0)
4609         mips_abi = ABI_O64;
4610       else if (strcmp (mips_abi_string, "n32") == 0)
4611         mips_abi = ABI_N32;
4612       else if (strcmp (mips_abi_string, "64") == 0)
4613         mips_abi = ABI_64;
4614       else if (strcmp (mips_abi_string, "eabi") == 0)
4615         mips_abi = ABI_EABI;
4616       else
4617         fatal_error ("bad value (%s) for -mabi= switch", mips_abi_string);
4618     }
4619
4620   /* The following code determines the architecture and register size.
4621      Similar code was added to GAS 2.14 (see tc-mips.c:md_after_parse_args()).
4622      The GAS and GCC code should be kept in sync as much as possible.  */
4623
4624   if (mips_arch_string != 0)
4625     mips_set_architecture (mips_parse_cpu ("-march", mips_arch_string));
4626
4627   if (mips_isa_string != 0)
4628     {
4629       /* Handle -mipsN.  */
4630       char *whole_isa_str = concat ("mips", mips_isa_string, NULL);
4631       const struct mips_cpu_info *isa_info;
4632
4633       isa_info = mips_parse_cpu ("-mips option", whole_isa_str);
4634       free (whole_isa_str);
4635
4636       /* -march takes precedence over -mipsN, since it is more descriptive.
4637          There's no harm in specifying both as long as the ISA levels
4638          are the same.  */
4639       if (mips_arch_info != 0 && mips_isa != isa_info->isa)
4640         error ("-mips%s conflicts with the other architecture options, "
4641                "which specify a MIPS%d processor",
4642                mips_isa_string, mips_isa);
4643
4644       /* Set architecture based on the given option.  */
4645       mips_set_architecture (isa_info);
4646     }
4647
4648   if (mips_arch_info == 0)
4649     {
4650 #ifdef MIPS_CPU_STRING_DEFAULT
4651       mips_set_architecture (mips_parse_cpu ("default CPU",
4652                                              MIPS_CPU_STRING_DEFAULT));
4653 #else
4654       mips_set_architecture (mips_cpu_info_from_isa (MIPS_ISA_DEFAULT));
4655 #endif
4656     }
4657
4658   if (ABI_NEEDS_64BIT_REGS && !ISA_HAS_64BIT_REGS)
4659     error ("-march=%s is not compatible with the selected ABI",
4660            mips_arch_info->name);
4661
4662   /* Optimize for mips_arch, unless -mtune selects a different processor.  */
4663   if (mips_tune_string != 0)
4664     mips_set_tune (mips_parse_cpu ("-mtune", mips_tune_string));
4665
4666   if (mips_tune_info == 0)
4667     mips_set_tune (mips_arch_info);
4668
4669   if ((target_flags_explicit & MASK_64BIT) != 0)
4670     {
4671       /* The user specified the size of the integer registers.  Make sure
4672          it agrees with the ABI and ISA.  */
4673       if (TARGET_64BIT && !ISA_HAS_64BIT_REGS)
4674         error ("-mgp64 used with a 32-bit processor");
4675       else if (!TARGET_64BIT && ABI_NEEDS_64BIT_REGS)
4676         error ("-mgp32 used with a 64-bit ABI");
4677       else if (TARGET_64BIT && ABI_NEEDS_32BIT_REGS)
4678         error ("-mgp64 used with a 32-bit ABI");
4679     }
4680   else
4681     {
4682       /* Infer the integer register size from the ABI and processor.
4683          Restrict ourselves to 32-bit registers if that's all the
4684          processor has, or if the ABI cannot handle 64-bit registers.  */
4685       if (ABI_NEEDS_32BIT_REGS || !ISA_HAS_64BIT_REGS)
4686         target_flags &= ~MASK_64BIT;
4687       else
4688         target_flags |= MASK_64BIT;
4689     }
4690
4691   if ((target_flags_explicit & MASK_FLOAT64) != 0)
4692     {
4693       /* Really, -mfp32 and -mfp64 are ornamental options.  There's
4694          only one right answer here.  */
4695       if (TARGET_64BIT && TARGET_DOUBLE_FLOAT && !TARGET_FLOAT64)
4696         error ("unsupported combination: %s", "-mgp64 -mfp32 -mdouble-float");
4697       else if (!TARGET_64BIT && TARGET_FLOAT64)
4698         error ("unsupported combination: %s", "-mgp32 -mfp64");
4699       else if (TARGET_SINGLE_FLOAT && TARGET_FLOAT64)
4700         error ("unsupported combination: %s", "-mfp64 -msingle-float");
4701     }
4702   else
4703     {
4704       /* -msingle-float selects 32-bit float registers.  Otherwise the
4705          float registers should be the same size as the integer ones.  */
4706       if (TARGET_64BIT && TARGET_DOUBLE_FLOAT)
4707         target_flags |= MASK_FLOAT64;
4708       else
4709         target_flags &= ~MASK_FLOAT64;
4710     }
4711
4712   /* End of code shared with GAS.  */
4713
4714   if ((target_flags_explicit & MASK_LONG64) == 0)
4715     {
4716       /* If no type size setting options (-mlong64,-mint64,-mlong32)
4717          were used, then set the type sizes.  In the EABI in 64 bit mode,
4718          longs and pointers are 64 bits.  Likewise for the SGI Irix6 N64
4719          ABI.  */
4720       if ((mips_abi == ABI_EABI && TARGET_64BIT) || mips_abi == ABI_64)
4721         target_flags |= MASK_LONG64;
4722       else
4723         target_flags &= ~MASK_LONG64;
4724     }
4725
4726   if (MIPS_MARCH_CONTROLS_SOFT_FLOAT
4727       && (target_flags_explicit & MASK_SOFT_FLOAT) == 0)
4728     {
4729       /* For some configurations, it is useful to have -march control
4730          the default setting of MASK_SOFT_FLOAT.  */
4731       switch ((int) mips_arch)
4732         {
4733         case PROCESSOR_R4100:
4734         case PROCESSOR_R4111:
4735         case PROCESSOR_R4120:
4736           target_flags |= MASK_SOFT_FLOAT;
4737           break;
4738
4739         default:
4740           target_flags &= ~MASK_SOFT_FLOAT;
4741           break;
4742         }
4743     }
4744
4745   if (mips_abi != ABI_32 && mips_abi != ABI_O64)
4746     flag_pcc_struct_return = 0;
4747
4748 #if defined(USE_COLLECT2)
4749   /* For IRIX 5 or IRIX 6 with integrated O32 ABI support, USE_COLLECT2 is
4750      always defined when GNU as is not in use, but collect2 is only used
4751      for the O32 ABI, so override the toplev.c and target-def.h defaults
4752      for flag_gnu_linker, TARGET_ASM_{CONSTRUCTOR, DESTRUCTOR} and
4753      TARGET_HAVE_CTORS_DTORS.
4754
4755      Since the IRIX 5 and IRIX 6 O32 assemblers cannot handle named
4756      sections, constructor/destructor handling depends on the ABI in use.
4757
4758      Since USE_COLLECT2 is defined, we only need to restore the non-collect2
4759      defaults for the N32/N64 ABIs.  */
4760   if (TARGET_IRIX && !TARGET_SGI_O32_AS)
4761     {
4762       targetm.have_ctors_dtors = true;
4763       targetm.asm_out.constructor = default_named_section_asm_out_constructor;
4764       targetm.asm_out.destructor = default_named_section_asm_out_destructor;
4765     }
4766 #endif
4767
4768   /* Handle some quirks of the IRIX 5 and IRIX 6 O32 assemblers.  */
4769
4770   if (TARGET_SGI_O32_AS)
4771     {
4772       /* They don't recognize `.[248]byte'.  */
4773       targetm.asm_out.unaligned_op.hi = "\t.align 0\n\t.half\t";
4774       targetm.asm_out.unaligned_op.si = "\t.align 0\n\t.word\t";
4775       /* The IRIX 6 O32 assembler gives an error for `align 0; .dword',
4776          contrary to the documentation, so disable it.  */
4777       targetm.asm_out.unaligned_op.di = NULL;
4778
4779       /* They cannot handle named sections.  */
4780       targetm.have_named_sections = false;
4781       /* Therefore, EH_FRAME_SECTION_NAME isn't defined and we must use
4782          collect2.  */
4783       targetm.terminate_dw2_eh_frame_info = true;
4784       targetm.asm_out.eh_frame_section = collect2_eh_frame_section;
4785
4786       /* They cannot handle debug information.  */
4787       if (write_symbols != NO_DEBUG)
4788         {
4789           /* Adapt wording to IRIX version: IRIX 5 only had a single ABI,
4790              so -mabi=32 isn't usually specified.  */
4791           if (TARGET_IRIX5)
4792             inform ("-g is only supported using GNU as,");
4793           else
4794             inform ("-g is only supported using GNU as with -mabi=32,");
4795           inform ("-g option disabled");
4796           write_symbols = NO_DEBUG;
4797         }
4798     }
4799
4800   if ((target_flags_explicit & MASK_BRANCHLIKELY) == 0)
4801     {
4802       /* If neither -mbranch-likely nor -mno-branch-likely was given
4803          on the command line, set MASK_BRANCHLIKELY based on the target
4804          architecture.
4805
4806          By default, we enable use of Branch Likely instructions on
4807          all architectures which support them except for MIPS32 and MIPS64
4808          (i.e., the generic MIPS32 and MIPS64 ISAs, and processors which
4809          implement them).
4810
4811          The MIPS32 and MIPS64 architecture specifications say "Software
4812          is strongly encouraged to avoid use of Branch Likely
4813          instructions, as they will be removed from a future revision
4814          of the [MIPS32 and MIPS64] architecture."  Therefore, we do not
4815          issue those instructions unless instructed to do so by
4816          -mbranch-likely.  */
4817       if (ISA_HAS_BRANCHLIKELY && !(ISA_MIPS32 || ISA_MIPS32R2 || ISA_MIPS64))
4818         target_flags |= MASK_BRANCHLIKELY;
4819       else
4820         target_flags &= ~MASK_BRANCHLIKELY;
4821     }
4822   if (TARGET_BRANCHLIKELY && !ISA_HAS_BRANCHLIKELY)
4823     warning ("generation of Branch Likely instructions enabled, but not supported by architecture");
4824
4825   /* The effect of -mabicalls isn't defined for the EABI.  */
4826   if (mips_abi == ABI_EABI && TARGET_ABICALLS)
4827     {
4828       error ("unsupported combination: %s", "-mabicalls -mabi=eabi");
4829       target_flags &= ~MASK_ABICALLS;
4830     }
4831
4832   /* -fpic (-KPIC) is the default when TARGET_ABICALLS is defined.  We need
4833      to set flag_pic so that the LEGITIMATE_PIC_OPERAND_P macro will work.  */
4834   /* ??? -non_shared turns off pic code generation, but this is not
4835      implemented.  */
4836   if (TARGET_ABICALLS)
4837     {
4838       flag_pic = 1;
4839       if (mips_section_threshold > 0)
4840         warning ("-G is incompatible with PIC code which is the default");
4841     }
4842
4843   /* The MIPS and SGI o32 assemblers expect small-data variables to
4844      be declared before they are used.  Although we once had code to
4845      do this, it was very invasive and fragile.  It no longer seems
4846      worth the effort.  */
4847   if (!TARGET_EXPLICIT_RELOCS && !TARGET_GAS)
4848     mips_section_threshold = 0;
4849
4850   /* We switch to small data sections using ".section", which the native
4851      o32 irix assemblers don't understand.  Disable -G accordingly.
4852      We must do this regardless of command-line options since otherwise
4853      the compiler would abort.  */
4854   if (!targetm.have_named_sections)
4855     mips_section_threshold = 0;
4856
4857   /* -membedded-pic is a form of PIC code suitable for embedded
4858      systems.  All calls are made using PC relative addressing, and
4859      all data is addressed using the $gp register.  This requires gas,
4860      which does most of the work, and GNU ld, which automatically
4861      expands PC relative calls which are out of range into a longer
4862      instruction sequence.  All gcc really does differently is
4863      generate a different sequence for a switch.  */
4864   if (TARGET_EMBEDDED_PIC)
4865     {
4866       flag_pic = 1;
4867       if (TARGET_ABICALLS)
4868         warning ("-membedded-pic and -mabicalls are incompatible");
4869
4870       if (g_switch_set)
4871         warning ("-G and -membedded-pic are incompatible");
4872
4873       /* Setting mips_section_threshold is not required, because gas
4874          will force everything to be GP addressable anyhow, but
4875          setting it will cause gcc to make better estimates of the
4876          number of instructions required to access a particular data
4877          item.  */
4878       mips_section_threshold = 0x7fffffff;
4879     }
4880
4881   /* mips_split_addresses is a half-way house between explicit
4882      relocations and the traditional assembler macros.  It can
4883      split absolute 32-bit symbolic constants into a high/lo_sum
4884      pair but uses macros for other sorts of access.
4885
4886      Like explicit relocation support for REL targets, it relies
4887      on GNU extensions in the assembler and the linker.
4888
4889      Although this code should work for -O0, it has traditionally
4890      been treated as an optimization.  */
4891   if (TARGET_GAS && !TARGET_MIPS16 && TARGET_SPLIT_ADDRESSES
4892       && optimize && !flag_pic
4893       && !ABI_HAS_64BIT_SYMBOLS)
4894     mips_split_addresses = 1;
4895   else
4896     mips_split_addresses = 0;
4897
4898   /* -mexplicit-relocs doesn't yet support non-PIC n64.  We don't know
4899      how to generate %highest/%higher/%hi/%lo sequences.  */
4900   if (mips_abi == ABI_64 && !TARGET_ABICALLS)
4901     {
4902       if ((target_flags_explicit & target_flags & MASK_EXPLICIT_RELOCS) != 0)
4903         sorry ("non-PIC n64 with explicit relocations");
4904       target_flags &= ~MASK_EXPLICIT_RELOCS;
4905     }
4906
4907   /* Explicit relocations for "old" ABIs are a GNU extension.  Unless
4908      the user has said otherwise, assume that they are not available
4909      with assemblers other than gas.  */
4910   if (!TARGET_NEWABI && !TARGET_GAS
4911       && (target_flags_explicit & MASK_EXPLICIT_RELOCS) == 0)
4912     target_flags &= ~MASK_EXPLICIT_RELOCS;
4913
4914   /* Make -mabicalls -fno-unit-at-a-time imply -mno-explicit-relocs
4915      unless the user says otherwise.
4916
4917      There are two problems here:
4918
4919        (1) The value of an R_MIPS_GOT16 relocation depends on whether
4920            the symbol is local or global.  We therefore need to know
4921            a symbol's binding before refering to it using %got().
4922
4923        (2) R_MIPS_CALL16 can only be applied to global symbols.
4924
4925      When not using -funit-at-a-time, a symbol's binding may change
4926      after it has been used.  For example, the C++ front-end will
4927      initially assume that the typeinfo for an incomplete type will be
4928      comdat, on the basis that the type could be completed later in the
4929      file.  But if the type never is completed, the typeinfo will become
4930      local instead.  */
4931   if (!flag_unit_at_a_time
4932       && TARGET_ABICALLS
4933       && (target_flags_explicit & MASK_EXPLICIT_RELOCS) == 0)
4934     target_flags &= ~MASK_EXPLICIT_RELOCS;
4935
4936   /* -mrnames says to use the MIPS software convention for register
4937      names instead of the hardware names (ie, $a0 instead of $4).
4938      We do this by switching the names in mips_reg_names, which the
4939      reg_names points into via the REGISTER_NAMES macro.  */
4940
4941   if (TARGET_NAME_REGS)
4942     memcpy (mips_reg_names, mips_sw_reg_names, sizeof (mips_reg_names));
4943
4944   /* When compiling for the mips16, we can not use floating point.  We
4945      record the original hard float value in mips16_hard_float.  */
4946   if (TARGET_MIPS16)
4947     {
4948       if (TARGET_SOFT_FLOAT)
4949         mips16_hard_float = 0;
4950       else
4951         mips16_hard_float = 1;
4952       target_flags |= MASK_SOFT_FLOAT;
4953
4954       /* Don't run the scheduler before reload, since it tends to
4955          increase register pressure.  */
4956       flag_schedule_insns = 0;
4957
4958       /* Silently disable -mexplicit-relocs since it doesn't apply
4959          to mips16 code.  Even so, it would overly pedantic to warn
4960          about "-mips16 -mexplicit-relocs", especially given that
4961          we use a %gprel() operator.  */
4962       target_flags &= ~MASK_EXPLICIT_RELOCS;
4963     }
4964
4965   /* When using explicit relocs, we call dbr_schedule from within
4966      mips_reorg.  */
4967   if (TARGET_EXPLICIT_RELOCS)
4968     {
4969       mips_flag_delayed_branch = flag_delayed_branch;
4970       flag_delayed_branch = 0;
4971     }
4972
4973 #ifdef MIPS_TFMODE_FORMAT
4974   REAL_MODE_FORMAT (TFmode) = &MIPS_TFMODE_FORMAT;
4975 #endif
4976
4977   mips_print_operand_punct['?'] = 1;
4978   mips_print_operand_punct['#'] = 1;
4979   mips_print_operand_punct['/'] = 1;
4980   mips_print_operand_punct['&'] = 1;
4981   mips_print_operand_punct['!'] = 1;
4982   mips_print_operand_punct['*'] = 1;
4983   mips_print_operand_punct['@'] = 1;
4984   mips_print_operand_punct['.'] = 1;
4985   mips_print_operand_punct['('] = 1;
4986   mips_print_operand_punct[')'] = 1;
4987   mips_print_operand_punct['['] = 1;
4988   mips_print_operand_punct[']'] = 1;
4989   mips_print_operand_punct['<'] = 1;
4990   mips_print_operand_punct['>'] = 1;
4991   mips_print_operand_punct['{'] = 1;
4992   mips_print_operand_punct['}'] = 1;
4993   mips_print_operand_punct['^'] = 1;
4994   mips_print_operand_punct['$'] = 1;
4995   mips_print_operand_punct['+'] = 1;
4996   mips_print_operand_punct['~'] = 1;
4997
4998   mips_char_to_class['d'] = TARGET_MIPS16 ? M16_REGS : GR_REGS;
4999   mips_char_to_class['e'] = M16_NA_REGS;
5000   mips_char_to_class['t'] = T_REG;
5001   mips_char_to_class['f'] = (TARGET_HARD_FLOAT ? FP_REGS : NO_REGS);
5002   mips_char_to_class['h'] = HI_REG;
5003   mips_char_to_class['l'] = LO_REG;
5004   mips_char_to_class['x'] = MD_REGS;
5005   mips_char_to_class['b'] = ALL_REGS;
5006   mips_char_to_class['c'] = (TARGET_ABICALLS ? PIC_FN_ADDR_REG :
5007                              TARGET_MIPS16 ? M16_NA_REGS :
5008                              GR_REGS);
5009   mips_char_to_class['e'] = LEA_REGS;
5010   mips_char_to_class['j'] = PIC_FN_ADDR_REG;
5011   mips_char_to_class['y'] = GR_REGS;
5012   mips_char_to_class['z'] = ST_REGS;
5013   mips_char_to_class['B'] = COP0_REGS;
5014   mips_char_to_class['C'] = COP2_REGS;
5015   mips_char_to_class['D'] = COP3_REGS;
5016
5017   /* Set up array to map GCC register number to debug register number.
5018      Ignore the special purpose register numbers.  */
5019
5020   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
5021     mips_dbx_regno[i] = -1;
5022
5023   start = GP_DBX_FIRST - GP_REG_FIRST;
5024   for (i = GP_REG_FIRST; i <= GP_REG_LAST; i++)
5025     mips_dbx_regno[i] = i + start;
5026
5027   start = FP_DBX_FIRST - FP_REG_FIRST;
5028   for (i = FP_REG_FIRST; i <= FP_REG_LAST; i++)
5029     mips_dbx_regno[i] = i + start;
5030
5031   mips_dbx_regno[HI_REGNUM] = MD_DBX_FIRST + 0;
5032   mips_dbx_regno[LO_REGNUM] = MD_DBX_FIRST + 1;
5033
5034   /* Set up array giving whether a given register can hold a given mode.  */
5035
5036   for (mode = VOIDmode;
5037        mode != MAX_MACHINE_MODE;
5038        mode = (enum machine_mode) ((int)mode + 1))
5039     {
5040       register int size              = GET_MODE_SIZE (mode);
5041       register enum mode_class class = GET_MODE_CLASS (mode);
5042
5043       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
5044         {
5045           register int temp;
5046
5047           if (mode == CCmode)
5048             {
5049               if (! ISA_HAS_8CC)
5050                 temp = (regno == FPSW_REGNUM);
5051               else
5052                 temp = (ST_REG_P (regno) || GP_REG_P (regno)
5053                         || FP_REG_P (regno));
5054             }
5055
5056           else if (GP_REG_P (regno))
5057             temp = ((regno & 1) == 0 || size <= UNITS_PER_WORD);
5058
5059           else if (FP_REG_P (regno))
5060             temp = ((regno % FP_INC) == 0)
5061                     && (((class == MODE_FLOAT || class == MODE_COMPLEX_FLOAT)
5062                          && size <= UNITS_PER_FPVALUE)
5063                         /* Allow integer modes that fit into a single
5064                            register.  We need to put integers into FPRs
5065                            when using instructions like cvt and trunc.  */
5066                         || (class == MODE_INT && size <= UNITS_PER_FPREG)
5067                         /* Allow TFmode for CCmode reloads.  */
5068                         || (ISA_HAS_8CC && mode == TFmode));
5069
5070           else if (MD_REG_P (regno))
5071             temp = (class == MODE_INT
5072                     && (size <= UNITS_PER_WORD
5073                         || (regno == MD_REG_FIRST
5074                             && size == 2 * UNITS_PER_WORD)));
5075
5076           else if (ALL_COP_REG_P (regno))
5077             temp = (class == MODE_INT && size <= UNITS_PER_WORD);
5078           else
5079             temp = 0;
5080
5081           mips_hard_regno_mode_ok[(int)mode][regno] = temp;
5082         }
5083     }
5084
5085   /* Save GPR registers in word_mode sized hunks.  word_mode hasn't been
5086      initialized yet, so we can't use that here.  */
5087   gpr_mode = TARGET_64BIT ? DImode : SImode;
5088
5089   /* Provide default values for align_* for 64-bit targets.  */
5090   if (TARGET_64BIT && !TARGET_MIPS16)
5091     {
5092       if (align_loops == 0)
5093         align_loops = 8;
5094       if (align_jumps == 0)
5095         align_jumps = 8;
5096       if (align_functions == 0)
5097         align_functions = 8;
5098     }
5099
5100   /* Function to allocate machine-dependent function status.  */
5101   init_machine_status = &mips_init_machine_status;
5102
5103   /* Create a unique alias set for GOT references.  */
5104   mips_got_alias_set = new_alias_set ();
5105
5106   if (TARGET_EXPLICIT_RELOCS || mips_split_addresses)
5107     {
5108       mips_split_p[SYMBOL_GENERAL] = true;
5109       mips_hi_relocs[SYMBOL_GENERAL] = "%hi(";
5110       mips_lo_relocs[SYMBOL_GENERAL] = "%lo(";
5111     }
5112
5113   if (TARGET_MIPS16)
5114     {
5115       /* The high part is provided by a pseudo copy of $gp.  */
5116       mips_split_p[SYMBOL_SMALL_DATA] = true;
5117       mips_lo_relocs[SYMBOL_SMALL_DATA] = "%gprel(";
5118     }
5119
5120   if (TARGET_EXPLICIT_RELOCS)
5121     {
5122       /* Small data constants are kept whole until after reload,
5123          then lowered by mips_rewrite_small_data.  */
5124       mips_lo_relocs[SYMBOL_SMALL_DATA] = "%gp_rel(";
5125
5126       mips_split_p[SYMBOL_GOT_LOCAL] = true;
5127       if (TARGET_NEWABI)
5128         {
5129           mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got_page(";
5130           mips_lo_relocs[SYMBOL_GOT_LOCAL] = "%got_ofst(";
5131         }
5132       else
5133         {
5134           mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got(";
5135           mips_lo_relocs[SYMBOL_GOT_LOCAL] = "%lo(";
5136         }
5137
5138       if (TARGET_XGOT)
5139         {
5140           /* The HIGH and LO_SUM are matched by special .md patterns.  */
5141           mips_split_p[SYMBOL_GOT_GLOBAL] = true;
5142
5143           mips_split_p[SYMBOL_GOTOFF_GLOBAL] = true;
5144           mips_hi_relocs[SYMBOL_GOTOFF_GLOBAL] = "%got_hi(";
5145           mips_lo_relocs[SYMBOL_GOTOFF_GLOBAL] = "%got_lo(";
5146
5147           mips_split_p[SYMBOL_GOTOFF_CALL] = true;
5148           mips_hi_relocs[SYMBOL_GOTOFF_CALL] = "%call_hi(";
5149           mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call_lo(";
5150         }
5151       else
5152         {
5153           if (TARGET_NEWABI)
5154             mips_lo_relocs[SYMBOL_GOTOFF_GLOBAL] = "%got_disp(";
5155           else
5156             mips_lo_relocs[SYMBOL_GOTOFF_GLOBAL] = "%got(";
5157           mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call16(";
5158         }
5159     }
5160
5161   if (TARGET_NEWABI)
5162     {
5163       mips_split_p[SYMBOL_GOTOFF_LOADGP] = true;
5164       mips_hi_relocs[SYMBOL_GOTOFF_LOADGP] = "%hi(%neg(%gp_rel(";
5165       mips_lo_relocs[SYMBOL_GOTOFF_LOADGP] = "%lo(%neg(%gp_rel(";
5166     }
5167 }
5168
5169 /* Implement CONDITIONAL_REGISTER_USAGE.  */
5170
5171 void
5172 mips_conditional_register_usage (void)
5173 {
5174   if (!TARGET_HARD_FLOAT)
5175     {
5176       int regno;
5177
5178       for (regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
5179         fixed_regs[regno] = call_used_regs[regno] = 1;
5180       for (regno = ST_REG_FIRST; regno <= ST_REG_LAST; regno++)
5181         fixed_regs[regno] = call_used_regs[regno] = 1;
5182     }
5183   else if (! ISA_HAS_8CC)
5184     {
5185       int regno;
5186
5187       /* We only have a single condition code register.  We
5188          implement this by hiding all the condition code registers,
5189          and generating RTL that refers directly to ST_REG_FIRST.  */
5190       for (regno = ST_REG_FIRST; regno <= ST_REG_LAST; regno++)
5191         fixed_regs[regno] = call_used_regs[regno] = 1;
5192     }
5193   /* In mips16 mode, we permit the $t temporary registers to be used
5194      for reload.  We prohibit the unused $s registers, since they
5195      are caller saved, and saving them via a mips16 register would
5196      probably waste more time than just reloading the value.  */
5197   if (TARGET_MIPS16)
5198     {
5199       fixed_regs[18] = call_used_regs[18] = 1;
5200       fixed_regs[19] = call_used_regs[19] = 1;
5201       fixed_regs[20] = call_used_regs[20] = 1;
5202       fixed_regs[21] = call_used_regs[21] = 1;
5203       fixed_regs[22] = call_used_regs[22] = 1;
5204       fixed_regs[23] = call_used_regs[23] = 1;
5205       fixed_regs[26] = call_used_regs[26] = 1;
5206       fixed_regs[27] = call_used_regs[27] = 1;
5207       fixed_regs[30] = call_used_regs[30] = 1;
5208     }
5209   /* fp20-23 are now caller saved.  */
5210   if (mips_abi == ABI_64)
5211     {
5212       int regno;
5213       for (regno = FP_REG_FIRST + 20; regno < FP_REG_FIRST + 24; regno++)
5214         call_really_used_regs[regno] = call_used_regs[regno] = 1;
5215     }
5216   /* Odd registers from fp21 to fp31 are now caller saved.  */
5217   if (mips_abi == ABI_N32)
5218     {
5219       int regno;
5220       for (regno = FP_REG_FIRST + 21; regno <= FP_REG_FIRST + 31; regno+=2)
5221         call_really_used_regs[regno] = call_used_regs[regno] = 1;
5222     }
5223 }
5224
5225 /* Allocate a chunk of memory for per-function machine-dependent data.  */
5226 static struct machine_function *
5227 mips_init_machine_status (void)
5228 {
5229   return ((struct machine_function *)
5230           ggc_alloc_cleared (sizeof (struct machine_function)));
5231 }
5232
5233 /* On the mips16, we want to allocate $24 (T_REG) before other
5234    registers for instructions for which it is possible.  This helps
5235    avoid shuffling registers around in order to set up for an xor,
5236    encouraging the compiler to use a cmp instead.  */
5237
5238 void
5239 mips_order_regs_for_local_alloc (void)
5240 {
5241   register int i;
5242
5243   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
5244     reg_alloc_order[i] = i;
5245
5246   if (TARGET_MIPS16)
5247     {
5248       /* It really doesn't matter where we put register 0, since it is
5249          a fixed register anyhow.  */
5250       reg_alloc_order[0] = 24;
5251       reg_alloc_order[24] = 0;
5252     }
5253 }
5254
5255 \f
5256 /* The MIPS debug format wants all automatic variables and arguments
5257    to be in terms of the virtual frame pointer (stack pointer before
5258    any adjustment in the function), while the MIPS 3.0 linker wants
5259    the frame pointer to be the stack pointer after the initial
5260    adjustment.  So, we do the adjustment here.  The arg pointer (which
5261    is eliminated) points to the virtual frame pointer, while the frame
5262    pointer (which may be eliminated) points to the stack pointer after
5263    the initial adjustments.  */
5264
5265 HOST_WIDE_INT
5266 mips_debugger_offset (rtx addr, HOST_WIDE_INT offset)
5267 {
5268   rtx offset2 = const0_rtx;
5269   rtx reg = eliminate_constant_term (addr, &offset2);
5270
5271   if (offset == 0)
5272     offset = INTVAL (offset2);
5273
5274   if (reg == stack_pointer_rtx || reg == frame_pointer_rtx
5275       || reg == hard_frame_pointer_rtx)
5276     {
5277       HOST_WIDE_INT frame_size = (!cfun->machine->frame.initialized)
5278                                   ? compute_frame_size (get_frame_size ())
5279                                   : cfun->machine->frame.total_size;
5280
5281       /* MIPS16 frame is smaller */
5282       if (frame_pointer_needed && TARGET_MIPS16)
5283         frame_size -= cfun->machine->frame.args_size;
5284
5285       offset = offset - frame_size;
5286     }
5287
5288   /* sdbout_parms does not want this to crash for unrecognized cases.  */
5289 #if 0
5290   else if (reg != arg_pointer_rtx)
5291     fatal_insn ("mips_debugger_offset called with non stack/frame/arg pointer",
5292                 addr);
5293 #endif
5294
5295   return offset;
5296 }
5297 \f
5298 /* Implement the PRINT_OPERAND macro.  The MIPS-specific operand codes are:
5299
5300    'X'  OP is CONST_INT, prints 32 bits in hexadecimal format = "0x%08x",
5301    'x'  OP is CONST_INT, prints 16 bits in hexadecimal format = "0x%04x",
5302    'h'  OP is HIGH, prints %hi(X),
5303    'd'  output integer constant in decimal,
5304    'z'  if the operand is 0, use $0 instead of normal operand.
5305    'D'  print second part of double-word register or memory operand.
5306    'L'  print low-order register of double-word register operand.
5307    'M'  print high-order register of double-word register operand.
5308    'C'  print part of opcode for a branch condition.
5309    'F'  print part of opcode for a floating-point branch condition.
5310    'N'  print part of opcode for a branch condition, inverted.
5311    'W'  print part of opcode for a floating-point branch condition, inverted.
5312    'S'  OP is CODE_LABEL, print with prefix of "LS" (for embedded switch).
5313    'B'  print 'z' for EQ, 'n' for NE
5314    'b'  print 'n' for EQ, 'z' for NE
5315    'T'  print 'f' for EQ, 't' for NE
5316    't'  print 't' for EQ, 'f' for NE
5317    'Z'  print register and a comma, but print nothing for $fcc0
5318    'R'  print the reloc associated with LO_SUM
5319
5320    The punctuation characters are:
5321
5322    '('  Turn on .set noreorder
5323    ')'  Turn on .set reorder
5324    '['  Turn on .set noat
5325    ']'  Turn on .set at
5326    '<'  Turn on .set nomacro
5327    '>'  Turn on .set macro
5328    '{'  Turn on .set volatile (not GAS)
5329    '}'  Turn on .set novolatile (not GAS)
5330    '&'  Turn on .set noreorder if filling delay slots
5331    '*'  Turn on both .set noreorder and .set nomacro if filling delay slots
5332    '!'  Turn on .set nomacro if filling delay slots
5333    '#'  Print nop if in a .set noreorder section.
5334    '/'  Like '#', but does nothing within a delayed branch sequence
5335    '?'  Print 'l' if we are to use a branch likely instead of normal branch.
5336    '@'  Print the name of the assembler temporary register (at or $1).
5337    '.'  Print the name of the register with a hard-wired zero (zero or $0).
5338    '^'  Print the name of the pic call-through register (t9 or $25).
5339    '$'  Print the name of the stack pointer register (sp or $29).
5340    '+'  Print the name of the gp register (usually gp or $28).
5341    '~'  Output a branch alignment to LABEL_ALIGN(NULL).  */
5342
5343 void
5344 print_operand (FILE *file, rtx op, int letter)
5345 {
5346   register enum rtx_code code;
5347
5348   if (PRINT_OPERAND_PUNCT_VALID_P (letter))
5349     {
5350       switch (letter)
5351         {
5352         case '?':
5353           if (mips_branch_likely)
5354             putc ('l', file);
5355           break;
5356
5357         case '@':
5358           fputs (reg_names [GP_REG_FIRST + 1], file);
5359           break;
5360
5361         case '^':
5362           fputs (reg_names [PIC_FUNCTION_ADDR_REGNUM], file);
5363           break;
5364
5365         case '.':
5366           fputs (reg_names [GP_REG_FIRST + 0], file);
5367           break;
5368
5369         case '$':
5370           fputs (reg_names[STACK_POINTER_REGNUM], file);
5371           break;
5372
5373         case '+':
5374           fputs (reg_names[PIC_OFFSET_TABLE_REGNUM], file);
5375           break;
5376
5377         case '&':
5378           if (final_sequence != 0 && set_noreorder++ == 0)
5379             fputs (".set\tnoreorder\n\t", file);
5380           break;
5381
5382         case '*':
5383           if (final_sequence != 0)
5384             {
5385               if (set_noreorder++ == 0)
5386                 fputs (".set\tnoreorder\n\t", file);
5387
5388               if (set_nomacro++ == 0)
5389                 fputs (".set\tnomacro\n\t", file);
5390             }
5391           break;
5392
5393         case '!':
5394           if (final_sequence != 0 && set_nomacro++ == 0)
5395             fputs ("\n\t.set\tnomacro", file);
5396           break;
5397
5398         case '#':
5399           if (set_noreorder != 0)
5400             fputs ("\n\tnop", file);
5401           break;
5402
5403         case '/':
5404           /* Print an extra newline so that the delayed insn is separated
5405              from the following ones.  This looks neater and is consistent
5406              with non-nop delayed sequences.  */
5407           if (set_noreorder != 0 && final_sequence == 0)
5408             fputs ("\n\tnop\n", file);
5409           break;
5410
5411         case '(':
5412           if (set_noreorder++ == 0)
5413             fputs (".set\tnoreorder\n\t", file);
5414           break;
5415
5416         case ')':
5417           if (set_noreorder == 0)
5418             error ("internal error: %%) found without a %%( in assembler pattern");
5419
5420           else if (--set_noreorder == 0)
5421             fputs ("\n\t.set\treorder", file);
5422
5423           break;
5424
5425         case '[':
5426           if (set_noat++ == 0)
5427             fputs (".set\tnoat\n\t", file);
5428           break;
5429
5430         case ']':
5431           if (set_noat == 0)
5432             error ("internal error: %%] found without a %%[ in assembler pattern");
5433           else if (--set_noat == 0)
5434             fputs ("\n\t.set\tat", file);
5435
5436           break;
5437
5438         case '<':
5439           if (set_nomacro++ == 0)
5440             fputs (".set\tnomacro\n\t", file);
5441           break;
5442
5443         case '>':
5444           if (set_nomacro == 0)
5445             error ("internal error: %%> found without a %%< in assembler pattern");
5446           else if (--set_nomacro == 0)
5447             fputs ("\n\t.set\tmacro", file);
5448
5449           break;
5450
5451         case '{':
5452           if (set_volatile++ == 0)
5453             fprintf (file, "%s.set\tvolatile\n\t", TARGET_MIPS_AS ? "" : "#");
5454           break;
5455
5456         case '}':
5457           if (set_volatile == 0)
5458             error ("internal error: %%} found without a %%{ in assembler pattern");
5459           else if (--set_volatile == 0)
5460             fprintf (file, "\n\t%s.set\tnovolatile", (TARGET_MIPS_AS) ? "" : "#");
5461
5462           break;
5463
5464         case '~':
5465           {
5466             if (align_labels_log > 0)
5467               ASM_OUTPUT_ALIGN (file, align_labels_log);
5468           }
5469         break;
5470
5471         default:
5472           error ("PRINT_OPERAND: unknown punctuation '%c'", letter);
5473           break;
5474         }
5475
5476       return;
5477     }
5478
5479   if (! op)
5480     {
5481       error ("PRINT_OPERAND null pointer");
5482       return;
5483     }
5484
5485   code = GET_CODE (op);
5486
5487   if (letter == 'C')
5488     switch (code)
5489       {
5490       case EQ:  fputs ("eq",  file); break;
5491       case NE:  fputs ("ne",  file); break;
5492       case GT:  fputs ("gt",  file); break;
5493       case GE:  fputs ("ge",  file); break;
5494       case LT:  fputs ("lt",  file); break;
5495       case LE:  fputs ("le",  file); break;
5496       case GTU: fputs ("gtu", file); break;
5497       case GEU: fputs ("geu", file); break;
5498       case LTU: fputs ("ltu", file); break;
5499       case LEU: fputs ("leu", file); break;
5500       default:
5501         fatal_insn ("PRINT_OPERAND, invalid insn for %%C", op);
5502       }
5503
5504   else if (letter == 'N')
5505     switch (code)
5506       {
5507       case EQ:  fputs ("ne",  file); break;
5508       case NE:  fputs ("eq",  file); break;
5509       case GT:  fputs ("le",  file); break;
5510       case GE:  fputs ("lt",  file); break;
5511       case LT:  fputs ("ge",  file); break;
5512       case LE:  fputs ("gt",  file); break;
5513       case GTU: fputs ("leu", file); break;
5514       case GEU: fputs ("ltu", file); break;
5515       case LTU: fputs ("geu", file); break;
5516       case LEU: fputs ("gtu", file); break;
5517       default:
5518         fatal_insn ("PRINT_OPERAND, invalid insn for %%N", op);
5519       }
5520
5521   else if (letter == 'F')
5522     switch (code)
5523       {
5524       case EQ: fputs ("c1f", file); break;
5525       case NE: fputs ("c1t", file); break;
5526       default:
5527         fatal_insn ("PRINT_OPERAND, invalid insn for %%F", op);
5528       }
5529
5530   else if (letter == 'W')
5531     switch (code)
5532       {
5533       case EQ: fputs ("c1t", file); break;
5534       case NE: fputs ("c1f", file); break;
5535       default:
5536         fatal_insn ("PRINT_OPERAND, invalid insn for %%W", op);
5537       }
5538
5539   else if (letter == 'h')
5540     {
5541       if (GET_CODE (op) == HIGH)
5542         op = XEXP (op, 0);
5543
5544       print_operand_reloc (file, op, mips_hi_relocs);
5545     }
5546
5547   else if (letter == 'R')
5548     print_operand_reloc (file, op, mips_lo_relocs);
5549
5550   else if (letter == 'S')
5551     {
5552       char buffer[100];
5553
5554       ASM_GENERATE_INTERNAL_LABEL (buffer, "LS", CODE_LABEL_NUMBER (op));
5555       assemble_name (file, buffer);
5556     }
5557
5558   else if (letter == 'Z')
5559     {
5560       register int regnum;
5561
5562       if (code != REG)
5563         abort ();
5564
5565       regnum = REGNO (op);
5566       if (! ST_REG_P (regnum))
5567         abort ();
5568
5569       if (regnum != ST_REG_FIRST)
5570         fprintf (file, "%s,", reg_names[regnum]);
5571     }
5572
5573   else if (code == REG || code == SUBREG)
5574     {
5575       register int regnum;
5576
5577       if (code == REG)
5578         regnum = REGNO (op);
5579       else
5580         regnum = true_regnum (op);
5581
5582       if ((letter == 'M' && ! WORDS_BIG_ENDIAN)
5583           || (letter == 'L' && WORDS_BIG_ENDIAN)
5584           || letter == 'D')
5585         regnum++;
5586
5587       fprintf (file, "%s", reg_names[regnum]);
5588     }
5589
5590   else if (code == MEM)
5591     {
5592       if (letter == 'D')
5593         output_address (plus_constant (XEXP (op, 0), 4));
5594       else
5595         output_address (XEXP (op, 0));
5596     }
5597
5598   else if (letter == 'x' && GET_CODE (op) == CONST_INT)
5599     fprintf (file, HOST_WIDE_INT_PRINT_HEX, 0xffff & INTVAL(op));
5600
5601   else if (letter == 'X' && GET_CODE(op) == CONST_INT)
5602     fprintf (file, HOST_WIDE_INT_PRINT_HEX, INTVAL (op));
5603
5604   else if (letter == 'd' && GET_CODE(op) == CONST_INT)
5605     fprintf (file, HOST_WIDE_INT_PRINT_DEC, (INTVAL(op)));
5606
5607   else if (letter == 'z' && op == CONST0_RTX (GET_MODE (op)))
5608     fputs (reg_names[GP_REG_FIRST], file);
5609
5610   else if (letter == 'd' || letter == 'x' || letter == 'X')
5611     output_operand_lossage ("invalid use of %%d, %%x, or %%X");
5612
5613   else if (letter == 'B')
5614     fputs (code == EQ ? "z" : "n", file);
5615   else if (letter == 'b')
5616     fputs (code == EQ ? "n" : "z", file);
5617   else if (letter == 'T')
5618     fputs (code == EQ ? "f" : "t", file);
5619   else if (letter == 't')
5620     fputs (code == EQ ? "t" : "f", file);
5621
5622   else if (CONST_GP_P (op))
5623     print_operand (file, XEXP (op, 0), letter);
5624
5625   else
5626     output_addr_const (file, op);
5627 }
5628
5629
5630 /* Print symbolic operand OP, which is part of a HIGH or LO_SUM.
5631    RELOCS is the array of relocations to use.  */
5632
5633 static void
5634 print_operand_reloc (FILE *file, rtx op, const char **relocs)
5635 {
5636   enum mips_symbol_type symbol_type;
5637   const char *p;
5638   rtx base;
5639   HOST_WIDE_INT offset;
5640
5641   if (!mips_symbolic_constant_p (op, &symbol_type) || relocs[symbol_type] == 0)
5642     fatal_insn ("PRINT_OPERAND, invalid operand for relocation", op);
5643
5644   /* If OP uses an UNSPEC address, we want to print the inner symbol.  */
5645   mips_split_const (op, &base, &offset);
5646   if (UNSPEC_ADDRESS_P (base))
5647     op = plus_constant (UNSPEC_ADDRESS (base), offset);
5648
5649   fputs (relocs[symbol_type], file);
5650   output_addr_const (file, op);
5651   for (p = relocs[symbol_type]; *p != 0; p++)
5652     if (*p == '(')
5653       fputc (')', file);
5654 }
5655 \f
5656 /* Output address operand X to FILE.  */
5657
5658 void
5659 print_operand_address (FILE *file, rtx x)
5660 {
5661   struct mips_address_info addr;
5662
5663   if (mips_classify_address (&addr, x, word_mode, true))
5664     switch (addr.type)
5665       {
5666       case ADDRESS_REG:
5667         print_operand (file, addr.offset, 0);
5668         fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
5669         return;
5670
5671       case ADDRESS_LO_SUM:
5672         print_operand (file, addr.offset, 'R');
5673         fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
5674         return;
5675
5676       case ADDRESS_CONST_INT:
5677       case ADDRESS_SYMBOLIC:
5678         output_addr_const (file, x);
5679         return;
5680       }
5681   abort ();
5682 }
5683 \f
5684 /* Target hook for assembling integer objects.  It appears that the Irix
5685    6 assembler can't handle 64-bit decimal integers, so avoid printing
5686    such an integer here.  */
5687
5688 static bool
5689 mips_assemble_integer (rtx x, unsigned int size, int aligned_p)
5690 {
5691   if ((TARGET_64BIT || TARGET_GAS) && size == 8 && aligned_p)
5692     {
5693       fputs ("\t.dword\t", asm_out_file);
5694       if (HOST_BITS_PER_WIDE_INT < 64 || GET_CODE (x) != CONST_INT)
5695         output_addr_const (asm_out_file, x);
5696       else
5697         print_operand (asm_out_file, x, 'X');
5698       fputc ('\n', asm_out_file);
5699       return true;
5700     }
5701   return default_assemble_integer (x, size, aligned_p);
5702 }
5703 \f
5704 /* When using assembler macros, keep track of all of small-data externs
5705    so that mips_file_end can emit the appropriate declarations for them.
5706
5707    In most cases it would be safe (though pointless) to emit .externs
5708    for other symbols too.  One exception is when an object is within
5709    the -G limit but declared by the user to be in a section other
5710    than .sbss or .sdata.  */
5711
5712 int
5713 mips_output_external (FILE *file ATTRIBUTE_UNUSED, tree decl, const char *name)
5714 {
5715   register struct extern_list *p;
5716
5717   if (!TARGET_EXPLICIT_RELOCS && mips_in_small_data_p (decl))
5718     {
5719       p = (struct extern_list *) ggc_alloc (sizeof (struct extern_list));
5720       p->next = extern_head;
5721       p->name = name;
5722       p->size = int_size_in_bytes (TREE_TYPE (decl));
5723       extern_head = p;
5724     }
5725
5726   if (TARGET_IRIX && mips_abi == ABI_32 && TREE_CODE (decl) == FUNCTION_DECL)
5727     {
5728       p = (struct extern_list *) ggc_alloc (sizeof (struct extern_list));
5729       p->next = extern_head;
5730       p->name = name;
5731       p->size = -1;
5732       extern_head = p;
5733     }
5734
5735   return 0;
5736 }
5737
5738 #if TARGET_IRIX
5739 void
5740 irix_output_external_libcall (rtx fun)
5741 {
5742   register struct extern_list *p;
5743
5744   if (mips_abi == ABI_32)
5745     {
5746       p = (struct extern_list *) ggc_alloc (sizeof (struct extern_list));
5747       p->next = extern_head;
5748       p->name = XSTR (fun, 0);
5749       p->size = -1;
5750       extern_head = p;
5751     }
5752 }
5753 #endif
5754 \f
5755 /* Emit a new filename to a stream.  If we are smuggling stabs, try to
5756    put out a MIPS ECOFF file and a stab.  */
5757
5758 void
5759 mips_output_filename (FILE *stream, const char *name)
5760 {
5761   char ltext_label_name[100];
5762
5763   /* If we are emitting DWARF-2, let dwarf2out handle the ".file"
5764      directives.  */
5765   if (write_symbols == DWARF2_DEBUG)
5766     return;
5767   else if (mips_output_filename_first_time)
5768     {
5769       mips_output_filename_first_time = 0;
5770       SET_FILE_NUMBER ();
5771       current_function_file = name;
5772       ASM_OUTPUT_FILENAME (stream, num_source_filenames, name);
5773       /* This tells mips-tfile that stabs will follow.  */
5774       if (!TARGET_GAS && write_symbols == DBX_DEBUG)
5775         fprintf (stream, "\t#@stabs\n");
5776     }
5777
5778   else if (write_symbols == DBX_DEBUG)
5779     {
5780       ASM_GENERATE_INTERNAL_LABEL (ltext_label_name, "Ltext", 0);
5781       fprintf (stream, "%s", ASM_STABS_OP);
5782       output_quoted_string (stream, name);
5783       fprintf (stream, ",%d,0,0,%s\n", N_SOL, &ltext_label_name[1]);
5784     }
5785
5786   else if (name != current_function_file
5787            && strcmp (name, current_function_file) != 0)
5788     {
5789       SET_FILE_NUMBER ();
5790       current_function_file = name;
5791       ASM_OUTPUT_FILENAME (stream, num_source_filenames, name);
5792     }
5793 }
5794 \f
5795 /* Emit a linenumber.  For encapsulated stabs, we need to put out a stab
5796    as well as a .loc, since it is possible that MIPS ECOFF might not be
5797    able to represent the location for inlines that come from a different
5798    file.  */
5799
5800 void
5801 mips_output_lineno (FILE *stream, int line)
5802 {
5803   if (write_symbols == DBX_DEBUG)
5804     {
5805       ++sym_lineno;
5806       fprintf (stream, "%sLM%d:\n%s%d,0,%d,%sLM%d\n",
5807                LOCAL_LABEL_PREFIX, sym_lineno, ASM_STABN_OP, N_SLINE, line,
5808                LOCAL_LABEL_PREFIX, sym_lineno);
5809     }
5810   else
5811     {
5812       fprintf (stream, "\n\t.loc\t%d %d\n", num_source_filenames, line);
5813       LABEL_AFTER_LOC (stream);
5814     }
5815 }
5816 \f
5817 /* Output an ASCII string, in a space-saving way.  */
5818
5819 void
5820 mips_output_ascii (FILE *stream, const char *string_param, size_t len)
5821 {
5822   size_t i;
5823   int cur_pos = 17;
5824   register const unsigned char *string =
5825     (const unsigned char *)string_param;
5826
5827   fprintf (stream, "\t.ascii\t\"");
5828   for (i = 0; i < len; i++)
5829     {
5830       register int c = string[i];
5831
5832       switch (c)
5833         {
5834         case '\"':
5835         case '\\':
5836           putc ('\\', stream);
5837           putc (c, stream);
5838           cur_pos += 2;
5839           break;
5840
5841         case TARGET_NEWLINE:
5842           fputs ("\\n", stream);
5843           if (i+1 < len
5844               && (((c = string[i+1]) >= '\040' && c <= '~')
5845                   || c == TARGET_TAB))
5846             cur_pos = 32767;            /* break right here */
5847           else
5848             cur_pos += 2;
5849           break;
5850
5851         case TARGET_TAB:
5852           fputs ("\\t", stream);
5853           cur_pos += 2;
5854           break;
5855
5856         case TARGET_FF:
5857           fputs ("\\f", stream);
5858           cur_pos += 2;
5859           break;
5860
5861         case TARGET_BS:
5862           fputs ("\\b", stream);
5863           cur_pos += 2;
5864           break;
5865
5866         case TARGET_CR:
5867           fputs ("\\r", stream);
5868           cur_pos += 2;
5869           break;
5870
5871         default:
5872           if (c >= ' ' && c < 0177)
5873             {
5874               putc (c, stream);
5875               cur_pos++;
5876             }
5877           else
5878             {
5879               fprintf (stream, "\\%03o", c);
5880               cur_pos += 4;
5881             }
5882         }
5883
5884       if (cur_pos > 72 && i+1 < len)
5885         {
5886           cur_pos = 17;
5887           fprintf (stream, "\"\n\t.ascii\t\"");
5888         }
5889     }
5890   fprintf (stream, "\"\n");
5891 }
5892 \f
5893 /* Implement TARGET_ASM_FILE_START.  */
5894
5895 static void
5896 mips_file_start (void)
5897 {
5898   default_file_start ();
5899
5900   /* Versions of the MIPS assembler before 2.20 generate errors if a branch
5901      inside of a .set noreorder section jumps to a label outside of the .set
5902      noreorder section.  Revision 2.20 just set nobopt silently rather than
5903      fixing the bug.  */
5904
5905   if (TARGET_MIPS_AS && optimize && flag_delayed_branch)
5906     fprintf (asm_out_file, "\t.set\tnobopt\n");
5907
5908   if (TARGET_GAS)
5909     {
5910 #if defined(OBJECT_FORMAT_ELF) && !TARGET_IRIX
5911       /* Generate a special section to describe the ABI switches used to
5912          produce the resultant binary.  This used to be done by the assembler
5913          setting bits in the ELF header's flags field, but we have run out of
5914          bits.  GDB needs this information in order to be able to correctly
5915          debug these binaries.  See the function mips_gdbarch_init() in
5916          gdb/mips-tdep.c.  This is unnecessary for the IRIX 5/6 ABIs and
5917          causes unnecessary IRIX 6 ld warnings.  */
5918       const char * abi_string = NULL;
5919
5920       switch (mips_abi)
5921         {
5922         case ABI_32:   abi_string = "abi32"; break;
5923         case ABI_N32:  abi_string = "abiN32"; break;
5924         case ABI_64:   abi_string = "abi64"; break;
5925         case ABI_O64:  abi_string = "abiO64"; break;
5926         case ABI_EABI: abi_string = TARGET_64BIT ? "eabi64" : "eabi32"; break;
5927         default:
5928           abort ();
5929         }
5930       /* Note - we use fprintf directly rather than called named_section()
5931          because in this way we can avoid creating an allocated section.  We
5932          do not want this section to take up any space in the running
5933          executable.  */
5934       fprintf (asm_out_file, "\t.section .mdebug.%s\n", abi_string);
5935
5936       /* Restore the default section.  */
5937       fprintf (asm_out_file, "\t.previous\n");
5938 #endif
5939     }
5940
5941   /* Generate the pseudo ops that System V.4 wants.  */
5942 #ifndef ABICALLS_ASM_OP
5943 #define ABICALLS_ASM_OP "\t.abicalls"
5944 #endif
5945   if (TARGET_ABICALLS)
5946     /* ??? but do not want this (or want pic0) if -non-shared? */
5947     fprintf (asm_out_file, "%s\n", ABICALLS_ASM_OP);
5948
5949   if (TARGET_MIPS16)
5950     fprintf (asm_out_file, "\t.set\tmips16\n");
5951
5952   if (flag_verbose_asm)
5953     fprintf (asm_out_file, "\n%s -G value = %d, Arch = %s, ISA = %d\n",
5954              ASM_COMMENT_START,
5955              mips_section_threshold, mips_arch_info->name, mips_isa);
5956 }
5957
5958 #ifdef BSS_SECTION_ASM_OP
5959 /* Implement ASM_OUTPUT_ALIGNED_BSS.  This differs from the default only
5960    in the use of sbss.  */
5961
5962 void
5963 mips_output_aligned_bss (FILE *stream, tree decl, const char *name,
5964                          unsigned HOST_WIDE_INT size, int align)
5965 {
5966   extern tree last_assemble_variable_decl;
5967
5968   if (mips_in_small_data_p (decl))
5969     named_section (0, ".sbss", 0);
5970   else
5971     bss_section ();
5972   ASM_OUTPUT_ALIGN (stream, floor_log2 (align / BITS_PER_UNIT));
5973   last_assemble_variable_decl = decl;
5974   ASM_DECLARE_OBJECT_NAME (stream, name, decl);
5975   ASM_OUTPUT_SKIP (stream, size != 0 ? size : 1);
5976 }
5977 #endif
5978 \f
5979 /* Implement TARGET_ASM_FILE_END.  When using assembler macros, emit
5980    .externs for any small-data variables that turned out to be external.  */
5981
5982 static void
5983 mips_file_end (void)
5984 {
5985   tree name_tree;
5986   struct extern_list *p;
5987
5988   if (extern_head)
5989     {
5990       fputs ("\n", asm_out_file);
5991
5992       for (p = extern_head; p != 0; p = p->next)
5993         {
5994           name_tree = get_identifier (p->name);
5995
5996           /* Positively ensure only one .extern for any given symbol.  */
5997           if (!TREE_ASM_WRITTEN (name_tree)
5998               && TREE_SYMBOL_REFERENCED (name_tree))
5999             {
6000               TREE_ASM_WRITTEN (name_tree) = 1;
6001               /* In IRIX 5 or IRIX 6 for the O32 ABI, we must output a
6002                  `.global name .text' directive for every used but
6003                  undefined function.  If we don't, the linker may perform
6004                  an optimization (skipping over the insns that set $gp)
6005                  when it is unsafe.  */
6006               if (TARGET_IRIX && mips_abi == ABI_32 && p->size == -1)
6007                 {
6008                   fputs ("\t.globl ", asm_out_file);                   
6009                   assemble_name (asm_out_file, p->name);
6010                   fputs (" .text\n", asm_out_file);
6011                 }
6012               else
6013                 {
6014                   fputs ("\t.extern\t", asm_out_file);
6015                   assemble_name (asm_out_file, p->name);
6016                   fprintf (asm_out_file, ", %d\n", p->size);
6017                 }
6018             }
6019         }
6020     }
6021 }
6022
6023 /* Emit either a label, .comm, or .lcomm directive.  When using assembler
6024    macros, mark the symbol as written so that mips_file_end won't emit an
6025    .extern for it.  */
6026
6027 void
6028 mips_declare_object (FILE *stream, const char *name, const char *init_string,
6029                      const char *final_string, int size)
6030 {
6031   fputs (init_string, stream);          /* "", "\t.comm\t", or "\t.lcomm\t" */
6032   assemble_name (stream, name);
6033   fprintf (stream, final_string, size); /* ":\n", ",%u\n", ",%u\n" */
6034
6035   if (!TARGET_EXPLICIT_RELOCS)
6036     {
6037       tree name_tree = get_identifier (name);
6038       TREE_ASM_WRITTEN (name_tree) = 1;
6039     }
6040 }
6041
6042 #ifdef ASM_OUTPUT_SIZE_DIRECTIVE
6043 extern int size_directive_output;
6044
6045 /* Implement ASM_DECLARE_OBJECT_NAME.  This is like most of the standard ELF
6046    definitions except that it uses mips_declare_object() to emit the label.  */
6047
6048 void
6049 mips_declare_object_name (FILE *stream, const char *name,
6050                           tree decl ATTRIBUTE_UNUSED)
6051 {
6052   if (!TARGET_SGI_O32_AS)
6053     {
6054 #ifdef ASM_OUTPUT_TYPE_DIRECTIVE
6055       ASM_OUTPUT_TYPE_DIRECTIVE (stream, name, "object");
6056 #endif
6057
6058       size_directive_output = 0;
6059       if (!flag_inhibit_size_directive && DECL_SIZE (decl))
6060         {
6061           HOST_WIDE_INT size;
6062
6063           size_directive_output = 1;
6064           size = int_size_in_bytes (TREE_TYPE (decl));
6065           ASM_OUTPUT_SIZE_DIRECTIVE (stream, name, size);
6066         }
6067     }
6068
6069   mips_declare_object (stream, name, "", ":\n", 0);
6070 }
6071
6072 /* Implement ASM_FINISH_DECLARE_OBJECT.  This is generic ELF stuff.  */
6073
6074 void
6075 mips_finish_declare_object (FILE *stream, tree decl, int top_level, int at_end)
6076 {
6077   const char *name;
6078
6079   name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
6080   if (!TARGET_SGI_O32_AS
6081       && !flag_inhibit_size_directive
6082       && DECL_SIZE (decl) != 0
6083       && !at_end && top_level
6084       && DECL_INITIAL (decl) == error_mark_node
6085       && !size_directive_output)
6086     {
6087       HOST_WIDE_INT size;
6088
6089       size_directive_output = 1;
6090       size = int_size_in_bytes (TREE_TYPE (decl));
6091       ASM_OUTPUT_SIZE_DIRECTIVE (stream, name, size);
6092     }
6093 }
6094 #endif
6095 \f
6096 /* Return true if X is a small data address that can be rewritten
6097    as a LO_SUM.  */
6098
6099 static bool
6100 mips_rewrite_small_data_p (rtx x)
6101 {
6102   enum mips_symbol_type symbol_type;
6103
6104   return (TARGET_EXPLICIT_RELOCS
6105           && mips_symbolic_constant_p (x, &symbol_type)
6106           && symbol_type == SYMBOL_SMALL_DATA);
6107 }
6108
6109
6110 /* A for_each_rtx callback for small_data_pattern.  */
6111
6112 static int
6113 small_data_pattern_1 (rtx *loc, void *data ATTRIBUTE_UNUSED)
6114 {
6115   if (GET_CODE (*loc) == LO_SUM)
6116     return -1;
6117
6118   return mips_rewrite_small_data_p (*loc);
6119 }
6120
6121 /* Return true if OP refers to small data symbols directly, not through
6122    a LO_SUM.  */
6123
6124 int
6125 small_data_pattern (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
6126 {
6127   return (GET_CODE (op) != SEQUENCE
6128           && for_each_rtx (&op, small_data_pattern_1, 0));
6129 }
6130 \f
6131 /* A for_each_rtx callback, used by mips_rewrite_small_data.  */
6132
6133 static int
6134 mips_rewrite_small_data_1 (rtx *loc, void *data ATTRIBUTE_UNUSED)
6135 {
6136   if (mips_rewrite_small_data_p (*loc))
6137     *loc = gen_rtx_LO_SUM (Pmode, pic_offset_table_rtx, *loc);
6138
6139   if (GET_CODE (*loc) == LO_SUM)
6140     return -1;
6141
6142   return 0;
6143 }
6144
6145 /* If possible, rewrite OP so that it refers to small data using
6146    explicit relocations.  */
6147
6148 rtx
6149 mips_rewrite_small_data (rtx op)
6150 {
6151   op = copy_insn (op);
6152   for_each_rtx (&op, mips_rewrite_small_data_1, 0);
6153   return op;
6154 }
6155 \f
6156 /* Return true if the current function has an insn that implicitly
6157    refers to $gp.  */
6158
6159 static bool
6160 mips_function_has_gp_insn (void)
6161 {
6162   /* Don't bother rechecking if we found one last time.  */
6163   if (!cfun->machine->has_gp_insn_p)
6164     {
6165       rtx insn;
6166
6167       push_topmost_sequence ();
6168       for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
6169         if (INSN_P (insn)
6170             && GET_CODE (PATTERN (insn)) != USE
6171             && GET_CODE (PATTERN (insn)) != CLOBBER
6172             && (get_attr_got (insn) != GOT_UNSET
6173                 || small_data_pattern (PATTERN (insn), VOIDmode)))
6174           break;
6175       pop_topmost_sequence ();
6176
6177       cfun->machine->has_gp_insn_p = (insn != 0);
6178     }
6179   return cfun->machine->has_gp_insn_p;
6180 }
6181
6182
6183 /* Return the register that should be used as the global pointer
6184    within this function.  Return 0 if the function doesn't need
6185    a global pointer.  */
6186
6187 static unsigned int
6188 mips_global_pointer (void)
6189 {
6190   unsigned int regno;
6191
6192   /* $gp is always available in non-abicalls code.  */
6193   if (!TARGET_ABICALLS)
6194     return GLOBAL_POINTER_REGNUM;
6195
6196   /* We must always provide $gp when it is used implicitly.  */
6197   if (!TARGET_EXPLICIT_RELOCS)
6198     return GLOBAL_POINTER_REGNUM;
6199
6200   /* FUNCTION_PROFILER includes a jal macro, so we need to give it
6201      a valid gp.  */
6202   if (current_function_profile)
6203     return GLOBAL_POINTER_REGNUM;
6204
6205   /* If the function has a nonlocal goto, $gp must hold the correct
6206      global pointer for the target function.  */
6207   if (current_function_has_nonlocal_goto)
6208     return GLOBAL_POINTER_REGNUM;
6209
6210   /* If the gp is never referenced, there's no need to initialize it.
6211      Note that reload can sometimes introduce constant pool references
6212      into a function that otherwise didn't need them.  For example,
6213      suppose we have an instruction like:
6214
6215           (set (reg:DF R1) (float:DF (reg:SI R2)))
6216
6217      If R2 turns out to be constant such as 1, the instruction may have a
6218      REG_EQUAL note saying that R1 == 1.0.  Reload then has the option of
6219      using this constant if R2 doesn't get allocated to a register.
6220
6221      In cases like these, reload will have added the constant to the pool
6222      but no instruction will yet refer to it.  */
6223   if (!regs_ever_live[GLOBAL_POINTER_REGNUM]
6224       && !current_function_uses_const_pool
6225       && !mips_function_has_gp_insn ())
6226     return 0;
6227
6228   /* We need a global pointer, but perhaps we can use a call-clobbered
6229      register instead of $gp.  */
6230   if (TARGET_NEWABI && current_function_is_leaf)
6231     for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
6232       if (!regs_ever_live[regno]
6233           && call_used_regs[regno]
6234           && !fixed_regs[regno]
6235           && regno != PIC_FUNCTION_ADDR_REGNUM)
6236         return regno;
6237
6238   return GLOBAL_POINTER_REGNUM;
6239 }
6240
6241
6242 /* Return true if the current function must save REGNO.  */
6243
6244 static bool
6245 mips_save_reg_p (unsigned int regno)
6246 {
6247   /* We only need to save $gp for NewABI PIC.  */
6248   if (regno == GLOBAL_POINTER_REGNUM)
6249     return (TARGET_ABICALLS && TARGET_NEWABI
6250             && cfun->machine->global_pointer == regno);
6251
6252   /* Check call-saved registers.  */
6253   if (regs_ever_live[regno] && !call_used_regs[regno])
6254     return true;
6255
6256   /* We need to save the old frame pointer before setting up a new one.  */
6257   if (regno == HARD_FRAME_POINTER_REGNUM && frame_pointer_needed)
6258     return true;
6259
6260   /* We need to save the incoming return address if it is ever clobbered
6261      within the function.  */
6262   if (regno == GP_REG_FIRST + 31 && regs_ever_live[regno])
6263     return true;
6264
6265   if (TARGET_MIPS16)
6266     {
6267       tree return_type;
6268
6269       return_type = DECL_RESULT (current_function_decl);
6270
6271       /* $18 is a special case in mips16 code.  It may be used to call
6272          a function which returns a floating point value, but it is
6273          marked in call_used_regs.  */
6274       if (regno == GP_REG_FIRST + 18 && regs_ever_live[regno])
6275         return true;
6276
6277       /* $31 is also a special case.  It will be used to copy a return
6278          value into the floating point registers if the return value is
6279          floating point.  */
6280       if (regno == GP_REG_FIRST + 31
6281           && mips16_hard_float
6282           && !aggregate_value_p (return_type, current_function_decl)
6283           && GET_MODE_CLASS (DECL_MODE (return_type)) == MODE_FLOAT
6284           && GET_MODE_SIZE (DECL_MODE (return_type)) <= UNITS_PER_FPVALUE)
6285         return true;
6286     }
6287
6288   return false;
6289 }
6290
6291
6292 /* Return the bytes needed to compute the frame pointer from the current
6293    stack pointer.  SIZE is the size (in bytes) of the local variables.
6294
6295    Mips stack frames look like:
6296
6297              Before call                        After call
6298         +-----------------------+       +-----------------------+
6299    high |                       |       |                       |
6300    mem. |                       |       |                       |
6301         |  caller's temps.      |       |  caller's temps.      |
6302         |                       |       |                       |
6303         +-----------------------+       +-----------------------+
6304         |                       |       |                       |
6305         |  arguments on stack.  |       |  arguments on stack.  |
6306         |                       |       |                       |
6307         +-----------------------+       +-----------------------+
6308         |  4 words to save      |       |  4 words to save      |
6309         |  arguments passed     |       |  arguments passed     |
6310         |  in registers, even   |       |  in registers, even   |
6311     SP->|  if not passed.       |  VFP->|  if not passed.       |
6312         +-----------------------+       +-----------------------+
6313                                         |                       |
6314                                         |  fp register save     |
6315                                         |                       |
6316                                         +-----------------------+
6317                                         |                       |
6318                                         |  gp register save     |
6319                                         |                       |
6320                                         +-----------------------+
6321                                         |                       |
6322                                         |  local variables      |
6323                                         |                       |
6324                                         +-----------------------+
6325                                         |                       |
6326                                         |  alloca allocations   |
6327                                         |                       |
6328                                         +-----------------------+
6329                                         |                       |
6330                                         |  GP save for V.4 abi  |
6331                                         |                       |
6332                                         +-----------------------+
6333                                         |                       |
6334                                         |  arguments on stack   |
6335                                         |                       |
6336                                         +-----------------------+
6337                                         |  4 words to save      |
6338                                         |  arguments passed     |
6339                                         |  in registers, even   |
6340    low                              SP->|  if not passed.       |
6341    memory                               +-----------------------+
6342
6343 */
6344
6345 HOST_WIDE_INT
6346 compute_frame_size (HOST_WIDE_INT size)
6347 {
6348   unsigned int regno;
6349   HOST_WIDE_INT total_size;     /* # bytes that the entire frame takes up */
6350   HOST_WIDE_INT var_size;       /* # bytes that variables take up */
6351   HOST_WIDE_INT args_size;      /* # bytes that outgoing arguments take up */
6352   HOST_WIDE_INT cprestore_size; /* # bytes that the cprestore slot takes up */
6353   HOST_WIDE_INT gp_reg_rounded; /* # bytes needed to store gp after rounding */
6354   HOST_WIDE_INT gp_reg_size;    /* # bytes needed to store gp regs */
6355   HOST_WIDE_INT fp_reg_size;    /* # bytes needed to store fp regs */
6356   unsigned int mask;            /* mask of saved gp registers */
6357   unsigned int fmask;           /* mask of saved fp registers */
6358
6359   cfun->machine->global_pointer = mips_global_pointer ();
6360
6361   gp_reg_size = 0;
6362   fp_reg_size = 0;
6363   mask = 0;
6364   fmask = 0;
6365   var_size = MIPS_STACK_ALIGN (size);
6366   args_size = current_function_outgoing_args_size;
6367   cprestore_size = MIPS_STACK_ALIGN (STARTING_FRAME_OFFSET) - args_size;
6368
6369   /* The space set aside by STARTING_FRAME_OFFSET isn't needed in leaf
6370      functions.  If the function has local variables, we're committed
6371      to allocating it anyway.  Otherwise reclaim it here.  */
6372   if (var_size == 0 && current_function_is_leaf)
6373     cprestore_size = args_size = 0;
6374
6375   /* The MIPS 3.0 linker does not like functions that dynamically
6376      allocate the stack and have 0 for STACK_DYNAMIC_OFFSET, since it
6377      looks like we are trying to create a second frame pointer to the
6378      function, so allocate some stack space to make it happy.  */
6379
6380   if (args_size == 0 && current_function_calls_alloca)
6381     args_size = 4 * UNITS_PER_WORD;
6382
6383   total_size = var_size + args_size + cprestore_size;
6384
6385   /* Calculate space needed for gp registers.  */
6386   for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
6387     if (mips_save_reg_p (regno))
6388       {
6389         gp_reg_size += GET_MODE_SIZE (gpr_mode);
6390         mask |= 1 << (regno - GP_REG_FIRST);
6391       }
6392
6393   /* We need to restore these for the handler.  */
6394   if (current_function_calls_eh_return)
6395     {
6396       unsigned int i;
6397       for (i = 0; ; ++i)
6398         {
6399           regno = EH_RETURN_DATA_REGNO (i);
6400           if (regno == INVALID_REGNUM)
6401             break;
6402           gp_reg_size += GET_MODE_SIZE (gpr_mode);
6403           mask |= 1 << (regno - GP_REG_FIRST);
6404         }
6405     }
6406
6407   /* This loop must iterate over the same space as its companion in
6408      save_restore_insns.  */
6409   for (regno = (FP_REG_LAST - FP_INC + 1);
6410        regno >= FP_REG_FIRST;
6411        regno -= FP_INC)
6412     {
6413       if (mips_save_reg_p (regno))
6414         {
6415           fp_reg_size += FP_INC * UNITS_PER_FPREG;
6416           fmask |= ((1 << FP_INC) - 1) << (regno - FP_REG_FIRST);
6417         }
6418     }
6419
6420   gp_reg_rounded = MIPS_STACK_ALIGN (gp_reg_size);
6421   total_size += gp_reg_rounded + MIPS_STACK_ALIGN (fp_reg_size);
6422
6423   /* Add in space reserved on the stack by the callee for storing arguments
6424      passed in registers.  */
6425   if (mips_abi != ABI_32 && mips_abi != ABI_O64)
6426     total_size += MIPS_STACK_ALIGN (current_function_pretend_args_size);
6427
6428   /* Save other computed information.  */
6429   cfun->machine->frame.total_size = total_size;
6430   cfun->machine->frame.var_size = var_size;
6431   cfun->machine->frame.args_size = args_size;
6432   cfun->machine->frame.cprestore_size = cprestore_size;
6433   cfun->machine->frame.gp_reg_size = gp_reg_size;
6434   cfun->machine->frame.fp_reg_size = fp_reg_size;
6435   cfun->machine->frame.mask = mask;
6436   cfun->machine->frame.fmask = fmask;
6437   cfun->machine->frame.initialized = reload_completed;
6438   cfun->machine->frame.num_gp = gp_reg_size / UNITS_PER_WORD;
6439   cfun->machine->frame.num_fp = fp_reg_size / (FP_INC * UNITS_PER_FPREG);
6440
6441   if (mask)
6442     {
6443       HOST_WIDE_INT offset;
6444
6445       offset = (args_size + cprestore_size + var_size
6446                 + gp_reg_size - GET_MODE_SIZE (gpr_mode));
6447       cfun->machine->frame.gp_sp_offset = offset;
6448       cfun->machine->frame.gp_save_offset = offset - total_size;
6449     }
6450   else
6451     {
6452       cfun->machine->frame.gp_sp_offset = 0;
6453       cfun->machine->frame.gp_save_offset = 0;
6454     }
6455
6456   if (fmask)
6457     {
6458       HOST_WIDE_INT offset;
6459
6460       offset = (args_size + cprestore_size + var_size
6461                 + gp_reg_rounded + fp_reg_size
6462                 - FP_INC * UNITS_PER_FPREG);
6463       cfun->machine->frame.fp_sp_offset = offset;
6464       cfun->machine->frame.fp_save_offset = offset - total_size;
6465     }
6466   else
6467     {
6468       cfun->machine->frame.fp_sp_offset = 0;
6469       cfun->machine->frame.fp_save_offset = 0;
6470     }
6471
6472   /* Ok, we're done.  */
6473   return total_size;
6474 }
6475 \f
6476 /* Implement INITIAL_ELIMINATION_OFFSET.  FROM is either the frame
6477    pointer or argument pointer.  TO is either the stack pointer or
6478    hard frame pointer.  */
6479
6480 HOST_WIDE_INT
6481 mips_initial_elimination_offset (int from, int to)
6482 {
6483   HOST_WIDE_INT offset;
6484
6485   compute_frame_size (get_frame_size ());
6486
6487   /* Set OFFSET to the offset from the stack pointer.  */
6488   switch (from)
6489     {
6490     case FRAME_POINTER_REGNUM:
6491       offset = 0;
6492       break;
6493
6494     case ARG_POINTER_REGNUM:
6495       offset = cfun->machine->frame.total_size;
6496       if (mips_abi == ABI_N32 || mips_abi == ABI_64)
6497         offset -= current_function_pretend_args_size;
6498       break;
6499
6500     default:
6501       abort ();
6502     }
6503
6504   if (TARGET_MIPS16 && to == HARD_FRAME_POINTER_REGNUM)
6505     offset -= cfun->machine->frame.args_size;
6506
6507   return offset;
6508 }
6509 \f
6510 /* Implement RETURN_ADDR_RTX.  Note, we do not support moving
6511    back to a previous frame.  */
6512 rtx
6513 mips_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
6514 {
6515   if (count != 0)
6516     return const0_rtx;
6517
6518   return get_hard_reg_initial_val (Pmode, GP_REG_FIRST + 31);
6519 }
6520 \f
6521 /* Use FN to save or restore register REGNO.  MODE is the register's
6522    mode and OFFSET is the offset of its save slot from the current
6523    stack pointer.  */
6524
6525 static void
6526 mips_save_restore_reg (enum machine_mode mode, int regno,
6527                        HOST_WIDE_INT offset, mips_save_restore_fn fn)
6528 {
6529   rtx mem;
6530
6531   mem = gen_rtx_MEM (mode, plus_constant (stack_pointer_rtx, offset));
6532   if (!current_function_calls_eh_return)
6533     RTX_UNCHANGING_P (mem) = 1;
6534
6535   fn (gen_rtx_REG (mode, regno), mem);
6536 }
6537
6538
6539 /* Call FN for each register that is saved by the current function.
6540    SP_OFFSET is the offset of the current stack pointer from the start
6541    of the frame.  */
6542
6543 static void
6544 mips_for_each_saved_reg (HOST_WIDE_INT sp_offset, mips_save_restore_fn fn)
6545 {
6546 #define BITSET_P(VALUE, BIT) (((VALUE) & (1L << (BIT))) != 0)
6547
6548   enum machine_mode fpr_mode;
6549   HOST_WIDE_INT offset;
6550   int regno;
6551
6552   /* Save registers starting from high to low.  The debuggers prefer at least
6553      the return register be stored at func+4, and also it allows us not to
6554      need a nop in the epilog if at least one register is reloaded in
6555      addition to return address.  */
6556   offset = cfun->machine->frame.gp_sp_offset - sp_offset;
6557   for (regno = GP_REG_LAST; regno >= GP_REG_FIRST; regno--)
6558     if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
6559       {
6560         mips_save_restore_reg (gpr_mode, regno, offset, fn);
6561         offset -= GET_MODE_SIZE (gpr_mode);
6562       }
6563
6564   /* This loop must iterate over the same space as its companion in
6565      compute_frame_size.  */
6566   offset = cfun->machine->frame.fp_sp_offset - sp_offset;
6567   fpr_mode = (TARGET_SINGLE_FLOAT ? SFmode : DFmode);
6568   for (regno = (FP_REG_LAST - FP_INC + 1);
6569        regno >= FP_REG_FIRST;
6570        regno -= FP_INC)
6571     if (BITSET_P (cfun->machine->frame.fmask, regno - FP_REG_FIRST))
6572       {
6573         mips_save_restore_reg (fpr_mode, regno, offset, fn);
6574         offset -= GET_MODE_SIZE (fpr_mode);
6575       }
6576 #undef BITSET_P
6577 }
6578 \f
6579 /* If we're generating n32 or n64 abicalls, and the current function
6580    does not use $28 as its global pointer, emit a cplocal directive.
6581    Use pic_offset_table_rtx as the argument to the directive.  */
6582
6583 static void
6584 mips_output_cplocal (void)
6585 {
6586   if (!TARGET_EXPLICIT_RELOCS
6587       && cfun->machine->global_pointer > 0
6588       && cfun->machine->global_pointer != GLOBAL_POINTER_REGNUM)
6589     output_asm_insn (".cplocal %+", 0);
6590 }
6591
6592 /* If we're generating n32 or n64 abicalls, emit instructions
6593    to set up the global pointer.  */
6594
6595 static void
6596 mips_emit_loadgp (void)
6597 {
6598   if (TARGET_ABICALLS && TARGET_NEWABI && cfun->machine->global_pointer > 0)
6599     {
6600       rtx addr, offset, incoming_address;
6601
6602       addr = XEXP (DECL_RTL (current_function_decl), 0);
6603       offset = mips_unspec_address (addr, SYMBOL_GOTOFF_LOADGP);
6604       incoming_address = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
6605       emit_insn (gen_loadgp (offset, incoming_address));
6606       if (!TARGET_EXPLICIT_RELOCS)
6607         emit_insn (gen_loadgp_blockage ());
6608     }
6609 }
6610
6611 /* Set up the stack and frame (if desired) for the function.  */
6612
6613 static void
6614 mips_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
6615 {
6616   const char *fnname;
6617   HOST_WIDE_INT tsize = cfun->machine->frame.total_size;
6618
6619   /* ??? When is this really needed?  At least the GNU assembler does not
6620      need the source filename more than once in the file, beyond what is
6621      emitted by the debug information.  */
6622   if (!TARGET_GAS)
6623     ASM_OUTPUT_SOURCE_FILENAME (file, DECL_SOURCE_FILE (current_function_decl));
6624
6625 #ifdef SDB_DEBUGGING_INFO
6626   if (debug_info_level != DINFO_LEVEL_TERSE && write_symbols == SDB_DEBUG)
6627     ASM_OUTPUT_SOURCE_LINE (file, DECL_SOURCE_LINE (current_function_decl), 0);
6628 #endif
6629
6630   /* In mips16 mode, we may need to generate a 32 bit to handle
6631      floating point arguments.  The linker will arrange for any 32 bit
6632      functions to call this stub, which will then jump to the 16 bit
6633      function proper.  */
6634   if (TARGET_MIPS16 && !TARGET_SOFT_FLOAT
6635       && current_function_args_info.fp_code != 0)
6636     build_mips16_function_stub (file);
6637
6638   if (!FUNCTION_NAME_ALREADY_DECLARED)
6639     {
6640       /* Get the function name the same way that toplev.c does before calling
6641          assemble_start_function.  This is needed so that the name used here
6642          exactly matches the name used in ASM_DECLARE_FUNCTION_NAME.  */
6643       fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
6644
6645       if (!flag_inhibit_size_directive)
6646         {
6647           fputs ("\t.ent\t", file);
6648           assemble_name (file, fnname);
6649           fputs ("\n", file);
6650         }
6651
6652       assemble_name (file, fnname);
6653       fputs (":\n", file);
6654     }
6655
6656   if (!flag_inhibit_size_directive)
6657     {
6658       /* .frame FRAMEREG, FRAMESIZE, RETREG */
6659       fprintf (file,
6660                "\t.frame\t%s," HOST_WIDE_INT_PRINT_DEC ",%s\t\t"
6661                "# vars= " HOST_WIDE_INT_PRINT_DEC ", regs= %d/%d"
6662                ", args= " HOST_WIDE_INT_PRINT_DEC
6663                ", gp= " HOST_WIDE_INT_PRINT_DEC "\n",
6664                (reg_names[(frame_pointer_needed)
6665                           ? HARD_FRAME_POINTER_REGNUM : STACK_POINTER_REGNUM]),
6666                ((frame_pointer_needed && TARGET_MIPS16)
6667                 ? tsize - cfun->machine->frame.args_size
6668                 : tsize),
6669                reg_names[GP_REG_FIRST + 31],
6670                cfun->machine->frame.var_size,
6671                cfun->machine->frame.num_gp,
6672                cfun->machine->frame.num_fp,
6673                cfun->machine->frame.args_size,
6674                cfun->machine->frame.cprestore_size);
6675
6676       /* .mask MASK, GPOFFSET; .fmask FPOFFSET */
6677       fprintf (file, "\t.mask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
6678                cfun->machine->frame.mask,
6679                cfun->machine->frame.gp_save_offset);
6680       fprintf (file, "\t.fmask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
6681                cfun->machine->frame.fmask,
6682                cfun->machine->frame.fp_save_offset);
6683
6684       /* Require:
6685          OLD_SP == *FRAMEREG + FRAMESIZE => can find old_sp from nominated FP reg.
6686          HIGHEST_GP_SAVED == *FRAMEREG + FRAMESIZE + GPOFFSET => can find saved regs.  */
6687     }
6688
6689   if (TARGET_ABICALLS && !TARGET_NEWABI && cfun->machine->global_pointer > 0)
6690     {
6691       /* Handle the initialization of $gp for SVR4 PIC.  */
6692       if (!cfun->machine->all_noreorder_p)
6693         output_asm_insn ("%(.cpload\t%^%)", 0);
6694       else
6695         output_asm_insn ("%(.cpload\t%^\n\t%<", 0);
6696     }
6697   else if (cfun->machine->all_noreorder_p)
6698     output_asm_insn ("%(%<", 0);
6699
6700   /* Tell the assembler which register we're using as the global
6701      pointer.  This is needed for thunks, since they can use either
6702      explicit relocs or assembler macros.  */
6703   mips_output_cplocal ();
6704 }
6705 \f
6706 /* Make the last instruction frame related and note that it performs
6707    the operation described by FRAME_PATTERN.  */
6708
6709 static void
6710 mips_set_frame_expr (rtx frame_pattern)
6711 {
6712   rtx insn;
6713
6714   insn = get_last_insn ();
6715   RTX_FRAME_RELATED_P (insn) = 1;
6716   REG_NOTES (insn) = alloc_EXPR_LIST (REG_FRAME_RELATED_EXPR,
6717                                       frame_pattern,
6718                                       REG_NOTES (insn));
6719 }
6720
6721
6722 /* Return a frame-related rtx that stores REG at MEM.
6723    REG must be a single register.  */
6724
6725 static rtx
6726 mips_frame_set (rtx mem, rtx reg)
6727 {
6728   rtx set = gen_rtx_SET (VOIDmode, mem, reg);
6729   RTX_FRAME_RELATED_P (set) = 1;
6730   return set;
6731 }
6732
6733
6734 /* Save register REG to MEM.  Make the instruction frame-related.  */
6735
6736 static void
6737 mips_save_reg (rtx reg, rtx mem)
6738 {
6739   if (GET_MODE (reg) == DFmode && !TARGET_FLOAT64)
6740     {
6741       rtx x1, x2;
6742
6743       if (mips_split_64bit_move_p (mem, reg))
6744         mips_split_64bit_move (mem, reg);
6745       else
6746         emit_move_insn (mem, reg);
6747
6748       x1 = mips_frame_set (mips_subword (mem, 0), mips_subword (reg, 0));
6749       x2 = mips_frame_set (mips_subword (mem, 1), mips_subword (reg, 1));
6750       mips_set_frame_expr (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, x1, x2)));
6751     }
6752   else
6753     {
6754       if (TARGET_MIPS16
6755           && REGNO (reg) != GP_REG_FIRST + 31
6756           && !M16_REG_P (REGNO (reg)))
6757         {
6758           /* Save a non-mips16 register by moving it through a temporary.
6759              We don't need to do this for $31 since there's a special
6760              instruction for it.  */
6761           emit_move_insn (MIPS_PROLOGUE_TEMP (GET_MODE (reg)), reg);
6762           emit_move_insn (mem, MIPS_PROLOGUE_TEMP (GET_MODE (reg)));
6763         }
6764       else
6765         emit_move_insn (mem, reg);
6766
6767       mips_set_frame_expr (mips_frame_set (mem, reg));
6768     }
6769 }
6770
6771
6772 /* Expand the prologue into a bunch of separate insns.  */
6773
6774 void
6775 mips_expand_prologue (void)
6776 {
6777   HOST_WIDE_INT size;
6778
6779   if (cfun->machine->global_pointer > 0)
6780     REGNO (pic_offset_table_rtx) = cfun->machine->global_pointer;
6781
6782   size = compute_frame_size (get_frame_size ());
6783
6784   /* Save the registers.  Allocate up to MIPS_MAX_FIRST_STACK_STEP
6785      bytes beforehand; this is enough to cover the register save area
6786      without going out of range.  */
6787   if ((cfun->machine->frame.mask | cfun->machine->frame.fmask) != 0)
6788     {
6789       HOST_WIDE_INT step1;
6790
6791       step1 = MIN (size, MIPS_MAX_FIRST_STACK_STEP);
6792       RTX_FRAME_RELATED_P (emit_insn (gen_add3_insn (stack_pointer_rtx,
6793                                                      stack_pointer_rtx,
6794                                                      GEN_INT (-step1)))) = 1;
6795       size -= step1;
6796       mips_for_each_saved_reg (size, mips_save_reg);
6797     }
6798
6799   /* Allocate the rest of the frame.  */
6800   if (size > 0)
6801     {
6802       if (SMALL_OPERAND (-size))
6803         RTX_FRAME_RELATED_P (emit_insn (gen_add3_insn (stack_pointer_rtx,
6804                                                        stack_pointer_rtx,
6805                                                        GEN_INT (-size)))) = 1;
6806       else
6807         {
6808           emit_move_insn (MIPS_PROLOGUE_TEMP (Pmode), GEN_INT (size));
6809           if (TARGET_MIPS16)
6810             {
6811               /* There are no instructions to add or subtract registers
6812                  from the stack pointer, so use the frame pointer as a
6813                  temporary.  We should always be using a frame pointer
6814                  in this case anyway.  */
6815               if (!frame_pointer_needed)
6816                 abort ();
6817
6818               emit_move_insn (hard_frame_pointer_rtx, stack_pointer_rtx);
6819               emit_insn (gen_sub3_insn (hard_frame_pointer_rtx,
6820                                         hard_frame_pointer_rtx,
6821                                         MIPS_PROLOGUE_TEMP (Pmode)));
6822               emit_move_insn (stack_pointer_rtx, hard_frame_pointer_rtx);
6823             }
6824           else
6825             emit_insn (gen_sub3_insn (stack_pointer_rtx,
6826                                       stack_pointer_rtx,
6827                                       MIPS_PROLOGUE_TEMP (Pmode)));
6828
6829           /* Describe the combined effect of the previous instructions.  */
6830           mips_set_frame_expr
6831             (gen_rtx_SET (VOIDmode, stack_pointer_rtx,
6832                           plus_constant (stack_pointer_rtx, -size)));
6833         }
6834     }
6835
6836   /* Set up the frame pointer, if we're using one.  In mips16 code,
6837      we point the frame pointer ahead of the outgoing argument area.
6838      This should allow more variables & incoming arguments to be
6839      accessed with unextended instructions.  */
6840   if (frame_pointer_needed)
6841     {
6842       if (TARGET_MIPS16 && cfun->machine->frame.args_size != 0)
6843         {
6844           rtx offset = GEN_INT (cfun->machine->frame.args_size);
6845           RTX_FRAME_RELATED_P
6846             (emit_insn (gen_add3_insn (hard_frame_pointer_rtx,
6847                                        stack_pointer_rtx,
6848                                        offset))) = 1;
6849         }
6850       else
6851         RTX_FRAME_RELATED_P (emit_move_insn (hard_frame_pointer_rtx,
6852                                              stack_pointer_rtx)) = 1;
6853     }
6854
6855   /* If generating o32/o64 abicalls, save $gp on the stack.  */
6856   if (TARGET_ABICALLS && !TARGET_NEWABI && !current_function_is_leaf)
6857     emit_insn (gen_cprestore (GEN_INT (current_function_outgoing_args_size)));
6858
6859   mips_emit_loadgp ();
6860
6861   /* If we are profiling, make sure no instructions are scheduled before
6862      the call to mcount.  */
6863
6864   if (current_function_profile)
6865     emit_insn (gen_blockage ());
6866 }
6867 \f
6868 /* Do any necessary cleanup after a function to restore stack, frame,
6869    and regs.  */
6870
6871 #define RA_MASK BITMASK_HIGH    /* 1 << 31 */
6872 #define PIC_OFFSET_TABLE_MASK (1 << (PIC_OFFSET_TABLE_REGNUM - GP_REG_FIRST))
6873
6874 static void
6875 mips_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
6876                                HOST_WIDE_INT size ATTRIBUTE_UNUSED)
6877 {
6878   rtx string;
6879
6880   /* Reinstate the normal $gp.  */
6881   REGNO (pic_offset_table_rtx) = GLOBAL_POINTER_REGNUM;
6882   mips_output_cplocal ();
6883
6884   if (cfun->machine->all_noreorder_p)
6885     {
6886       /* Avoid using %>%) since it adds excess whitespace.  */
6887       output_asm_insn (".set\tmacro", 0);
6888       output_asm_insn (".set\treorder", 0);
6889       set_noreorder = set_nomacro = 0;
6890     }
6891
6892   if (!FUNCTION_NAME_ALREADY_DECLARED && !flag_inhibit_size_directive)
6893     {
6894       const char *fnname;
6895
6896       /* Get the function name the same way that toplev.c does before calling
6897          assemble_start_function.  This is needed so that the name used here
6898          exactly matches the name used in ASM_DECLARE_FUNCTION_NAME.  */
6899       fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
6900       fputs ("\t.end\t", file);
6901       assemble_name (file, fnname);
6902       fputs ("\n", file);
6903     }
6904
6905   while (string_constants != NULL)
6906     {
6907       struct string_constant *next;
6908
6909       next = string_constants->next;
6910       free (string_constants);
6911       string_constants = next;
6912     }
6913
6914   /* If any following function uses the same strings as this one, force
6915      them to refer those strings indirectly.  Nearby functions could
6916      refer them using pc-relative addressing, but it isn't safe in
6917      general.  For instance, some functions may be placed in sections
6918      other than .text, and we don't know whether they be close enough
6919      to this one.  In large files, even other .text functions can be
6920      too far away.  */
6921   for (string = mips16_strings; string != 0; string = XEXP (string, 1))
6922     SYMBOL_REF_FLAG (XEXP (string, 0)) = 0;
6923   free_EXPR_LIST_list (&mips16_strings);
6924 }
6925 \f
6926 /* Emit instructions to restore register REG from slot MEM.  */
6927
6928 static void
6929 mips_restore_reg (rtx reg, rtx mem)
6930 {
6931   /* There's no mips16 instruction to load $31 directly.  Load into
6932      $7 instead and adjust the return insn appropriately.  */
6933   if (TARGET_MIPS16 && REGNO (reg) == GP_REG_FIRST + 31)
6934     reg = gen_rtx_REG (GET_MODE (reg), 7);
6935
6936   if (TARGET_MIPS16 && !M16_REG_P (REGNO (reg)))
6937     {
6938       /* Can't restore directly; move through a temporary.  */
6939       emit_move_insn (MIPS_EPILOGUE_TEMP (GET_MODE (reg)), mem);
6940       emit_move_insn (reg, MIPS_EPILOGUE_TEMP (GET_MODE (reg)));
6941     }
6942   else
6943     emit_move_insn (reg, mem);
6944 }
6945
6946
6947 /* Expand the epilogue into a bunch of separate insns.  SIBCALL_P is true
6948    if this epilogue precedes a sibling call, false if it is for a normal
6949    "epilogue" pattern.  */
6950
6951 void
6952 mips_expand_epilogue (int sibcall_p)
6953 {
6954   HOST_WIDE_INT step1, step2;
6955   rtx base, target;
6956
6957   if (!sibcall_p && mips_can_use_return_insn ())
6958     {
6959       emit_jump_insn (gen_return ());
6960       return;
6961     }
6962
6963   /* Split the frame into two.  STEP1 is the amount of stack we should
6964      deallocate before restoring the registers.  STEP2 is the amount we
6965      should deallocate afterwards.
6966
6967      Start off by assuming that no registers need to be restored.  */
6968   step1 = cfun->machine->frame.total_size;
6969   step2 = 0;
6970
6971   /* Work out which register holds the frame address.  Account for the
6972      frame pointer offset used by mips16 code.  */
6973   if (!frame_pointer_needed)
6974     base = stack_pointer_rtx;
6975   else
6976     {
6977       base = hard_frame_pointer_rtx;
6978       if (TARGET_MIPS16)
6979         step1 -= cfun->machine->frame.args_size;
6980     }
6981
6982   /* If we need to restore registers, deallocate as much stack as
6983      possible in the second step without going out of range.  */
6984   if ((cfun->machine->frame.mask | cfun->machine->frame.fmask) != 0)
6985     {
6986       step2 = MIN (step1, MIPS_MAX_FIRST_STACK_STEP);
6987       step1 -= step2;
6988     }
6989
6990   /* Set TARGET to BASE + STEP1.  */
6991   target = base;
6992   if (step1 > 0)
6993     {
6994       rtx adjust;
6995
6996       /* Get an rtx for STEP1 that we can add to BASE.  */
6997       adjust = GEN_INT (step1);
6998       if (!SMALL_OPERAND (step1))
6999         {
7000           emit_move_insn (MIPS_EPILOGUE_TEMP (Pmode), adjust);
7001           adjust = MIPS_EPILOGUE_TEMP (Pmode);
7002         }
7003
7004       /* Normal mode code can copy the result straight into $sp.  */
7005       if (!TARGET_MIPS16)
7006         target = stack_pointer_rtx;
7007
7008       emit_insn (gen_add3_insn (target, base, adjust));
7009     }
7010
7011   /* Copy TARGET into the stack pointer.  */
7012   if (target != stack_pointer_rtx)
7013     emit_move_insn (stack_pointer_rtx, target);
7014
7015   /* If we're using addressing macros for n32/n64 abicalls, $gp is
7016      implicitly used by all SYMBOL_REFs.  We must emit a blockage
7017      insn before restoring it.  */
7018   if (TARGET_ABICALLS && TARGET_NEWABI && !TARGET_EXPLICIT_RELOCS)
7019     emit_insn (gen_blockage ());
7020
7021   /* Restore the registers.  */
7022   mips_for_each_saved_reg (cfun->machine->frame.total_size - step2,
7023                            mips_restore_reg);
7024
7025   /* Deallocate the final bit of the frame.  */
7026   if (step2 > 0)
7027     emit_insn (gen_add3_insn (stack_pointer_rtx,
7028                               stack_pointer_rtx,
7029                               GEN_INT (step2)));
7030     
7031   /* Add in the __builtin_eh_return stack adjustment.   We need to
7032      use a temporary in mips16 code.  */
7033   if (current_function_calls_eh_return)
7034     {
7035       if (TARGET_MIPS16)
7036         {
7037           emit_move_insn (MIPS_EPILOGUE_TEMP (Pmode), stack_pointer_rtx);
7038           emit_insn (gen_add3_insn (MIPS_EPILOGUE_TEMP (Pmode),
7039                                     MIPS_EPILOGUE_TEMP (Pmode),
7040                                     EH_RETURN_STACKADJ_RTX));
7041           emit_move_insn (stack_pointer_rtx, MIPS_EPILOGUE_TEMP (Pmode));
7042         }
7043       else
7044         emit_insn (gen_add3_insn (stack_pointer_rtx,
7045                                   stack_pointer_rtx,
7046                                   EH_RETURN_STACKADJ_RTX));
7047     }
7048
7049   if (!sibcall_p)
7050     {
7051       /* The mips16 loads the return address into $7, not $31.  */
7052       if (TARGET_MIPS16 && (cfun->machine->frame.mask & RA_MASK) != 0)
7053         emit_jump_insn (gen_return_internal (gen_rtx_REG (Pmode,
7054                                                       GP_REG_FIRST + 7)));
7055       else
7056         emit_jump_insn (gen_return_internal (gen_rtx_REG (Pmode,
7057                                                       GP_REG_FIRST + 31)));
7058     }
7059 }
7060 \f
7061 /* Return nonzero if this function is known to have a null epilogue.
7062    This allows the optimizer to omit jumps to jumps if no stack
7063    was created.  */
7064
7065 int
7066 mips_can_use_return_insn (void)
7067 {
7068   tree return_type;
7069
7070   if (! reload_completed)
7071     return 0;
7072
7073   if (regs_ever_live[31] || current_function_profile)
7074     return 0;
7075
7076   return_type = DECL_RESULT (current_function_decl);
7077
7078   /* In mips16 mode, a function which returns a floating point value
7079      needs to arrange to copy the return value into the floating point
7080      registers.  */
7081   if (TARGET_MIPS16
7082       && mips16_hard_float
7083       && ! aggregate_value_p (return_type, current_function_decl)
7084       && GET_MODE_CLASS (DECL_MODE (return_type)) == MODE_FLOAT
7085       && GET_MODE_SIZE (DECL_MODE (return_type)) <= UNITS_PER_FPVALUE)
7086     return 0;
7087
7088   if (cfun->machine->frame.initialized)
7089     return cfun->machine->frame.total_size == 0;
7090
7091   return compute_frame_size (get_frame_size ()) == 0;
7092 }
7093 \f
7094 /* Implement TARGET_ASM_OUTPUT_MI_THUNK.  Generate rtl rather than asm text
7095    in order to avoid duplicating too much logic from elsewhere.  */
7096
7097 static void
7098 mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
7099                       HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
7100                       tree function)
7101 {
7102   rtx this, temp1, temp2, insn, fnaddr;
7103
7104   /* Pretend to be a post-reload pass while generating rtl.  */
7105   no_new_pseudos = 1;
7106   reload_completed = 1;
7107
7108   /* Pick a global pointer for -mabicalls.  Use $15 rather than $28
7109      for TARGET_NEWABI since the latter is a call-saved register.  */
7110   if (TARGET_ABICALLS)
7111     cfun->machine->global_pointer
7112       = REGNO (pic_offset_table_rtx)
7113       = TARGET_NEWABI ? 15 : GLOBAL_POINTER_REGNUM;
7114
7115   /* Set up the global pointer for n32 or n64 abicalls.  */
7116   mips_emit_loadgp ();
7117
7118   /* We need two temporary registers in some cases.  */
7119   temp1 = gen_rtx_REG (Pmode, 2);
7120   temp2 = gen_rtx_REG (Pmode, 3);
7121
7122   /* Find out which register contains the "this" pointer.  */
7123   if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
7124     this = gen_rtx_REG (Pmode, GP_ARG_FIRST + 1);
7125   else
7126     this = gen_rtx_REG (Pmode, GP_ARG_FIRST);
7127
7128   /* Add DELTA to THIS.  */
7129   if (delta != 0)
7130     {
7131       rtx offset = GEN_INT (delta);
7132       if (!SMALL_OPERAND (delta))
7133         {
7134           emit_move_insn (temp1, offset);
7135           offset = temp1;
7136         }
7137       emit_insn (gen_add3_insn (this, this, offset));
7138     }
7139
7140   /* If needed, add *(*THIS + VCALL_OFFSET) to THIS.  */
7141   if (vcall_offset != 0)
7142     {
7143       rtx addr;
7144
7145       /* Set TEMP1 to *THIS.  */
7146       emit_move_insn (temp1, gen_rtx_MEM (Pmode, this));
7147
7148       /* Set ADDR to a legitimate address for *THIS + VCALL_OFFSET.  */
7149       if (SMALL_OPERAND (vcall_offset))
7150         addr = gen_rtx_PLUS (Pmode, temp1, GEN_INT (vcall_offset));
7151       else if (TARGET_MIPS16)
7152         {
7153           /* Load the full offset into a register so that we can use
7154              an unextended instruction for the load itself.  */
7155           emit_move_insn (temp2, GEN_INT (vcall_offset));
7156           emit_insn (gen_add3_insn (temp1, temp1, temp2));
7157           addr = temp1;
7158         }
7159       else
7160         {
7161           /* Load the high part of the offset into a register and
7162              leave the low part for the address.  */
7163           emit_move_insn (temp2, GEN_INT (CONST_HIGH_PART (vcall_offset)));
7164           emit_insn (gen_add3_insn (temp1, temp1, temp2));
7165           addr = gen_rtx_PLUS (Pmode, temp1,
7166                                GEN_INT (CONST_LOW_PART (vcall_offset)));
7167         }
7168
7169       /* Load the offset and add it to THIS.  */
7170       emit_move_insn (temp1, gen_rtx_MEM (Pmode, addr));
7171       emit_insn (gen_add3_insn (this, this, temp1));
7172     }
7173
7174   /* Jump to the target function.  Use a sibcall if direct jumps are
7175      allowed, otherwise load the address into a register first.  */
7176   fnaddr = XEXP (DECL_RTL (function), 0);
7177   if (TARGET_MIPS16 || TARGET_ABICALLS || TARGET_LONG_CALLS)
7178     {
7179       /* This is messy.  gas treats "la $25,foo" as part of a call
7180          sequence and may allow a global "foo" to be lazily bound.
7181          The general move patterns therefore reject this combination.
7182
7183          In this context, lazy binding would actually be OK for o32 and o64,
7184          but it's still wrong for n32 and n64; see mips_load_call_address.
7185          We must therefore load the address via a temporary register if
7186          mips_dangerous_for_la25_p.
7187
7188          If we jump to the temporary register rather than $25, the assembler
7189          can use the move insn to fill the jump's delay slot.  */
7190       if (TARGET_ABICALLS && !mips_dangerous_for_la25_p (fnaddr))
7191         temp1 = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
7192       mips_load_call_address (temp1, fnaddr, true);
7193
7194       if (TARGET_ABICALLS && REGNO (temp1) != PIC_FUNCTION_ADDR_REGNUM)
7195         emit_move_insn (gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM), temp1);
7196       emit_jump_insn (gen_indirect_jump (temp1));
7197     }
7198   else
7199     {
7200       insn = emit_call_insn (gen_sibcall_internal (fnaddr, const0_rtx));
7201       SIBLING_CALL_P (insn) = 1;
7202     }
7203
7204   /* Run just enough of rest_of_compilation.  This sequence was
7205      "borrowed" from alpha.c.  */
7206   insn = get_insns ();
7207   insn_locators_initialize ();
7208   split_all_insns_noflow ();
7209   shorten_branches (insn);
7210   final_start_function (insn, file, 1);
7211   final (insn, file, 1, 0);
7212   final_end_function ();
7213
7214   /* Clean up the vars set above.  Note that final_end_function resets
7215      the global pointer for us.  */
7216   reload_completed = 0;
7217   no_new_pseudos = 0;
7218 }
7219 \f
7220 /* Returns nonzero if X contains a SYMBOL_REF.  */
7221
7222 static int
7223 symbolic_expression_p (rtx x)
7224 {
7225   if (GET_CODE (x) == SYMBOL_REF)
7226     return 1;
7227
7228   if (GET_CODE (x) == CONST)
7229     return symbolic_expression_p (XEXP (x, 0));
7230
7231   if (GET_RTX_CLASS (GET_CODE (x)) == '1')
7232     return symbolic_expression_p (XEXP (x, 0));
7233
7234   if (GET_RTX_CLASS (GET_CODE (x)) == 'c'
7235       || GET_RTX_CLASS (GET_CODE (x)) == '2')
7236     return (symbolic_expression_p (XEXP (x, 0))
7237             || symbolic_expression_p (XEXP (x, 1)));
7238
7239   return 0;
7240 }
7241
7242 /* Choose the section to use for the constant rtx expression X that has
7243    mode MODE.  */
7244
7245 static void
7246 mips_select_rtx_section (enum machine_mode mode, rtx x,
7247                          unsigned HOST_WIDE_INT align)
7248 {
7249   if (TARGET_MIPS16)
7250     {
7251       /* In mips16 mode, the constant table always goes in the same section
7252          as the function, so that constants can be loaded using PC relative
7253          addressing.  */
7254       function_section (current_function_decl);
7255     }
7256   else if (TARGET_EMBEDDED_DATA)
7257     {
7258       /* For embedded applications, always put constants in read-only data,
7259          in order to reduce RAM usage.  */
7260       mergeable_constant_section (mode, align, 0);
7261     }
7262   else
7263     {
7264       /* For hosted applications, always put constants in small data if
7265          possible, as this gives the best performance.  */
7266       /* ??? Consider using mergeable small data sections.  */
7267
7268       if (GET_MODE_SIZE (mode) <= (unsigned) mips_section_threshold
7269           && mips_section_threshold > 0)
7270         named_section (0, ".sdata", 0);
7271       else if (flag_pic && symbolic_expression_p (x))
7272         {
7273           if (targetm.have_named_sections)
7274             named_section (0, ".data.rel.ro", 3);
7275           else
7276             data_section ();
7277         }
7278       else
7279         mergeable_constant_section (mode, align, 0);
7280     }
7281 }
7282
7283 /* Choose the section to use for DECL.  RELOC is true if its value contains
7284    any relocatable expression.  */
7285
7286 static void
7287 mips_select_section (tree decl, int reloc,
7288                      unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)
7289 {
7290   if ((TARGET_EMBEDDED_PIC || TARGET_MIPS16)
7291       && TREE_CODE (decl) == STRING_CST
7292       && !flag_writable_strings)
7293     /* For embedded position independent code, put constant strings in the
7294        text section, because the data section is limited to 64K in size.
7295        For mips16 code, put strings in the text section so that a PC
7296        relative load instruction can be used to get their address.  */
7297     text_section ();
7298   else if (targetm.have_named_sections)
7299     default_elf_select_section (decl, reloc, align);
7300   else
7301     /* The native irix o32 assembler doesn't support named sections.  */
7302     default_select_section (decl, reloc, align);
7303 }
7304
7305
7306 /* Implement TARGET_IN_SMALL_DATA_P.  Return true if it would be safe to
7307    access DECL using %gp_rel(...)($gp).  */
7308
7309 static bool
7310 mips_in_small_data_p (tree decl)
7311 {
7312   HOST_WIDE_INT size;
7313
7314   if (TREE_CODE (decl) == STRING_CST || TREE_CODE (decl) == FUNCTION_DECL)
7315     return false;
7316
7317   if (TREE_CODE (decl) == VAR_DECL && DECL_SECTION_NAME (decl) != 0)
7318     {
7319       const char *name;
7320
7321       /* Reject anything that isn't in a known small-data section.  */
7322       name = TREE_STRING_POINTER (DECL_SECTION_NAME (decl));
7323       if (strcmp (name, ".sdata") != 0 && strcmp (name, ".sbss") != 0)
7324         return false;
7325
7326       /* If a symbol is defined externally, the assembler will use the
7327          usual -G rules when deciding how to implement macros.  */
7328       if (TARGET_EXPLICIT_RELOCS || !DECL_EXTERNAL (decl))
7329         return true;
7330     }
7331   else if (TARGET_EMBEDDED_DATA)
7332     {
7333       /* Don't put constants into the small data section: we want them
7334          to be in ROM rather than RAM.  */
7335       if (TREE_CODE (decl) != VAR_DECL)
7336         return false;
7337
7338       if (TREE_READONLY (decl)
7339           && !TREE_SIDE_EFFECTS (decl)
7340           && (!DECL_INITIAL (decl) || TREE_CONSTANT (DECL_INITIAL (decl))))
7341         return false;
7342     }
7343
7344   size = int_size_in_bytes (TREE_TYPE (decl));
7345   return (size > 0 && size <= mips_section_threshold);
7346 }
7347
7348
7349 /* When generating embedded PIC code, SYMBOL_REF_FLAG is set for
7350    symbols which are not in the .text section.
7351
7352    When generating mips16 code, SYMBOL_REF_FLAG is set for string
7353    constants which are put in the .text section.  We also record the
7354    total length of all such strings; this total is used to decide
7355    whether we need to split the constant table, and need not be
7356    precisely correct.  */
7357
7358 static void
7359 mips_encode_section_info (tree decl, rtx rtl, int first)
7360 {
7361   rtx symbol;
7362
7363   if (GET_CODE (rtl) != MEM)
7364     return;
7365
7366   symbol = XEXP (rtl, 0);
7367
7368   if (GET_CODE (symbol) != SYMBOL_REF)
7369     return;
7370
7371   if (TARGET_MIPS16)
7372     {
7373       if (first && TREE_CODE (decl) == STRING_CST
7374           && ! flag_writable_strings
7375           /* If this string is from a function, and the function will
7376              go in a gnu linkonce section, then we can't directly
7377              access the string.  This gets an assembler error
7378              "unsupported PC relative reference to different section".
7379              If we modify SELECT_SECTION to put it in function_section
7380              instead of text_section, it still fails because
7381              DECL_SECTION_NAME isn't set until assemble_start_function.
7382              If we fix that, it still fails because strings are shared
7383              among multiple functions, and we have cross section
7384              references again.  We force it to work by putting string
7385              addresses in the constant pool and indirecting.  */
7386           && (! current_function_decl
7387               || ! DECL_ONE_ONLY (current_function_decl)))
7388         {
7389           mips16_strings = alloc_EXPR_LIST (0, symbol, mips16_strings);
7390           SYMBOL_REF_FLAG (symbol) = 1;
7391           mips_string_length += TREE_STRING_LENGTH (decl);
7392         }
7393     }
7394
7395   if (TARGET_EMBEDDED_PIC)
7396     {
7397       if (TREE_CODE (decl) == VAR_DECL)
7398         SYMBOL_REF_FLAG (symbol) = 1;
7399       else if (TREE_CODE (decl) == FUNCTION_DECL)
7400         SYMBOL_REF_FLAG (symbol) = 0;
7401       else if (TREE_CODE (decl) == STRING_CST
7402                && ! flag_writable_strings)
7403         SYMBOL_REF_FLAG (symbol) = 0;
7404       else
7405         SYMBOL_REF_FLAG (symbol) = 1;
7406     }
7407
7408   default_encode_section_info (decl, rtl, first);
7409 }
7410 \f
7411 /* See whether VALTYPE is a record whose fields should be returned in
7412    floating-point registers.  If so, return the number of fields and
7413    list them in FIELDS (which should have two elements).  Return 0
7414    otherwise.
7415
7416    For n32 & n64, a structure with one or two fields is returned in
7417    floating-point registers as long as every field has a floating-point
7418    type.  */
7419
7420 static int
7421 mips_fpr_return_fields (tree valtype, tree *fields)
7422 {
7423   tree field;
7424   int i;
7425
7426   if (!TARGET_NEWABI)
7427     return 0;
7428
7429   if (TREE_CODE (valtype) != RECORD_TYPE)
7430     return 0;
7431
7432   i = 0;
7433   for (field = TYPE_FIELDS (valtype); field != 0; field = TREE_CHAIN (field))
7434     {
7435       if (TREE_CODE (field) != FIELD_DECL)
7436         continue;
7437
7438       if (TREE_CODE (TREE_TYPE (field)) != REAL_TYPE)
7439         return 0;
7440
7441       if (i == 2)
7442         return 0;
7443
7444       fields[i++] = field;
7445     }
7446   return i;
7447 }
7448
7449
7450 /* Implement TARGET_RETURN_IN_MSB.  For n32 & n64, we should return
7451    a value in the most significant part of $2/$3 if:
7452
7453       - the target is big-endian;
7454
7455       - the value has a structure or union type (we generalize this to
7456         cover aggregates from other languages too); and
7457
7458       - the structure is not returned in floating-point registers.  */
7459
7460 static bool
7461 mips_return_in_msb (tree valtype)
7462 {
7463   tree fields[2];
7464
7465   return (TARGET_NEWABI
7466           && TARGET_BIG_ENDIAN
7467           && AGGREGATE_TYPE_P (valtype)
7468           && mips_fpr_return_fields (valtype, fields) == 0);
7469 }
7470
7471
7472 /* Return a composite value in a pair of floating-point registers.
7473    MODE1 and OFFSET1 are the mode and byte offset for the first value,
7474    likewise MODE2 and OFFSET2 for the second.  MODE is the mode of the
7475    complete value.
7476
7477    For n32 & n64, $f0 always holds the first value and $f2 the second.
7478    Otherwise the values are packed together as closely as possible.  */
7479
7480 static rtx
7481 mips_return_fpr_pair (enum machine_mode mode,
7482                       enum machine_mode mode1, HOST_WIDE_INT offset1,
7483                       enum machine_mode mode2, HOST_WIDE_INT offset2)
7484 {
7485   int inc;
7486
7487   inc = (TARGET_NEWABI ? 2 : FP_INC);
7488   return gen_rtx_PARALLEL
7489     (mode,
7490      gen_rtvec (2,
7491                 gen_rtx_EXPR_LIST (VOIDmode,
7492                                    gen_rtx_REG (mode1, FP_RETURN),
7493                                    GEN_INT (offset1)),
7494                 gen_rtx_EXPR_LIST (VOIDmode,
7495                                    gen_rtx_REG (mode2, FP_RETURN + inc),
7496                                    GEN_INT (offset2))));
7497
7498 }
7499
7500
7501 /* Implement FUNCTION_VALUE and LIBCALL_VALUE.  For normal calls,
7502    VALTYPE is the return type and MODE is VOIDmode.  For libcalls,
7503    VALTYPE is null and MODE is the mode of the return value.  */
7504
7505 rtx
7506 mips_function_value (tree valtype, tree func ATTRIBUTE_UNUSED,
7507                      enum machine_mode mode)
7508 {
7509   if (valtype)
7510     {
7511       tree fields[2];
7512       int unsignedp;
7513
7514       mode = TYPE_MODE (valtype);
7515       unsignedp = TREE_UNSIGNED (valtype);
7516
7517       /* Since we define TARGET_PROMOTE_FUNCTION_RETURN that returns
7518          true, we must promote the mode just as PROMOTE_MODE does.  */
7519       mode = promote_mode (valtype, mode, &unsignedp, 1);
7520
7521       /* Handle structures whose fields are returned in $f0/$f2.  */
7522       switch (mips_fpr_return_fields (valtype, fields))
7523         {
7524         case 1:
7525           return gen_rtx_REG (mode, FP_RETURN);
7526
7527         case 2:
7528           return mips_return_fpr_pair (mode,
7529                                        TYPE_MODE (TREE_TYPE (fields[0])),
7530                                        int_byte_position (fields[0]),
7531                                        TYPE_MODE (TREE_TYPE (fields[1])),
7532                                        int_byte_position (fields[1]));
7533         }
7534
7535       /* If a value is passed in the most significant part of a register, see
7536          whether we have to round the mode up to a whole number of words.  */
7537       if (mips_return_in_msb (valtype))
7538         {
7539           HOST_WIDE_INT size = int_size_in_bytes (valtype);
7540           if (size % UNITS_PER_WORD != 0)
7541             {
7542               size += UNITS_PER_WORD - size % UNITS_PER_WORD;
7543               mode = mode_for_size (size * BITS_PER_UNIT, MODE_INT, 0);
7544             }
7545         }
7546     }
7547
7548   if (GET_MODE_CLASS (mode) == MODE_FLOAT
7549       && GET_MODE_SIZE (mode) <= UNITS_PER_HWFPVALUE)
7550     return gen_rtx_REG (mode, FP_RETURN);
7551
7552   /* Handle long doubles for n32 & n64.  */
7553   if (mode == TFmode)
7554     return mips_return_fpr_pair (mode,
7555                                  DImode, 0,
7556                                  DImode, GET_MODE_SIZE (mode) / 2);
7557
7558   if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT
7559       && GET_MODE_SIZE (mode) <= UNITS_PER_HWFPVALUE * 2)
7560     return mips_return_fpr_pair (mode,
7561                                  GET_MODE_INNER (mode), 0,
7562                                  GET_MODE_INNER (mode),
7563                                  GET_MODE_SIZE (mode) / 2);
7564
7565   return gen_rtx_REG (mode, GP_RETURN);
7566 }
7567
7568 /* The implementation of FUNCTION_ARG_PASS_BY_REFERENCE.  Return
7569    nonzero when an argument must be passed by reference.  */
7570
7571 int
7572 function_arg_pass_by_reference (const CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
7573                                 enum machine_mode mode, tree type,
7574                                 int named ATTRIBUTE_UNUSED)
7575 {
7576   int size;
7577
7578   /* The EABI is the only one to pass args by reference.  */
7579   if (mips_abi != ABI_EABI)
7580     return 0;
7581
7582   /* ??? How should SCmode be handled?  */
7583   if (type == NULL_TREE || mode == DImode || mode == DFmode)
7584     return 0;
7585
7586   size = int_size_in_bytes (type);
7587   return size == -1 || size > UNITS_PER_WORD;
7588 }
7589
7590 /* Return the class of registers for which a mode change from FROM to TO
7591    is invalid.
7592
7593    In little-endian mode, the hi-lo registers are numbered backwards,
7594    so (subreg:SI (reg:DI hi) 0) gets the high word instead of the low
7595    word as intended.
7596
7597    Similarly, when using paired floating-point registers, the first
7598    register holds the low word, regardless of endianness.  So in big
7599    endian mode, (subreg:SI (reg:DF $f0) 0) does not get the high word
7600    as intended.
7601
7602    Also, loading a 32-bit value into a 64-bit floating-point register
7603    will not sign-extend the value, despite what LOAD_EXTEND_OP says.
7604    We can't allow 64-bit float registers to change from a 32-bit
7605    mode to a 64-bit mode.  */
7606
7607 bool
7608 mips_cannot_change_mode_class (enum machine_mode from,
7609                                enum machine_mode to, enum reg_class class)
7610 {
7611   if (GET_MODE_SIZE (from) != GET_MODE_SIZE (to))
7612     {
7613       if (TARGET_BIG_ENDIAN)
7614         return reg_classes_intersect_p (FP_REGS, class);
7615       if (TARGET_FLOAT64)
7616         return reg_classes_intersect_p (HI_AND_FP_REGS, class);
7617       return reg_classes_intersect_p (HI_REG, class);
7618     }
7619   return false;
7620 }
7621
7622 /* Return true if X should not be moved directly into register $25.
7623    We need this because many versions of GAS will treat "la $25,foo" as
7624    part of a call sequence and so allow a global "foo" to be lazily bound.  */
7625
7626 bool
7627 mips_dangerous_for_la25_p (rtx x)
7628 {
7629   HOST_WIDE_INT offset;
7630
7631   if (TARGET_EXPLICIT_RELOCS)
7632     return false;
7633
7634   mips_split_const (x, &x, &offset);
7635   return global_got_operand (x, VOIDmode);
7636 }
7637
7638 /* Implement PREFERRED_RELOAD_CLASS.  */
7639
7640 enum reg_class
7641 mips_preferred_reload_class (rtx x, enum reg_class class)
7642 {
7643   if (mips_dangerous_for_la25_p (x) && reg_class_subset_p (LEA_REGS, class))
7644     return LEA_REGS;
7645
7646   if (TARGET_HARD_FLOAT
7647       && FLOAT_MODE_P (GET_MODE (x))
7648       && reg_class_subset_p (FP_REGS, class))
7649     return FP_REGS;
7650
7651   if (reg_class_subset_p (GR_REGS, class))
7652     class = GR_REGS;
7653
7654   if (TARGET_MIPS16 && reg_class_subset_p (M16_REGS, class))
7655     class = M16_REGS;
7656
7657   return class;
7658 }
7659
7660 /* This function returns the register class required for a secondary
7661    register when copying between one of the registers in CLASS, and X,
7662    using MODE.  If IN_P is nonzero, the copy is going from X to the
7663    register, otherwise the register is the source.  A return value of
7664    NO_REGS means that no secondary register is required.  */
7665
7666 enum reg_class
7667 mips_secondary_reload_class (enum reg_class class,
7668                              enum machine_mode mode, rtx x, int in_p)
7669 {
7670   enum reg_class gr_regs = TARGET_MIPS16 ? M16_REGS : GR_REGS;
7671   int regno = -1;
7672   int gp_reg_p;
7673
7674   if (GET_CODE (x) == REG || GET_CODE (x) == SUBREG)
7675     regno = true_regnum (x);
7676
7677   gp_reg_p = TARGET_MIPS16 ? M16_REG_P (regno) : GP_REG_P (regno);
7678
7679   if (mips_dangerous_for_la25_p (x))
7680     {
7681       gr_regs = LEA_REGS;
7682       if (TEST_HARD_REG_BIT (reg_class_contents[(int) class], 25))
7683         return gr_regs;
7684     }
7685
7686   /* Copying from HI or LO to anywhere other than a general register
7687      requires a general register.  */
7688   if (class == HI_REG || class == LO_REG || class == MD_REGS)
7689     {
7690       if (TARGET_MIPS16 && in_p)
7691         {
7692           /* We can't really copy to HI or LO at all in mips16 mode.  */
7693           return M16_REGS;
7694         }
7695       return gp_reg_p ? NO_REGS : gr_regs;
7696     }
7697   if (MD_REG_P (regno))
7698     {
7699       if (TARGET_MIPS16 && ! in_p)
7700         {
7701           /* We can't really copy to HI or LO at all in mips16 mode.  */
7702           return M16_REGS;
7703         }
7704       return class == gr_regs ? NO_REGS : gr_regs;
7705     }
7706
7707   /* We can only copy a value to a condition code register from a
7708      floating point register, and even then we require a scratch
7709      floating point register.  We can only copy a value out of a
7710      condition code register into a general register.  */
7711   if (class == ST_REGS)
7712     {
7713       if (in_p)
7714         return FP_REGS;
7715       return gp_reg_p ? NO_REGS : gr_regs;
7716     }
7717   if (ST_REG_P (regno))
7718     {
7719       if (! in_p)
7720         return FP_REGS;
7721       return class == gr_regs ? NO_REGS : gr_regs;
7722     }
7723
7724   if (class == FP_REGS)
7725     {
7726       if (GET_CODE (x) == MEM)
7727         {
7728           /* In this case we can use lwc1, swc1, ldc1 or sdc1.  */
7729           return NO_REGS;
7730         }
7731       else if (CONSTANT_P (x) && GET_MODE_CLASS (mode) == MODE_FLOAT)
7732         {
7733           /* We can use the l.s and l.d macros to load floating-point
7734              constants.  ??? For l.s, we could probably get better
7735              code by returning GR_REGS here.  */
7736           return NO_REGS;
7737         }
7738       else if (gp_reg_p || x == CONST0_RTX (mode))
7739         {
7740           /* In this case we can use mtc1, mfc1, dmtc1 or dmfc1.  */
7741           return NO_REGS;
7742         }
7743       else if (FP_REG_P (regno))
7744         {
7745           /* In this case we can use mov.s or mov.d.  */
7746           return NO_REGS;
7747         }
7748       else
7749         {
7750           /* Otherwise, we need to reload through an integer register.  */
7751           return gr_regs;
7752         }
7753     }
7754
7755   /* In mips16 mode, going between memory and anything but M16_REGS
7756      requires an M16_REG.  */
7757   if (TARGET_MIPS16)
7758     {
7759       if (class != M16_REGS && class != M16_NA_REGS)
7760         {
7761           if (gp_reg_p)
7762             return NO_REGS;
7763           return M16_REGS;
7764         }
7765       if (! gp_reg_p)
7766         {
7767           if (class == M16_REGS || class == M16_NA_REGS)
7768             return NO_REGS;
7769           return M16_REGS;
7770         }
7771     }
7772
7773   return NO_REGS;
7774 }
7775
7776 /* Implement CLASS_MAX_NREGS.
7777
7778    Usually all registers are word-sized.  The only supported exception
7779    is -mgp64 -msingle-float, which has 64-bit words but 32-bit float
7780    registers.  A word-based calculation is correct even in that case,
7781    since -msingle-float disallows multi-FPR values.  */
7782
7783 int
7784 mips_class_max_nregs (enum reg_class class ATTRIBUTE_UNUSED,
7785                       enum machine_mode mode)
7786 {
7787   return (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
7788 }
7789
7790 bool
7791 mips_valid_pointer_mode (enum machine_mode mode)
7792 {
7793   return (mode == SImode || (TARGET_64BIT && mode == DImode));
7794 }
7795
7796 \f
7797 /* If we can access small data directly (using gp-relative relocation
7798    operators) return the small data pointer, otherwise return null.
7799
7800    For each mips16 function which refers to GP relative symbols, we
7801    use a pseudo register, initialized at the start of the function, to
7802    hold the $gp value.  */
7803
7804 static rtx
7805 mips16_gp_pseudo_reg (void)
7806 {
7807   if (cfun->machine->mips16_gp_pseudo_rtx == NULL_RTX)
7808     {
7809       rtx const_gp;
7810       rtx insn, scan;
7811
7812       cfun->machine->mips16_gp_pseudo_rtx = gen_reg_rtx (Pmode);
7813       RTX_UNCHANGING_P (cfun->machine->mips16_gp_pseudo_rtx) = 1;
7814
7815       /* We want to initialize this to a value which gcc will believe
7816          is constant.  */
7817       const_gp = gen_rtx_CONST (Pmode, pic_offset_table_rtx);
7818       start_sequence ();
7819       emit_move_insn (cfun->machine->mips16_gp_pseudo_rtx,
7820                       const_gp);
7821       insn = get_insns ();
7822       end_sequence ();
7823
7824       push_topmost_sequence ();
7825       /* We need to emit the initialization after the FUNCTION_BEG
7826          note, so that it will be integrated.  */
7827       for (scan = get_insns (); scan != NULL_RTX; scan = NEXT_INSN (scan))
7828         if (GET_CODE (scan) == NOTE
7829             && NOTE_LINE_NUMBER (scan) == NOTE_INSN_FUNCTION_BEG)
7830           break;
7831       if (scan == NULL_RTX)
7832         scan = get_insns ();
7833       insn = emit_insn_after (insn, scan);
7834       pop_topmost_sequence ();
7835     }
7836
7837   return cfun->machine->mips16_gp_pseudo_rtx;
7838 }
7839
7840 /* Write out code to move floating point arguments in or out of
7841    general registers.  Output the instructions to FILE.  FP_CODE is
7842    the code describing which arguments are present (see the comment at
7843    the definition of CUMULATIVE_ARGS in mips.h).  FROM_FP_P is nonzero if
7844    we are copying from the floating point registers.  */
7845
7846 static void
7847 mips16_fp_args (FILE *file, int fp_code, int from_fp_p)
7848 {
7849   const char *s;
7850   int gparg, fparg;
7851   unsigned int f;
7852
7853   /* This code only works for the original 32 bit ABI and the O64 ABI.  */
7854   if (mips_abi != ABI_32 && mips_abi != ABI_O64)
7855     abort ();
7856
7857   if (from_fp_p)
7858     s = "mfc1";
7859   else
7860     s = "mtc1";
7861   gparg = GP_ARG_FIRST;
7862   fparg = FP_ARG_FIRST;
7863   for (f = (unsigned int) fp_code; f != 0; f >>= 2)
7864     {
7865       if ((f & 3) == 1)
7866         {
7867           if ((fparg & 1) != 0)
7868             ++fparg;
7869           fprintf (file, "\t%s\t%s,%s\n", s,
7870                    reg_names[gparg], reg_names[fparg]);
7871         }
7872       else if ((f & 3) == 2)
7873         {
7874           if (TARGET_64BIT)
7875             fprintf (file, "\td%s\t%s,%s\n", s,
7876                      reg_names[gparg], reg_names[fparg]);
7877           else
7878             {
7879               if ((fparg & 1) != 0)
7880                 ++fparg;
7881               if (TARGET_BIG_ENDIAN)
7882                 fprintf (file, "\t%s\t%s,%s\n\t%s\t%s,%s\n", s,
7883                          reg_names[gparg], reg_names[fparg + 1], s,
7884                          reg_names[gparg + 1], reg_names[fparg]);
7885               else
7886                 fprintf (file, "\t%s\t%s,%s\n\t%s\t%s,%s\n", s,
7887                          reg_names[gparg], reg_names[fparg], s,
7888                          reg_names[gparg + 1], reg_names[fparg + 1]);
7889               ++gparg;
7890               ++fparg;
7891             }
7892         }
7893       else
7894         abort ();
7895
7896       ++gparg;
7897       ++fparg;
7898     }
7899 }
7900
7901 /* Build a mips16 function stub.  This is used for functions which
7902    take arguments in the floating point registers.  It is 32 bit code
7903    that moves the floating point args into the general registers, and
7904    then jumps to the 16 bit code.  */
7905
7906 static void
7907 build_mips16_function_stub (FILE *file)
7908 {
7909   const char *fnname;
7910   char *secname, *stubname;
7911   tree stubid, stubdecl;
7912   int need_comma;
7913   unsigned int f;
7914
7915   fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
7916   secname = (char *) alloca (strlen (fnname) + 20);
7917   sprintf (secname, ".mips16.fn.%s", fnname);
7918   stubname = (char *) alloca (strlen (fnname) + 20);
7919   sprintf (stubname, "__fn_stub_%s", fnname);
7920   stubid = get_identifier (stubname);
7921   stubdecl = build_decl (FUNCTION_DECL, stubid,
7922                          build_function_type (void_type_node, NULL_TREE));
7923   DECL_SECTION_NAME (stubdecl) = build_string (strlen (secname), secname);
7924
7925   fprintf (file, "\t# Stub function for %s (", current_function_name ());
7926   need_comma = 0;
7927   for (f = (unsigned int) current_function_args_info.fp_code; f != 0; f >>= 2)
7928     {
7929       fprintf (file, "%s%s",
7930                need_comma ? ", " : "",
7931                (f & 3) == 1 ? "float" : "double");
7932       need_comma = 1;
7933     }
7934   fprintf (file, ")\n");
7935
7936   fprintf (file, "\t.set\tnomips16\n");
7937   function_section (stubdecl);
7938   ASM_OUTPUT_ALIGN (file, floor_log2 (FUNCTION_BOUNDARY / BITS_PER_UNIT));
7939
7940   /* ??? If FUNCTION_NAME_ALREADY_DECLARED is defined, then we are
7941      within a .ent, and we can not emit another .ent.  */
7942   if (!FUNCTION_NAME_ALREADY_DECLARED)
7943     {
7944       fputs ("\t.ent\t", file);
7945       assemble_name (file, stubname);
7946       fputs ("\n", file);
7947     }
7948
7949   assemble_name (file, stubname);
7950   fputs (":\n", file);
7951
7952   /* We don't want the assembler to insert any nops here.  */
7953   fprintf (file, "\t.set\tnoreorder\n");
7954
7955   mips16_fp_args (file, current_function_args_info.fp_code, 1);
7956
7957   fprintf (asm_out_file, "\t.set\tnoat\n");
7958   fprintf (asm_out_file, "\tla\t%s,", reg_names[GP_REG_FIRST + 1]);
7959   assemble_name (file, fnname);
7960   fprintf (file, "\n");
7961   fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 1]);
7962   fprintf (asm_out_file, "\t.set\tat\n");
7963
7964   /* Unfortunately, we can't fill the jump delay slot.  We can't fill
7965      with one of the mfc1 instructions, because the result is not
7966      available for one instruction, so if the very first instruction
7967      in the function refers to the register, it will see the wrong
7968      value.  */
7969   fprintf (file, "\tnop\n");
7970
7971   fprintf (file, "\t.set\treorder\n");
7972
7973   if (!FUNCTION_NAME_ALREADY_DECLARED)
7974     {
7975       fputs ("\t.end\t", file);
7976       assemble_name (file, stubname);
7977       fputs ("\n", file);
7978     }
7979
7980   fprintf (file, "\t.set\tmips16\n");
7981
7982   function_section (current_function_decl);
7983 }
7984
7985 /* We keep a list of functions for which we have already built stubs
7986    in build_mips16_call_stub.  */
7987
7988 struct mips16_stub
7989 {
7990   struct mips16_stub *next;
7991   char *name;
7992   int fpret;
7993 };
7994
7995 static struct mips16_stub *mips16_stubs;
7996
7997 /* Build a call stub for a mips16 call.  A stub is needed if we are
7998    passing any floating point values which should go into the floating
7999    point registers.  If we are, and the call turns out to be to a 32
8000    bit function, the stub will be used to move the values into the
8001    floating point registers before calling the 32 bit function.  The
8002    linker will magically adjust the function call to either the 16 bit
8003    function or the 32 bit stub, depending upon where the function call
8004    is actually defined.
8005
8006    Similarly, we need a stub if the return value might come back in a
8007    floating point register.
8008
8009    RETVAL is the location of the return value, or null if this is
8010    a call rather than a call_value.  FN is the address of the
8011    function and ARG_SIZE is the size of the arguments.  FP_CODE
8012    is the code built by function_arg.  This function returns a nonzero
8013    value if it builds the call instruction itself.  */
8014
8015 int
8016 build_mips16_call_stub (rtx retval, rtx fn, rtx arg_size, int fp_code)
8017 {
8018   int fpret;
8019   const char *fnname;
8020   char *secname, *stubname;
8021   struct mips16_stub *l;
8022   tree stubid, stubdecl;
8023   int need_comma;
8024   unsigned int f;
8025
8026   /* We don't need to do anything if we aren't in mips16 mode, or if
8027      we were invoked with the -msoft-float option.  */
8028   if (! TARGET_MIPS16 || ! mips16_hard_float)
8029     return 0;
8030
8031   /* Figure out whether the value might come back in a floating point
8032      register.  */
8033   fpret = (retval != 0
8034            && GET_MODE_CLASS (GET_MODE (retval)) == MODE_FLOAT
8035            && GET_MODE_SIZE (GET_MODE (retval)) <= UNITS_PER_FPVALUE);
8036
8037   /* We don't need to do anything if there were no floating point
8038      arguments and the value will not be returned in a floating point
8039      register.  */
8040   if (fp_code == 0 && ! fpret)
8041     return 0;
8042
8043   /* We don't need to do anything if this is a call to a special
8044      mips16 support function.  */
8045   if (GET_CODE (fn) == SYMBOL_REF
8046       && strncmp (XSTR (fn, 0), "__mips16_", 9) == 0)
8047     return 0;
8048
8049   /* This code will only work for o32 and o64 abis.  The other ABI's
8050      require more sophisticated support.  */
8051   if (mips_abi != ABI_32 && mips_abi != ABI_O64)
8052     abort ();
8053
8054   /* We can only handle SFmode and DFmode floating point return
8055      values.  */
8056   if (fpret && GET_MODE (retval) != SFmode && GET_MODE (retval) != DFmode)
8057     abort ();
8058
8059   /* If we're calling via a function pointer, then we must always call
8060      via a stub.  There are magic stubs provided in libgcc.a for each
8061      of the required cases.  Each of them expects the function address
8062      to arrive in register $2.  */
8063
8064   if (GET_CODE (fn) != SYMBOL_REF)
8065     {
8066       char buf[30];
8067       tree id;
8068       rtx stub_fn, insn;
8069
8070       /* ??? If this code is modified to support other ABI's, we need
8071          to handle PARALLEL return values here.  */
8072
8073       sprintf (buf, "__mips16_call_stub_%s%d",
8074                (fpret
8075                 ? (GET_MODE (retval) == SFmode ? "sf_" : "df_")
8076                 : ""),
8077                fp_code);
8078       id = get_identifier (buf);
8079       stub_fn = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (id));
8080
8081       emit_move_insn (gen_rtx_REG (Pmode, 2), fn);
8082
8083       if (retval == NULL_RTX)
8084         insn = gen_call_internal (stub_fn, arg_size);
8085       else
8086         insn = gen_call_value_internal (retval, stub_fn, arg_size);
8087       insn = emit_call_insn (insn);
8088
8089       /* Put the register usage information on the CALL.  */
8090       if (GET_CODE (insn) != CALL_INSN)
8091         abort ();
8092       CALL_INSN_FUNCTION_USAGE (insn) =
8093         gen_rtx_EXPR_LIST (VOIDmode,
8094                            gen_rtx_USE (VOIDmode, gen_rtx_REG (Pmode, 2)),
8095                            CALL_INSN_FUNCTION_USAGE (insn));
8096
8097       /* If we are handling a floating point return value, we need to
8098          save $18 in the function prologue.  Putting a note on the
8099          call will mean that regs_ever_live[$18] will be true if the
8100          call is not eliminated, and we can check that in the prologue
8101          code.  */
8102       if (fpret)
8103         CALL_INSN_FUNCTION_USAGE (insn) =
8104           gen_rtx_EXPR_LIST (VOIDmode,
8105                              gen_rtx_USE (VOIDmode,
8106                                           gen_rtx_REG (word_mode, 18)),
8107                              CALL_INSN_FUNCTION_USAGE (insn));
8108
8109       /* Return 1 to tell the caller that we've generated the call
8110          insn.  */
8111       return 1;
8112     }
8113
8114   /* We know the function we are going to call.  If we have already
8115      built a stub, we don't need to do anything further.  */
8116
8117   fnname = XSTR (fn, 0);
8118   for (l = mips16_stubs; l != NULL; l = l->next)
8119     if (strcmp (l->name, fnname) == 0)
8120       break;
8121
8122   if (l == NULL)
8123     {
8124       /* Build a special purpose stub.  When the linker sees a
8125          function call in mips16 code, it will check where the target
8126          is defined.  If the target is a 32 bit call, the linker will
8127          search for the section defined here.  It can tell which
8128          symbol this section is associated with by looking at the
8129          relocation information (the name is unreliable, since this
8130          might be a static function).  If such a section is found, the
8131          linker will redirect the call to the start of the magic
8132          section.
8133
8134          If the function does not return a floating point value, the
8135          special stub section is named
8136              .mips16.call.FNNAME
8137
8138          If the function does return a floating point value, the stub
8139          section is named
8140              .mips16.call.fp.FNNAME
8141          */
8142
8143       secname = (char *) alloca (strlen (fnname) + 40);
8144       sprintf (secname, ".mips16.call.%s%s",
8145                fpret ? "fp." : "",
8146                fnname);
8147       stubname = (char *) alloca (strlen (fnname) + 20);
8148       sprintf (stubname, "__call_stub_%s%s",
8149                fpret ? "fp_" : "",
8150                fnname);
8151       stubid = get_identifier (stubname);
8152       stubdecl = build_decl (FUNCTION_DECL, stubid,
8153                              build_function_type (void_type_node, NULL_TREE));
8154       DECL_SECTION_NAME (stubdecl) = build_string (strlen (secname), secname);
8155
8156       fprintf (asm_out_file, "\t# Stub function to call %s%s (",
8157                (fpret
8158                 ? (GET_MODE (retval) == SFmode ? "float " : "double ")
8159                 : ""),
8160                fnname);
8161       need_comma = 0;
8162       for (f = (unsigned int) fp_code; f != 0; f >>= 2)
8163         {
8164           fprintf (asm_out_file, "%s%s",
8165                    need_comma ? ", " : "",
8166                    (f & 3) == 1 ? "float" : "double");
8167           need_comma = 1;
8168         }
8169       fprintf (asm_out_file, ")\n");
8170
8171       fprintf (asm_out_file, "\t.set\tnomips16\n");
8172       assemble_start_function (stubdecl, stubname);
8173
8174       if (!FUNCTION_NAME_ALREADY_DECLARED)
8175         {
8176           fputs ("\t.ent\t", asm_out_file);
8177           assemble_name (asm_out_file, stubname);
8178           fputs ("\n", asm_out_file);
8179
8180           assemble_name (asm_out_file, stubname);
8181           fputs (":\n", asm_out_file);
8182         }
8183
8184       /* We build the stub code by hand.  That's the only way we can
8185          do it, since we can't generate 32 bit code during a 16 bit
8186          compilation.  */
8187
8188       /* We don't want the assembler to insert any nops here.  */
8189       fprintf (asm_out_file, "\t.set\tnoreorder\n");
8190
8191       mips16_fp_args (asm_out_file, fp_code, 0);
8192
8193       if (! fpret)
8194         {
8195           fprintf (asm_out_file, "\t.set\tnoat\n");
8196           fprintf (asm_out_file, "\tla\t%s,%s\n", reg_names[GP_REG_FIRST + 1],
8197                    fnname);
8198           fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 1]);
8199           fprintf (asm_out_file, "\t.set\tat\n");
8200           /* Unfortunately, we can't fill the jump delay slot.  We
8201              can't fill with one of the mtc1 instructions, because the
8202              result is not available for one instruction, so if the
8203              very first instruction in the function refers to the
8204              register, it will see the wrong value.  */
8205           fprintf (asm_out_file, "\tnop\n");
8206         }
8207       else
8208         {
8209           fprintf (asm_out_file, "\tmove\t%s,%s\n",
8210                    reg_names[GP_REG_FIRST + 18], reg_names[GP_REG_FIRST + 31]);
8211           fprintf (asm_out_file, "\tjal\t%s\n", fnname);
8212           /* As above, we can't fill the delay slot.  */
8213           fprintf (asm_out_file, "\tnop\n");
8214           if (GET_MODE (retval) == SFmode)
8215             fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
8216                      reg_names[GP_REG_FIRST + 2], reg_names[FP_REG_FIRST + 0]);
8217           else
8218             {
8219               if (TARGET_BIG_ENDIAN)
8220                 {
8221                   fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
8222                            reg_names[GP_REG_FIRST + 2],
8223                            reg_names[FP_REG_FIRST + 1]);
8224                   fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
8225                            reg_names[GP_REG_FIRST + 3],
8226                            reg_names[FP_REG_FIRST + 0]);
8227                 }
8228               else
8229                 {
8230                   fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
8231                            reg_names[GP_REG_FIRST + 2],
8232                            reg_names[FP_REG_FIRST + 0]);
8233                   fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
8234                            reg_names[GP_REG_FIRST + 3],
8235                            reg_names[FP_REG_FIRST + 1]);
8236                 }
8237             }
8238           fprintf (asm_out_file, "\tj\t%s\n", reg_names[GP_REG_FIRST + 18]);
8239           /* As above, we can't fill the delay slot.  */
8240           fprintf (asm_out_file, "\tnop\n");
8241         }
8242
8243       fprintf (asm_out_file, "\t.set\treorder\n");
8244
8245 #ifdef ASM_DECLARE_FUNCTION_SIZE
8246       ASM_DECLARE_FUNCTION_SIZE (asm_out_file, stubname, stubdecl);
8247 #endif
8248
8249       if (!FUNCTION_NAME_ALREADY_DECLARED)
8250         {
8251           fputs ("\t.end\t", asm_out_file);
8252           assemble_name (asm_out_file, stubname);
8253           fputs ("\n", asm_out_file);
8254         }
8255
8256       fprintf (asm_out_file, "\t.set\tmips16\n");
8257
8258       /* Record this stub.  */
8259       l = (struct mips16_stub *) xmalloc (sizeof *l);
8260       l->name = xstrdup (fnname);
8261       l->fpret = fpret;
8262       l->next = mips16_stubs;
8263       mips16_stubs = l;
8264     }
8265
8266   /* If we expect a floating point return value, but we've built a
8267      stub which does not expect one, then we're in trouble.  We can't
8268      use the existing stub, because it won't handle the floating point
8269      value.  We can't build a new stub, because the linker won't know
8270      which stub to use for the various calls in this object file.
8271      Fortunately, this case is illegal, since it means that a function
8272      was declared in two different ways in a single compilation.  */
8273   if (fpret && ! l->fpret)
8274     error ("can not handle inconsistent calls to `%s'", fnname);
8275
8276   /* If we are calling a stub which handles a floating point return
8277      value, we need to arrange to save $18 in the prologue.  We do
8278      this by marking the function call as using the register.  The
8279      prologue will later see that it is used, and emit code to save
8280      it.  */
8281
8282   if (l->fpret)
8283     {
8284       rtx insn;
8285
8286       if (retval == NULL_RTX)
8287         insn = gen_call_internal (fn, arg_size);
8288       else
8289         insn = gen_call_value_internal (retval, fn, arg_size);
8290       insn = emit_call_insn (insn);
8291
8292       if (GET_CODE (insn) != CALL_INSN)
8293         abort ();
8294
8295       CALL_INSN_FUNCTION_USAGE (insn) =
8296         gen_rtx_EXPR_LIST (VOIDmode,
8297                            gen_rtx_USE (VOIDmode, gen_rtx_REG (word_mode, 18)),
8298                            CALL_INSN_FUNCTION_USAGE (insn));
8299
8300       /* Return 1 to tell the caller that we've generated the call
8301          insn.  */
8302       return 1;
8303     }
8304
8305   /* Return 0 to let the caller generate the call insn.  */
8306   return 0;
8307 }
8308
8309 /* We keep a list of constants we which we have to add to internal
8310    constant tables in the middle of large functions.  */
8311
8312 struct constant
8313 {
8314   struct constant *next;
8315   rtx value;
8316   rtx label;
8317   enum machine_mode mode;
8318 };
8319
8320 /* Add a constant to the list in *PCONSTANTS.  */
8321
8322 static rtx
8323 add_constant (struct constant **pconstants, rtx val, enum machine_mode mode)
8324 {
8325   struct constant *c;
8326
8327   for (c = *pconstants; c != NULL; c = c->next)
8328     if (mode == c->mode && rtx_equal_p (val, c->value))
8329       return c->label;
8330
8331   c = (struct constant *) xmalloc (sizeof *c);
8332   c->value = val;
8333   c->mode = mode;
8334   c->label = gen_label_rtx ();
8335   c->next = *pconstants;
8336   *pconstants = c;
8337   return c->label;
8338 }
8339
8340 /* Dump out the constants in CONSTANTS after INSN.  */
8341
8342 static void
8343 dump_constants (struct constant *constants, rtx insn)
8344 {
8345   struct constant *c;
8346   int align;
8347
8348   c = constants;
8349   align = 0;
8350   while (c != NULL)
8351     {
8352       rtx r;
8353       struct constant *next;
8354
8355       switch (GET_MODE_SIZE (c->mode))
8356         {
8357         case 1:
8358           align = 0;
8359           break;
8360         case 2:
8361           if (align < 1)
8362             insn = emit_insn_after (gen_align_2 (), insn);
8363           align = 1;
8364           break;
8365         case 4:
8366           if (align < 2)
8367             insn = emit_insn_after (gen_align_4 (), insn);
8368           align = 2;
8369           break;
8370         default:
8371           if (align < 3)
8372             insn = emit_insn_after (gen_align_8 (), insn);
8373           align = 3;
8374           break;
8375         }
8376
8377       insn = emit_label_after (c->label, insn);
8378
8379       switch (c->mode)
8380         {
8381         case QImode:
8382           r = gen_consttable_qi (c->value);
8383           break;
8384         case HImode:
8385           r = gen_consttable_hi (c->value);
8386           break;
8387         case SImode:
8388           r = gen_consttable_si (c->value);
8389           break;
8390         case SFmode:
8391           r = gen_consttable_sf (c->value);
8392           break;
8393         case DImode:
8394           r = gen_consttable_di (c->value);
8395           break;
8396         case DFmode:
8397           r = gen_consttable_df (c->value);
8398           break;
8399         default:
8400           abort ();
8401         }
8402
8403       insn = emit_insn_after (r, insn);
8404
8405       next = c->next;
8406       free (c);
8407       c = next;
8408     }
8409
8410   emit_barrier_after (insn);
8411 }
8412
8413 /* Find the symbol in an address expression.  */
8414
8415 static rtx
8416 mips_find_symbol (rtx addr)
8417 {
8418   if (GET_CODE (addr) == MEM)
8419     addr = XEXP (addr, 0);
8420   while (GET_CODE (addr) == CONST)
8421     addr = XEXP (addr, 0);
8422   if (GET_CODE (addr) == SYMBOL_REF || GET_CODE (addr) == LABEL_REF)
8423     return addr;
8424   if (GET_CODE (addr) == PLUS)
8425     {
8426       rtx l1, l2;
8427
8428       l1 = mips_find_symbol (XEXP (addr, 0));
8429       l2 = mips_find_symbol (XEXP (addr, 1));
8430       if (l1 != NULL_RTX && l2 == NULL_RTX)
8431         return l1;
8432       else if (l1 == NULL_RTX && l2 != NULL_RTX)
8433         return l2;
8434     }
8435   return NULL_RTX;
8436 }
8437
8438 /* In mips16 mode, we need to look through the function to check for
8439    PC relative loads that are out of range.  */
8440
8441 static void
8442 mips16_lay_out_constants (void)
8443 {
8444   int insns_len, max_internal_pool_size, pool_size, addr, first_constant_ref;
8445   rtx first, insn;
8446   struct constant *constants;
8447
8448   first = get_insns ();
8449
8450   /* Scan the function looking for PC relative loads which may be out
8451      of range.  All such loads will either be from the constant table,
8452      or be getting the address of a constant string.  If the size of
8453      the function plus the size of the constant table is less than
8454      0x8000, then all loads are in range.  */
8455
8456   insns_len = 0;
8457   for (insn = first; insn; insn = NEXT_INSN (insn))
8458     {
8459       insns_len += get_attr_length (insn);
8460
8461       /* ??? We put switch tables in .text, but we don't define
8462          JUMP_TABLES_IN_TEXT_SECTION, so get_attr_length will not
8463          compute their lengths correctly.  */
8464       if (GET_CODE (insn) == JUMP_INSN)
8465         {
8466           rtx body;
8467
8468           body = PATTERN (insn);
8469           if (GET_CODE (body) == ADDR_VEC || GET_CODE (body) == ADDR_DIFF_VEC)
8470             insns_len += (XVECLEN (body, GET_CODE (body) == ADDR_DIFF_VEC)
8471                           * GET_MODE_SIZE (GET_MODE (body)));
8472           insns_len += GET_MODE_SIZE (GET_MODE (body)) - 1;
8473         }
8474     }
8475
8476   /* Store the original value of insns_len in cfun->machine, so
8477      that m16_usym8_4 and m16_usym5_4 can look at it.  */
8478   cfun->machine->insns_len = insns_len;
8479
8480   pool_size = get_pool_size ();
8481   if (insns_len + pool_size + mips_string_length < 0x8000)
8482     return;
8483
8484   /* Loop over the insns and figure out what the maximum internal pool
8485      size could be.  */
8486   max_internal_pool_size = 0;
8487   for (insn = first; insn; insn = NEXT_INSN (insn))
8488     {
8489       if (GET_CODE (insn) == INSN
8490           && GET_CODE (PATTERN (insn)) == SET)
8491         {
8492           rtx src;
8493
8494           src = mips_find_symbol (SET_SRC (PATTERN (insn)));
8495           if (src == NULL_RTX)
8496             continue;
8497           if (CONSTANT_POOL_ADDRESS_P (src))
8498             max_internal_pool_size += GET_MODE_SIZE (get_pool_mode (src));
8499           else if (SYMBOL_REF_FLAG (src))
8500             max_internal_pool_size += GET_MODE_SIZE (Pmode);
8501         }
8502     }
8503
8504   constants = NULL;
8505   addr = 0;
8506   first_constant_ref = -1;
8507
8508   for (insn = first; insn; insn = NEXT_INSN (insn))
8509     {
8510       if (GET_CODE (insn) == INSN
8511           && GET_CODE (PATTERN (insn)) == SET)
8512         {
8513           rtx val, src;
8514           enum machine_mode mode = VOIDmode;
8515
8516           val = NULL_RTX;
8517           src = mips_find_symbol (SET_SRC (PATTERN (insn)));
8518           if (src != NULL_RTX && CONSTANT_POOL_ADDRESS_P (src))
8519             {
8520               /* ??? This is very conservative, which means that we
8521                  will generate too many copies of the constant table.
8522                  The only solution would seem to be some form of
8523                  relaxing.  */
8524               if (((insns_len - addr)
8525                    + max_internal_pool_size
8526                    + get_pool_offset (src))
8527                   >= 0x8000)
8528                 {
8529                   val = get_pool_constant (src);
8530                   mode = get_pool_mode (src);
8531                 }
8532               max_internal_pool_size -= GET_MODE_SIZE (get_pool_mode (src));
8533             }
8534           else if (src != NULL_RTX && SYMBOL_REF_FLAG (src))
8535             {
8536               /* Including all of mips_string_length is conservative,
8537                  and so is including all of max_internal_pool_size.  */
8538               if (((insns_len - addr)
8539                    + max_internal_pool_size
8540                    + pool_size
8541                    + mips_string_length)
8542                   >= 0x8000)
8543                 {
8544                   val = src;
8545                   mode = Pmode;
8546                 }
8547               max_internal_pool_size -= Pmode;
8548             }
8549
8550           if (val != NULL_RTX)
8551             {
8552               rtx lab, newsrc;
8553
8554               /* This PC relative load is out of range.  ??? In the
8555                  case of a string constant, we are only guessing that
8556                  it is range, since we don't know the offset of a
8557                  particular string constant.  */
8558
8559               lab = add_constant (&constants, val, mode);
8560               newsrc = gen_rtx_MEM (mode,
8561                                     gen_rtx_LABEL_REF (VOIDmode, lab));
8562               RTX_UNCHANGING_P (newsrc) = 1;
8563               PATTERN (insn) = gen_rtx_SET (VOIDmode,
8564                                             SET_DEST (PATTERN (insn)),
8565                                             newsrc);
8566               INSN_CODE (insn) = -1;
8567
8568               if (first_constant_ref < 0)
8569                 first_constant_ref = addr;
8570             }
8571         }
8572
8573       addr += get_attr_length (insn);
8574
8575       /* ??? We put switch tables in .text, but we don't define
8576          JUMP_TABLES_IN_TEXT_SECTION, so get_attr_length will not
8577          compute their lengths correctly.  */
8578       if (GET_CODE (insn) == JUMP_INSN)
8579         {
8580           rtx body;
8581
8582           body = PATTERN (insn);
8583           if (GET_CODE (body) == ADDR_VEC || GET_CODE (body) == ADDR_DIFF_VEC)
8584             addr += (XVECLEN (body, GET_CODE (body) == ADDR_DIFF_VEC)
8585                           * GET_MODE_SIZE (GET_MODE (body)));
8586           addr += GET_MODE_SIZE (GET_MODE (body)) - 1;
8587         }
8588
8589       if (GET_CODE (insn) == BARRIER)
8590         {
8591           /* Output any constants we have accumulated.  Note that we
8592              don't need to change ADDR, since its only use is
8593              subtraction from INSNS_LEN, and both would be changed by
8594              the same amount.
8595              ??? If the instructions up to the next barrier reuse a
8596              constant, it would often be better to continue
8597              accumulating.  */
8598           if (constants != NULL)
8599             dump_constants (constants, insn);
8600           constants = NULL;
8601           first_constant_ref = -1;
8602         }
8603
8604       if (constants != NULL
8605                && (NEXT_INSN (insn) == NULL
8606                    || (first_constant_ref >= 0
8607                        && (((addr - first_constant_ref)
8608                             + 2 /* for alignment */
8609                             + 2 /* for a short jump insn */
8610                             + pool_size)
8611                            >= 0x8000))))
8612         {
8613           /* If we haven't had a barrier within 0x8000 bytes of a
8614              constant reference or we are at the end of the function,
8615              emit a barrier now.  */
8616
8617           rtx label, jump, barrier;
8618
8619           label = gen_label_rtx ();
8620           jump = emit_jump_insn_after (gen_jump (label), insn);
8621           JUMP_LABEL (jump) = label;
8622           LABEL_NUSES (label) = 1;
8623           barrier = emit_barrier_after (jump);
8624           emit_label_after (label, barrier);
8625           first_constant_ref = -1;
8626         }
8627      }
8628
8629   /* ??? If we output all references to a constant in internal
8630      constants table, we don't need to output the constant in the real
8631      constant table, but we have no way to prevent that.  */
8632 }
8633
8634
8635 /* Subroutine of mips_reorg.  If there is a hazard between INSN
8636    and a previous instruction, avoid it by inserting nops after
8637    instruction AFTER.
8638
8639    *DELAYED_REG and *HILO_DELAY describe the hazards that apply at
8640    this point.  If *DELAYED_REG is non-null, INSN must wait a cycle
8641    before using the value of that register.  *HILO_DELAY counts the
8642    number of instructions since the last hilo hazard (that is,
8643    the number of instructions since the last mflo or mfhi).
8644
8645    After inserting nops for INSN, update *DELAYED_REG and *HILO_DELAY
8646    for the next instruction.
8647
8648    LO_REG is an rtx for the LO register, used in dependence checking.  */
8649
8650 static void
8651 mips_avoid_hazard (rtx after, rtx insn, int *hilo_delay,
8652                    rtx *delayed_reg, rtx lo_reg)
8653 {
8654   rtx pattern, set;
8655   int nops, ninsns;
8656
8657   if (!INSN_P (insn))
8658     return;
8659
8660   pattern = PATTERN (insn);
8661
8662   /* Do not put the whole function in .set noreorder if it contains
8663      an asm statement.  We don't know whether there will be hazards
8664      between the asm statement and the gcc-generated code.  */
8665   if (GET_CODE (pattern) == ASM_INPUT || asm_noperands (pattern) >= 0)
8666     cfun->machine->all_noreorder_p = false;
8667
8668   /* Ignore zero-length instructions (barriers and the like).  */
8669   ninsns = get_attr_length (insn) / 4;
8670   if (ninsns == 0)
8671     return;
8672
8673   /* Work out how many nops are needed.  Note that we only care about
8674      registers that are explicitly mentioned in the instruction's pattern.
8675      It doesn't matter that calls use the argument registers or that they
8676      clobber hi and lo.  */
8677   if (*hilo_delay < 2 && reg_set_p (lo_reg, pattern))
8678     nops = 2 - *hilo_delay;
8679   else if (*delayed_reg != 0 && reg_referenced_p (*delayed_reg, pattern))
8680     nops = 1;
8681   else
8682     nops = 0;
8683
8684   /* Insert the nops between this instruction and the previous one.
8685      Each new nop takes us further from the last hilo hazard.  */
8686   *hilo_delay += nops;
8687   while (nops-- > 0)
8688     emit_insn_after (gen_hazard_nop (), after);
8689
8690   /* Set up the state for the next instruction.  */
8691   *hilo_delay += ninsns;
8692   *delayed_reg = 0;
8693   if (INSN_CODE (insn) >= 0)
8694     switch (get_attr_hazard (insn))
8695       {
8696       case HAZARD_NONE:
8697         break;
8698
8699       case HAZARD_HILO:
8700         *hilo_delay = 0;
8701         break;
8702
8703       case HAZARD_DELAY:
8704         set = single_set (insn);
8705         if (set == 0)
8706           abort ();
8707         *delayed_reg = SET_DEST (set);
8708         break;
8709       }
8710 }
8711
8712
8713 /* Go through the instruction stream and insert nops where necessary.
8714    See if the whole function can then be put into .set noreorder &
8715    .set nomacro.  */
8716
8717 static void
8718 mips_avoid_hazards (void)
8719 {
8720   rtx insn, last_insn, lo_reg, delayed_reg;
8721   int hilo_delay, i;
8722
8723   /* Recalculate instruction lengths without taking nops into account.  */
8724   cfun->machine->ignore_hazard_length_p = true;
8725   shorten_branches (get_insns ());
8726
8727   /* The profiler code uses assembler macros.  */
8728   cfun->machine->all_noreorder_p = !current_function_profile;
8729
8730   last_insn = 0;
8731   hilo_delay = 2;
8732   delayed_reg = 0;
8733   lo_reg = gen_rtx_REG (SImode, LO_REGNUM);
8734
8735   for (insn = get_insns (); insn != 0; insn = NEXT_INSN (insn))
8736     if (INSN_P (insn))
8737       {
8738         if (GET_CODE (PATTERN (insn)) == SEQUENCE)
8739           for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
8740             mips_avoid_hazard (last_insn, XVECEXP (PATTERN (insn), 0, i),
8741                                &hilo_delay, &delayed_reg, lo_reg);
8742         else
8743           mips_avoid_hazard (last_insn, insn, &hilo_delay,
8744                              &delayed_reg, lo_reg);
8745
8746         last_insn = insn;
8747       }
8748 }
8749
8750
8751 /* Implement TARGET_MACHINE_DEPENDENT_REORG.  */
8752
8753 static void
8754 mips_reorg (void)
8755 {
8756   if (TARGET_MIPS16)
8757     mips16_lay_out_constants ();
8758   else if (TARGET_EXPLICIT_RELOCS)
8759     {
8760       if (mips_flag_delayed_branch)
8761         dbr_schedule (get_insns (), rtl_dump_file);
8762       mips_avoid_hazards ();
8763     }
8764 }
8765
8766 /* We need to use a special set of functions to handle hard floating
8767    point code in mips16 mode.  Also, allow for --enable-gofast.  */
8768
8769 #include "config/gofast.h"
8770
8771 static void
8772 mips_init_libfuncs (void)
8773 {
8774   if (TARGET_MIPS16 && mips16_hard_float)
8775     {
8776       set_optab_libfunc (add_optab, SFmode, "__mips16_addsf3");
8777       set_optab_libfunc (sub_optab, SFmode, "__mips16_subsf3");
8778       set_optab_libfunc (smul_optab, SFmode, "__mips16_mulsf3");
8779       set_optab_libfunc (sdiv_optab, SFmode, "__mips16_divsf3");
8780
8781       set_optab_libfunc (eq_optab, SFmode, "__mips16_eqsf2");
8782       set_optab_libfunc (ne_optab, SFmode, "__mips16_nesf2");
8783       set_optab_libfunc (gt_optab, SFmode, "__mips16_gtsf2");
8784       set_optab_libfunc (ge_optab, SFmode, "__mips16_gesf2");
8785       set_optab_libfunc (lt_optab, SFmode, "__mips16_ltsf2");
8786       set_optab_libfunc (le_optab, SFmode, "__mips16_lesf2");
8787
8788       set_conv_libfunc (sfix_optab, SImode, SFmode, "__mips16_fixsfsi");
8789       set_conv_libfunc (sfloat_optab, SFmode, SImode, "__mips16_floatsisf");
8790
8791       if (TARGET_DOUBLE_FLOAT)
8792         {
8793           set_optab_libfunc (add_optab, DFmode, "__mips16_adddf3");
8794           set_optab_libfunc (sub_optab, DFmode, "__mips16_subdf3");
8795           set_optab_libfunc (smul_optab, DFmode, "__mips16_muldf3");
8796           set_optab_libfunc (sdiv_optab, DFmode, "__mips16_divdf3");
8797
8798           set_optab_libfunc (eq_optab, DFmode, "__mips16_eqdf2");
8799           set_optab_libfunc (ne_optab, DFmode, "__mips16_nedf2");
8800           set_optab_libfunc (gt_optab, DFmode, "__mips16_gtdf2");
8801           set_optab_libfunc (ge_optab, DFmode, "__mips16_gedf2");
8802           set_optab_libfunc (lt_optab, DFmode, "__mips16_ltdf2");
8803           set_optab_libfunc (le_optab, DFmode, "__mips16_ledf2");
8804
8805           set_conv_libfunc (sext_optab, DFmode, SFmode, "__mips16_extendsfdf2");
8806           set_conv_libfunc (trunc_optab, SFmode, DFmode, "__mips16_truncdfsf2");
8807
8808           set_conv_libfunc (sfix_optab, SImode, DFmode, "__mips16_fixdfsi");
8809           set_conv_libfunc (sfloat_optab, DFmode, SImode, "__mips16_floatsidf");
8810         }
8811     }
8812   else
8813     gofast_maybe_init_libfuncs ();
8814 }
8815
8816 /* Return a number assessing the cost of moving a register in class
8817    FROM to class TO.  The classes are expressed using the enumeration
8818    values such as `GENERAL_REGS'.  A value of 2 is the default; other
8819    values are interpreted relative to that.
8820
8821    It is not required that the cost always equal 2 when FROM is the
8822    same as TO; on some machines it is expensive to move between
8823    registers if they are not general registers.
8824
8825    If reload sees an insn consisting of a single `set' between two
8826    hard registers, and if `REGISTER_MOVE_COST' applied to their
8827    classes returns a value of 2, reload does not check to ensure that
8828    the constraints of the insn are met.  Setting a cost of other than
8829    2 will allow reload to verify that the constraints are met.  You
8830    should do this if the `movM' pattern's constraints do not allow
8831    such copying.
8832
8833    ??? We make the cost of moving from HI/LO into general
8834    registers the same as for one of moving general registers to
8835    HI/LO for TARGET_MIPS16 in order to prevent allocating a
8836    pseudo to HI/LO.  This might hurt optimizations though, it
8837    isn't clear if it is wise.  And it might not work in all cases.  We
8838    could solve the DImode LO reg problem by using a multiply, just
8839    like reload_{in,out}si.  We could solve the SImode/HImode HI reg
8840    problem by using divide instructions.  divu puts the remainder in
8841    the HI reg, so doing a divide by -1 will move the value in the HI
8842    reg for all values except -1.  We could handle that case by using a
8843    signed divide, e.g.  -1 / 2 (or maybe 1 / -2?).  We'd have to emit
8844    a compare/branch to test the input value to see which instruction
8845    we need to use.  This gets pretty messy, but it is feasible.  */
8846
8847 int
8848 mips_register_move_cost (enum machine_mode mode ATTRIBUTE_UNUSED,
8849                          enum reg_class to, enum reg_class from)
8850 {
8851   if (from == M16_REGS && GR_REG_CLASS_P (to))
8852     return 2;
8853   else if (from == M16_NA_REGS && GR_REG_CLASS_P (to))
8854     return 2;
8855   else if (GR_REG_CLASS_P (from))
8856     {
8857       if (to == M16_REGS)
8858         return 2;
8859       else if (to == M16_NA_REGS)
8860         return 2;
8861       else if (GR_REG_CLASS_P (to))
8862         {
8863           if (TARGET_MIPS16)
8864             return 4;
8865           else
8866             return 2;
8867         }
8868       else if (to == FP_REGS)
8869         return 4;
8870       else if (to == HI_REG || to == LO_REG || to == MD_REGS)
8871         {
8872           if (TARGET_MIPS16)
8873             return 12;
8874           else
8875             return 6;
8876         }
8877       else if (COP_REG_CLASS_P (to))
8878         {
8879           return 5;
8880         }
8881     }  /* GR_REG_CLASS_P (from) */
8882   else if (from == FP_REGS)
8883     {
8884       if (GR_REG_CLASS_P (to))
8885         return 4;
8886       else if (to == FP_REGS)
8887         return 2;
8888       else if (to == ST_REGS)
8889         return 8;
8890     }  /* from == FP_REGS */
8891   else if (from == HI_REG || from == LO_REG || from == MD_REGS)
8892     {
8893       if (GR_REG_CLASS_P (to))
8894         {
8895           if (TARGET_MIPS16)
8896             return 12;
8897           else
8898             return 6;
8899         }
8900     }  /* from == HI_REG, etc.  */
8901   else if (from == ST_REGS && GR_REG_CLASS_P (to))
8902     return 4;
8903   else if (COP_REG_CLASS_P (from))
8904     {
8905       return 5;
8906     }  /* COP_REG_CLASS_P (from) */
8907
8908   /* Fall through.  */
8909
8910   return 12;
8911 }
8912
8913 /* Return the length of INSN.  LENGTH is the initial length computed by
8914    attributes in the machine-description file.  */
8915
8916 int
8917 mips_adjust_insn_length (rtx insn, int length)
8918 {
8919   /* A unconditional jump has an unfilled delay slot if it is not part
8920      of a sequence.  A conditional jump normally has a delay slot, but
8921      does not on MIPS16.  */
8922   if (simplejump_p (insn)
8923       || (!TARGET_MIPS16  && (GET_CODE (insn) == JUMP_INSN
8924                               || GET_CODE (insn) == CALL_INSN)))
8925     length += 4;
8926
8927   /* See how many nops might be needed to avoid hardware hazards.  */
8928   if (!cfun->machine->ignore_hazard_length_p && INSN_CODE (insn) >= 0)
8929     switch (get_attr_hazard (insn))
8930       {
8931       case HAZARD_NONE:
8932         break;
8933
8934       case HAZARD_DELAY:
8935         length += 4;
8936         break;
8937
8938       case HAZARD_HILO:
8939         length += 8;
8940         break;
8941       }
8942
8943   /* All MIPS16 instructions are a measly two bytes.  */
8944   if (TARGET_MIPS16)
8945     length /= 2;
8946
8947   return length;
8948 }
8949
8950
8951 /* Return an asm sequence to start a noat block and load the address
8952    of a label into $1.  */
8953
8954 const char *
8955 mips_output_load_label (void)
8956 {
8957   if (TARGET_EXPLICIT_RELOCS)
8958     switch (mips_abi)
8959       {
8960       case ABI_N32:
8961         return "%[lw\t%@,%%got_page(%0)(%+)\n\taddiu\t%@,%@,%%got_ofst(%0)";
8962
8963       case ABI_64:
8964         return "%[ld\t%@,%%got_page(%0)(%+)\n\tdaddiu\t%@,%@,%%got_ofst(%0)";
8965
8966       default:
8967         if (ISA_HAS_LOAD_DELAY)
8968           return "%[lw\t%@,%%got(%0)(%+)%#\n\taddiu\t%@,%@,%%lo(%0)";
8969         return "%[lw\t%@,%%got(%0)(%+)\n\taddiu\t%@,%@,%%lo(%0)";
8970       }
8971   else
8972     {
8973       if (Pmode == DImode)
8974         return "%[dla\t%@,%0";
8975       else
8976         return "%[la\t%@,%0";
8977     }
8978 }
8979
8980
8981 /* Output assembly instructions to peform a conditional branch.
8982
8983    INSN is the branch instruction.  OPERANDS[0] is the condition.
8984    OPERANDS[1] is the target of the branch.  OPERANDS[2] is the target
8985    of the first operand to the condition.  If TWO_OPERANDS_P is
8986    nonzero the comparison takes two operands; OPERANDS[3] will be the
8987    second operand.
8988
8989    If INVERTED_P is nonzero we are to branch if the condition does
8990    not hold.  If FLOAT_P is nonzero this is a floating-point comparison.
8991
8992    LENGTH is the length (in bytes) of the sequence we are to generate.
8993    That tells us whether to generate a simple conditional branch, or a
8994    reversed conditional branch around a `jr' instruction.  */
8995 const char *
8996 mips_output_conditional_branch (rtx insn, rtx *operands, int two_operands_p,
8997                                 int float_p, int inverted_p, int length)
8998 {
8999   static char buffer[200];
9000   /* The kind of comparison we are doing.  */
9001   enum rtx_code code = GET_CODE (operands[0]);
9002   /* Nonzero if the opcode for the comparison needs a `z' indicating
9003      that it is a comparison against zero.  */
9004   int need_z_p;
9005   /* A string to use in the assembly output to represent the first
9006      operand.  */
9007   const char *op1 = "%z2";
9008   /* A string to use in the assembly output to represent the second
9009      operand.  Use the hard-wired zero register if there's no second
9010      operand.  */
9011   const char *op2 = (two_operands_p ? ",%z3" : ",%.");
9012   /* The operand-printing string for the comparison.  */
9013   const char *const comp = (float_p ? "%F0" : "%C0");
9014   /* The operand-printing string for the inverted comparison.  */
9015   const char *const inverted_comp = (float_p ? "%W0" : "%N0");
9016
9017   /* The MIPS processors (for levels of the ISA at least two), have
9018      "likely" variants of each branch instruction.  These instructions
9019      annul the instruction in the delay slot if the branch is not
9020      taken.  */
9021   mips_branch_likely = (final_sequence && INSN_ANNULLED_BRANCH_P (insn));
9022
9023   if (!two_operands_p)
9024     {
9025       /* To compute whether than A > B, for example, we normally
9026          subtract B from A and then look at the sign bit.  But, if we
9027          are doing an unsigned comparison, and B is zero, we don't
9028          have to do the subtraction.  Instead, we can just check to
9029          see if A is nonzero.  Thus, we change the CODE here to
9030          reflect the simpler comparison operation.  */
9031       switch (code)
9032         {
9033         case GTU:
9034           code = NE;
9035           break;
9036
9037         case LEU:
9038           code = EQ;
9039           break;
9040
9041         case GEU:
9042           /* A condition which will always be true.  */
9043           code = EQ;
9044           op1 = "%.";
9045           break;
9046
9047         case LTU:
9048           /* A condition which will always be false.  */
9049           code = NE;
9050           op1 = "%.";
9051           break;
9052
9053         default:
9054           /* Not a special case.  */
9055           break;
9056         }
9057     }
9058
9059   /* Relative comparisons are always done against zero.  But
9060      equality comparisons are done between two operands, and therefore
9061      do not require a `z' in the assembly language output.  */
9062   need_z_p = (!float_p && code != EQ && code != NE);
9063   /* For comparisons against zero, the zero is not provided
9064      explicitly.  */
9065   if (need_z_p)
9066     op2 = "";
9067
9068   /* Begin by terminating the buffer.  That way we can always use
9069      strcat to add to it.  */
9070   buffer[0] = '\0';
9071
9072   switch (length)
9073     {
9074     case 4:
9075     case 8:
9076       /* Just a simple conditional branch.  */
9077       if (float_p)
9078         sprintf (buffer, "%%*b%s%%?\t%%Z2%%1%%/",
9079                  inverted_p ? inverted_comp : comp);
9080       else
9081         sprintf (buffer, "%%*b%s%s%%?\t%s%s,%%1%%/",
9082                  inverted_p ? inverted_comp : comp,
9083                  need_z_p ? "z" : "",
9084                  op1,
9085                  op2);
9086       return buffer;
9087
9088     case 12:
9089     case 16:
9090     case 24:
9091     case 28:
9092       {
9093         /* Generate a reversed conditional branch around ` j'
9094            instruction:
9095
9096                 .set noreorder
9097                 .set nomacro
9098                 bc    l
9099                 delay_slot or #nop
9100                 j     target
9101                 #nop
9102              l:
9103                 .set macro
9104                 .set reorder
9105
9106            If the original branch was a likely branch, the delay slot
9107            must be executed only if the branch is taken, so generate:
9108
9109                 .set noreorder
9110                 .set nomacro
9111                 bc    l
9112                 #nop
9113                 j     target
9114                 delay slot or #nop
9115              l:
9116                 .set macro
9117                 .set reorder
9118
9119            When generating non-embedded PIC, instead of:
9120
9121                 j     target
9122
9123            we emit:
9124
9125                 .set noat
9126                 la    $at, target
9127                 jr    $at
9128                 .set at
9129         */
9130
9131         rtx orig_target;
9132         rtx target = gen_label_rtx ();
9133
9134         orig_target = operands[1];
9135         operands[1] = target;
9136         /* Generate the reversed comparison.  This takes four
9137            bytes.  */
9138         if (float_p)
9139           sprintf (buffer, "%%*b%s\t%%Z2%%1",
9140                    inverted_p ? comp : inverted_comp);
9141         else
9142           sprintf (buffer, "%%*b%s%s\t%s%s,%%1",
9143                    inverted_p ? comp : inverted_comp,
9144                    need_z_p ? "z" : "",
9145                    op1,
9146                    op2);
9147         output_asm_insn (buffer, operands);
9148
9149         if (length != 16 && length != 28 && ! mips_branch_likely)
9150           {
9151             /* Output delay slot instruction.  */
9152             rtx insn = final_sequence;
9153             final_scan_insn (XVECEXP (insn, 0, 1), asm_out_file,
9154                              optimize, 0, 1, NULL);
9155             INSN_DELETED_P (XVECEXP (insn, 0, 1)) = 1;
9156           }
9157         else
9158           output_asm_insn ("%#", 0);
9159
9160         if (length <= 16)
9161           output_asm_insn ("j\t%0", &orig_target);
9162         else
9163           {
9164             output_asm_insn (mips_output_load_label (), &orig_target);
9165             output_asm_insn ("jr\t%@%]", 0);
9166           }
9167
9168         if (length != 16 && length != 28 && mips_branch_likely)
9169           {
9170             /* Output delay slot instruction.  */
9171             rtx insn = final_sequence;
9172             final_scan_insn (XVECEXP (insn, 0, 1), asm_out_file,
9173                              optimize, 0, 1, NULL);
9174             INSN_DELETED_P (XVECEXP (insn, 0, 1)) = 1;
9175           }
9176         else
9177           output_asm_insn ("%#", 0);
9178
9179         (*targetm.asm_out.internal_label) (asm_out_file, "L",
9180                                    CODE_LABEL_NUMBER (target));
9181
9182         return "";
9183       }
9184
9185     default:
9186       abort ();
9187     }
9188
9189   /* NOTREACHED */
9190   return 0;
9191 }
9192 \f
9193 /* Used to output div or ddiv instruction DIVISION, which has the
9194    operands given by OPERANDS.  If we need a divide-by-zero check,
9195    output the instruction and return an asm string that traps if
9196    operand 2 is zero.  Otherwise just return DIVISION itself.  */
9197
9198 const char *
9199 mips_output_division (const char *division, rtx *operands)
9200 {
9201   if (TARGET_CHECK_ZERO_DIV)
9202     {
9203       output_asm_insn (division, operands);
9204
9205       if (TARGET_MIPS16)
9206         return "bnez\t%2,1f\n\tbreak\t7\n1:";
9207       else
9208         return "bne\t%2,%.,1f%#\n\tbreak\t7\n1:";
9209     }
9210   return division;
9211 }
9212 \f
9213 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
9214    with a final "000" replaced by "k".  Ignore case.
9215
9216    Note: this function is shared between GCC and GAS.  */
9217
9218 static bool
9219 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
9220 {
9221   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
9222     given++, canonical++;
9223
9224   return ((*given == 0 && *canonical == 0)
9225           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
9226 }
9227
9228
9229 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
9230    CPU name.  We've traditionally allowed a lot of variation here.
9231
9232    Note: this function is shared between GCC and GAS.  */
9233
9234 static bool
9235 mips_matching_cpu_name_p (const char *canonical, const char *given)
9236 {
9237   /* First see if the name matches exactly, or with a final "000"
9238      turned into "k".  */
9239   if (mips_strict_matching_cpu_name_p (canonical, given))
9240     return true;
9241
9242   /* If not, try comparing based on numerical designation alone.
9243      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
9244   if (TOLOWER (*given) == 'r')
9245     given++;
9246   if (!ISDIGIT (*given))
9247     return false;
9248
9249   /* Skip over some well-known prefixes in the canonical name,
9250      hoping to find a number there too.  */
9251   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
9252     canonical += 2;
9253   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
9254     canonical += 2;
9255   else if (TOLOWER (canonical[0]) == 'r')
9256     canonical += 1;
9257
9258   return mips_strict_matching_cpu_name_p (canonical, given);
9259 }
9260
9261
9262 /* Parse an option that takes the name of a processor as its argument.
9263    OPTION is the name of the option and CPU_STRING is the argument.
9264    Return the corresponding processor enumeration if the CPU_STRING is
9265    recognized, otherwise report an error and return null.
9266
9267    A similar function exists in GAS.  */
9268
9269 static const struct mips_cpu_info *
9270 mips_parse_cpu (const char *option, const char *cpu_string)
9271 {
9272   const struct mips_cpu_info *p;
9273   const char *s;
9274
9275   /* In the past, we allowed upper-case CPU names, but it doesn't
9276      work well with the multilib machinery.  */
9277   for (s = cpu_string; *s != 0; s++)
9278     if (ISUPPER (*s))
9279       {
9280         warning ("the cpu name must be lower case");
9281         break;
9282       }
9283
9284   /* 'from-abi' selects the most compatible architecture for the given
9285      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
9286      EABIs, we have to decide whether we're using the 32-bit or 64-bit
9287      version.  Look first at the -mgp options, if given, otherwise base
9288      the choice on MASK_64BIT in TARGET_DEFAULT.  */
9289   if (strcasecmp (cpu_string, "from-abi") == 0)
9290     return mips_cpu_info_from_isa (ABI_NEEDS_32BIT_REGS ? 1
9291                                    : ABI_NEEDS_64BIT_REGS ? 3
9292                                    : (TARGET_64BIT ? 3 : 1));
9293
9294   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
9295   if (strcasecmp (cpu_string, "default") == 0)
9296     return 0;
9297
9298   for (p = mips_cpu_info_table; p->name != 0; p++)
9299     if (mips_matching_cpu_name_p (p->name, cpu_string))
9300       return p;
9301
9302   error ("bad value (%s) for %s", cpu_string, option);
9303   return 0;
9304 }
9305
9306
9307 /* Return the processor associated with the given ISA level, or null
9308    if the ISA isn't valid.  */
9309
9310 static const struct mips_cpu_info *
9311 mips_cpu_info_from_isa (int isa)
9312 {
9313   const struct mips_cpu_info *p;
9314
9315   for (p = mips_cpu_info_table; p->name != 0; p++)
9316     if (p->isa == isa)
9317       return p;
9318
9319   return 0;
9320 }
9321 \f
9322 /* Adjust the cost of INSN based on the relationship between INSN that
9323    is dependent on DEP_INSN through the dependence LINK.  The default
9324    is to make no adjustment to COST.
9325
9326    On the MIPS, ignore the cost of anti- and output-dependencies.  */
9327 static int
9328 mips_adjust_cost (rtx insn ATTRIBUTE_UNUSED, rtx link,
9329                   rtx dep ATTRIBUTE_UNUSED, int cost)
9330 {
9331   if (REG_NOTE_KIND (link) != 0)
9332     return 0;   /* Anti or output dependence.  */
9333   return cost;
9334 }
9335
9336 /* Implement HARD_REGNO_NREGS.  The size of FP registers are controlled
9337    by UNITS_PER_FPREG.  All other registers are word sized.  */
9338
9339 unsigned int
9340 mips_hard_regno_nregs (int regno, enum machine_mode mode)
9341 {
9342   if (! FP_REG_P (regno))
9343     return ((GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD);
9344   else
9345     return ((GET_MODE_SIZE (mode) + UNITS_PER_FPREG - 1) / UNITS_PER_FPREG);
9346 }
9347
9348 /* Implement TARGET_RETURN_IN_MEMORY.  Under the old (i.e., 32 and O64 ABIs)
9349    all BLKmode objects are returned in memory.  Under the new (N32 and
9350    64-bit MIPS ABIs) small structures are returned in a register.
9351    Objects with varying size must still be returned in memory, of
9352    course.  */
9353
9354 static bool
9355 mips_return_in_memory (tree type, tree fndecl ATTRIBUTE_UNUSED)
9356 {
9357   if (mips_abi == ABI_32 || mips_abi == ABI_O64)
9358     return (TYPE_MODE (type) == BLKmode);
9359   else
9360     return ((int_size_in_bytes (type) > (2 * UNITS_PER_WORD))
9361             || (int_size_in_bytes (type) == -1));
9362 }
9363
9364 static bool
9365 mips_strict_argument_naming (CUMULATIVE_ARGS *ca ATTRIBUTE_UNUSED)
9366 {
9367   return (mips_abi != ABI_32 && mips_abi != ABI_O64);
9368 }
9369
9370 static int
9371 mips_issue_rate (void)
9372 {
9373   switch (mips_tune)
9374     {
9375     case PROCESSOR_R5400:
9376     case PROCESSOR_R5500:
9377     case PROCESSOR_R7000:
9378     case PROCESSOR_R9000:
9379       return 2;
9380
9381     default:
9382       return 1;
9383     }
9384
9385   abort ();
9386
9387 }
9388
9389 /* Implements TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE.  Return true for
9390    processors that have a DFA pipeline description.  */
9391
9392 static int
9393 mips_use_dfa_pipeline_interface (void)
9394 {
9395   switch (mips_tune)
9396     {
9397     case PROCESSOR_R5400:
9398     case PROCESSOR_R5500:
9399     case PROCESSOR_R7000:
9400     case PROCESSOR_R9000:
9401     case PROCESSOR_SR71000:
9402       return true;
9403
9404     default:
9405       return false;
9406     }
9407 }
9408
9409
9410 const char *
9411 mips_emit_prefetch (rtx *operands)
9412 {
9413   int write = INTVAL (operands[1]);
9414   int locality = INTVAL (operands[2]);
9415   int indexed = GET_CODE (operands[3]) == REG;
9416   int code;
9417   char buffer[30];
9418   
9419   if (locality <= 0)
9420     code = (write ? 5 : 4);     /* store_streamed / load_streamed.  */
9421   else if (locality <= 2)
9422     code = (write ? 1 : 0);     /* store / load.  */
9423   else
9424     code = (write ? 7 : 6);     /* store_retained / load_retained.  */
9425
9426   sprintf (buffer, "%s\t%d,%%3(%%0)", indexed ? "prefx" : "pref", code);
9427   output_asm_insn (buffer, operands);
9428   return "";
9429 }
9430
9431
9432 \f
9433 #if TARGET_IRIX
9434 /* Output assembly to switch to section NAME with attribute FLAGS.  */
9435
9436 static void
9437 irix_asm_named_section_1 (const char *name, unsigned int flags,
9438                            unsigned int align)
9439 {
9440   unsigned int sh_type, sh_flags, sh_entsize;
9441
9442   sh_flags = 0;
9443   if (!(flags & SECTION_DEBUG))
9444     sh_flags |= 2; /* SHF_ALLOC */
9445   if (flags & SECTION_WRITE)
9446     sh_flags |= 1; /* SHF_WRITE */
9447   if (flags & SECTION_CODE)
9448     sh_flags |= 4; /* SHF_EXECINSTR */
9449   if (flags & SECTION_SMALL)
9450     sh_flags |= 0x10000000; /* SHF_MIPS_GPREL */
9451   if (strcmp (name, ".debug_frame") == 0)
9452     sh_flags |= 0x08000000; /* SHF_MIPS_NOSTRIP */
9453   if (flags & SECTION_DEBUG)
9454     sh_type = 0x7000001e; /* SHT_MIPS_DWARF */
9455   else if (flags & SECTION_BSS)
9456     sh_type = 8; /* SHT_NOBITS */
9457   else
9458     sh_type = 1; /* SHT_PROGBITS */
9459
9460   if (flags & SECTION_CODE)
9461     sh_entsize = 4;
9462   else
9463     sh_entsize = 0;
9464
9465   fprintf (asm_out_file, "\t.section %s,%#x,%#x,%u,%u\n",
9466            name, sh_type, sh_flags, sh_entsize, align);
9467 }
9468
9469 static void
9470 irix_asm_named_section (const char *name, unsigned int flags)
9471 {
9472   if (TARGET_SGI_O32_AS)
9473     default_no_named_section (name, flags);
9474   else if (mips_abi == ABI_32 && TARGET_GAS)
9475     default_elf_asm_named_section (name, flags);
9476   else
9477     irix_asm_named_section_1 (name, flags, 0);
9478 }
9479
9480 /* In addition to emitting a .align directive, record the maximum
9481    alignment requested for the current section.  */
9482
9483 struct GTY (()) irix_section_align_entry
9484 {
9485   const char *name;
9486   unsigned int log;
9487   unsigned int flags;
9488 };
9489
9490 static htab_t irix_section_align_htab;
9491 static FILE *irix_orig_asm_out_file;
9492
9493 static int
9494 irix_section_align_entry_eq (const void *p1, const void *p2)
9495 {
9496   const struct irix_section_align_entry *old = p1;
9497   const char *new = p2;
9498
9499   return strcmp (old->name, new) == 0;
9500 }
9501
9502 static hashval_t
9503 irix_section_align_entry_hash (const void *p)
9504 {
9505   const struct irix_section_align_entry *old = p;
9506   return htab_hash_string (old->name);
9507 }
9508
9509 void
9510 irix_asm_output_align (FILE *file, unsigned int log)
9511 {
9512   const char *section = current_section_name ();
9513   struct irix_section_align_entry **slot, *entry;
9514
9515   if (mips_abi != ABI_32)
9516     {
9517       if (! section)
9518         abort ();
9519
9520       slot = (struct irix_section_align_entry **)
9521         htab_find_slot_with_hash (irix_section_align_htab, section,
9522                                   htab_hash_string (section), INSERT);
9523       entry = *slot;
9524       if (! entry)
9525         {
9526           entry = (struct irix_section_align_entry *)
9527             xmalloc (sizeof (struct irix_section_align_entry));
9528           *slot = entry;
9529           entry->name = section;
9530           entry->log = log;
9531           entry->flags = current_section_flags ();
9532         }
9533       else if (entry->log < log)
9534         entry->log = log;
9535     }
9536
9537   fprintf (file, "\t.align\t%u\n", log);
9538 }
9539
9540 /* The IRIX assembler does not record alignment from .align directives,
9541    but takes it from the first .section directive seen.  Play file
9542    switching games so that we can emit a .section directive at the
9543    beginning of the file with the proper alignment attached.  */
9544
9545 static void
9546 irix_file_start (void)
9547 {
9548   mips_file_start ();
9549
9550   if (mips_abi == ABI_32)
9551     return;
9552
9553   irix_orig_asm_out_file = asm_out_file;
9554   asm_out_file = tmpfile ();
9555
9556   irix_section_align_htab = htab_create (31, irix_section_align_entry_hash,
9557                                          irix_section_align_entry_eq, NULL);
9558 }
9559
9560 static int
9561 irix_section_align_1 (void **slot, void *data ATTRIBUTE_UNUSED)
9562 {
9563   const struct irix_section_align_entry *entry
9564     = *(const struct irix_section_align_entry **) slot;
9565
9566   irix_asm_named_section_1 (entry->name, entry->flags, 1 << entry->log);
9567   return 1;
9568 }
9569
9570 static void
9571 copy_file_data (FILE *to, FILE *from)
9572 {
9573   char buffer[8192];
9574   size_t len;
9575   rewind (from);
9576   if (ferror (from))
9577     fatal_error ("can't rewind temp file: %m");
9578
9579   while ((len = fread (buffer, 1, sizeof (buffer), from)) > 0)
9580     if (fwrite (buffer, 1, len, to) != len)
9581       fatal_error ("can't write to output file: %m");
9582
9583   if (ferror (from))
9584     fatal_error ("can't read from temp file: %m");
9585
9586   if (fclose (from))
9587     fatal_error ("can't close temp file: %m");
9588 }
9589
9590 static void
9591 irix_file_end (void)
9592 {
9593   if (mips_abi != ABI_32)
9594     {
9595       /* Emit section directives with the proper alignment at the top of the
9596          real output file.  */
9597       FILE *temp = asm_out_file;
9598       asm_out_file = irix_orig_asm_out_file;
9599       htab_traverse (irix_section_align_htab, irix_section_align_1, NULL);
9600
9601       /* Copy the data emitted to the temp file to the real output file.  */
9602       copy_file_data (asm_out_file, temp);
9603     }
9604
9605   mips_file_end ();
9606 }
9607
9608
9609 /* Implement TARGET_SECTION_TYPE_FLAGS.  Make sure that .sdata and
9610    .sbss sections get the SECTION_SMALL flag: this isn't set by the
9611    default code.  */
9612
9613 static unsigned int
9614 irix_section_type_flags (tree decl, const char *section, int relocs_p)
9615 {
9616   unsigned int flags;
9617
9618   flags = default_section_type_flags (decl, section, relocs_p);
9619
9620   if (strcmp (section, ".sdata") == 0
9621       || strcmp (section, ".sbss") == 0
9622       || strncmp (section, ".gnu.linkonce.s.", 16) == 0
9623       || strncmp (section, ".gnu.linkonce.sb.", 17) == 0)
9624     flags |= SECTION_SMALL;
9625
9626   return flags;
9627 }
9628
9629 #endif /* TARGET_IRIX */
9630
9631 #include "gt-mips.h"