OSDN Git Service

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