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