OSDN Git Service

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