OSDN Git Service

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