OSDN Git Service

* doc/tm.texi.in (US_SOFTWARE_GOFAST): Don't document.
[pf3gnuchains/gcc-fork.git] / gcc / config / mips / mips.c
1 /* Subroutines used for MIPS code generation.
2    Copyright (C) 1989, 1990, 1991, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5    Contributed by A. Lichnewsky, lich@inria.inria.fr.
6    Changes by Michael Meissner, meissner@osf.org.
7    64-bit r4000 support by Ian Lance Taylor, ian@cygnus.com, and
8    Brendan Eich, brendan@microunity.com.
9
10 This file is part of GCC.
11
12 GCC is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 3, or (at your option)
15 any later version.
16
17 GCC is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with GCC; see the file COPYING3.  If not see
24 <http://www.gnu.org/licenses/>.  */
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tm.h"
30 #include "rtl.h"
31 #include "regs.h"
32 #include "hard-reg-set.h"
33 #include "insn-config.h"
34 #include "conditions.h"
35 #include "insn-attr.h"
36 #include "recog.h"
37 #include "output.h"
38 #include "tree.h"
39 #include "function.h"
40 #include "expr.h"
41 #include "optabs.h"
42 #include "libfuncs.h"
43 #include "flags.h"
44 #include "reload.h"
45 #include "tm_p.h"
46 #include "ggc.h"
47 #include "gstab.h"
48 #include "hashtab.h"
49 #include "debug.h"
50 #include "target.h"
51 #include "target-def.h"
52 #include "integrate.h"
53 #include "langhooks.h"
54 #include "cfglayout.h"
55 #include "sched-int.h"
56 #include "gimple.h"
57 #include "bitmap.h"
58 #include "diagnostic.h"
59 #include "target-globals.h"
60
61 /* True if X is an UNSPEC wrapper around a SYMBOL_REF or LABEL_REF.  */
62 #define UNSPEC_ADDRESS_P(X)                                     \
63   (GET_CODE (X) == UNSPEC                                       \
64    && XINT (X, 1) >= UNSPEC_ADDRESS_FIRST                       \
65    && XINT (X, 1) < UNSPEC_ADDRESS_FIRST + NUM_SYMBOL_TYPES)
66
67 /* Extract the symbol or label from UNSPEC wrapper X.  */
68 #define UNSPEC_ADDRESS(X) \
69   XVECEXP (X, 0, 0)
70
71 /* Extract the symbol type from UNSPEC wrapper X.  */
72 #define UNSPEC_ADDRESS_TYPE(X) \
73   ((enum mips_symbol_type) (XINT (X, 1) - UNSPEC_ADDRESS_FIRST))
74
75 /* The maximum distance between the top of the stack frame and the
76    value $sp has when we save and restore registers.
77
78    The value for normal-mode code must be a SMALL_OPERAND and must
79    preserve the maximum stack alignment.  We therefore use a value
80    of 0x7ff0 in this case.
81
82    MIPS16e SAVE and RESTORE instructions can adjust the stack pointer by
83    up to 0x7f8 bytes and can usually save or restore all the registers
84    that we need to save or restore.  (Note that we can only use these
85    instructions for o32, for which the stack alignment is 8 bytes.)
86
87    We use a maximum gap of 0x100 or 0x400 for MIPS16 code when SAVE and
88    RESTORE are not available.  We can then use unextended instructions
89    to save and restore registers, and to allocate and deallocate the top
90    part of the frame.  */
91 #define MIPS_MAX_FIRST_STACK_STEP                                       \
92   (!TARGET_MIPS16 ? 0x7ff0                                              \
93    : GENERATE_MIPS16E_SAVE_RESTORE ? 0x7f8                              \
94    : TARGET_64BIT ? 0x100 : 0x400)
95
96 /* True if INSN is a mips.md pattern or asm statement.  */
97 #define USEFUL_INSN_P(INSN)                                             \
98   (NONDEBUG_INSN_P (INSN)                                               \
99    && GET_CODE (PATTERN (INSN)) != USE                                  \
100    && GET_CODE (PATTERN (INSN)) != CLOBBER                              \
101    && GET_CODE (PATTERN (INSN)) != ADDR_VEC                             \
102    && GET_CODE (PATTERN (INSN)) != ADDR_DIFF_VEC)
103
104 /* If INSN is a delayed branch sequence, return the first instruction
105    in the sequence, otherwise return INSN itself.  */
106 #define SEQ_BEGIN(INSN)                                                 \
107   (INSN_P (INSN) && GET_CODE (PATTERN (INSN)) == SEQUENCE               \
108    ? XVECEXP (PATTERN (INSN), 0, 0)                                     \
109    : (INSN))
110
111 /* Likewise for the last instruction in a delayed branch sequence.  */
112 #define SEQ_END(INSN)                                                   \
113   (INSN_P (INSN) && GET_CODE (PATTERN (INSN)) == SEQUENCE               \
114    ? XVECEXP (PATTERN (INSN), 0, XVECLEN (PATTERN (INSN), 0) - 1)       \
115    : (INSN))
116
117 /* Execute the following loop body with SUBINSN set to each instruction
118    between SEQ_BEGIN (INSN) and SEQ_END (INSN) inclusive.  */
119 #define FOR_EACH_SUBINSN(SUBINSN, INSN)                                 \
120   for ((SUBINSN) = SEQ_BEGIN (INSN);                                    \
121        (SUBINSN) != NEXT_INSN (SEQ_END (INSN));                         \
122        (SUBINSN) = NEXT_INSN (SUBINSN))
123
124 /* True if bit BIT is set in VALUE.  */
125 #define BITSET_P(VALUE, BIT) (((VALUE) & (1 << (BIT))) != 0)
126
127 /* Return the opcode for a ptr_mode load of the form:
128
129        l[wd]    DEST, OFFSET(BASE).  */
130 #define MIPS_LOAD_PTR(DEST, OFFSET, BASE)       \
131   (((ptr_mode == DImode ? 0x37 : 0x23) << 26)   \
132    | ((BASE) << 21)                             \
133    | ((DEST) << 16)                             \
134    | (OFFSET))
135
136 /* Return the opcode to move register SRC into register DEST.  */
137 #define MIPS_MOVE(DEST, SRC)            \
138   ((TARGET_64BIT ? 0x2d : 0x21)         \
139    | ((DEST) << 11)                     \
140    | ((SRC) << 21))
141
142 /* Return the opcode for:
143
144        lui      DEST, VALUE.  */
145 #define MIPS_LUI(DEST, VALUE) \
146   ((0xf << 26) | ((DEST) << 16) | (VALUE))
147
148 /* Return the opcode to jump to register DEST.  */
149 #define MIPS_JR(DEST) \
150   (((DEST) << 21) | 0x8)
151
152 /* Return the opcode for:
153
154        bal     . + (1 + OFFSET) * 4.  */
155 #define MIPS_BAL(OFFSET) \
156   ((0x1 << 26) | (0x11 << 16) | (OFFSET))
157
158 /* Return the usual opcode for a nop.  */
159 #define MIPS_NOP 0
160
161 /* Classifies an address.
162
163    ADDRESS_REG
164        A natural register + offset address.  The register satisfies
165        mips_valid_base_register_p and the offset is a const_arith_operand.
166
167    ADDRESS_LO_SUM
168        A LO_SUM rtx.  The first operand is a valid base register and
169        the second operand is a symbolic address.
170
171    ADDRESS_CONST_INT
172        A signed 16-bit constant address.
173
174    ADDRESS_SYMBOLIC:
175        A constant symbolic address.  */
176 enum mips_address_type {
177   ADDRESS_REG,
178   ADDRESS_LO_SUM,
179   ADDRESS_CONST_INT,
180   ADDRESS_SYMBOLIC
181 };
182
183 /* Enumerates the setting of the -mr10k-cache-barrier option.  */
184 enum mips_r10k_cache_barrier_setting {
185   R10K_CACHE_BARRIER_NONE,
186   R10K_CACHE_BARRIER_STORE,
187   R10K_CACHE_BARRIER_LOAD_STORE
188 };
189
190 /* Macros to create an enumeration identifier for a function prototype.  */
191 #define MIPS_FTYPE_NAME1(A, B) MIPS_##A##_FTYPE_##B
192 #define MIPS_FTYPE_NAME2(A, B, C) MIPS_##A##_FTYPE_##B##_##C
193 #define MIPS_FTYPE_NAME3(A, B, C, D) MIPS_##A##_FTYPE_##B##_##C##_##D
194 #define MIPS_FTYPE_NAME4(A, B, C, D, E) MIPS_##A##_FTYPE_##B##_##C##_##D##_##E
195
196 /* Classifies the prototype of a built-in function.  */
197 enum mips_function_type {
198 #define DEF_MIPS_FTYPE(NARGS, LIST) MIPS_FTYPE_NAME##NARGS LIST,
199 #include "config/mips/mips-ftypes.def"
200 #undef DEF_MIPS_FTYPE
201   MIPS_MAX_FTYPE_MAX
202 };
203
204 /* Specifies how a built-in function should be converted into rtl.  */
205 enum mips_builtin_type {
206   /* The function corresponds directly to an .md pattern.  The return
207      value is mapped to operand 0 and the arguments are mapped to
208      operands 1 and above.  */
209   MIPS_BUILTIN_DIRECT,
210
211   /* The function corresponds directly to an .md pattern.  There is no return
212      value and the arguments are mapped to operands 0 and above.  */
213   MIPS_BUILTIN_DIRECT_NO_TARGET,
214
215   /* The function corresponds to a comparison instruction followed by
216      a mips_cond_move_tf_ps pattern.  The first two arguments are the
217      values to compare and the second two arguments are the vector
218      operands for the movt.ps or movf.ps instruction (in assembly order).  */
219   MIPS_BUILTIN_MOVF,
220   MIPS_BUILTIN_MOVT,
221
222   /* The function corresponds to a V2SF comparison instruction.  Operand 0
223      of this instruction is the result of the comparison, which has mode
224      CCV2 or CCV4.  The function arguments are mapped to operands 1 and
225      above.  The function's return value is an SImode boolean that is
226      true under the following conditions:
227
228      MIPS_BUILTIN_CMP_ANY: one of the registers is true
229      MIPS_BUILTIN_CMP_ALL: all of the registers are true
230      MIPS_BUILTIN_CMP_LOWER: the first register is true
231      MIPS_BUILTIN_CMP_UPPER: the second register is true.  */
232   MIPS_BUILTIN_CMP_ANY,
233   MIPS_BUILTIN_CMP_ALL,
234   MIPS_BUILTIN_CMP_UPPER,
235   MIPS_BUILTIN_CMP_LOWER,
236
237   /* As above, but the instruction only sets a single $fcc register.  */
238   MIPS_BUILTIN_CMP_SINGLE,
239
240   /* For generating bposge32 branch instructions in MIPS32 DSP ASE.  */
241   MIPS_BUILTIN_BPOSGE32
242 };
243
244 /* Invoke MACRO (COND) for each C.cond.fmt condition.  */
245 #define MIPS_FP_CONDITIONS(MACRO) \
246   MACRO (f),    \
247   MACRO (un),   \
248   MACRO (eq),   \
249   MACRO (ueq),  \
250   MACRO (olt),  \
251   MACRO (ult),  \
252   MACRO (ole),  \
253   MACRO (ule),  \
254   MACRO (sf),   \
255   MACRO (ngle), \
256   MACRO (seq),  \
257   MACRO (ngl),  \
258   MACRO (lt),   \
259   MACRO (nge),  \
260   MACRO (le),   \
261   MACRO (ngt)
262
263 /* Enumerates the codes above as MIPS_FP_COND_<X>.  */
264 #define DECLARE_MIPS_COND(X) MIPS_FP_COND_ ## X
265 enum mips_fp_condition {
266   MIPS_FP_CONDITIONS (DECLARE_MIPS_COND)
267 };
268
269 /* Index X provides the string representation of MIPS_FP_COND_<X>.  */
270 #define STRINGIFY(X) #X
271 static const char *const mips_fp_conditions[] = {
272   MIPS_FP_CONDITIONS (STRINGIFY)
273 };
274
275 /* Information about a function's frame layout.  */
276 struct GTY(())  mips_frame_info {
277   /* The size of the frame in bytes.  */
278   HOST_WIDE_INT total_size;
279
280   /* The number of bytes allocated to variables.  */
281   HOST_WIDE_INT var_size;
282
283   /* The number of bytes allocated to outgoing function arguments.  */
284   HOST_WIDE_INT args_size;
285
286   /* The number of bytes allocated to the .cprestore slot, or 0 if there
287      is no such slot.  */
288   HOST_WIDE_INT cprestore_size;
289
290   /* Bit X is set if the function saves or restores GPR X.  */
291   unsigned int mask;
292
293   /* Likewise FPR X.  */
294   unsigned int fmask;
295
296   /* Likewise doubleword accumulator X ($acX).  */
297   unsigned int acc_mask;
298
299   /* The number of GPRs, FPRs, doubleword accumulators and COP0
300      registers saved.  */
301   unsigned int num_gp;
302   unsigned int num_fp;
303   unsigned int num_acc;
304   unsigned int num_cop0_regs;
305
306   /* The offset of the topmost GPR, FPR, accumulator and COP0-register
307      save slots from the top of the frame, or zero if no such slots are
308      needed.  */
309   HOST_WIDE_INT gp_save_offset;
310   HOST_WIDE_INT fp_save_offset;
311   HOST_WIDE_INT acc_save_offset;
312   HOST_WIDE_INT cop0_save_offset;
313
314   /* Likewise, but giving offsets from the bottom of the frame.  */
315   HOST_WIDE_INT gp_sp_offset;
316   HOST_WIDE_INT fp_sp_offset;
317   HOST_WIDE_INT acc_sp_offset;
318   HOST_WIDE_INT cop0_sp_offset;
319
320   /* Similar, but the value passed to _mcount.  */
321   HOST_WIDE_INT ra_fp_offset;
322
323   /* The offset of arg_pointer_rtx from the bottom of the frame.  */
324   HOST_WIDE_INT arg_pointer_offset;
325
326   /* The offset of hard_frame_pointer_rtx from the bottom of the frame.  */
327   HOST_WIDE_INT hard_frame_pointer_offset;
328 };
329
330 struct GTY(())  machine_function {
331   /* The register returned by mips16_gp_pseudo_reg; see there for details.  */
332   rtx mips16_gp_pseudo_rtx;
333
334   /* The number of extra stack bytes taken up by register varargs.
335      This area is allocated by the callee at the very top of the frame.  */
336   int varargs_size;
337
338   /* The current frame information, calculated by mips_compute_frame_info.  */
339   struct mips_frame_info frame;
340
341   /* The register to use as the function's global pointer, or INVALID_REGNUM
342      if the function doesn't need one.  */
343   unsigned int global_pointer;
344
345   /* How many instructions it takes to load a label into $AT, or 0 if
346      this property hasn't yet been calculated.  */
347   unsigned int load_label_num_insns;
348
349   /* True if mips_adjust_insn_length should ignore an instruction's
350      hazard attribute.  */
351   bool ignore_hazard_length_p;
352
353   /* True if the whole function is suitable for .set noreorder and
354      .set nomacro.  */
355   bool all_noreorder_p;
356
357   /* True if the function has "inflexible" and "flexible" references
358      to the global pointer.  See mips_cfun_has_inflexible_gp_ref_p
359      and mips_cfun_has_flexible_gp_ref_p for details.  */
360   bool has_inflexible_gp_insn_p;
361   bool has_flexible_gp_insn_p;
362
363   /* True if the function's prologue must load the global pointer
364      value into pic_offset_table_rtx and store the same value in
365      the function's cprestore slot (if any).  Even if this value
366      is currently false, we may decide to set it to true later;
367      see mips_must_initialize_gp_p () for details.  */
368   bool must_initialize_gp_p;
369
370   /* True if the current function must restore $gp after any potential
371      clobber.  This value is only meaningful during the first post-epilogue
372      split_insns pass; see mips_must_initialize_gp_p () for details.  */
373   bool must_restore_gp_when_clobbered_p;
374
375   /* True if this is an interrupt handler.  */
376   bool interrupt_handler_p;
377
378   /* True if this is an interrupt handler that uses shadow registers.  */
379   bool use_shadow_register_set_p;
380
381   /* True if this is an interrupt handler that should keep interrupts
382      masked.  */
383   bool keep_interrupts_masked_p;
384
385   /* True if this is an interrupt handler that should use DERET
386      instead of ERET.  */
387   bool use_debug_exception_return_p;
388 };
389
390 /* Information about a single argument.  */
391 struct mips_arg_info {
392   /* True if the argument is passed in a floating-point register, or
393      would have been if we hadn't run out of registers.  */
394   bool fpr_p;
395
396   /* The number of words passed in registers, rounded up.  */
397   unsigned int reg_words;
398
399   /* For EABI, the offset of the first register from GP_ARG_FIRST or
400      FP_ARG_FIRST.  For other ABIs, the offset of the first register from
401      the start of the ABI's argument structure (see the CUMULATIVE_ARGS
402      comment for details).
403
404      The value is MAX_ARGS_IN_REGISTERS if the argument is passed entirely
405      on the stack.  */
406   unsigned int reg_offset;
407
408   /* The number of words that must be passed on the stack, rounded up.  */
409   unsigned int stack_words;
410
411   /* The offset from the start of the stack overflow area of the argument's
412      first stack word.  Only meaningful when STACK_WORDS is nonzero.  */
413   unsigned int stack_offset;
414 };
415
416 /* Information about an address described by mips_address_type.
417
418    ADDRESS_CONST_INT
419        No fields are used.
420
421    ADDRESS_REG
422        REG is the base register and OFFSET is the constant offset.
423
424    ADDRESS_LO_SUM
425        REG and OFFSET are the operands to the LO_SUM and SYMBOL_TYPE
426        is the type of symbol it references.
427
428    ADDRESS_SYMBOLIC
429        SYMBOL_TYPE is the type of symbol that the address references.  */
430 struct mips_address_info {
431   enum mips_address_type type;
432   rtx reg;
433   rtx offset;
434   enum mips_symbol_type symbol_type;
435 };
436
437 /* One stage in a constant building sequence.  These sequences have
438    the form:
439
440         A = VALUE[0]
441         A = A CODE[1] VALUE[1]
442         A = A CODE[2] VALUE[2]
443         ...
444
445    where A is an accumulator, each CODE[i] is a binary rtl operation
446    and each VALUE[i] is a constant integer.  CODE[0] is undefined.  */
447 struct mips_integer_op {
448   enum rtx_code code;
449   unsigned HOST_WIDE_INT value;
450 };
451
452 /* The largest number of operations needed to load an integer constant.
453    The worst accepted case for 64-bit constants is LUI,ORI,SLL,ORI,SLL,ORI.
454    When the lowest bit is clear, we can try, but reject a sequence with
455    an extra SLL at the end.  */
456 #define MIPS_MAX_INTEGER_OPS 7
457
458 /* Information about a MIPS16e SAVE or RESTORE instruction.  */
459 struct mips16e_save_restore_info {
460   /* The number of argument registers saved by a SAVE instruction.
461      0 for RESTORE instructions.  */
462   unsigned int nargs;
463
464   /* Bit X is set if the instruction saves or restores GPR X.  */
465   unsigned int mask;
466
467   /* The total number of bytes to allocate.  */
468   HOST_WIDE_INT size;
469 };
470
471 /* Costs of various operations on the different architectures.  */
472
473 struct mips_rtx_cost_data
474 {
475   unsigned short fp_add;
476   unsigned short fp_mult_sf;
477   unsigned short fp_mult_df;
478   unsigned short fp_div_sf;
479   unsigned short fp_div_df;
480   unsigned short int_mult_si;
481   unsigned short int_mult_di;
482   unsigned short int_div_si;
483   unsigned short int_div_di;
484   unsigned short branch_cost;
485   unsigned short memory_latency;
486 };
487
488 /* Global variables for machine-dependent things.  */
489
490 /* The -G setting, or the configuration's default small-data limit if
491    no -G option is given.  */
492 static unsigned int mips_small_data_threshold;
493
494 /* The number of file directives written by mips_output_filename.  */
495 int num_source_filenames;
496
497 /* The name that appeared in the last .file directive written by
498    mips_output_filename, or "" if mips_output_filename hasn't
499    written anything yet.  */
500 const char *current_function_file = "";
501
502 /* A label counter used by PUT_SDB_BLOCK_START and PUT_SDB_BLOCK_END.  */
503 int sdb_label_count;
504
505 /* Arrays that map GCC register numbers to debugger register numbers.  */
506 int mips_dbx_regno[FIRST_PSEUDO_REGISTER];
507 int mips_dwarf_regno[FIRST_PSEUDO_REGISTER];
508
509 /* The nesting depth of the PRINT_OPERAND '%(', '%<' and '%[' constructs.  */
510 struct mips_asm_switch mips_noreorder = { "reorder", 0 };
511 struct mips_asm_switch mips_nomacro = { "macro", 0 };
512 struct mips_asm_switch mips_noat = { "at", 0 };
513
514 /* True if we're writing out a branch-likely instruction rather than a
515    normal branch.  */
516 static bool mips_branch_likely;
517
518 /* The current instruction-set architecture.  */
519 enum processor mips_arch;
520 const struct mips_cpu_info *mips_arch_info;
521
522 /* The processor that we should tune the code for.  */
523 enum processor mips_tune;
524 const struct mips_cpu_info *mips_tune_info;
525
526 /* The ISA level associated with mips_arch.  */
527 int mips_isa;
528
529 /* The architecture selected by -mipsN, or null if -mipsN wasn't used.  */
530 static const struct mips_cpu_info *mips_isa_option_info;
531
532 /* Which ABI to use.  */
533 int mips_abi = MIPS_ABI_DEFAULT;
534
535 /* Which cost information to use.  */
536 static const struct mips_rtx_cost_data *mips_cost;
537
538 /* The ambient target flags, excluding MASK_MIPS16.  */
539 static int mips_base_target_flags;
540
541 /* True if MIPS16 is the default mode.  */
542 bool mips_base_mips16;
543
544 /* The ambient values of other global variables.  */
545 static int mips_base_schedule_insns; /* flag_schedule_insns */
546 static int mips_base_reorder_blocks_and_partition; /* flag_reorder... */
547 static int mips_base_move_loop_invariants; /* flag_move_loop_invariants */
548 static int mips_base_align_loops; /* align_loops */
549 static int mips_base_align_jumps; /* align_jumps */
550 static int mips_base_align_functions; /* align_functions */
551
552 /* The -mcode-readable setting.  */
553 enum mips_code_readable_setting mips_code_readable = CODE_READABLE_YES;
554
555 /* The -mr10k-cache-barrier setting.  */
556 static enum mips_r10k_cache_barrier_setting mips_r10k_cache_barrier;
557
558 /* Index [M][R] is true if register R is allowed to hold a value of mode M.  */
559 bool mips_hard_regno_mode_ok[(int) MAX_MACHINE_MODE][FIRST_PSEUDO_REGISTER];
560
561 /* Index C is true if character C is a valid PRINT_OPERAND punctation
562    character.  */
563 static bool mips_print_operand_punct[256];
564
565 static GTY (()) int mips_output_filename_first_time = 1;
566
567 /* mips_split_p[X] is true if symbols of type X can be split by
568    mips_split_symbol.  */
569 bool mips_split_p[NUM_SYMBOL_TYPES];
570
571 /* mips_split_hi_p[X] is true if the high parts of symbols of type X
572    can be split by mips_split_symbol.  */
573 bool mips_split_hi_p[NUM_SYMBOL_TYPES];
574
575 /* mips_lo_relocs[X] is the relocation to use when a symbol of type X
576    appears in a LO_SUM.  It can be null if such LO_SUMs aren't valid or
577    if they are matched by a special .md file pattern.  */
578 static const char *mips_lo_relocs[NUM_SYMBOL_TYPES];
579
580 /* Likewise for HIGHs.  */
581 static const char *mips_hi_relocs[NUM_SYMBOL_TYPES];
582
583 /* Target state for MIPS16.  */
584 struct target_globals *mips16_globals;
585
586 /* Cached value of can_issue_more. This is cached in mips_variable_issue hook
587    and returned from mips_sched_reorder2.  */
588 static int cached_can_issue_more;
589
590 /* Index R is the smallest register class that contains register R.  */
591 const enum reg_class mips_regno_to_class[FIRST_PSEUDO_REGISTER] = {
592   LEA_REGS,     LEA_REGS,       M16_REGS,       V1_REG,
593   M16_REGS,     M16_REGS,       M16_REGS,       M16_REGS,
594   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
595   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
596   M16_REGS,     M16_REGS,       LEA_REGS,       LEA_REGS,
597   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
598   T_REG,        PIC_FN_ADDR_REG, LEA_REGS,      LEA_REGS,
599   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
600   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
601   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
602   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
603   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
604   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
605   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
606   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
607   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
608   MD0_REG,      MD1_REG,        NO_REGS,        ST_REGS,
609   ST_REGS,      ST_REGS,        ST_REGS,        ST_REGS,
610   ST_REGS,      ST_REGS,        ST_REGS,        NO_REGS,
611   NO_REGS,      FRAME_REGS,     FRAME_REGS,     NO_REGS,
612   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
613   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
614   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
615   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
616   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
617   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
618   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
619   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
620   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
621   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
622   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
623   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
624   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
625   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
626   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
627   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
628   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
629   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
630   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
631   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
632   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
633   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
634   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
635   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
636   DSP_ACC_REGS, DSP_ACC_REGS,   DSP_ACC_REGS,   DSP_ACC_REGS,
637   DSP_ACC_REGS, DSP_ACC_REGS,   ALL_REGS,       ALL_REGS,
638   ALL_REGS,     ALL_REGS,       ALL_REGS,       ALL_REGS
639 };
640
641 /* The value of TARGET_ATTRIBUTE_TABLE.  */
642 static const struct attribute_spec mips_attribute_table[] = {
643   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
644   { "long_call",   0, 0, false, true,  true,  NULL },
645   { "far",         0, 0, false, true,  true,  NULL },
646   { "near",        0, 0, false, true,  true,  NULL },
647   /* We would really like to treat "mips16" and "nomips16" as type
648      attributes, but GCC doesn't provide the hooks we need to support
649      the right conversion rules.  As declaration attributes, they affect
650      code generation but don't carry other semantics.  */
651   { "mips16",      0, 0, true,  false, false, NULL },
652   { "nomips16",    0, 0, true,  false, false, NULL },
653   /* Allow functions to be specified as interrupt handlers */
654   { "interrupt",   0, 0, false, true,  true, NULL },
655   { "use_shadow_register_set",  0, 0, false, true,  true, NULL },
656   { "keep_interrupts_masked",   0, 0, false, true,  true, NULL },
657   { "use_debug_exception_return", 0, 0, false, true,  true, NULL },
658   { NULL,          0, 0, false, false, false, NULL }
659 };
660 \f
661 /* A table describing all the processors GCC knows about.  Names are
662    matched in the order listed.  The first mention of an ISA level is
663    taken as the canonical name for that ISA.
664
665    To ease comparison, please keep this table in the same order
666    as GAS's mips_cpu_info_table.  Please also make sure that
667    MIPS_ISA_LEVEL_SPEC and MIPS_ARCH_FLOAT_SPEC handle all -march
668    options correctly.  */
669 static const struct mips_cpu_info mips_cpu_info_table[] = {
670   /* Entries for generic ISAs.  */
671   { "mips1", PROCESSOR_R3000, 1, 0 },
672   { "mips2", PROCESSOR_R6000, 2, 0 },
673   { "mips3", PROCESSOR_R4000, 3, 0 },
674   { "mips4", PROCESSOR_R8000, 4, 0 },
675   /* Prefer not to use branch-likely instructions for generic MIPS32rX
676      and MIPS64rX code.  The instructions were officially deprecated
677      in revisions 2 and earlier, but revision 3 is likely to downgrade
678      that to a recommendation to avoid the instructions in code that
679      isn't tuned to a specific processor.  */
680   { "mips32", PROCESSOR_4KC, 32, PTF_AVOID_BRANCHLIKELY },
681   { "mips32r2", PROCESSOR_M4K, 33, PTF_AVOID_BRANCHLIKELY },
682   { "mips64", PROCESSOR_5KC, 64, PTF_AVOID_BRANCHLIKELY },
683   /* ??? For now just tune the generic MIPS64r2 for 5KC as well.   */
684   { "mips64r2", PROCESSOR_5KC, 65, PTF_AVOID_BRANCHLIKELY },
685
686   /* MIPS I processors.  */
687   { "r3000", PROCESSOR_R3000, 1, 0 },
688   { "r2000", PROCESSOR_R3000, 1, 0 },
689   { "r3900", PROCESSOR_R3900, 1, 0 },
690
691   /* MIPS II processors.  */
692   { "r6000", PROCESSOR_R6000, 2, 0 },
693
694   /* MIPS III processors.  */
695   { "r4000", PROCESSOR_R4000, 3, 0 },
696   { "vr4100", PROCESSOR_R4100, 3, 0 },
697   { "vr4111", PROCESSOR_R4111, 3, 0 },
698   { "vr4120", PROCESSOR_R4120, 3, 0 },
699   { "vr4130", PROCESSOR_R4130, 3, 0 },
700   { "vr4300", PROCESSOR_R4300, 3, 0 },
701   { "r4400", PROCESSOR_R4000, 3, 0 },
702   { "r4600", PROCESSOR_R4600, 3, 0 },
703   { "orion", PROCESSOR_R4600, 3, 0 },
704   { "r4650", PROCESSOR_R4650, 3, 0 },
705   /* ST Loongson 2E/2F processors.  */
706   { "loongson2e", PROCESSOR_LOONGSON_2E, 3, PTF_AVOID_BRANCHLIKELY },
707   { "loongson2f", PROCESSOR_LOONGSON_2F, 3, PTF_AVOID_BRANCHLIKELY },
708
709   /* MIPS IV processors. */
710   { "r8000", PROCESSOR_R8000, 4, 0 },
711   { "r10000", PROCESSOR_R10000, 4, 0 },
712   { "r12000", PROCESSOR_R10000, 4, 0 },
713   { "r14000", PROCESSOR_R10000, 4, 0 },
714   { "r16000", PROCESSOR_R10000, 4, 0 },
715   { "vr5000", PROCESSOR_R5000, 4, 0 },
716   { "vr5400", PROCESSOR_R5400, 4, 0 },
717   { "vr5500", PROCESSOR_R5500, 4, PTF_AVOID_BRANCHLIKELY },
718   { "rm7000", PROCESSOR_R7000, 4, 0 },
719   { "rm9000", PROCESSOR_R9000, 4, 0 },
720
721   /* MIPS32 processors.  */
722   { "4kc", PROCESSOR_4KC, 32, 0 },
723   { "4km", PROCESSOR_4KC, 32, 0 },
724   { "4kp", PROCESSOR_4KP, 32, 0 },
725   { "4ksc", PROCESSOR_4KC, 32, 0 },
726
727   /* MIPS32 Release 2 processors.  */
728   { "m4k", PROCESSOR_M4K, 33, 0 },
729   { "4kec", PROCESSOR_4KC, 33, 0 },
730   { "4kem", PROCESSOR_4KC, 33, 0 },
731   { "4kep", PROCESSOR_4KP, 33, 0 },
732   { "4ksd", PROCESSOR_4KC, 33, 0 },
733
734   { "24kc", PROCESSOR_24KC, 33, 0 },
735   { "24kf2_1", PROCESSOR_24KF2_1, 33, 0 },
736   { "24kf", PROCESSOR_24KF2_1, 33, 0 },
737   { "24kf1_1", PROCESSOR_24KF1_1, 33, 0 },
738   { "24kfx", PROCESSOR_24KF1_1, 33, 0 },
739   { "24kx", PROCESSOR_24KF1_1, 33, 0 },
740
741   { "24kec", PROCESSOR_24KC, 33, 0 }, /* 24K with DSP.  */
742   { "24kef2_1", PROCESSOR_24KF2_1, 33, 0 },
743   { "24kef", PROCESSOR_24KF2_1, 33, 0 },
744   { "24kef1_1", PROCESSOR_24KF1_1, 33, 0 },
745   { "24kefx", PROCESSOR_24KF1_1, 33, 0 },
746   { "24kex", PROCESSOR_24KF1_1, 33, 0 },
747
748   { "34kc", PROCESSOR_24KC, 33, 0 }, /* 34K with MT/DSP.  */
749   { "34kf2_1", PROCESSOR_24KF2_1, 33, 0 },
750   { "34kf", PROCESSOR_24KF2_1, 33, 0 },
751   { "34kf1_1", PROCESSOR_24KF1_1, 33, 0 },
752   { "34kfx", PROCESSOR_24KF1_1, 33, 0 },
753   { "34kx", PROCESSOR_24KF1_1, 33, 0 },
754
755   { "74kc", PROCESSOR_74KC, 33, 0 }, /* 74K with DSPr2.  */
756   { "74kf2_1", PROCESSOR_74KF2_1, 33, 0 },
757   { "74kf", PROCESSOR_74KF2_1, 33, 0 },
758   { "74kf1_1", PROCESSOR_74KF1_1, 33, 0 },
759   { "74kfx", PROCESSOR_74KF1_1, 33, 0 },
760   { "74kx", PROCESSOR_74KF1_1, 33, 0 },
761   { "74kf3_2", PROCESSOR_74KF3_2, 33, 0 },
762
763   { "1004kc", PROCESSOR_24KC, 33, 0 }, /* 1004K with MT/DSP.  */
764   { "1004kf2_1", PROCESSOR_24KF2_1, 33, 0 },
765   { "1004kf", PROCESSOR_24KF2_1, 33, 0 },
766   { "1004kf1_1", PROCESSOR_24KF1_1, 33, 0 },
767
768   /* MIPS64 processors.  */
769   { "5kc", PROCESSOR_5KC, 64, 0 },
770   { "5kf", PROCESSOR_5KF, 64, 0 },
771   { "20kc", PROCESSOR_20KC, 64, PTF_AVOID_BRANCHLIKELY },
772   { "sb1", PROCESSOR_SB1, 64, PTF_AVOID_BRANCHLIKELY },
773   { "sb1a", PROCESSOR_SB1A, 64, PTF_AVOID_BRANCHLIKELY },
774   { "sr71000", PROCESSOR_SR71000, 64, PTF_AVOID_BRANCHLIKELY },
775   { "xlr", PROCESSOR_XLR, 64, 0 },
776   { "loongson3a", PROCESSOR_LOONGSON_3A, 64, PTF_AVOID_BRANCHLIKELY },
777
778   /* MIPS64 Release 2 processors.  */
779   { "octeon", PROCESSOR_OCTEON, 65, PTF_AVOID_BRANCHLIKELY }
780 };
781
782 /* Default costs.  If these are used for a processor we should look
783    up the actual costs.  */
784 #define DEFAULT_COSTS COSTS_N_INSNS (6),  /* fp_add */       \
785                       COSTS_N_INSNS (7),  /* fp_mult_sf */   \
786                       COSTS_N_INSNS (8),  /* fp_mult_df */   \
787                       COSTS_N_INSNS (23), /* fp_div_sf */    \
788                       COSTS_N_INSNS (36), /* fp_div_df */    \
789                       COSTS_N_INSNS (10), /* int_mult_si */  \
790                       COSTS_N_INSNS (10), /* int_mult_di */  \
791                       COSTS_N_INSNS (69), /* int_div_si */   \
792                       COSTS_N_INSNS (69), /* int_div_di */   \
793                                        2, /* branch_cost */  \
794                                        4  /* memory_latency */
795
796 /* Floating-point costs for processors without an FPU.  Just assume that
797    all floating-point libcalls are very expensive.  */
798 #define SOFT_FP_COSTS COSTS_N_INSNS (256), /* fp_add */       \
799                       COSTS_N_INSNS (256), /* fp_mult_sf */   \
800                       COSTS_N_INSNS (256), /* fp_mult_df */   \
801                       COSTS_N_INSNS (256), /* fp_div_sf */    \
802                       COSTS_N_INSNS (256)  /* fp_div_df */
803
804 /* Costs to use when optimizing for size.  */
805 static const struct mips_rtx_cost_data mips_rtx_cost_optimize_size = {
806   COSTS_N_INSNS (1),            /* fp_add */
807   COSTS_N_INSNS (1),            /* fp_mult_sf */
808   COSTS_N_INSNS (1),            /* fp_mult_df */
809   COSTS_N_INSNS (1),            /* fp_div_sf */
810   COSTS_N_INSNS (1),            /* fp_div_df */
811   COSTS_N_INSNS (1),            /* int_mult_si */
812   COSTS_N_INSNS (1),            /* int_mult_di */
813   COSTS_N_INSNS (1),            /* int_div_si */
814   COSTS_N_INSNS (1),            /* int_div_di */
815                    2,           /* branch_cost */
816                    4            /* memory_latency */
817 };
818
819 /* Costs to use when optimizing for speed, indexed by processor.  */
820 static const struct mips_rtx_cost_data
821   mips_rtx_cost_data[NUM_PROCESSOR_VALUES] = {
822   { /* R3000 */
823     COSTS_N_INSNS (2),            /* fp_add */
824     COSTS_N_INSNS (4),            /* fp_mult_sf */
825     COSTS_N_INSNS (5),            /* fp_mult_df */
826     COSTS_N_INSNS (12),           /* fp_div_sf */
827     COSTS_N_INSNS (19),           /* fp_div_df */
828     COSTS_N_INSNS (12),           /* int_mult_si */
829     COSTS_N_INSNS (12),           /* int_mult_di */
830     COSTS_N_INSNS (35),           /* int_div_si */
831     COSTS_N_INSNS (35),           /* int_div_di */
832                      1,           /* branch_cost */
833                      4            /* memory_latency */
834   },
835   { /* 4KC */
836     SOFT_FP_COSTS,
837     COSTS_N_INSNS (6),            /* int_mult_si */
838     COSTS_N_INSNS (6),            /* int_mult_di */
839     COSTS_N_INSNS (36),           /* int_div_si */
840     COSTS_N_INSNS (36),           /* int_div_di */
841                      1,           /* branch_cost */
842                      4            /* memory_latency */
843   },
844   { /* 4KP */
845     SOFT_FP_COSTS,
846     COSTS_N_INSNS (36),           /* int_mult_si */
847     COSTS_N_INSNS (36),           /* int_mult_di */
848     COSTS_N_INSNS (37),           /* int_div_si */
849     COSTS_N_INSNS (37),           /* int_div_di */
850                      1,           /* branch_cost */
851                      4            /* memory_latency */
852   },
853   { /* 5KC */
854     SOFT_FP_COSTS,
855     COSTS_N_INSNS (4),            /* int_mult_si */
856     COSTS_N_INSNS (11),           /* int_mult_di */
857     COSTS_N_INSNS (36),           /* int_div_si */
858     COSTS_N_INSNS (68),           /* int_div_di */
859                      1,           /* branch_cost */
860                      4            /* memory_latency */
861   },
862   { /* 5KF */
863     COSTS_N_INSNS (4),            /* fp_add */
864     COSTS_N_INSNS (4),            /* fp_mult_sf */
865     COSTS_N_INSNS (5),            /* fp_mult_df */
866     COSTS_N_INSNS (17),           /* fp_div_sf */
867     COSTS_N_INSNS (32),           /* fp_div_df */
868     COSTS_N_INSNS (4),            /* int_mult_si */
869     COSTS_N_INSNS (11),           /* int_mult_di */
870     COSTS_N_INSNS (36),           /* int_div_si */
871     COSTS_N_INSNS (68),           /* int_div_di */
872                      1,           /* branch_cost */
873                      4            /* memory_latency */
874   },
875   { /* 20KC */
876     COSTS_N_INSNS (4),            /* fp_add */
877     COSTS_N_INSNS (4),            /* fp_mult_sf */
878     COSTS_N_INSNS (5),            /* fp_mult_df */
879     COSTS_N_INSNS (17),           /* fp_div_sf */
880     COSTS_N_INSNS (32),           /* fp_div_df */
881     COSTS_N_INSNS (4),            /* int_mult_si */
882     COSTS_N_INSNS (7),            /* int_mult_di */
883     COSTS_N_INSNS (42),           /* int_div_si */
884     COSTS_N_INSNS (72),           /* int_div_di */
885                      1,           /* branch_cost */
886                      4            /* memory_latency */
887   },
888   { /* 24KC */
889     SOFT_FP_COSTS,
890     COSTS_N_INSNS (5),            /* int_mult_si */
891     COSTS_N_INSNS (5),            /* int_mult_di */
892     COSTS_N_INSNS (41),           /* int_div_si */
893     COSTS_N_INSNS (41),           /* int_div_di */
894                      1,           /* branch_cost */
895                      4            /* memory_latency */
896   },
897   { /* 24KF2_1 */
898     COSTS_N_INSNS (8),            /* fp_add */
899     COSTS_N_INSNS (8),            /* fp_mult_sf */
900     COSTS_N_INSNS (10),           /* fp_mult_df */
901     COSTS_N_INSNS (34),           /* fp_div_sf */
902     COSTS_N_INSNS (64),           /* fp_div_df */
903     COSTS_N_INSNS (5),            /* int_mult_si */
904     COSTS_N_INSNS (5),            /* int_mult_di */
905     COSTS_N_INSNS (41),           /* int_div_si */
906     COSTS_N_INSNS (41),           /* int_div_di */
907                      1,           /* branch_cost */
908                      4            /* memory_latency */
909   },
910   { /* 24KF1_1 */
911     COSTS_N_INSNS (4),            /* fp_add */
912     COSTS_N_INSNS (4),            /* fp_mult_sf */
913     COSTS_N_INSNS (5),            /* fp_mult_df */
914     COSTS_N_INSNS (17),           /* fp_div_sf */
915     COSTS_N_INSNS (32),           /* fp_div_df */
916     COSTS_N_INSNS (5),            /* int_mult_si */
917     COSTS_N_INSNS (5),            /* int_mult_di */
918     COSTS_N_INSNS (41),           /* int_div_si */
919     COSTS_N_INSNS (41),           /* int_div_di */
920                      1,           /* branch_cost */
921                      4            /* memory_latency */
922   },
923   { /* 74KC */
924     SOFT_FP_COSTS,
925     COSTS_N_INSNS (5),            /* int_mult_si */
926     COSTS_N_INSNS (5),            /* int_mult_di */
927     COSTS_N_INSNS (41),           /* int_div_si */
928     COSTS_N_INSNS (41),           /* int_div_di */
929                      1,           /* branch_cost */
930                      4            /* memory_latency */
931   },
932   { /* 74KF2_1 */
933     COSTS_N_INSNS (8),            /* fp_add */
934     COSTS_N_INSNS (8),            /* fp_mult_sf */
935     COSTS_N_INSNS (10),           /* fp_mult_df */
936     COSTS_N_INSNS (34),           /* fp_div_sf */
937     COSTS_N_INSNS (64),           /* fp_div_df */
938     COSTS_N_INSNS (5),            /* int_mult_si */
939     COSTS_N_INSNS (5),            /* int_mult_di */
940     COSTS_N_INSNS (41),           /* int_div_si */
941     COSTS_N_INSNS (41),           /* int_div_di */
942                      1,           /* branch_cost */
943                      4            /* memory_latency */
944   },
945   { /* 74KF1_1 */
946     COSTS_N_INSNS (4),            /* fp_add */
947     COSTS_N_INSNS (4),            /* fp_mult_sf */
948     COSTS_N_INSNS (5),            /* fp_mult_df */
949     COSTS_N_INSNS (17),           /* fp_div_sf */
950     COSTS_N_INSNS (32),           /* fp_div_df */
951     COSTS_N_INSNS (5),            /* int_mult_si */
952     COSTS_N_INSNS (5),            /* int_mult_di */
953     COSTS_N_INSNS (41),           /* int_div_si */
954     COSTS_N_INSNS (41),           /* int_div_di */
955                      1,           /* branch_cost */
956                      4            /* memory_latency */
957   },
958   { /* 74KF3_2 */
959     COSTS_N_INSNS (6),            /* fp_add */
960     COSTS_N_INSNS (6),            /* fp_mult_sf */
961     COSTS_N_INSNS (7),            /* fp_mult_df */
962     COSTS_N_INSNS (25),           /* fp_div_sf */
963     COSTS_N_INSNS (48),           /* fp_div_df */
964     COSTS_N_INSNS (5),            /* int_mult_si */
965     COSTS_N_INSNS (5),            /* int_mult_di */
966     COSTS_N_INSNS (41),           /* int_div_si */
967     COSTS_N_INSNS (41),           /* int_div_di */
968                      1,           /* branch_cost */
969                      4            /* memory_latency */
970   },
971   { /* Loongson-2E */
972     DEFAULT_COSTS
973   },
974   { /* Loongson-2F */
975     DEFAULT_COSTS
976   },
977   { /* Loongson-3A */
978     DEFAULT_COSTS
979   },
980   { /* M4k */
981     DEFAULT_COSTS
982   },
983     /* Octeon */
984   {
985     SOFT_FP_COSTS,
986     COSTS_N_INSNS (5),            /* int_mult_si */
987     COSTS_N_INSNS (5),            /* int_mult_di */
988     COSTS_N_INSNS (72),           /* int_div_si */
989     COSTS_N_INSNS (72),           /* int_div_di */
990                      1,           /* branch_cost */
991                      4            /* memory_latency */
992   },
993   { /* R3900 */
994     COSTS_N_INSNS (2),            /* fp_add */
995     COSTS_N_INSNS (4),            /* fp_mult_sf */
996     COSTS_N_INSNS (5),            /* fp_mult_df */
997     COSTS_N_INSNS (12),           /* fp_div_sf */
998     COSTS_N_INSNS (19),           /* fp_div_df */
999     COSTS_N_INSNS (2),            /* int_mult_si */
1000     COSTS_N_INSNS (2),            /* int_mult_di */
1001     COSTS_N_INSNS (35),           /* int_div_si */
1002     COSTS_N_INSNS (35),           /* int_div_di */
1003                      1,           /* branch_cost */
1004                      4            /* memory_latency */
1005   },
1006   { /* R6000 */
1007     COSTS_N_INSNS (3),            /* fp_add */
1008     COSTS_N_INSNS (5),            /* fp_mult_sf */
1009     COSTS_N_INSNS (6),            /* fp_mult_df */
1010     COSTS_N_INSNS (15),           /* fp_div_sf */
1011     COSTS_N_INSNS (16),           /* fp_div_df */
1012     COSTS_N_INSNS (17),           /* int_mult_si */
1013     COSTS_N_INSNS (17),           /* int_mult_di */
1014     COSTS_N_INSNS (38),           /* int_div_si */
1015     COSTS_N_INSNS (38),           /* int_div_di */
1016                      2,           /* branch_cost */
1017                      6            /* memory_latency */
1018   },
1019   { /* R4000 */
1020      COSTS_N_INSNS (6),           /* fp_add */
1021      COSTS_N_INSNS (7),           /* fp_mult_sf */
1022      COSTS_N_INSNS (8),           /* fp_mult_df */
1023      COSTS_N_INSNS (23),          /* fp_div_sf */
1024      COSTS_N_INSNS (36),          /* fp_div_df */
1025      COSTS_N_INSNS (10),          /* int_mult_si */
1026      COSTS_N_INSNS (10),          /* int_mult_di */
1027      COSTS_N_INSNS (69),          /* int_div_si */
1028      COSTS_N_INSNS (69),          /* int_div_di */
1029                       2,          /* branch_cost */
1030                       6           /* memory_latency */
1031   },
1032   { /* R4100 */
1033     DEFAULT_COSTS
1034   },
1035   { /* R4111 */
1036     DEFAULT_COSTS
1037   },
1038   { /* R4120 */
1039     DEFAULT_COSTS
1040   },
1041   { /* R4130 */
1042     /* The only costs that appear to be updated here are
1043        integer multiplication.  */
1044     SOFT_FP_COSTS,
1045     COSTS_N_INSNS (4),            /* int_mult_si */
1046     COSTS_N_INSNS (6),            /* int_mult_di */
1047     COSTS_N_INSNS (69),           /* int_div_si */
1048     COSTS_N_INSNS (69),           /* int_div_di */
1049                      1,           /* branch_cost */
1050                      4            /* memory_latency */
1051   },
1052   { /* R4300 */
1053     DEFAULT_COSTS
1054   },
1055   { /* R4600 */
1056     DEFAULT_COSTS
1057   },
1058   { /* R4650 */
1059     DEFAULT_COSTS
1060   },
1061   { /* R5000 */
1062     COSTS_N_INSNS (6),            /* fp_add */
1063     COSTS_N_INSNS (4),            /* fp_mult_sf */
1064     COSTS_N_INSNS (5),            /* fp_mult_df */
1065     COSTS_N_INSNS (23),           /* fp_div_sf */
1066     COSTS_N_INSNS (36),           /* fp_div_df */
1067     COSTS_N_INSNS (5),            /* int_mult_si */
1068     COSTS_N_INSNS (5),            /* int_mult_di */
1069     COSTS_N_INSNS (36),           /* int_div_si */
1070     COSTS_N_INSNS (36),           /* int_div_di */
1071                      1,           /* branch_cost */
1072                      4            /* memory_latency */
1073   },
1074   { /* R5400 */
1075     COSTS_N_INSNS (6),            /* fp_add */
1076     COSTS_N_INSNS (5),            /* fp_mult_sf */
1077     COSTS_N_INSNS (6),            /* fp_mult_df */
1078     COSTS_N_INSNS (30),           /* fp_div_sf */
1079     COSTS_N_INSNS (59),           /* fp_div_df */
1080     COSTS_N_INSNS (3),            /* int_mult_si */
1081     COSTS_N_INSNS (4),            /* int_mult_di */
1082     COSTS_N_INSNS (42),           /* int_div_si */
1083     COSTS_N_INSNS (74),           /* int_div_di */
1084                      1,           /* branch_cost */
1085                      4            /* memory_latency */
1086   },
1087   { /* R5500 */
1088     COSTS_N_INSNS (6),            /* fp_add */
1089     COSTS_N_INSNS (5),            /* fp_mult_sf */
1090     COSTS_N_INSNS (6),            /* fp_mult_df */
1091     COSTS_N_INSNS (30),           /* fp_div_sf */
1092     COSTS_N_INSNS (59),           /* fp_div_df */
1093     COSTS_N_INSNS (5),            /* int_mult_si */
1094     COSTS_N_INSNS (9),            /* int_mult_di */
1095     COSTS_N_INSNS (42),           /* int_div_si */
1096     COSTS_N_INSNS (74),           /* int_div_di */
1097                      1,           /* branch_cost */
1098                      4            /* memory_latency */
1099   },
1100   { /* R7000 */
1101     /* The only costs that are changed here are
1102        integer multiplication.  */
1103     COSTS_N_INSNS (6),            /* fp_add */
1104     COSTS_N_INSNS (7),            /* fp_mult_sf */
1105     COSTS_N_INSNS (8),            /* fp_mult_df */
1106     COSTS_N_INSNS (23),           /* fp_div_sf */
1107     COSTS_N_INSNS (36),           /* fp_div_df */
1108     COSTS_N_INSNS (5),            /* int_mult_si */
1109     COSTS_N_INSNS (9),            /* int_mult_di */
1110     COSTS_N_INSNS (69),           /* int_div_si */
1111     COSTS_N_INSNS (69),           /* int_div_di */
1112                      1,           /* branch_cost */
1113                      4            /* memory_latency */
1114   },
1115   { /* R8000 */
1116     DEFAULT_COSTS
1117   },
1118   { /* R9000 */
1119     /* The only costs that are changed here are
1120        integer multiplication.  */
1121     COSTS_N_INSNS (6),            /* fp_add */
1122     COSTS_N_INSNS (7),            /* fp_mult_sf */
1123     COSTS_N_INSNS (8),            /* fp_mult_df */
1124     COSTS_N_INSNS (23),           /* fp_div_sf */
1125     COSTS_N_INSNS (36),           /* fp_div_df */
1126     COSTS_N_INSNS (3),            /* int_mult_si */
1127     COSTS_N_INSNS (8),            /* int_mult_di */
1128     COSTS_N_INSNS (69),           /* int_div_si */
1129     COSTS_N_INSNS (69),           /* int_div_di */
1130                      1,           /* branch_cost */
1131                      4            /* memory_latency */
1132   },
1133   { /* R1x000 */
1134     COSTS_N_INSNS (2),            /* fp_add */
1135     COSTS_N_INSNS (2),            /* fp_mult_sf */
1136     COSTS_N_INSNS (2),            /* fp_mult_df */
1137     COSTS_N_INSNS (12),           /* fp_div_sf */
1138     COSTS_N_INSNS (19),           /* fp_div_df */
1139     COSTS_N_INSNS (5),            /* int_mult_si */
1140     COSTS_N_INSNS (9),            /* int_mult_di */
1141     COSTS_N_INSNS (34),           /* int_div_si */
1142     COSTS_N_INSNS (66),           /* int_div_di */
1143                      1,           /* branch_cost */
1144                      4            /* memory_latency */
1145   },
1146   { /* SB1 */
1147     /* These costs are the same as the SB-1A below.  */
1148     COSTS_N_INSNS (4),            /* fp_add */
1149     COSTS_N_INSNS (4),            /* fp_mult_sf */
1150     COSTS_N_INSNS (4),            /* fp_mult_df */
1151     COSTS_N_INSNS (24),           /* fp_div_sf */
1152     COSTS_N_INSNS (32),           /* fp_div_df */
1153     COSTS_N_INSNS (3),            /* int_mult_si */
1154     COSTS_N_INSNS (4),            /* int_mult_di */
1155     COSTS_N_INSNS (36),           /* int_div_si */
1156     COSTS_N_INSNS (68),           /* int_div_di */
1157                      1,           /* branch_cost */
1158                      4            /* memory_latency */
1159   },
1160   { /* SB1-A */
1161     /* These costs are the same as the SB-1 above.  */
1162     COSTS_N_INSNS (4),            /* fp_add */
1163     COSTS_N_INSNS (4),            /* fp_mult_sf */
1164     COSTS_N_INSNS (4),            /* fp_mult_df */
1165     COSTS_N_INSNS (24),           /* fp_div_sf */
1166     COSTS_N_INSNS (32),           /* fp_div_df */
1167     COSTS_N_INSNS (3),            /* int_mult_si */
1168     COSTS_N_INSNS (4),            /* int_mult_di */
1169     COSTS_N_INSNS (36),           /* int_div_si */
1170     COSTS_N_INSNS (68),           /* int_div_di */
1171                      1,           /* branch_cost */
1172                      4            /* memory_latency */
1173   },
1174   { /* SR71000 */
1175     DEFAULT_COSTS
1176   },
1177   { /* XLR */
1178     SOFT_FP_COSTS,
1179     COSTS_N_INSNS (8),            /* int_mult_si */
1180     COSTS_N_INSNS (8),            /* int_mult_di */
1181     COSTS_N_INSNS (72),           /* int_div_si */
1182     COSTS_N_INSNS (72),           /* int_div_di */
1183                      1,           /* branch_cost */
1184                      4            /* memory_latency */
1185   }
1186 };
1187 \f
1188 static rtx mips_find_pic_call_symbol (rtx, rtx);
1189 static int mips_register_move_cost (enum machine_mode, reg_class_t,
1190                                     reg_class_t);
1191 static unsigned int mips_function_arg_boundary (enum machine_mode, const_tree);
1192 \f
1193 /* This hash table keeps track of implicit "mips16" and "nomips16" attributes
1194    for -mflip_mips16.  It maps decl names onto a boolean mode setting.  */
1195 struct GTY (())  mflip_mips16_entry {
1196   const char *name;
1197   bool mips16_p;
1198 };
1199 static GTY ((param_is (struct mflip_mips16_entry))) htab_t mflip_mips16_htab;
1200
1201 /* Hash table callbacks for mflip_mips16_htab.  */
1202
1203 static hashval_t
1204 mflip_mips16_htab_hash (const void *entry)
1205 {
1206   return htab_hash_string (((const struct mflip_mips16_entry *) entry)->name);
1207 }
1208
1209 static int
1210 mflip_mips16_htab_eq (const void *entry, const void *name)
1211 {
1212   return strcmp (((const struct mflip_mips16_entry *) entry)->name,
1213                  (const char *) name) == 0;
1214 }
1215
1216 /* True if -mflip-mips16 should next add an attribute for the default MIPS16
1217    mode, false if it should next add an attribute for the opposite mode.  */
1218 static GTY(()) bool mips16_flipper;
1219
1220 /* DECL is a function that needs a default "mips16" or "nomips16" attribute
1221    for -mflip-mips16.  Return true if it should use "mips16" and false if
1222    it should use "nomips16".  */
1223
1224 static bool
1225 mflip_mips16_use_mips16_p (tree decl)
1226 {
1227   struct mflip_mips16_entry *entry;
1228   const char *name;
1229   hashval_t hash;
1230   void **slot;
1231
1232   /* Use the opposite of the command-line setting for anonymous decls.  */
1233   if (!DECL_NAME (decl))
1234     return !mips_base_mips16;
1235
1236   if (!mflip_mips16_htab)
1237     mflip_mips16_htab = htab_create_ggc (37, mflip_mips16_htab_hash,
1238                                          mflip_mips16_htab_eq, NULL);
1239
1240   name = IDENTIFIER_POINTER (DECL_NAME (decl));
1241   hash = htab_hash_string (name);
1242   slot = htab_find_slot_with_hash (mflip_mips16_htab, name, hash, INSERT);
1243   entry = (struct mflip_mips16_entry *) *slot;
1244   if (!entry)
1245     {
1246       mips16_flipper = !mips16_flipper;
1247       entry = ggc_alloc_mflip_mips16_entry ();
1248       entry->name = name;
1249       entry->mips16_p = mips16_flipper ? !mips_base_mips16 : mips_base_mips16;
1250       *slot = entry;
1251     }
1252   return entry->mips16_p;
1253 }
1254 \f
1255 /* Predicates to test for presence of "near" and "far"/"long_call"
1256    attributes on the given TYPE.  */
1257
1258 static bool
1259 mips_near_type_p (const_tree type)
1260 {
1261   return lookup_attribute ("near", TYPE_ATTRIBUTES (type)) != NULL;
1262 }
1263
1264 static bool
1265 mips_far_type_p (const_tree type)
1266 {
1267   return (lookup_attribute ("long_call", TYPE_ATTRIBUTES (type)) != NULL
1268           || lookup_attribute ("far", TYPE_ATTRIBUTES (type)) != NULL);
1269 }
1270
1271 /* Similar predicates for "mips16"/"nomips16" function attributes.  */
1272
1273 static bool
1274 mips_mips16_decl_p (const_tree decl)
1275 {
1276   return lookup_attribute ("mips16", DECL_ATTRIBUTES (decl)) != NULL;
1277 }
1278
1279 static bool
1280 mips_nomips16_decl_p (const_tree decl)
1281 {
1282   return lookup_attribute ("nomips16", DECL_ATTRIBUTES (decl)) != NULL;
1283 }
1284
1285 /* Check if the interrupt attribute is set for a function.  */
1286
1287 static bool
1288 mips_interrupt_type_p (tree type)
1289 {
1290   return lookup_attribute ("interrupt", TYPE_ATTRIBUTES (type)) != NULL;
1291 }
1292
1293 /* Check if the attribute to use shadow register set is set for a function.  */
1294
1295 static bool
1296 mips_use_shadow_register_set_p (tree type)
1297 {
1298   return lookup_attribute ("use_shadow_register_set",
1299                            TYPE_ATTRIBUTES (type)) != NULL;
1300 }
1301
1302 /* Check if the attribute to keep interrupts masked is set for a function.  */
1303
1304 static bool
1305 mips_keep_interrupts_masked_p (tree type)
1306 {
1307   return lookup_attribute ("keep_interrupts_masked",
1308                            TYPE_ATTRIBUTES (type)) != NULL;
1309 }
1310
1311 /* Check if the attribute to use debug exception return is set for
1312    a function.  */
1313
1314 static bool
1315 mips_use_debug_exception_return_p (tree type)
1316 {
1317   return lookup_attribute ("use_debug_exception_return",
1318                            TYPE_ATTRIBUTES (type)) != NULL;
1319 }
1320
1321 /* Return true if function DECL is a MIPS16 function.  Return the ambient
1322    setting if DECL is null.  */
1323
1324 static bool
1325 mips_use_mips16_mode_p (tree decl)
1326 {
1327   if (decl)
1328     {
1329       /* Nested functions must use the same frame pointer as their
1330          parent and must therefore use the same ISA mode.  */
1331       tree parent = decl_function_context (decl);
1332       if (parent)
1333         decl = parent;
1334       if (mips_mips16_decl_p (decl))
1335         return true;
1336       if (mips_nomips16_decl_p (decl))
1337         return false;
1338     }
1339   return mips_base_mips16;
1340 }
1341
1342 /* Implement TARGET_COMP_TYPE_ATTRIBUTES.  */
1343
1344 static int
1345 mips_comp_type_attributes (const_tree type1, const_tree type2)
1346 {
1347   /* Disallow mixed near/far attributes.  */
1348   if (mips_far_type_p (type1) && mips_near_type_p (type2))
1349     return 0;
1350   if (mips_near_type_p (type1) && mips_far_type_p (type2))
1351     return 0;
1352   return 1;
1353 }
1354
1355 /* Implement TARGET_INSERT_ATTRIBUTES.  */
1356
1357 static void
1358 mips_insert_attributes (tree decl, tree *attributes)
1359 {
1360   const char *name;
1361   bool mips16_p, nomips16_p;
1362
1363   /* Check for "mips16" and "nomips16" attributes.  */
1364   mips16_p = lookup_attribute ("mips16", *attributes) != NULL;
1365   nomips16_p = lookup_attribute ("nomips16", *attributes) != NULL;
1366   if (TREE_CODE (decl) != FUNCTION_DECL)
1367     {
1368       if (mips16_p)
1369         error ("%qs attribute only applies to functions", "mips16");
1370       if (nomips16_p)
1371         error ("%qs attribute only applies to functions", "nomips16");
1372     }
1373   else
1374     {
1375       mips16_p |= mips_mips16_decl_p (decl);
1376       nomips16_p |= mips_nomips16_decl_p (decl);
1377       if (mips16_p || nomips16_p)
1378         {
1379           /* DECL cannot be simultaneously "mips16" and "nomips16".  */
1380           if (mips16_p && nomips16_p)
1381             error ("%qE cannot have both %<mips16%> and "
1382                    "%<nomips16%> attributes",
1383                    DECL_NAME (decl));
1384         }
1385       else if (TARGET_FLIP_MIPS16 && !DECL_ARTIFICIAL (decl))
1386         {
1387           /* Implement -mflip-mips16.  If DECL has neither a "nomips16" nor a
1388              "mips16" attribute, arbitrarily pick one.  We must pick the same
1389              setting for duplicate declarations of a function.  */
1390           name = mflip_mips16_use_mips16_p (decl) ? "mips16" : "nomips16";
1391           *attributes = tree_cons (get_identifier (name), NULL, *attributes);
1392         }
1393     }
1394 }
1395
1396 /* Implement TARGET_MERGE_DECL_ATTRIBUTES.  */
1397
1398 static tree
1399 mips_merge_decl_attributes (tree olddecl, tree newdecl)
1400 {
1401   /* The decls' "mips16" and "nomips16" attributes must match exactly.  */
1402   if (mips_mips16_decl_p (olddecl) != mips_mips16_decl_p (newdecl))
1403     error ("%qE redeclared with conflicting %qs attributes",
1404            DECL_NAME (newdecl), "mips16");
1405   if (mips_nomips16_decl_p (olddecl) != mips_nomips16_decl_p (newdecl))
1406     error ("%qE redeclared with conflicting %qs attributes",
1407            DECL_NAME (newdecl), "nomips16");
1408
1409   return merge_attributes (DECL_ATTRIBUTES (olddecl),
1410                            DECL_ATTRIBUTES (newdecl));
1411 }
1412 \f
1413 /* If X is a PLUS of a CONST_INT, return the two terms in *BASE_PTR
1414    and *OFFSET_PTR.  Return X in *BASE_PTR and 0 in *OFFSET_PTR otherwise.  */
1415
1416 static void
1417 mips_split_plus (rtx x, rtx *base_ptr, HOST_WIDE_INT *offset_ptr)
1418 {
1419   if (GET_CODE (x) == PLUS && CONST_INT_P (XEXP (x, 1)))
1420     {
1421       *base_ptr = XEXP (x, 0);
1422       *offset_ptr = INTVAL (XEXP (x, 1));
1423     }
1424   else
1425     {
1426       *base_ptr = x;
1427       *offset_ptr = 0;
1428     }
1429 }
1430 \f
1431 static unsigned int mips_build_integer (struct mips_integer_op *,
1432                                         unsigned HOST_WIDE_INT);
1433
1434 /* A subroutine of mips_build_integer, with the same interface.
1435    Assume that the final action in the sequence should be a left shift.  */
1436
1437 static unsigned int
1438 mips_build_shift (struct mips_integer_op *codes, HOST_WIDE_INT value)
1439 {
1440   unsigned int i, shift;
1441
1442   /* Shift VALUE right until its lowest bit is set.  Shift arithmetically
1443      since signed numbers are easier to load than unsigned ones.  */
1444   shift = 0;
1445   while ((value & 1) == 0)
1446     value /= 2, shift++;
1447
1448   i = mips_build_integer (codes, value);
1449   codes[i].code = ASHIFT;
1450   codes[i].value = shift;
1451   return i + 1;
1452 }
1453
1454 /* As for mips_build_shift, but assume that the final action will be
1455    an IOR or PLUS operation.  */
1456
1457 static unsigned int
1458 mips_build_lower (struct mips_integer_op *codes, unsigned HOST_WIDE_INT value)
1459 {
1460   unsigned HOST_WIDE_INT high;
1461   unsigned int i;
1462
1463   high = value & ~(unsigned HOST_WIDE_INT) 0xffff;
1464   if (!LUI_OPERAND (high) && (value & 0x18000) == 0x18000)
1465     {
1466       /* The constant is too complex to load with a simple LUI/ORI pair,
1467          so we want to give the recursive call as many trailing zeros as
1468          possible.  In this case, we know bit 16 is set and that the
1469          low 16 bits form a negative number.  If we subtract that number
1470          from VALUE, we will clear at least the lowest 17 bits, maybe more.  */
1471       i = mips_build_integer (codes, CONST_HIGH_PART (value));
1472       codes[i].code = PLUS;
1473       codes[i].value = CONST_LOW_PART (value);
1474     }
1475   else
1476     {
1477       /* Either this is a simple LUI/ORI pair, or clearing the lowest 16
1478          bits gives a value with at least 17 trailing zeros.  */
1479       i = mips_build_integer (codes, high);
1480       codes[i].code = IOR;
1481       codes[i].value = value & 0xffff;
1482     }
1483   return i + 1;
1484 }
1485
1486 /* Fill CODES with a sequence of rtl operations to load VALUE.
1487    Return the number of operations needed.  */
1488
1489 static unsigned int
1490 mips_build_integer (struct mips_integer_op *codes,
1491                     unsigned HOST_WIDE_INT value)
1492 {
1493   if (SMALL_OPERAND (value)
1494       || SMALL_OPERAND_UNSIGNED (value)
1495       || LUI_OPERAND (value))
1496     {
1497       /* The value can be loaded with a single instruction.  */
1498       codes[0].code = UNKNOWN;
1499       codes[0].value = value;
1500       return 1;
1501     }
1502   else if ((value & 1) != 0 || LUI_OPERAND (CONST_HIGH_PART (value)))
1503     {
1504       /* Either the constant is a simple LUI/ORI combination or its
1505          lowest bit is set.  We don't want to shift in this case.  */
1506       return mips_build_lower (codes, value);
1507     }
1508   else if ((value & 0xffff) == 0)
1509     {
1510       /* The constant will need at least three actions.  The lowest
1511          16 bits are clear, so the final action will be a shift.  */
1512       return mips_build_shift (codes, value);
1513     }
1514   else
1515     {
1516       /* The final action could be a shift, add or inclusive OR.
1517          Rather than use a complex condition to select the best
1518          approach, try both mips_build_shift and mips_build_lower
1519          and pick the one that gives the shortest sequence.
1520          Note that this case is only used once per constant.  */
1521       struct mips_integer_op alt_codes[MIPS_MAX_INTEGER_OPS];
1522       unsigned int cost, alt_cost;
1523
1524       cost = mips_build_shift (codes, value);
1525       alt_cost = mips_build_lower (alt_codes, value);
1526       if (alt_cost < cost)
1527         {
1528           memcpy (codes, alt_codes, alt_cost * sizeof (codes[0]));
1529           cost = alt_cost;
1530         }
1531       return cost;
1532     }
1533 }
1534 \f
1535 /* Return true if symbols of type TYPE require a GOT access.  */
1536
1537 static bool
1538 mips_got_symbol_type_p (enum mips_symbol_type type)
1539 {
1540   switch (type)
1541     {
1542     case SYMBOL_GOT_PAGE_OFST:
1543     case SYMBOL_GOT_DISP:
1544       return true;
1545
1546     default:
1547       return false;
1548     }
1549 }
1550
1551 /* Return true if X is a thread-local symbol.  */
1552
1553 static bool
1554 mips_tls_symbol_p (rtx x)
1555 {
1556   return GET_CODE (x) == SYMBOL_REF && SYMBOL_REF_TLS_MODEL (x) != 0;
1557 }
1558
1559 /* Return true if SYMBOL_REF X is associated with a global symbol
1560    (in the STB_GLOBAL sense).  */
1561
1562 static bool
1563 mips_global_symbol_p (const_rtx x)
1564 {
1565   const_tree decl = SYMBOL_REF_DECL (x);
1566
1567   if (!decl)
1568     return !SYMBOL_REF_LOCAL_P (x) || SYMBOL_REF_EXTERNAL_P (x);
1569
1570   /* Weakref symbols are not TREE_PUBLIC, but their targets are global
1571      or weak symbols.  Relocations in the object file will be against
1572      the target symbol, so it's that symbol's binding that matters here.  */
1573   return DECL_P (decl) && (TREE_PUBLIC (decl) || DECL_WEAK (decl));
1574 }
1575
1576 /* Return true if function X is a libgcc MIPS16 stub function.  */
1577
1578 static bool
1579 mips16_stub_function_p (const_rtx x)
1580 {
1581   return (GET_CODE (x) == SYMBOL_REF
1582           && strncmp (XSTR (x, 0), "__mips16_", 9) == 0);
1583 }
1584
1585 /* Return true if function X is a locally-defined and locally-binding
1586    MIPS16 function.  */
1587
1588 static bool
1589 mips16_local_function_p (const_rtx x)
1590 {
1591   return (GET_CODE (x) == SYMBOL_REF
1592           && SYMBOL_REF_LOCAL_P (x)
1593           && !SYMBOL_REF_EXTERNAL_P (x)
1594           && mips_use_mips16_mode_p (SYMBOL_REF_DECL (x)));
1595 }
1596
1597 /* Return true if SYMBOL_REF X binds locally.  */
1598
1599 static bool
1600 mips_symbol_binds_local_p (const_rtx x)
1601 {
1602   return (SYMBOL_REF_DECL (x)
1603           ? targetm.binds_local_p (SYMBOL_REF_DECL (x))
1604           : SYMBOL_REF_LOCAL_P (x));
1605 }
1606
1607 /* Return true if rtx constants of mode MODE should be put into a small
1608    data section.  */
1609
1610 static bool
1611 mips_rtx_constant_in_small_data_p (enum machine_mode mode)
1612 {
1613   return (!TARGET_EMBEDDED_DATA
1614           && TARGET_LOCAL_SDATA
1615           && GET_MODE_SIZE (mode) <= mips_small_data_threshold);
1616 }
1617
1618 /* Return true if X should not be moved directly into register $25.
1619    We need this because many versions of GAS will treat "la $25,foo" as
1620    part of a call sequence and so allow a global "foo" to be lazily bound.  */
1621
1622 bool
1623 mips_dangerous_for_la25_p (rtx x)
1624 {
1625   return (!TARGET_EXPLICIT_RELOCS
1626           && TARGET_USE_GOT
1627           && GET_CODE (x) == SYMBOL_REF
1628           && mips_global_symbol_p (x));
1629 }
1630
1631 /* Return true if calls to X might need $25 to be valid on entry.  */
1632
1633 bool
1634 mips_use_pic_fn_addr_reg_p (const_rtx x)
1635 {
1636   if (!TARGET_USE_PIC_FN_ADDR_REG)
1637     return false;
1638
1639   /* MIPS16 stub functions are guaranteed not to use $25.  */
1640   if (mips16_stub_function_p (x))
1641     return false;
1642
1643   if (GET_CODE (x) == SYMBOL_REF)
1644     {
1645       /* If PLTs and copy relocations are available, the static linker
1646          will make sure that $25 is valid on entry to the target function.  */
1647       if (TARGET_ABICALLS_PIC0)
1648         return false;
1649
1650       /* Locally-defined functions use absolute accesses to set up
1651          the global pointer.  */
1652       if (TARGET_ABSOLUTE_ABICALLS
1653           && mips_symbol_binds_local_p (x)
1654           && !SYMBOL_REF_EXTERNAL_P (x))
1655         return false;
1656     }
1657
1658   return true;
1659 }
1660
1661 /* Return the method that should be used to access SYMBOL_REF or
1662    LABEL_REF X in context CONTEXT.  */
1663
1664 static enum mips_symbol_type
1665 mips_classify_symbol (const_rtx x, enum mips_symbol_context context)
1666 {
1667   if (TARGET_RTP_PIC)
1668     return SYMBOL_GOT_DISP;
1669
1670   if (GET_CODE (x) == LABEL_REF)
1671     {
1672       /* LABEL_REFs are used for jump tables as well as text labels.
1673          Only return SYMBOL_PC_RELATIVE if we know the label is in
1674          the text section.  */
1675       if (TARGET_MIPS16_SHORT_JUMP_TABLES)
1676         return SYMBOL_PC_RELATIVE;
1677
1678       if (TARGET_ABICALLS && !TARGET_ABSOLUTE_ABICALLS)
1679         return SYMBOL_GOT_PAGE_OFST;
1680
1681       return SYMBOL_ABSOLUTE;
1682     }
1683
1684   gcc_assert (GET_CODE (x) == SYMBOL_REF);
1685
1686   if (SYMBOL_REF_TLS_MODEL (x))
1687     return SYMBOL_TLS;
1688
1689   if (CONSTANT_POOL_ADDRESS_P (x))
1690     {
1691       if (TARGET_MIPS16_TEXT_LOADS)
1692         return SYMBOL_PC_RELATIVE;
1693
1694       if (TARGET_MIPS16_PCREL_LOADS && context == SYMBOL_CONTEXT_MEM)
1695         return SYMBOL_PC_RELATIVE;
1696
1697       if (mips_rtx_constant_in_small_data_p (get_pool_mode (x)))
1698         return SYMBOL_GP_RELATIVE;
1699     }
1700
1701   /* Do not use small-data accesses for weak symbols; they may end up
1702      being zero.  */
1703   if (TARGET_GPOPT && SYMBOL_REF_SMALL_P (x) && !SYMBOL_REF_WEAK (x))
1704     return SYMBOL_GP_RELATIVE;
1705
1706   /* Don't use GOT accesses for locally-binding symbols when -mno-shared
1707      is in effect.  */
1708   if (TARGET_ABICALLS_PIC2
1709       && !(TARGET_ABSOLUTE_ABICALLS && mips_symbol_binds_local_p (x)))
1710     {
1711       /* There are three cases to consider:
1712
1713             - o32 PIC (either with or without explicit relocs)
1714             - n32/n64 PIC without explicit relocs
1715             - n32/n64 PIC with explicit relocs
1716
1717          In the first case, both local and global accesses will use an
1718          R_MIPS_GOT16 relocation.  We must correctly predict which of
1719          the two semantics (local or global) the assembler and linker
1720          will apply.  The choice depends on the symbol's binding rather
1721          than its visibility.
1722
1723          In the second case, the assembler will not use R_MIPS_GOT16
1724          relocations, but it chooses between local and global accesses
1725          in the same way as for o32 PIC.
1726
1727          In the third case we have more freedom since both forms of
1728          access will work for any kind of symbol.  However, there seems
1729          little point in doing things differently.  */
1730       if (mips_global_symbol_p (x))
1731         return SYMBOL_GOT_DISP;
1732
1733       return SYMBOL_GOT_PAGE_OFST;
1734     }
1735
1736   if (TARGET_MIPS16_PCREL_LOADS && context != SYMBOL_CONTEXT_CALL)
1737     return SYMBOL_FORCE_TO_MEM;
1738
1739   return SYMBOL_ABSOLUTE;
1740 }
1741
1742 /* Classify the base of symbolic expression X, given that X appears in
1743    context CONTEXT.  */
1744
1745 static enum mips_symbol_type
1746 mips_classify_symbolic_expression (rtx x, enum mips_symbol_context context)
1747 {
1748   rtx offset;
1749
1750   split_const (x, &x, &offset);
1751   if (UNSPEC_ADDRESS_P (x))
1752     return UNSPEC_ADDRESS_TYPE (x);
1753
1754   return mips_classify_symbol (x, context);
1755 }
1756
1757 /* Return true if OFFSET is within the range [0, ALIGN), where ALIGN
1758    is the alignment in bytes of SYMBOL_REF X.  */
1759
1760 static bool
1761 mips_offset_within_alignment_p (rtx x, HOST_WIDE_INT offset)
1762 {
1763   HOST_WIDE_INT align;
1764
1765   align = SYMBOL_REF_DECL (x) ? DECL_ALIGN_UNIT (SYMBOL_REF_DECL (x)) : 1;
1766   return IN_RANGE (offset, 0, align - 1);
1767 }
1768
1769 /* Return true if X is a symbolic constant that can be used in context
1770    CONTEXT.  If it is, store the type of the symbol in *SYMBOL_TYPE.  */
1771
1772 bool
1773 mips_symbolic_constant_p (rtx x, enum mips_symbol_context context,
1774                           enum mips_symbol_type *symbol_type)
1775 {
1776   rtx offset;
1777
1778   split_const (x, &x, &offset);
1779   if (UNSPEC_ADDRESS_P (x))
1780     {
1781       *symbol_type = UNSPEC_ADDRESS_TYPE (x);
1782       x = UNSPEC_ADDRESS (x);
1783     }
1784   else if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF)
1785     {
1786       *symbol_type = mips_classify_symbol (x, context);
1787       if (*symbol_type == SYMBOL_TLS)
1788         return false;
1789     }
1790   else
1791     return false;
1792
1793   if (offset == const0_rtx)
1794     return true;
1795
1796   /* Check whether a nonzero offset is valid for the underlying
1797      relocations.  */
1798   switch (*symbol_type)
1799     {
1800     case SYMBOL_ABSOLUTE:
1801     case SYMBOL_FORCE_TO_MEM:
1802     case SYMBOL_32_HIGH:
1803     case SYMBOL_64_HIGH:
1804     case SYMBOL_64_MID:
1805     case SYMBOL_64_LOW:
1806       /* If the target has 64-bit pointers and the object file only
1807          supports 32-bit symbols, the values of those symbols will be
1808          sign-extended.  In this case we can't allow an arbitrary offset
1809          in case the 32-bit value X + OFFSET has a different sign from X.  */
1810       if (Pmode == DImode && !ABI_HAS_64BIT_SYMBOLS)
1811         return offset_within_block_p (x, INTVAL (offset));
1812
1813       /* In other cases the relocations can handle any offset.  */
1814       return true;
1815
1816     case SYMBOL_PC_RELATIVE:
1817       /* Allow constant pool references to be converted to LABEL+CONSTANT.
1818          In this case, we no longer have access to the underlying constant,
1819          but the original symbol-based access was known to be valid.  */
1820       if (GET_CODE (x) == LABEL_REF)
1821         return true;
1822
1823       /* Fall through.  */
1824
1825     case SYMBOL_GP_RELATIVE:
1826       /* Make sure that the offset refers to something within the
1827          same object block.  This should guarantee that the final
1828          PC- or GP-relative offset is within the 16-bit limit.  */
1829       return offset_within_block_p (x, INTVAL (offset));
1830
1831     case SYMBOL_GOT_PAGE_OFST:
1832     case SYMBOL_GOTOFF_PAGE:
1833       /* If the symbol is global, the GOT entry will contain the symbol's
1834          address, and we will apply a 16-bit offset after loading it.
1835          If the symbol is local, the linker should provide enough local
1836          GOT entries for a 16-bit offset, but larger offsets may lead
1837          to GOT overflow.  */
1838       return SMALL_INT (offset);
1839
1840     case SYMBOL_TPREL:
1841     case SYMBOL_DTPREL:
1842       /* There is no carry between the HI and LO REL relocations, so the
1843          offset is only valid if we know it won't lead to such a carry.  */
1844       return mips_offset_within_alignment_p (x, INTVAL (offset));
1845
1846     case SYMBOL_GOT_DISP:
1847     case SYMBOL_GOTOFF_DISP:
1848     case SYMBOL_GOTOFF_CALL:
1849     case SYMBOL_GOTOFF_LOADGP:
1850     case SYMBOL_TLSGD:
1851     case SYMBOL_TLSLDM:
1852     case SYMBOL_GOTTPREL:
1853     case SYMBOL_TLS:
1854     case SYMBOL_HALF:
1855       return false;
1856     }
1857   gcc_unreachable ();
1858 }
1859 \f
1860 /* Like mips_symbol_insns, but treat extended MIPS16 instructions as a
1861    single instruction.  We rely on the fact that, in the worst case,
1862    all instructions involved in a MIPS16 address calculation are usually
1863    extended ones.  */
1864
1865 static int
1866 mips_symbol_insns_1 (enum mips_symbol_type type, enum machine_mode mode)
1867 {
1868   switch (type)
1869     {
1870     case SYMBOL_ABSOLUTE:
1871       /* When using 64-bit symbols, we need 5 preparatory instructions,
1872          such as:
1873
1874              lui     $at,%highest(symbol)
1875              daddiu  $at,$at,%higher(symbol)
1876              dsll    $at,$at,16
1877              daddiu  $at,$at,%hi(symbol)
1878              dsll    $at,$at,16
1879
1880          The final address is then $at + %lo(symbol).  With 32-bit
1881          symbols we just need a preparatory LUI for normal mode and
1882          a preparatory LI and SLL for MIPS16.  */
1883       return ABI_HAS_64BIT_SYMBOLS ? 6 : TARGET_MIPS16 ? 3 : 2;
1884
1885     case SYMBOL_GP_RELATIVE:
1886       /* Treat GP-relative accesses as taking a single instruction on
1887          MIPS16 too; the copy of $gp can often be shared.  */
1888       return 1;
1889
1890     case SYMBOL_PC_RELATIVE:
1891       /* PC-relative constants can be only be used with ADDIUPC,
1892          DADDIUPC, LWPC and LDPC.  */
1893       if (mode == MAX_MACHINE_MODE
1894           || GET_MODE_SIZE (mode) == 4
1895           || GET_MODE_SIZE (mode) == 8)
1896         return 1;
1897
1898       /* The constant must be loaded using ADDIUPC or DADDIUPC first.  */
1899       return 0;
1900
1901     case SYMBOL_FORCE_TO_MEM:
1902       /* LEAs will be converted into constant-pool references by
1903          mips_reorg.  */
1904       if (mode == MAX_MACHINE_MODE)
1905         return 1;
1906
1907       /* The constant must be loaded and then dereferenced.  */
1908       return 0;
1909
1910     case SYMBOL_GOT_DISP:
1911       /* The constant will have to be loaded from the GOT before it
1912          is used in an address.  */
1913       if (mode != MAX_MACHINE_MODE)
1914         return 0;
1915
1916       /* Fall through.  */
1917
1918     case SYMBOL_GOT_PAGE_OFST:
1919       /* Unless -funit-at-a-time is in effect, we can't be sure whether the
1920          local/global classification is accurate.  The worst cases are:
1921
1922          (1) For local symbols when generating o32 or o64 code.  The assembler
1923              will use:
1924
1925                  lw           $at,%got(symbol)
1926                  nop
1927
1928              ...and the final address will be $at + %lo(symbol).
1929
1930          (2) For global symbols when -mxgot.  The assembler will use:
1931
1932                  lui     $at,%got_hi(symbol)
1933                  (d)addu $at,$at,$gp
1934
1935              ...and the final address will be $at + %got_lo(symbol).  */
1936       return 3;
1937
1938     case SYMBOL_GOTOFF_PAGE:
1939     case SYMBOL_GOTOFF_DISP:
1940     case SYMBOL_GOTOFF_CALL:
1941     case SYMBOL_GOTOFF_LOADGP:
1942     case SYMBOL_32_HIGH:
1943     case SYMBOL_64_HIGH:
1944     case SYMBOL_64_MID:
1945     case SYMBOL_64_LOW:
1946     case SYMBOL_TLSGD:
1947     case SYMBOL_TLSLDM:
1948     case SYMBOL_DTPREL:
1949     case SYMBOL_GOTTPREL:
1950     case SYMBOL_TPREL:
1951     case SYMBOL_HALF:
1952       /* A 16-bit constant formed by a single relocation, or a 32-bit
1953          constant formed from a high 16-bit relocation and a low 16-bit
1954          relocation.  Use mips_split_p to determine which.  32-bit
1955          constants need an "lui; addiu" sequence for normal mode and
1956          an "li; sll; addiu" sequence for MIPS16 mode.  */
1957       return !mips_split_p[type] ? 1 : TARGET_MIPS16 ? 3 : 2;
1958
1959     case SYMBOL_TLS:
1960       /* We don't treat a bare TLS symbol as a constant.  */
1961       return 0;
1962     }
1963   gcc_unreachable ();
1964 }
1965
1966 /* If MODE is MAX_MACHINE_MODE, return the number of instructions needed
1967    to load symbols of type TYPE into a register.  Return 0 if the given
1968    type of symbol cannot be used as an immediate operand.
1969
1970    Otherwise, return the number of instructions needed to load or store
1971    values of mode MODE to or from addresses of type TYPE.  Return 0 if
1972    the given type of symbol is not valid in addresses.
1973
1974    In both cases, treat extended MIPS16 instructions as two instructions.  */
1975
1976 static int
1977 mips_symbol_insns (enum mips_symbol_type type, enum machine_mode mode)
1978 {
1979   return mips_symbol_insns_1 (type, mode) * (TARGET_MIPS16 ? 2 : 1);
1980 }
1981 \f
1982 /* A for_each_rtx callback.  Stop the search if *X references a
1983    thread-local symbol.  */
1984
1985 static int
1986 mips_tls_symbol_ref_1 (rtx *x, void *data ATTRIBUTE_UNUSED)
1987 {
1988   return mips_tls_symbol_p (*x);
1989 }
1990
1991 /* Implement TARGET_CANNOT_FORCE_CONST_MEM.  */
1992
1993 static bool
1994 mips_cannot_force_const_mem (rtx x)
1995 {
1996   enum mips_symbol_type type;
1997   rtx base, offset;
1998
1999   /* There is no assembler syntax for expressing an address-sized
2000      high part.  */
2001   if (GET_CODE (x) == HIGH)
2002     return true;
2003
2004   /* As an optimization, reject constants that mips_legitimize_move
2005      can expand inline.
2006
2007      Suppose we have a multi-instruction sequence that loads constant C
2008      into register R.  If R does not get allocated a hard register, and
2009      R is used in an operand that allows both registers and memory
2010      references, reload will consider forcing C into memory and using
2011      one of the instruction's memory alternatives.  Returning false
2012      here will force it to use an input reload instead.  */
2013   if (CONST_INT_P (x) && LEGITIMATE_CONSTANT_P (x))
2014     return true;
2015
2016   split_const (x, &base, &offset);
2017   if (mips_symbolic_constant_p (base, SYMBOL_CONTEXT_LEA, &type)
2018       && type != SYMBOL_FORCE_TO_MEM)
2019     {
2020       /* The same optimization as for CONST_INT.  */
2021       if (SMALL_INT (offset) && mips_symbol_insns (type, MAX_MACHINE_MODE) > 0)
2022         return true;
2023
2024       /* If MIPS16 constant pools live in the text section, they should
2025          not refer to anything that might need run-time relocation.  */
2026       if (TARGET_MIPS16_PCREL_LOADS && mips_got_symbol_type_p (type))
2027         return true;
2028     }
2029
2030   /* TLS symbols must be computed by mips_legitimize_move.  */
2031   if (for_each_rtx (&x, &mips_tls_symbol_ref_1, NULL))
2032     return true;
2033
2034   return false;
2035 }
2036
2037 /* Implement TARGET_USE_BLOCKS_FOR_CONSTANT_P.  We can't use blocks for
2038    constants when we're using a per-function constant pool.  */
2039
2040 static bool
2041 mips_use_blocks_for_constant_p (enum machine_mode mode ATTRIBUTE_UNUSED,
2042                                 const_rtx x ATTRIBUTE_UNUSED)
2043 {
2044   return !TARGET_MIPS16_PCREL_LOADS;
2045 }
2046 \f
2047 /* Return true if register REGNO is a valid base register for mode MODE.
2048    STRICT_P is true if REG_OK_STRICT is in effect.  */
2049
2050 int
2051 mips_regno_mode_ok_for_base_p (int regno, enum machine_mode mode,
2052                                bool strict_p)
2053 {
2054   if (!HARD_REGISTER_NUM_P (regno))
2055     {
2056       if (!strict_p)
2057         return true;
2058       regno = reg_renumber[regno];
2059     }
2060
2061   /* These fake registers will be eliminated to either the stack or
2062      hard frame pointer, both of which are usually valid base registers.
2063      Reload deals with the cases where the eliminated form isn't valid.  */
2064   if (regno == ARG_POINTER_REGNUM || regno == FRAME_POINTER_REGNUM)
2065     return true;
2066
2067   /* In MIPS16 mode, the stack pointer can only address word and doubleword
2068      values, nothing smaller.  There are two problems here:
2069
2070        (a) Instantiating virtual registers can introduce new uses of the
2071            stack pointer.  If these virtual registers are valid addresses,
2072            the stack pointer should be too.
2073
2074        (b) Most uses of the stack pointer are not made explicit until
2075            FRAME_POINTER_REGNUM and ARG_POINTER_REGNUM have been eliminated.
2076            We don't know until that stage whether we'll be eliminating to the
2077            stack pointer (which needs the restriction) or the hard frame
2078            pointer (which doesn't).
2079
2080      All in all, it seems more consistent to only enforce this restriction
2081      during and after reload.  */
2082   if (TARGET_MIPS16 && regno == STACK_POINTER_REGNUM)
2083     return !strict_p || GET_MODE_SIZE (mode) == 4 || GET_MODE_SIZE (mode) == 8;
2084
2085   return TARGET_MIPS16 ? M16_REG_P (regno) : GP_REG_P (regno);
2086 }
2087
2088 /* Return true if X is a valid base register for mode MODE.
2089    STRICT_P is true if REG_OK_STRICT is in effect.  */
2090
2091 static bool
2092 mips_valid_base_register_p (rtx x, enum machine_mode mode, bool strict_p)
2093 {
2094   if (!strict_p && GET_CODE (x) == SUBREG)
2095     x = SUBREG_REG (x);
2096
2097   return (REG_P (x)
2098           && mips_regno_mode_ok_for_base_p (REGNO (x), mode, strict_p));
2099 }
2100
2101 /* Return true if, for every base register BASE_REG, (plus BASE_REG X)
2102    can address a value of mode MODE.  */
2103
2104 static bool
2105 mips_valid_offset_p (rtx x, enum machine_mode mode)
2106 {
2107   /* Check that X is a signed 16-bit number.  */
2108   if (!const_arith_operand (x, Pmode))
2109     return false;
2110
2111   /* We may need to split multiword moves, so make sure that every word
2112      is accessible.  */
2113   if (GET_MODE_SIZE (mode) > UNITS_PER_WORD
2114       && !SMALL_OPERAND (INTVAL (x) + GET_MODE_SIZE (mode) - UNITS_PER_WORD))
2115     return false;
2116
2117   return true;
2118 }
2119
2120 /* Return true if a LO_SUM can address a value of mode MODE when the
2121    LO_SUM symbol has type SYMBOL_TYPE.  */
2122
2123 static bool
2124 mips_valid_lo_sum_p (enum mips_symbol_type symbol_type, enum machine_mode mode)
2125 {
2126   /* Check that symbols of type SYMBOL_TYPE can be used to access values
2127      of mode MODE.  */
2128   if (mips_symbol_insns (symbol_type, mode) == 0)
2129     return false;
2130
2131   /* Check that there is a known low-part relocation.  */
2132   if (mips_lo_relocs[symbol_type] == NULL)
2133     return false;
2134
2135   /* We may need to split multiword moves, so make sure that each word
2136      can be accessed without inducing a carry.  This is mainly needed
2137      for o64, which has historically only guaranteed 64-bit alignment
2138      for 128-bit types.  */
2139   if (GET_MODE_SIZE (mode) > UNITS_PER_WORD
2140       && GET_MODE_BITSIZE (mode) > GET_MODE_ALIGNMENT (mode))
2141     return false;
2142
2143   return true;
2144 }
2145
2146 /* Return true if X is a valid address for machine mode MODE.  If it is,
2147    fill in INFO appropriately.  STRICT_P is true if REG_OK_STRICT is in
2148    effect.  */
2149
2150 static bool
2151 mips_classify_address (struct mips_address_info *info, rtx x,
2152                        enum machine_mode mode, bool strict_p)
2153 {
2154   switch (GET_CODE (x))
2155     {
2156     case REG:
2157     case SUBREG:
2158       info->type = ADDRESS_REG;
2159       info->reg = x;
2160       info->offset = const0_rtx;
2161       return mips_valid_base_register_p (info->reg, mode, strict_p);
2162
2163     case PLUS:
2164       info->type = ADDRESS_REG;
2165       info->reg = XEXP (x, 0);
2166       info->offset = XEXP (x, 1);
2167       return (mips_valid_base_register_p (info->reg, mode, strict_p)
2168               && mips_valid_offset_p (info->offset, mode));
2169
2170     case LO_SUM:
2171       info->type = ADDRESS_LO_SUM;
2172       info->reg = XEXP (x, 0);
2173       info->offset = XEXP (x, 1);
2174       /* We have to trust the creator of the LO_SUM to do something vaguely
2175          sane.  Target-independent code that creates a LO_SUM should also
2176          create and verify the matching HIGH.  Target-independent code that
2177          adds an offset to a LO_SUM must prove that the offset will not
2178          induce a carry.  Failure to do either of these things would be
2179          a bug, and we are not required to check for it here.  The MIPS
2180          backend itself should only create LO_SUMs for valid symbolic
2181          constants, with the high part being either a HIGH or a copy
2182          of _gp. */
2183       info->symbol_type
2184         = mips_classify_symbolic_expression (info->offset, SYMBOL_CONTEXT_MEM);
2185       return (mips_valid_base_register_p (info->reg, mode, strict_p)
2186               && mips_valid_lo_sum_p (info->symbol_type, mode));
2187
2188     case CONST_INT:
2189       /* Small-integer addresses don't occur very often, but they
2190          are legitimate if $0 is a valid base register.  */
2191       info->type = ADDRESS_CONST_INT;
2192       return !TARGET_MIPS16 && SMALL_INT (x);
2193
2194     case CONST:
2195     case LABEL_REF:
2196     case SYMBOL_REF:
2197       info->type = ADDRESS_SYMBOLIC;
2198       return (mips_symbolic_constant_p (x, SYMBOL_CONTEXT_MEM,
2199                                         &info->symbol_type)
2200               && mips_symbol_insns (info->symbol_type, mode) > 0
2201               && !mips_split_p[info->symbol_type]);
2202
2203     default:
2204       return false;
2205     }
2206 }
2207
2208 /* Implement TARGET_LEGITIMATE_ADDRESS_P.  */
2209
2210 static bool
2211 mips_legitimate_address_p (enum machine_mode mode, rtx x, bool strict_p)
2212 {
2213   struct mips_address_info addr;
2214
2215   return mips_classify_address (&addr, x, mode, strict_p);
2216 }
2217
2218 /* Return true if X is a legitimate $sp-based address for mode MDOE.  */
2219
2220 bool
2221 mips_stack_address_p (rtx x, enum machine_mode mode)
2222 {
2223   struct mips_address_info addr;
2224
2225   return (mips_classify_address (&addr, x, mode, false)
2226           && addr.type == ADDRESS_REG
2227           && addr.reg == stack_pointer_rtx);
2228 }
2229
2230 /* Return true if ADDR matches the pattern for the LWXS load scaled indexed
2231    address instruction.  Note that such addresses are not considered
2232    legitimate in the TARGET_LEGITIMATE_ADDRESS_P sense, because their use
2233    is so restricted.  */
2234
2235 static bool
2236 mips_lwxs_address_p (rtx addr)
2237 {
2238   if (ISA_HAS_LWXS
2239       && GET_CODE (addr) == PLUS
2240       && REG_P (XEXP (addr, 1)))
2241     {
2242       rtx offset = XEXP (addr, 0);
2243       if (GET_CODE (offset) == MULT
2244           && REG_P (XEXP (offset, 0))
2245           && CONST_INT_P (XEXP (offset, 1))
2246           && INTVAL (XEXP (offset, 1)) == 4)
2247         return true;
2248     }
2249   return false;
2250 }
2251 \f
2252 /* Return true if a value at OFFSET bytes from base register BASE can be
2253    accessed using an unextended MIPS16 instruction.  MODE is the mode of
2254    the value.
2255
2256    Usually the offset in an unextended instruction is a 5-bit field.
2257    The offset is unsigned and shifted left once for LH and SH, twice
2258    for LW and SW, and so on.  An exception is LWSP and SWSP, which have
2259    an 8-bit immediate field that's shifted left twice.  */
2260
2261 static bool
2262 mips16_unextended_reference_p (enum machine_mode mode, rtx base,
2263                                unsigned HOST_WIDE_INT offset)
2264 {
2265   if (offset % GET_MODE_SIZE (mode) == 0)
2266     {
2267       if (GET_MODE_SIZE (mode) == 4 && base == stack_pointer_rtx)
2268         return offset < 256U * GET_MODE_SIZE (mode);
2269       return offset < 32U * GET_MODE_SIZE (mode);
2270     }
2271   return false;
2272 }
2273
2274 /* Return the number of instructions needed to load or store a value
2275    of mode MODE at address X.  Return 0 if X isn't valid for MODE.
2276    Assume that multiword moves may need to be split into word moves
2277    if MIGHT_SPLIT_P, otherwise assume that a single load or store is
2278    enough.
2279
2280    For MIPS16 code, count extended instructions as two instructions.  */
2281
2282 int
2283 mips_address_insns (rtx x, enum machine_mode mode, bool might_split_p)
2284 {
2285   struct mips_address_info addr;
2286   int factor;
2287
2288   /* BLKmode is used for single unaligned loads and stores and should
2289      not count as a multiword mode.  (GET_MODE_SIZE (BLKmode) is pretty
2290      meaningless, so we have to single it out as a special case one way
2291      or the other.)  */
2292   if (mode != BLKmode && might_split_p)
2293     factor = (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
2294   else
2295     factor = 1;
2296
2297   if (mips_classify_address (&addr, x, mode, false))
2298     switch (addr.type)
2299       {
2300       case ADDRESS_REG:
2301         if (TARGET_MIPS16
2302             && !mips16_unextended_reference_p (mode, addr.reg,
2303                                                UINTVAL (addr.offset)))
2304           return factor * 2;
2305         return factor;
2306
2307       case ADDRESS_LO_SUM:
2308         return TARGET_MIPS16 ? factor * 2 : factor;
2309
2310       case ADDRESS_CONST_INT:
2311         return factor;
2312
2313       case ADDRESS_SYMBOLIC:
2314         return factor * mips_symbol_insns (addr.symbol_type, mode);
2315       }
2316   return 0;
2317 }
2318
2319 /* Return the number of instructions needed to load constant X.
2320    Return 0 if X isn't a valid constant.  */
2321
2322 int
2323 mips_const_insns (rtx x)
2324 {
2325   struct mips_integer_op codes[MIPS_MAX_INTEGER_OPS];
2326   enum mips_symbol_type symbol_type;
2327   rtx offset;
2328
2329   switch (GET_CODE (x))
2330     {
2331     case HIGH:
2332       if (!mips_symbolic_constant_p (XEXP (x, 0), SYMBOL_CONTEXT_LEA,
2333                                      &symbol_type)
2334           || !mips_split_p[symbol_type])
2335         return 0;
2336
2337       /* This is simply an LUI for normal mode.  It is an extended
2338          LI followed by an extended SLL for MIPS16.  */
2339       return TARGET_MIPS16 ? 4 : 1;
2340
2341     case CONST_INT:
2342       if (TARGET_MIPS16)
2343         /* Unsigned 8-bit constants can be loaded using an unextended
2344            LI instruction.  Unsigned 16-bit constants can be loaded
2345            using an extended LI.  Negative constants must be loaded
2346            using LI and then negated.  */
2347         return (IN_RANGE (INTVAL (x), 0, 255) ? 1
2348                 : SMALL_OPERAND_UNSIGNED (INTVAL (x)) ? 2
2349                 : IN_RANGE (-INTVAL (x), 0, 255) ? 2
2350                 : SMALL_OPERAND_UNSIGNED (-INTVAL (x)) ? 3
2351                 : 0);
2352
2353       return mips_build_integer (codes, INTVAL (x));
2354
2355     case CONST_DOUBLE:
2356     case CONST_VECTOR:
2357       /* Allow zeros for normal mode, where we can use $0.  */
2358       return !TARGET_MIPS16 && x == CONST0_RTX (GET_MODE (x)) ? 1 : 0;
2359
2360     case CONST:
2361       if (CONST_GP_P (x))
2362         return 1;
2363
2364       /* See if we can refer to X directly.  */
2365       if (mips_symbolic_constant_p (x, SYMBOL_CONTEXT_LEA, &symbol_type))
2366         return mips_symbol_insns (symbol_type, MAX_MACHINE_MODE);
2367
2368       /* Otherwise try splitting the constant into a base and offset.
2369          If the offset is a 16-bit value, we can load the base address
2370          into a register and then use (D)ADDIU to add in the offset.
2371          If the offset is larger, we can load the base and offset
2372          into separate registers and add them together with (D)ADDU.
2373          However, the latter is only possible before reload; during
2374          and after reload, we must have the option of forcing the
2375          constant into the pool instead.  */
2376       split_const (x, &x, &offset);
2377       if (offset != 0)
2378         {
2379           int n = mips_const_insns (x);
2380           if (n != 0)
2381             {
2382               if (SMALL_INT (offset))
2383                 return n + 1;
2384               else if (!targetm.cannot_force_const_mem (x))
2385                 return n + 1 + mips_build_integer (codes, INTVAL (offset));
2386             }
2387         }
2388       return 0;
2389
2390     case SYMBOL_REF:
2391     case LABEL_REF:
2392       return mips_symbol_insns (mips_classify_symbol (x, SYMBOL_CONTEXT_LEA),
2393                                 MAX_MACHINE_MODE);
2394
2395     default:
2396       return 0;
2397     }
2398 }
2399
2400 /* X is a doubleword constant that can be handled by splitting it into
2401    two words and loading each word separately.  Return the number of
2402    instructions required to do this.  */
2403
2404 int
2405 mips_split_const_insns (rtx x)
2406 {
2407   unsigned int low, high;
2408
2409   low = mips_const_insns (mips_subword (x, false));
2410   high = mips_const_insns (mips_subword (x, true));
2411   gcc_assert (low > 0 && high > 0);
2412   return low + high;
2413 }
2414
2415 /* Return the number of instructions needed to implement INSN,
2416    given that it loads from or stores to MEM.  Count extended
2417    MIPS16 instructions as two instructions.  */
2418
2419 int
2420 mips_load_store_insns (rtx mem, rtx insn)
2421 {
2422   enum machine_mode mode;
2423   bool might_split_p;
2424   rtx set;
2425
2426   gcc_assert (MEM_P (mem));
2427   mode = GET_MODE (mem);
2428
2429   /* Try to prove that INSN does not need to be split.  */
2430   might_split_p = true;
2431   if (GET_MODE_BITSIZE (mode) == 64)
2432     {
2433       set = single_set (insn);
2434       if (set && !mips_split_64bit_move_p (SET_DEST (set), SET_SRC (set)))
2435         might_split_p = false;
2436     }
2437
2438   return mips_address_insns (XEXP (mem, 0), mode, might_split_p);
2439 }
2440
2441 /* Return the number of instructions needed for an integer division.  */
2442
2443 int
2444 mips_idiv_insns (void)
2445 {
2446   int count;
2447
2448   count = 1;
2449   if (TARGET_CHECK_ZERO_DIV)
2450     {
2451       if (GENERATE_DIVIDE_TRAPS)
2452         count++;
2453       else
2454         count += 2;
2455     }
2456
2457   if (TARGET_FIX_R4000 || TARGET_FIX_R4400)
2458     count++;
2459   return count;
2460 }
2461 \f
2462 /* Emit a move from SRC to DEST.  Assume that the move expanders can
2463    handle all moves if !can_create_pseudo_p ().  The distinction is
2464    important because, unlike emit_move_insn, the move expanders know
2465    how to force Pmode objects into the constant pool even when the
2466    constant pool address is not itself legitimate.  */
2467
2468 rtx
2469 mips_emit_move (rtx dest, rtx src)
2470 {
2471   return (can_create_pseudo_p ()
2472           ? emit_move_insn (dest, src)
2473           : emit_move_insn_1 (dest, src));
2474 }
2475
2476 /* Emit an instruction of the form (set TARGET (CODE OP0)).  */
2477
2478 static void
2479 mips_emit_unary (enum rtx_code code, rtx target, rtx op0)
2480 {
2481   emit_insn (gen_rtx_SET (VOIDmode, target,
2482                           gen_rtx_fmt_e (code, GET_MODE (op0), op0)));
2483 }
2484
2485 /* Compute (CODE OP0) and store the result in a new register of mode MODE.
2486    Return that new register.  */
2487
2488 static rtx
2489 mips_force_unary (enum machine_mode mode, enum rtx_code code, rtx op0)
2490 {
2491   rtx reg;
2492
2493   reg = gen_reg_rtx (mode);
2494   mips_emit_unary (code, reg, op0);
2495   return reg;
2496 }
2497
2498 /* Emit an instruction of the form (set TARGET (CODE OP0 OP1)).  */
2499
2500 static void
2501 mips_emit_binary (enum rtx_code code, rtx target, rtx op0, rtx op1)
2502 {
2503   emit_insn (gen_rtx_SET (VOIDmode, target,
2504                           gen_rtx_fmt_ee (code, GET_MODE (target), op0, op1)));
2505 }
2506
2507 /* Compute (CODE OP0 OP1) and store the result in a new register
2508    of mode MODE.  Return that new register.  */
2509
2510 static rtx
2511 mips_force_binary (enum machine_mode mode, enum rtx_code code, rtx op0, rtx op1)
2512 {
2513   rtx reg;
2514
2515   reg = gen_reg_rtx (mode);
2516   mips_emit_binary (code, reg, op0, op1);
2517   return reg;
2518 }
2519
2520 /* Copy VALUE to a register and return that register.  If new pseudos
2521    are allowed, copy it into a new register, otherwise use DEST.  */
2522
2523 static rtx
2524 mips_force_temporary (rtx dest, rtx value)
2525 {
2526   if (can_create_pseudo_p ())
2527     return force_reg (Pmode, value);
2528   else
2529     {
2530       mips_emit_move (dest, value);
2531       return dest;
2532     }
2533 }
2534
2535 /* Emit a call sequence with call pattern PATTERN and return the call
2536    instruction itself (which is not necessarily the last instruction
2537    emitted).  ORIG_ADDR is the original, unlegitimized address,
2538    ADDR is the legitimized form, and LAZY_P is true if the call
2539    address is lazily-bound.  */
2540
2541 static rtx
2542 mips_emit_call_insn (rtx pattern, rtx orig_addr, rtx addr, bool lazy_p)
2543 {
2544   rtx insn, reg;
2545
2546   insn = emit_call_insn (pattern);
2547
2548   if (TARGET_MIPS16 && mips_use_pic_fn_addr_reg_p (orig_addr))
2549     {
2550       /* MIPS16 JALRs only take MIPS16 registers.  If the target
2551          function requires $25 to be valid on entry, we must copy it
2552          there separately.  The move instruction can be put in the
2553          call's delay slot.  */
2554       reg = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
2555       emit_insn_before (gen_move_insn (reg, addr), insn);
2556       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), reg);
2557     }
2558
2559   if (lazy_p)
2560     /* Lazy-binding stubs require $gp to be valid on entry.  */
2561     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
2562
2563   if (TARGET_USE_GOT)
2564     {
2565       /* See the comment above load_call<mode> for details.  */
2566       use_reg (&CALL_INSN_FUNCTION_USAGE (insn),
2567                gen_rtx_REG (Pmode, GOT_VERSION_REGNUM));
2568       emit_insn (gen_update_got_version ());
2569     }
2570   return insn;
2571 }
2572 \f
2573 /* Wrap symbol or label BASE in an UNSPEC address of type SYMBOL_TYPE,
2574    then add CONST_INT OFFSET to the result.  */
2575
2576 static rtx
2577 mips_unspec_address_offset (rtx base, rtx offset,
2578                             enum mips_symbol_type symbol_type)
2579 {
2580   base = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, base),
2581                          UNSPEC_ADDRESS_FIRST + symbol_type);
2582   if (offset != const0_rtx)
2583     base = gen_rtx_PLUS (Pmode, base, offset);
2584   return gen_rtx_CONST (Pmode, base);
2585 }
2586
2587 /* Return an UNSPEC address with underlying address ADDRESS and symbol
2588    type SYMBOL_TYPE.  */
2589
2590 rtx
2591 mips_unspec_address (rtx address, enum mips_symbol_type symbol_type)
2592 {
2593   rtx base, offset;
2594
2595   split_const (address, &base, &offset);
2596   return mips_unspec_address_offset (base, offset, symbol_type);
2597 }
2598
2599 /* If OP is an UNSPEC address, return the address to which it refers,
2600    otherwise return OP itself.  */
2601
2602 static rtx
2603 mips_strip_unspec_address (rtx op)
2604 {
2605   rtx base, offset;
2606
2607   split_const (op, &base, &offset);
2608   if (UNSPEC_ADDRESS_P (base))
2609     op = plus_constant (UNSPEC_ADDRESS (base), INTVAL (offset));
2610   return op;
2611 }
2612
2613 /* If mips_unspec_address (ADDR, SYMBOL_TYPE) is a 32-bit value, add the
2614    high part to BASE and return the result.  Just return BASE otherwise.
2615    TEMP is as for mips_force_temporary.
2616
2617    The returned expression can be used as the first operand to a LO_SUM.  */
2618
2619 static rtx
2620 mips_unspec_offset_high (rtx temp, rtx base, rtx addr,
2621                          enum mips_symbol_type symbol_type)
2622 {
2623   if (mips_split_p[symbol_type])
2624     {
2625       addr = gen_rtx_HIGH (Pmode, mips_unspec_address (addr, symbol_type));
2626       addr = mips_force_temporary (temp, addr);
2627       base = mips_force_temporary (temp, gen_rtx_PLUS (Pmode, addr, base));
2628     }
2629   return base;
2630 }
2631 \f
2632 /* Return an instruction that copies $gp into register REG.  We want
2633    GCC to treat the register's value as constant, so that its value
2634    can be rematerialized on demand.  */
2635
2636 static rtx
2637 gen_load_const_gp (rtx reg)
2638 {
2639   return (Pmode == SImode
2640           ? gen_load_const_gp_si (reg)
2641           : gen_load_const_gp_di (reg));
2642 }
2643
2644 /* Return a pseudo register that contains the value of $gp throughout
2645    the current function.  Such registers are needed by MIPS16 functions,
2646    for which $gp itself is not a valid base register or addition operand.  */
2647
2648 static rtx
2649 mips16_gp_pseudo_reg (void)
2650 {
2651   if (cfun->machine->mips16_gp_pseudo_rtx == NULL_RTX)
2652     {
2653       rtx insn, scan;
2654
2655       cfun->machine->mips16_gp_pseudo_rtx = gen_reg_rtx (Pmode);
2656
2657       push_topmost_sequence ();
2658
2659       scan = get_insns ();
2660       while (NEXT_INSN (scan) && !INSN_P (NEXT_INSN (scan)))
2661         scan = NEXT_INSN (scan);
2662
2663       insn = gen_load_const_gp (cfun->machine->mips16_gp_pseudo_rtx);
2664       emit_insn_after (insn, scan);
2665
2666       pop_topmost_sequence ();
2667     }
2668
2669   return cfun->machine->mips16_gp_pseudo_rtx;
2670 }
2671
2672 /* Return a base register that holds pic_offset_table_rtx.
2673    TEMP, if nonnull, is a scratch Pmode base register.  */
2674
2675 rtx
2676 mips_pic_base_register (rtx temp)
2677 {
2678   if (!TARGET_MIPS16)
2679     return pic_offset_table_rtx;
2680
2681   if (currently_expanding_to_rtl)
2682     return mips16_gp_pseudo_reg ();
2683
2684   if (can_create_pseudo_p ())
2685     temp = gen_reg_rtx (Pmode);
2686
2687   if (TARGET_USE_GOT)
2688     /* The first post-reload split exposes all references to $gp
2689        (both uses and definitions).  All references must remain
2690        explicit after that point.
2691
2692        It is safe to introduce uses of $gp at any time, so for
2693        simplicity, we do that before the split too.  */
2694     mips_emit_move (temp, pic_offset_table_rtx);
2695   else
2696     emit_insn (gen_load_const_gp (temp));
2697   return temp;
2698 }
2699
2700 /* Return the RHS of a load_call<mode> insn.  */
2701
2702 static rtx
2703 mips_unspec_call (rtx reg, rtx symbol)
2704 {
2705   rtvec vec;
2706
2707   vec = gen_rtvec (3, reg, symbol, gen_rtx_REG (SImode, GOT_VERSION_REGNUM));
2708   return gen_rtx_UNSPEC (Pmode, vec, UNSPEC_LOAD_CALL);
2709 }
2710
2711 /* If SRC is the RHS of a load_call<mode> insn, return the underlying symbol
2712    reference.  Return NULL_RTX otherwise.  */
2713
2714 static rtx
2715 mips_strip_unspec_call (rtx src)
2716 {
2717   if (GET_CODE (src) == UNSPEC && XINT (src, 1) == UNSPEC_LOAD_CALL)
2718     return mips_strip_unspec_address (XVECEXP (src, 0, 1));
2719   return NULL_RTX;
2720 }
2721
2722 /* Create and return a GOT reference of type TYPE for address ADDR.
2723    TEMP, if nonnull, is a scratch Pmode base register.  */
2724
2725 rtx
2726 mips_got_load (rtx temp, rtx addr, enum mips_symbol_type type)
2727 {
2728   rtx base, high, lo_sum_symbol;
2729
2730   base = mips_pic_base_register (temp);
2731
2732   /* If we used the temporary register to load $gp, we can't use
2733      it for the high part as well.  */
2734   if (temp != NULL && reg_overlap_mentioned_p (base, temp))
2735     temp = NULL;
2736
2737   high = mips_unspec_offset_high (temp, base, addr, type);
2738   lo_sum_symbol = mips_unspec_address (addr, type);
2739
2740   if (type == SYMBOL_GOTOFF_CALL)
2741     return mips_unspec_call (high, lo_sum_symbol);
2742   else
2743     return (Pmode == SImode
2744             ? gen_unspec_gotsi (high, lo_sum_symbol)
2745             : gen_unspec_gotdi (high, lo_sum_symbol));
2746 }
2747
2748 /* If MODE is MAX_MACHINE_MODE, ADDR appears as a move operand, otherwise
2749    it appears in a MEM of that mode.  Return true if ADDR is a legitimate
2750    constant in that context and can be split into high and low parts.
2751    If so, and if LOW_OUT is nonnull, emit the high part and store the
2752    low part in *LOW_OUT.  Leave *LOW_OUT unchanged otherwise.
2753
2754    TEMP is as for mips_force_temporary and is used to load the high
2755    part into a register.
2756
2757    When MODE is MAX_MACHINE_MODE, the low part is guaranteed to be
2758    a legitimize SET_SRC for an .md pattern, otherwise the low part
2759    is guaranteed to be a legitimate address for mode MODE.  */
2760
2761 bool
2762 mips_split_symbol (rtx temp, rtx addr, enum machine_mode mode, rtx *low_out)
2763 {
2764   enum mips_symbol_context context;
2765   enum mips_symbol_type symbol_type;
2766   rtx high;
2767
2768   context = (mode == MAX_MACHINE_MODE
2769              ? SYMBOL_CONTEXT_LEA
2770              : SYMBOL_CONTEXT_MEM);
2771   if (GET_CODE (addr) == HIGH && context == SYMBOL_CONTEXT_LEA)
2772     {
2773       addr = XEXP (addr, 0);
2774       if (mips_symbolic_constant_p (addr, context, &symbol_type)
2775           && mips_symbol_insns (symbol_type, mode) > 0
2776           && mips_split_hi_p[symbol_type])
2777         {
2778           if (low_out)
2779             switch (symbol_type)
2780               {
2781               case SYMBOL_GOT_PAGE_OFST:
2782                 /* The high part of a page/ofst pair is loaded from the GOT.  */
2783                 *low_out = mips_got_load (temp, addr, SYMBOL_GOTOFF_PAGE);
2784                 break;
2785
2786               default:
2787                 gcc_unreachable ();
2788               }
2789           return true;
2790         }
2791     }
2792   else
2793     {
2794       if (mips_symbolic_constant_p (addr, context, &symbol_type)
2795           && mips_symbol_insns (symbol_type, mode) > 0
2796           && mips_split_p[symbol_type])
2797         {
2798           if (low_out)
2799             switch (symbol_type)
2800               {
2801               case SYMBOL_GOT_DISP:
2802                 /* SYMBOL_GOT_DISP symbols are loaded from the GOT.  */
2803                 *low_out = mips_got_load (temp, addr, SYMBOL_GOTOFF_DISP);
2804                 break;
2805
2806               case SYMBOL_GP_RELATIVE:
2807                 high = mips_pic_base_register (temp);
2808                 *low_out = gen_rtx_LO_SUM (Pmode, high, addr);
2809                 break;
2810
2811               default:
2812                 high = gen_rtx_HIGH (Pmode, copy_rtx (addr));
2813                 high = mips_force_temporary (temp, high);
2814                 *low_out = gen_rtx_LO_SUM (Pmode, high, addr);
2815                 break;
2816               }
2817           return true;
2818         }
2819     }
2820   return false;
2821 }
2822
2823 /* Return a legitimate address for REG + OFFSET.  TEMP is as for
2824    mips_force_temporary; it is only needed when OFFSET is not a
2825    SMALL_OPERAND.  */
2826
2827 static rtx
2828 mips_add_offset (rtx temp, rtx reg, HOST_WIDE_INT offset)
2829 {
2830   if (!SMALL_OPERAND (offset))
2831     {
2832       rtx high;
2833
2834       if (TARGET_MIPS16)
2835         {
2836           /* Load the full offset into a register so that we can use
2837              an unextended instruction for the address itself.  */
2838           high = GEN_INT (offset);
2839           offset = 0;
2840         }
2841       else
2842         {
2843           /* Leave OFFSET as a 16-bit offset and put the excess in HIGH.
2844              The addition inside the macro CONST_HIGH_PART may cause an
2845              overflow, so we need to force a sign-extension check.  */
2846           high = gen_int_mode (CONST_HIGH_PART (offset), Pmode);
2847           offset = CONST_LOW_PART (offset);
2848         }
2849       high = mips_force_temporary (temp, high);
2850       reg = mips_force_temporary (temp, gen_rtx_PLUS (Pmode, high, reg));
2851     }
2852   return plus_constant (reg, offset);
2853 }
2854 \f
2855 /* The __tls_get_attr symbol.  */
2856 static GTY(()) rtx mips_tls_symbol;
2857
2858 /* Return an instruction sequence that calls __tls_get_addr.  SYM is
2859    the TLS symbol we are referencing and TYPE is the symbol type to use
2860    (either global dynamic or local dynamic).  V0 is an RTX for the
2861    return value location.  */
2862
2863 static rtx
2864 mips_call_tls_get_addr (rtx sym, enum mips_symbol_type type, rtx v0)
2865 {
2866   rtx insn, loc, a0;
2867
2868   a0 = gen_rtx_REG (Pmode, GP_ARG_FIRST);
2869
2870   if (!mips_tls_symbol)
2871     mips_tls_symbol = init_one_libfunc ("__tls_get_addr");
2872
2873   loc = mips_unspec_address (sym, type);
2874
2875   start_sequence ();
2876
2877   emit_insn (gen_rtx_SET (Pmode, a0,
2878                           gen_rtx_LO_SUM (Pmode, pic_offset_table_rtx, loc)));
2879   insn = mips_expand_call (MIPS_CALL_NORMAL, v0, mips_tls_symbol,
2880                            const0_rtx, NULL_RTX, false);
2881   RTL_CONST_CALL_P (insn) = 1;
2882   use_reg (&CALL_INSN_FUNCTION_USAGE (insn), a0);
2883   insn = get_insns ();
2884
2885   end_sequence ();
2886
2887   return insn;
2888 }
2889
2890 /* Return a pseudo register that contains the current thread pointer.  */
2891
2892 static rtx
2893 mips_get_tp (void)
2894 {
2895   rtx tp;
2896
2897   tp = gen_reg_rtx (Pmode);
2898   if (Pmode == DImode)
2899     emit_insn (gen_tls_get_tp_di (tp));
2900   else
2901     emit_insn (gen_tls_get_tp_si (tp));
2902   return tp;
2903 }
2904
2905 /* Generate the code to access LOC, a thread-local SYMBOL_REF, and return
2906    its address.  The return value will be both a valid address and a valid
2907    SET_SRC (either a REG or a LO_SUM).  */
2908
2909 static rtx
2910 mips_legitimize_tls_address (rtx loc)
2911 {
2912   rtx dest, insn, v0, tp, tmp1, tmp2, eqv;
2913   enum tls_model model;
2914
2915   if (TARGET_MIPS16)
2916     {
2917       sorry ("MIPS16 TLS");
2918       return gen_reg_rtx (Pmode);
2919     }
2920
2921   model = SYMBOL_REF_TLS_MODEL (loc);
2922   /* Only TARGET_ABICALLS code can have more than one module; other
2923      code must be be static and should not use a GOT.  All TLS models
2924      reduce to local exec in this situation.  */
2925   if (!TARGET_ABICALLS)
2926     model = TLS_MODEL_LOCAL_EXEC;
2927
2928   switch (model)
2929     {
2930     case TLS_MODEL_GLOBAL_DYNAMIC:
2931       v0 = gen_rtx_REG (Pmode, GP_RETURN);
2932       insn = mips_call_tls_get_addr (loc, SYMBOL_TLSGD, v0);
2933       dest = gen_reg_rtx (Pmode);
2934       emit_libcall_block (insn, dest, v0, loc);
2935       break;
2936
2937     case TLS_MODEL_LOCAL_DYNAMIC:
2938       v0 = gen_rtx_REG (Pmode, GP_RETURN);
2939       insn = mips_call_tls_get_addr (loc, SYMBOL_TLSLDM, v0);
2940       tmp1 = gen_reg_rtx (Pmode);
2941
2942       /* Attach a unique REG_EQUIV, to allow the RTL optimizers to
2943          share the LDM result with other LD model accesses.  */
2944       eqv = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx),
2945                             UNSPEC_TLS_LDM);
2946       emit_libcall_block (insn, tmp1, v0, eqv);
2947
2948       tmp2 = mips_unspec_offset_high (NULL, tmp1, loc, SYMBOL_DTPREL);
2949       dest = gen_rtx_LO_SUM (Pmode, tmp2,
2950                              mips_unspec_address (loc, SYMBOL_DTPREL));
2951       break;
2952
2953     case TLS_MODEL_INITIAL_EXEC:
2954       tp = mips_get_tp ();
2955       tmp1 = gen_reg_rtx (Pmode);
2956       tmp2 = mips_unspec_address (loc, SYMBOL_GOTTPREL);
2957       if (Pmode == DImode)
2958         emit_insn (gen_load_gotdi (tmp1, pic_offset_table_rtx, tmp2));
2959       else
2960         emit_insn (gen_load_gotsi (tmp1, pic_offset_table_rtx, tmp2));
2961       dest = gen_reg_rtx (Pmode);
2962       emit_insn (gen_add3_insn (dest, tmp1, tp));
2963       break;
2964
2965     case TLS_MODEL_LOCAL_EXEC:
2966       tp = mips_get_tp ();
2967       tmp1 = mips_unspec_offset_high (NULL, tp, loc, SYMBOL_TPREL);
2968       dest = gen_rtx_LO_SUM (Pmode, tmp1,
2969                              mips_unspec_address (loc, SYMBOL_TPREL));
2970       break;
2971
2972     default:
2973       gcc_unreachable ();
2974     }
2975   return dest;
2976 }
2977 \f
2978 /* If X is not a valid address for mode MODE, force it into a register.  */
2979
2980 static rtx
2981 mips_force_address (rtx x, enum machine_mode mode)
2982 {
2983   if (!mips_legitimate_address_p (mode, x, false))
2984     x = force_reg (Pmode, x);
2985   return x;
2986 }
2987
2988 /* This function is used to implement LEGITIMIZE_ADDRESS.  If X can
2989    be legitimized in a way that the generic machinery might not expect,
2990    return a new address, otherwise return NULL.  MODE is the mode of
2991    the memory being accessed.  */
2992
2993 static rtx
2994 mips_legitimize_address (rtx x, rtx oldx ATTRIBUTE_UNUSED,
2995                          enum machine_mode mode)
2996 {
2997   rtx base, addr;
2998   HOST_WIDE_INT offset;
2999
3000   if (mips_tls_symbol_p (x))
3001     return mips_legitimize_tls_address (x);
3002
3003   /* See if the address can split into a high part and a LO_SUM.  */
3004   if (mips_split_symbol (NULL, x, mode, &addr))
3005     return mips_force_address (addr, mode);
3006
3007   /* Handle BASE + OFFSET using mips_add_offset.  */
3008   mips_split_plus (x, &base, &offset);
3009   if (offset != 0)
3010     {
3011       if (!mips_valid_base_register_p (base, mode, false))
3012         base = copy_to_mode_reg (Pmode, base);
3013       addr = mips_add_offset (NULL, base, offset);
3014       return mips_force_address (addr, mode);
3015     }
3016
3017   return x;
3018 }
3019
3020 /* Load VALUE into DEST.  TEMP is as for mips_force_temporary.  */
3021
3022 void
3023 mips_move_integer (rtx temp, rtx dest, unsigned HOST_WIDE_INT value)
3024 {
3025   struct mips_integer_op codes[MIPS_MAX_INTEGER_OPS];
3026   enum machine_mode mode;
3027   unsigned int i, num_ops;
3028   rtx x;
3029
3030   mode = GET_MODE (dest);
3031   num_ops = mips_build_integer (codes, value);
3032
3033   /* Apply each binary operation to X.  Invariant: X is a legitimate
3034      source operand for a SET pattern.  */
3035   x = GEN_INT (codes[0].value);
3036   for (i = 1; i < num_ops; i++)
3037     {
3038       if (!can_create_pseudo_p ())
3039         {
3040           emit_insn (gen_rtx_SET (VOIDmode, temp, x));
3041           x = temp;
3042         }
3043       else
3044         x = force_reg (mode, x);
3045       x = gen_rtx_fmt_ee (codes[i].code, mode, x, GEN_INT (codes[i].value));
3046     }
3047
3048   emit_insn (gen_rtx_SET (VOIDmode, dest, x));
3049 }
3050
3051 /* Subroutine of mips_legitimize_move.  Move constant SRC into register
3052    DEST given that SRC satisfies immediate_operand but doesn't satisfy
3053    move_operand.  */
3054
3055 static void
3056 mips_legitimize_const_move (enum machine_mode mode, rtx dest, rtx src)
3057 {
3058   rtx base, offset;
3059
3060   /* Split moves of big integers into smaller pieces.  */
3061   if (splittable_const_int_operand (src, mode))
3062     {
3063       mips_move_integer (dest, dest, INTVAL (src));
3064       return;
3065     }
3066
3067   /* Split moves of symbolic constants into high/low pairs.  */
3068   if (mips_split_symbol (dest, src, MAX_MACHINE_MODE, &src))
3069     {
3070       emit_insn (gen_rtx_SET (VOIDmode, dest, src));
3071       return;
3072     }
3073
3074   /* Generate the appropriate access sequences for TLS symbols.  */
3075   if (mips_tls_symbol_p (src))
3076     {
3077       mips_emit_move (dest, mips_legitimize_tls_address (src));
3078       return;
3079     }
3080
3081   /* If we have (const (plus symbol offset)), and that expression cannot
3082      be forced into memory, load the symbol first and add in the offset.
3083      In non-MIPS16 mode, prefer to do this even if the constant _can_ be
3084      forced into memory, as it usually produces better code.  */
3085   split_const (src, &base, &offset);
3086   if (offset != const0_rtx
3087       && (targetm.cannot_force_const_mem (src)
3088           || (!TARGET_MIPS16 && can_create_pseudo_p ())))
3089     {
3090       base = mips_force_temporary (dest, base);
3091       mips_emit_move (dest, mips_add_offset (NULL, base, INTVAL (offset)));
3092       return;
3093     }
3094
3095   src = force_const_mem (mode, src);
3096
3097   /* When using explicit relocs, constant pool references are sometimes
3098      not legitimate addresses.  */
3099   mips_split_symbol (dest, XEXP (src, 0), mode, &XEXP (src, 0));
3100   mips_emit_move (dest, src);
3101 }
3102
3103 /* If (set DEST SRC) is not a valid move instruction, emit an equivalent
3104    sequence that is valid.  */
3105
3106 bool
3107 mips_legitimize_move (enum machine_mode mode, rtx dest, rtx src)
3108 {
3109   if (!register_operand (dest, mode) && !reg_or_0_operand (src, mode))
3110     {
3111       mips_emit_move (dest, force_reg (mode, src));
3112       return true;
3113     }
3114
3115   /* We need to deal with constants that would be legitimate
3116      immediate_operands but aren't legitimate move_operands.  */
3117   if (CONSTANT_P (src) && !move_operand (src, mode))
3118     {
3119       mips_legitimize_const_move (mode, dest, src);
3120       set_unique_reg_note (get_last_insn (), REG_EQUAL, copy_rtx (src));
3121       return true;
3122     }
3123   return false;
3124 }
3125 \f
3126 /* Return true if value X in context CONTEXT is a small-data address
3127    that can be rewritten as a LO_SUM.  */
3128
3129 static bool
3130 mips_rewrite_small_data_p (rtx x, enum mips_symbol_context context)
3131 {
3132   enum mips_symbol_type symbol_type;
3133
3134   return (mips_lo_relocs[SYMBOL_GP_RELATIVE]
3135           && !mips_split_p[SYMBOL_GP_RELATIVE]
3136           && mips_symbolic_constant_p (x, context, &symbol_type)
3137           && symbol_type == SYMBOL_GP_RELATIVE);
3138 }
3139
3140 /* A for_each_rtx callback for mips_small_data_pattern_p.  DATA is the
3141    containing MEM, or null if none.  */
3142
3143 static int
3144 mips_small_data_pattern_1 (rtx *loc, void *data)
3145 {
3146   enum mips_symbol_context context;
3147
3148   if (GET_CODE (*loc) == LO_SUM)
3149     return -1;
3150
3151   if (MEM_P (*loc))
3152     {
3153       if (for_each_rtx (&XEXP (*loc, 0), mips_small_data_pattern_1, *loc))
3154         return 1;
3155       return -1;
3156     }
3157
3158   context = data ? SYMBOL_CONTEXT_MEM : SYMBOL_CONTEXT_LEA;
3159   return mips_rewrite_small_data_p (*loc, context);
3160 }
3161
3162 /* Return true if OP refers to small data symbols directly, not through
3163    a LO_SUM.  */
3164
3165 bool
3166 mips_small_data_pattern_p (rtx op)
3167 {
3168   return for_each_rtx (&op, mips_small_data_pattern_1, NULL);
3169 }
3170
3171 /* A for_each_rtx callback, used by mips_rewrite_small_data.
3172    DATA is the containing MEM, or null if none.  */
3173
3174 static int
3175 mips_rewrite_small_data_1 (rtx *loc, void *data)
3176 {
3177   enum mips_symbol_context context;
3178
3179   if (MEM_P (*loc))
3180     {
3181       for_each_rtx (&XEXP (*loc, 0), mips_rewrite_small_data_1, *loc);
3182       return -1;
3183     }
3184
3185   context = data ? SYMBOL_CONTEXT_MEM : SYMBOL_CONTEXT_LEA;
3186   if (mips_rewrite_small_data_p (*loc, context))
3187     *loc = gen_rtx_LO_SUM (Pmode, pic_offset_table_rtx, *loc);
3188
3189   if (GET_CODE (*loc) == LO_SUM)
3190     return -1;
3191
3192   return 0;
3193 }
3194
3195 /* Rewrite instruction pattern PATTERN so that it refers to small data
3196    using explicit relocations.  */
3197
3198 rtx
3199 mips_rewrite_small_data (rtx pattern)
3200 {
3201   pattern = copy_insn (pattern);
3202   for_each_rtx (&pattern, mips_rewrite_small_data_1, NULL);
3203   return pattern;
3204 }
3205 \f
3206 /* We need a lot of little routines to check the range of MIPS16 immediate
3207    operands.  */
3208
3209 static int
3210 m16_check_op (rtx op, int low, int high, int mask)
3211 {
3212   return (CONST_INT_P (op)
3213           && IN_RANGE (INTVAL (op), low, high)
3214           && (INTVAL (op) & mask) == 0);
3215 }
3216
3217 int
3218 m16_uimm3_b (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3219 {
3220   return m16_check_op (op, 0x1, 0x8, 0);
3221 }
3222
3223 int
3224 m16_simm4_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3225 {
3226   return m16_check_op (op, -0x8, 0x7, 0);
3227 }
3228
3229 int
3230 m16_nsimm4_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3231 {
3232   return m16_check_op (op, -0x7, 0x8, 0);
3233 }
3234
3235 int
3236 m16_simm5_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3237 {
3238   return m16_check_op (op, -0x10, 0xf, 0);
3239 }
3240
3241 int
3242 m16_nsimm5_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3243 {
3244   return m16_check_op (op, -0xf, 0x10, 0);
3245 }
3246
3247 int
3248 m16_uimm5_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3249 {
3250   return m16_check_op (op, -0x10 << 2, 0xf << 2, 3);
3251 }
3252
3253 int
3254 m16_nuimm5_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3255 {
3256   return m16_check_op (op, -0xf << 2, 0x10 << 2, 3);
3257 }
3258
3259 int
3260 m16_simm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3261 {
3262   return m16_check_op (op, -0x80, 0x7f, 0);
3263 }
3264
3265 int
3266 m16_nsimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3267 {
3268   return m16_check_op (op, -0x7f, 0x80, 0);
3269 }
3270
3271 int
3272 m16_uimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3273 {
3274   return m16_check_op (op, 0x0, 0xff, 0);
3275 }
3276
3277 int
3278 m16_nuimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3279 {
3280   return m16_check_op (op, -0xff, 0x0, 0);
3281 }
3282
3283 int
3284 m16_uimm8_m1_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3285 {
3286   return m16_check_op (op, -0x1, 0xfe, 0);
3287 }
3288
3289 int
3290 m16_uimm8_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3291 {
3292   return m16_check_op (op, 0x0, 0xff << 2, 3);
3293 }
3294
3295 int
3296 m16_nuimm8_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3297 {
3298   return m16_check_op (op, -0xff << 2, 0x0, 3);
3299 }
3300
3301 int
3302 m16_simm8_8 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3303 {
3304   return m16_check_op (op, -0x80 << 3, 0x7f << 3, 7);
3305 }
3306
3307 int
3308 m16_nsimm8_8 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
3309 {
3310   return m16_check_op (op, -0x7f << 3, 0x80 << 3, 7);
3311 }
3312 \f
3313 /* The cost of loading values from the constant pool.  It should be
3314    larger than the cost of any constant we want to synthesize inline.  */
3315 #define CONSTANT_POOL_COST COSTS_N_INSNS (TARGET_MIPS16 ? 4 : 8)
3316
3317 /* Return the cost of X when used as an operand to the MIPS16 instruction
3318    that implements CODE.  Return -1 if there is no such instruction, or if
3319    X is not a valid immediate operand for it.  */
3320
3321 static int
3322 mips16_constant_cost (int code, HOST_WIDE_INT x)
3323 {
3324   switch (code)
3325     {
3326     case ASHIFT:
3327     case ASHIFTRT:
3328     case LSHIFTRT:
3329       /* Shifts by between 1 and 8 bits (inclusive) are unextended,
3330          other shifts are extended.  The shift patterns truncate the shift
3331          count to the right size, so there are no out-of-range values.  */
3332       if (IN_RANGE (x, 1, 8))
3333         return 0;
3334       return COSTS_N_INSNS (1);
3335
3336     case PLUS:
3337       if (IN_RANGE (x, -128, 127))
3338         return 0;
3339       if (SMALL_OPERAND (x))
3340         return COSTS_N_INSNS (1);
3341       return -1;
3342
3343     case LEU:
3344       /* Like LE, but reject the always-true case.  */
3345       if (x == -1)
3346         return -1;
3347     case LE:
3348       /* We add 1 to the immediate and use SLT.  */
3349       x += 1;
3350     case XOR:
3351       /* We can use CMPI for an xor with an unsigned 16-bit X.  */
3352     case LT:
3353     case LTU:
3354       if (IN_RANGE (x, 0, 255))
3355         return 0;
3356       if (SMALL_OPERAND_UNSIGNED (x))
3357         return COSTS_N_INSNS (1);
3358       return -1;
3359
3360     case EQ:
3361     case NE:
3362       /* Equality comparisons with 0 are cheap.  */
3363       if (x == 0)
3364         return 0;
3365       return -1;
3366
3367     default:
3368       return -1;
3369     }
3370 }
3371
3372 /* Return true if there is a non-MIPS16 instruction that implements CODE
3373    and if that instruction accepts X as an immediate operand.  */
3374
3375 static int
3376 mips_immediate_operand_p (int code, HOST_WIDE_INT x)
3377 {
3378   switch (code)
3379     {
3380     case ASHIFT:
3381     case ASHIFTRT:
3382     case LSHIFTRT:
3383       /* All shift counts are truncated to a valid constant.  */
3384       return true;
3385
3386     case ROTATE:
3387     case ROTATERT:
3388       /* Likewise rotates, if the target supports rotates at all.  */
3389       return ISA_HAS_ROR;
3390
3391     case AND:
3392     case IOR:
3393     case XOR:
3394       /* These instructions take 16-bit unsigned immediates.  */
3395       return SMALL_OPERAND_UNSIGNED (x);
3396
3397     case PLUS:
3398     case LT:
3399     case LTU:
3400       /* These instructions take 16-bit signed immediates.  */
3401       return SMALL_OPERAND (x);
3402
3403     case EQ:
3404     case NE:
3405     case GT:
3406     case GTU:
3407       /* The "immediate" forms of these instructions are really
3408          implemented as comparisons with register 0.  */
3409       return x == 0;
3410
3411     case GE:
3412     case GEU:
3413       /* Likewise, meaning that the only valid immediate operand is 1.  */
3414       return x == 1;
3415
3416     case LE:
3417       /* We add 1 to the immediate and use SLT.  */
3418       return SMALL_OPERAND (x + 1);
3419
3420     case LEU:
3421       /* Likewise SLTU, but reject the always-true case.  */
3422       return SMALL_OPERAND (x + 1) && x + 1 != 0;
3423
3424     case SIGN_EXTRACT:
3425     case ZERO_EXTRACT:
3426       /* The bit position and size are immediate operands.  */
3427       return ISA_HAS_EXT_INS;
3428
3429     default:
3430       /* By default assume that $0 can be used for 0.  */
3431       return x == 0;
3432     }
3433 }
3434
3435 /* Return the cost of binary operation X, given that the instruction
3436    sequence for a word-sized or smaller operation has cost SINGLE_COST
3437    and that the sequence of a double-word operation has cost DOUBLE_COST.
3438    If SPEED is true, optimize for speed otherwise optimize for size.  */
3439
3440 static int
3441 mips_binary_cost (rtx x, int single_cost, int double_cost, bool speed)
3442 {
3443   int cost;
3444
3445   if (GET_MODE_SIZE (GET_MODE (x)) == UNITS_PER_WORD * 2)
3446     cost = double_cost;
3447   else
3448     cost = single_cost;
3449   return (cost
3450           + rtx_cost (XEXP (x, 0), SET, speed)
3451           + rtx_cost (XEXP (x, 1), GET_CODE (x), speed));
3452 }
3453
3454 /* Return the cost of floating-point multiplications of mode MODE.  */
3455
3456 static int
3457 mips_fp_mult_cost (enum machine_mode mode)
3458 {
3459   return mode == DFmode ? mips_cost->fp_mult_df : mips_cost->fp_mult_sf;
3460 }
3461
3462 /* Return the cost of floating-point divisions of mode MODE.  */
3463
3464 static int
3465 mips_fp_div_cost (enum machine_mode mode)
3466 {
3467   return mode == DFmode ? mips_cost->fp_div_df : mips_cost->fp_div_sf;
3468 }
3469
3470 /* Return the cost of sign-extending OP to mode MODE, not including the
3471    cost of OP itself.  */
3472
3473 static int
3474 mips_sign_extend_cost (enum machine_mode mode, rtx op)
3475 {
3476   if (MEM_P (op))
3477     /* Extended loads are as cheap as unextended ones.  */
3478     return 0;
3479
3480   if (TARGET_64BIT && mode == DImode && GET_MODE (op) == SImode)
3481     /* A sign extension from SImode to DImode in 64-bit mode is free.  */
3482     return 0;
3483
3484   if (ISA_HAS_SEB_SEH || GENERATE_MIPS16E)
3485     /* We can use SEB or SEH.  */
3486     return COSTS_N_INSNS (1);
3487
3488   /* We need to use a shift left and a shift right.  */
3489   return COSTS_N_INSNS (TARGET_MIPS16 ? 4 : 2);
3490 }
3491
3492 /* Return the cost of zero-extending OP to mode MODE, not including the
3493    cost of OP itself.  */
3494
3495 static int
3496 mips_zero_extend_cost (enum machine_mode mode, rtx op)
3497 {
3498   if (MEM_P (op))
3499     /* Extended loads are as cheap as unextended ones.  */
3500     return 0;
3501
3502   if (TARGET_64BIT && mode == DImode && GET_MODE (op) == SImode)
3503     /* We need a shift left by 32 bits and a shift right by 32 bits.  */
3504     return COSTS_N_INSNS (TARGET_MIPS16 ? 4 : 2);
3505
3506   if (GENERATE_MIPS16E)
3507     /* We can use ZEB or ZEH.  */
3508     return COSTS_N_INSNS (1);
3509
3510   if (TARGET_MIPS16)
3511     /* We need to load 0xff or 0xffff into a register and use AND.  */
3512     return COSTS_N_INSNS (GET_MODE (op) == QImode ? 2 : 3);
3513
3514   /* We can use ANDI.  */
3515   return COSTS_N_INSNS (1);
3516 }
3517
3518 /* Implement TARGET_RTX_COSTS.  */
3519
3520 static bool
3521 mips_rtx_costs (rtx x, int code, int outer_code, int *total, bool speed)
3522 {
3523   enum machine_mode mode = GET_MODE (x);
3524   bool float_mode_p = FLOAT_MODE_P (mode);
3525   int cost;
3526   rtx addr;
3527
3528   /* The cost of a COMPARE is hard to define for MIPS.  COMPAREs don't
3529      appear in the instruction stream, and the cost of a comparison is
3530      really the cost of the branch or scc condition.  At the time of
3531      writing, GCC only uses an explicit outer COMPARE code when optabs
3532      is testing whether a constant is expensive enough to force into a
3533      register.  We want optabs to pass such constants through the MIPS
3534      expanders instead, so make all constants very cheap here.  */
3535   if (outer_code == COMPARE)
3536     {
3537       gcc_assert (CONSTANT_P (x));
3538       *total = 0;
3539       return true;
3540     }
3541
3542   switch (code)
3543     {
3544     case CONST_INT:
3545       /* Treat *clear_upper32-style ANDs as having zero cost in the
3546          second operand.  The cost is entirely in the first operand.
3547
3548          ??? This is needed because we would otherwise try to CSE
3549          the constant operand.  Although that's the right thing for
3550          instructions that continue to be a register operation throughout
3551          compilation, it is disastrous for instructions that could
3552          later be converted into a memory operation.  */
3553       if (TARGET_64BIT
3554           && outer_code == AND
3555           && UINTVAL (x) == 0xffffffff)
3556         {
3557           *total = 0;
3558           return true;
3559         }
3560
3561       if (TARGET_MIPS16)
3562         {
3563           cost = mips16_constant_cost (outer_code, INTVAL (x));
3564           if (cost >= 0)
3565             {
3566               *total = cost;
3567               return true;
3568             }
3569         }
3570       else
3571         {
3572           /* When not optimizing for size, we care more about the cost
3573              of hot code, and hot code is often in a loop.  If a constant
3574              operand needs to be forced into a register, we will often be
3575              able to hoist the constant load out of the loop, so the load
3576              should not contribute to the cost.  */
3577           if (speed || mips_immediate_operand_p (outer_code, INTVAL (x)))
3578             {
3579               *total = 0;
3580               return true;
3581             }
3582         }
3583       /* Fall through.  */
3584
3585     case CONST:
3586     case SYMBOL_REF:
3587     case LABEL_REF:
3588     case CONST_DOUBLE:
3589       if (force_to_mem_operand (x, VOIDmode))
3590         {
3591           *total = COSTS_N_INSNS (1);
3592           return true;
3593         }
3594       cost = mips_const_insns (x);
3595       if (cost > 0)
3596         {
3597           /* If the constant is likely to be stored in a GPR, SETs of
3598              single-insn constants are as cheap as register sets; we
3599              never want to CSE them.
3600
3601              Don't reduce the cost of storing a floating-point zero in
3602              FPRs.  If we have a zero in an FPR for other reasons, we
3603              can get better cfg-cleanup and delayed-branch results by
3604              using it consistently, rather than using $0 sometimes and
3605              an FPR at other times.  Also, moves between floating-point
3606              registers are sometimes cheaper than (D)MTC1 $0.  */
3607           if (cost == 1
3608               && outer_code == SET
3609               && !(float_mode_p && TARGET_HARD_FLOAT))
3610             cost = 0;
3611           /* When non-MIPS16 code loads a constant N>1 times, we rarely
3612              want to CSE the constant itself.  It is usually better to
3613              have N copies of the last operation in the sequence and one
3614              shared copy of the other operations.  (Note that this is
3615              not true for MIPS16 code, where the final operation in the
3616              sequence is often an extended instruction.)
3617
3618              Also, if we have a CONST_INT, we don't know whether it is
3619              for a word or doubleword operation, so we cannot rely on
3620              the result of mips_build_integer.  */
3621           else if (!TARGET_MIPS16
3622                    && (outer_code == SET || mode == VOIDmode))
3623             cost = 1;
3624           *total = COSTS_N_INSNS (cost);
3625           return true;
3626         }
3627       /* The value will need to be fetched from the constant pool.  */
3628       *total = CONSTANT_POOL_COST;
3629       return true;
3630
3631     case MEM:
3632       /* If the address is legitimate, return the number of
3633          instructions it needs.  */
3634       addr = XEXP (x, 0);
3635       cost = mips_address_insns (addr, mode, true);
3636       if (cost > 0)
3637         {
3638           *total = COSTS_N_INSNS (cost + 1);
3639           return true;
3640         }
3641       /* Check for a scaled indexed address.  */
3642       if (mips_lwxs_address_p (addr))
3643         {
3644           *total = COSTS_N_INSNS (2);
3645           return true;
3646         }
3647       /* Otherwise use the default handling.  */
3648       return false;
3649
3650     case FFS:
3651       *total = COSTS_N_INSNS (6);
3652       return false;
3653
3654     case NOT:
3655       *total = COSTS_N_INSNS (GET_MODE_SIZE (mode) > UNITS_PER_WORD ? 2 : 1);
3656       return false;
3657
3658     case AND:
3659       /* Check for a *clear_upper32 pattern and treat it like a zero
3660          extension.  See the pattern's comment for details.  */
3661       if (TARGET_64BIT
3662           && mode == DImode
3663           && CONST_INT_P (XEXP (x, 1))
3664           && UINTVAL (XEXP (x, 1)) == 0xffffffff)
3665         {
3666           *total = (mips_zero_extend_cost (mode, XEXP (x, 0))
3667                     + rtx_cost (XEXP (x, 0), SET, speed));
3668           return true;
3669         }
3670       /* Fall through.  */
3671
3672     case IOR:
3673     case XOR:
3674       /* Double-word operations use two single-word operations.  */
3675       *total = mips_binary_cost (x, COSTS_N_INSNS (1), COSTS_N_INSNS (2),
3676                                  speed);
3677       return true;
3678
3679     case ASHIFT:
3680     case ASHIFTRT:
3681     case LSHIFTRT:
3682     case ROTATE:
3683     case ROTATERT:
3684       if (CONSTANT_P (XEXP (x, 1)))
3685         *total = mips_binary_cost (x, COSTS_N_INSNS (1), COSTS_N_INSNS (4),
3686                                    speed);
3687       else
3688         *total = mips_binary_cost (x, COSTS_N_INSNS (1), COSTS_N_INSNS (12),
3689                                    speed);
3690       return true;
3691
3692     case ABS:
3693       if (float_mode_p)
3694         *total = mips_cost->fp_add;
3695       else
3696         *total = COSTS_N_INSNS (4);
3697       return false;
3698
3699     case LO_SUM:
3700       /* Low-part immediates need an extended MIPS16 instruction.  */
3701       *total = (COSTS_N_INSNS (TARGET_MIPS16 ? 2 : 1)
3702                 + rtx_cost (XEXP (x, 0), SET, speed));
3703       return true;
3704
3705     case LT:
3706     case LTU:
3707     case LE:
3708     case LEU:
3709     case GT:
3710     case GTU:
3711     case GE:
3712     case GEU:
3713     case EQ:
3714     case NE:
3715     case UNORDERED:
3716     case LTGT:
3717       /* Branch comparisons have VOIDmode, so use the first operand's
3718          mode instead.  */
3719       mode = GET_MODE (XEXP (x, 0));
3720       if (FLOAT_MODE_P (mode))
3721         {
3722           *total = mips_cost->fp_add;
3723           return false;
3724         }
3725       *total = mips_binary_cost (x, COSTS_N_INSNS (1), COSTS_N_INSNS (4),
3726                                  speed);
3727       return true;
3728
3729     case MINUS:
3730       if (float_mode_p
3731           && (ISA_HAS_NMADD4_NMSUB4 (mode) || ISA_HAS_NMADD3_NMSUB3 (mode))
3732           && TARGET_FUSED_MADD
3733           && !HONOR_NANS (mode)
3734           && !HONOR_SIGNED_ZEROS (mode))
3735         {
3736           /* See if we can use NMADD or NMSUB.  See mips.md for the
3737              associated patterns.  */
3738           rtx op0 = XEXP (x, 0);
3739           rtx op1 = XEXP (x, 1);
3740           if (GET_CODE (op0) == MULT && GET_CODE (XEXP (op0, 0)) == NEG)
3741             {
3742               *total = (mips_fp_mult_cost (mode)
3743                         + rtx_cost (XEXP (XEXP (op0, 0), 0), SET, speed)
3744                         + rtx_cost (XEXP (op0, 1), SET, speed)
3745                         + rtx_cost (op1, SET, speed));
3746               return true;
3747             }
3748           if (GET_CODE (op1) == MULT)
3749             {
3750               *total = (mips_fp_mult_cost (mode)
3751                         + rtx_cost (op0, SET, speed)
3752                         + rtx_cost (XEXP (op1, 0), SET, speed)
3753                         + rtx_cost (XEXP (op1, 1), SET, speed));
3754               return true;
3755             }
3756         }
3757       /* Fall through.  */
3758
3759     case PLUS:
3760       if (float_mode_p)
3761         {
3762           /* If this is part of a MADD or MSUB, treat the PLUS as
3763              being free.  */
3764           if (ISA_HAS_FP4
3765               && TARGET_FUSED_MADD
3766               && GET_CODE (XEXP (x, 0)) == MULT)
3767             *total = 0;
3768           else
3769             *total = mips_cost->fp_add;
3770           return false;
3771         }
3772
3773       /* Double-word operations require three single-word operations and
3774          an SLTU.  The MIPS16 version then needs to move the result of
3775          the SLTU from $24 to a MIPS16 register.  */
3776       *total = mips_binary_cost (x, COSTS_N_INSNS (1),
3777                                  COSTS_N_INSNS (TARGET_MIPS16 ? 5 : 4),
3778                                  speed);
3779       return true;
3780
3781     case NEG:
3782       if (float_mode_p
3783           && (ISA_HAS_NMADD4_NMSUB4 (mode) || ISA_HAS_NMADD3_NMSUB3 (mode))
3784           && TARGET_FUSED_MADD
3785           && !HONOR_NANS (mode)
3786           && HONOR_SIGNED_ZEROS (mode))
3787         {
3788           /* See if we can use NMADD or NMSUB.  See mips.md for the
3789              associated patterns.  */
3790           rtx op = XEXP (x, 0);
3791           if ((GET_CODE (op) == PLUS || GET_CODE (op) == MINUS)
3792               && GET_CODE (XEXP (op, 0)) == MULT)
3793             {
3794               *total = (mips_fp_mult_cost (mode)
3795                         + rtx_cost (XEXP (XEXP (op, 0), 0), SET, speed)
3796                         + rtx_cost (XEXP (XEXP (op, 0), 1), SET, speed)
3797                         + rtx_cost (XEXP (op, 1), SET, speed));
3798               return true;
3799             }
3800         }
3801
3802       if (float_mode_p)
3803         *total = mips_cost->fp_add;
3804       else
3805         *total = COSTS_N_INSNS (GET_MODE_SIZE (mode) > UNITS_PER_WORD ? 4 : 1);
3806       return false;
3807
3808     case MULT:
3809       if (float_mode_p)
3810         *total = mips_fp_mult_cost (mode);
3811       else if (mode == DImode && !TARGET_64BIT)
3812         /* Synthesized from 2 mulsi3s, 1 mulsidi3 and two additions,
3813            where the mulsidi3 always includes an MFHI and an MFLO.  */
3814         *total = (speed
3815                   ? mips_cost->int_mult_si * 3 + 6
3816                   : COSTS_N_INSNS (ISA_HAS_MUL3 ? 7 : 9));
3817       else if (!speed)
3818         *total = (ISA_HAS_MUL3 ? 1 : 2);
3819       else if (mode == DImode)
3820         *total = mips_cost->int_mult_di;
3821       else
3822         *total = mips_cost->int_mult_si;
3823       return false;
3824
3825     case DIV:
3826       /* Check for a reciprocal.  */
3827       if (float_mode_p
3828           && ISA_HAS_FP4
3829           && flag_unsafe_math_optimizations
3830           && XEXP (x, 0) == CONST1_RTX (mode))
3831         {
3832           if (outer_code == SQRT || GET_CODE (XEXP (x, 1)) == SQRT)
3833             /* An rsqrt<mode>a or rsqrt<mode>b pattern.  Count the
3834                division as being free.  */
3835             *total = rtx_cost (XEXP (x, 1), SET, speed);
3836           else
3837             *total = (mips_fp_div_cost (mode)
3838                       + rtx_cost (XEXP (x, 1), SET, speed));
3839           return true;
3840         }
3841       /* Fall through.  */
3842
3843     case SQRT:
3844     case MOD:
3845       if (float_mode_p)
3846         {
3847           *total = mips_fp_div_cost (mode);
3848           return false;
3849         }
3850       /* Fall through.  */
3851
3852     case UDIV:
3853     case UMOD:
3854       if (!speed)
3855         {
3856           /* It is our responsibility to make division by a power of 2
3857              as cheap as 2 register additions if we want the division
3858              expanders to be used for such operations; see the setting
3859              of sdiv_pow2_cheap in optabs.c.  Using (D)DIV for MIPS16
3860              should always produce shorter code than using
3861              expand_sdiv2_pow2.  */
3862           if (TARGET_MIPS16
3863               && CONST_INT_P (XEXP (x, 1))
3864               && exact_log2 (INTVAL (XEXP (x, 1))) >= 0)
3865             {
3866               *total = COSTS_N_INSNS (2) + rtx_cost (XEXP (x, 0), SET, speed);
3867               return true;
3868             }
3869           *total = COSTS_N_INSNS (mips_idiv_insns ());
3870         }
3871       else if (mode == DImode)
3872         *total = mips_cost->int_div_di;
3873       else
3874         *total = mips_cost->int_div_si;
3875       return false;
3876
3877     case SIGN_EXTEND:
3878       *total = mips_sign_extend_cost (mode, XEXP (x, 0));
3879       return false;
3880
3881     case ZERO_EXTEND:
3882       *total = mips_zero_extend_cost (mode, XEXP (x, 0));
3883       return false;
3884
3885     case FLOAT:
3886     case UNSIGNED_FLOAT:
3887     case FIX:
3888     case FLOAT_EXTEND:
3889     case FLOAT_TRUNCATE:
3890       *total = mips_cost->fp_add;
3891       return false;
3892
3893     default:
3894       return false;
3895     }
3896 }
3897
3898 /* Implement TARGET_ADDRESS_COST.  */
3899
3900 static int
3901 mips_address_cost (rtx addr, bool speed ATTRIBUTE_UNUSED)
3902 {
3903   return mips_address_insns (addr, SImode, false);
3904 }
3905 \f
3906 /* Information about a single instruction in a multi-instruction
3907    asm sequence.  */
3908 struct mips_multi_member {
3909   /* True if this is a label, false if it is code.  */
3910   bool is_label_p;
3911
3912   /* The output_asm_insn format of the instruction.  */
3913   const char *format;
3914
3915   /* The operands to the instruction.  */
3916   rtx operands[MAX_RECOG_OPERANDS];
3917 };
3918 typedef struct mips_multi_member mips_multi_member;
3919
3920 /* Vector definitions for the above.  */
3921 DEF_VEC_O(mips_multi_member);
3922 DEF_VEC_ALLOC_O(mips_multi_member, heap);
3923
3924 /* The instructions that make up the current multi-insn sequence.  */
3925 static VEC (mips_multi_member, heap) *mips_multi_members;
3926
3927 /* How many instructions (as opposed to labels) are in the current
3928    multi-insn sequence.  */
3929 static unsigned int mips_multi_num_insns;
3930
3931 /* Start a new multi-insn sequence.  */
3932
3933 static void
3934 mips_multi_start (void)
3935 {
3936   VEC_truncate (mips_multi_member, mips_multi_members, 0);
3937   mips_multi_num_insns = 0;
3938 }
3939
3940 /* Add a new, uninitialized member to the current multi-insn sequence.  */
3941
3942 static struct mips_multi_member *
3943 mips_multi_add (void)
3944 {
3945   return VEC_safe_push (mips_multi_member, heap, mips_multi_members, 0);
3946 }
3947
3948 /* Add a normal insn with the given asm format to the current multi-insn
3949    sequence.  The other arguments are a null-terminated list of operands.  */
3950
3951 static void
3952 mips_multi_add_insn (const char *format, ...)
3953 {
3954   struct mips_multi_member *member;
3955   va_list ap;
3956   unsigned int i;
3957   rtx op;
3958
3959   member = mips_multi_add ();
3960   member->is_label_p = false;
3961   member->format = format;
3962   va_start (ap, format);
3963   i = 0;
3964   while ((op = va_arg (ap, rtx)))
3965     member->operands[i++] = op;
3966   va_end (ap);
3967   mips_multi_num_insns++;
3968 }
3969
3970 /* Add the given label definition to the current multi-insn sequence.
3971    The definition should include the colon.  */
3972
3973 static void
3974 mips_multi_add_label (const char *label)
3975 {
3976   struct mips_multi_member *member;
3977
3978   member = mips_multi_add ();
3979   member->is_label_p = true;
3980   member->format = label;
3981 }
3982
3983 /* Return the index of the last member of the current multi-insn sequence.  */
3984
3985 static unsigned int
3986 mips_multi_last_index (void)
3987 {
3988   return VEC_length (mips_multi_member, mips_multi_members) - 1;
3989 }
3990
3991 /* Add a copy of an existing instruction to the current multi-insn
3992    sequence.  I is the index of the instruction that should be copied.  */
3993
3994 static void
3995 mips_multi_copy_insn (unsigned int i)
3996 {
3997   struct mips_multi_member *member;
3998
3999   member = mips_multi_add ();
4000   memcpy (member, VEC_index (mips_multi_member, mips_multi_members, i),
4001           sizeof (*member));
4002   gcc_assert (!member->is_label_p);
4003 }
4004
4005 /* Change the operand of an existing instruction in the current
4006    multi-insn sequence.  I is the index of the instruction,
4007    OP is the index of the operand, and X is the new value.  */
4008
4009 static void
4010 mips_multi_set_operand (unsigned int i, unsigned int op, rtx x)
4011 {
4012   VEC_index (mips_multi_member, mips_multi_members, i)->operands[op] = x;
4013 }
4014
4015 /* Write out the asm code for the current multi-insn sequence.  */
4016
4017 static void
4018 mips_multi_write (void)
4019 {
4020   struct mips_multi_member *member;
4021   unsigned int i;
4022
4023   FOR_EACH_VEC_ELT (mips_multi_member, mips_multi_members, i, member)
4024     if (member->is_label_p)
4025       fprintf (asm_out_file, "%s\n", member->format);
4026     else
4027       output_asm_insn (member->format, member->operands);
4028 }
4029 \f
4030 /* Return one word of double-word value OP, taking into account the fixed
4031    endianness of certain registers.  HIGH_P is true to select the high part,
4032    false to select the low part.  */
4033
4034 rtx
4035 mips_subword (rtx op, bool high_p)
4036 {
4037   unsigned int byte, offset;
4038   enum machine_mode mode;
4039
4040   mode = GET_MODE (op);
4041   if (mode == VOIDmode)
4042     mode = TARGET_64BIT ? TImode : DImode;
4043
4044   if (TARGET_BIG_ENDIAN ? !high_p : high_p)
4045     byte = UNITS_PER_WORD;
4046   else
4047     byte = 0;
4048
4049   if (FP_REG_RTX_P (op))
4050     {
4051       /* Paired FPRs are always ordered little-endian.  */
4052       offset = (UNITS_PER_WORD < UNITS_PER_HWFPVALUE ? high_p : byte != 0);
4053       return gen_rtx_REG (word_mode, REGNO (op) + offset);
4054     }
4055
4056   if (MEM_P (op))
4057     return mips_rewrite_small_data (adjust_address (op, word_mode, byte));
4058
4059   return simplify_gen_subreg (word_mode, op, mode, byte);
4060 }
4061
4062 /* Return true if a 64-bit move from SRC to DEST should be split into two.  */
4063
4064 bool
4065 mips_split_64bit_move_p (rtx dest, rtx src)
4066 {
4067   if (TARGET_64BIT)
4068     return false;
4069
4070   /* FPR-to-FPR moves can be done in a single instruction, if they're
4071      allowed at all.  */
4072   if (FP_REG_RTX_P (src) && FP_REG_RTX_P (dest))
4073     return false;
4074
4075   /* Check for floating-point loads and stores.  */
4076   if (ISA_HAS_LDC1_SDC1)
4077     {
4078       if (FP_REG_RTX_P (dest) && MEM_P (src))
4079         return false;
4080       if (FP_REG_RTX_P (src) && MEM_P (dest))
4081         return false;
4082     }
4083   return true;
4084 }
4085
4086 /* Split a doubleword move from SRC to DEST.  On 32-bit targets,
4087    this function handles 64-bit moves for which mips_split_64bit_move_p
4088    holds.  For 64-bit targets, this function handles 128-bit moves.  */
4089
4090 void
4091 mips_split_doubleword_move (rtx dest, rtx src)
4092 {
4093   rtx low_dest;
4094
4095   if (FP_REG_RTX_P (dest) || FP_REG_RTX_P (src))
4096     {
4097       if (!TARGET_64BIT && GET_MODE (dest) == DImode)
4098         emit_insn (gen_move_doubleword_fprdi (dest, src));
4099       else if (!TARGET_64BIT && GET_MODE (dest) == DFmode)
4100         emit_insn (gen_move_doubleword_fprdf (dest, src));
4101       else if (!TARGET_64BIT && GET_MODE (dest) == V2SFmode)
4102         emit_insn (gen_move_doubleword_fprv2sf (dest, src));
4103       else if (!TARGET_64BIT && GET_MODE (dest) == V2SImode)
4104         emit_insn (gen_move_doubleword_fprv2si (dest, src));
4105       else if (!TARGET_64BIT && GET_MODE (dest) == V4HImode)
4106         emit_insn (gen_move_doubleword_fprv4hi (dest, src));
4107       else if (!TARGET_64BIT && GET_MODE (dest) == V8QImode)
4108         emit_insn (gen_move_doubleword_fprv8qi (dest, src));
4109       else if (TARGET_64BIT && GET_MODE (dest) == TFmode)
4110         emit_insn (gen_move_doubleword_fprtf (dest, src));
4111       else
4112         gcc_unreachable ();
4113     }
4114   else if (REG_P (dest) && REGNO (dest) == MD_REG_FIRST)
4115     {
4116       low_dest = mips_subword (dest, false);
4117       mips_emit_move (low_dest, mips_subword (src, false));
4118       if (TARGET_64BIT)
4119         emit_insn (gen_mthidi_ti (dest, mips_subword (src, true), low_dest));
4120       else
4121         emit_insn (gen_mthisi_di (dest, mips_subword (src, true), low_dest));
4122     }
4123   else if (REG_P (src) && REGNO (src) == MD_REG_FIRST)
4124     {
4125       mips_emit_move (mips_subword (dest, false), mips_subword (src, false));
4126       if (TARGET_64BIT)
4127         emit_insn (gen_mfhidi_ti (mips_subword (dest, true), src));
4128       else
4129         emit_insn (gen_mfhisi_di (mips_subword (dest, true), src));
4130     }
4131   else
4132     {
4133       /* The operation can be split into two normal moves.  Decide in
4134          which order to do them.  */
4135       low_dest = mips_subword (dest, false);
4136       if (REG_P (low_dest)
4137           && reg_overlap_mentioned_p (low_dest, src))
4138         {
4139           mips_emit_move (mips_subword (dest, true), mips_subword (src, true));
4140           mips_emit_move (low_dest, mips_subword (src, false));
4141         }
4142       else
4143         {
4144           mips_emit_move (low_dest, mips_subword (src, false));
4145           mips_emit_move (mips_subword (dest, true), mips_subword (src, true));
4146         }
4147     }
4148 }
4149 \f
4150 /* Return the appropriate instructions to move SRC into DEST.  Assume
4151    that SRC is operand 1 and DEST is operand 0.  */
4152
4153 const char *
4154 mips_output_move (rtx dest, rtx src)
4155 {
4156   enum rtx_code dest_code, src_code;
4157   enum machine_mode mode;
4158   enum mips_symbol_type symbol_type;
4159   bool dbl_p;
4160
4161   dest_code = GET_CODE (dest);
4162   src_code = GET_CODE (src);
4163   mode = GET_MODE (dest);
4164   dbl_p = (GET_MODE_SIZE (mode) == 8);
4165
4166   if (dbl_p && mips_split_64bit_move_p (dest, src))
4167     return "#";
4168
4169   if ((src_code == REG && GP_REG_P (REGNO (src)))
4170       || (!TARGET_MIPS16 && src == CONST0_RTX (mode)))
4171     {
4172       if (dest_code == REG)
4173         {
4174           if (GP_REG_P (REGNO (dest)))
4175             return "move\t%0,%z1";
4176
4177           /* Moves to HI are handled by special .md insns.  */
4178           if (REGNO (dest) == LO_REGNUM)
4179             return "mtlo\t%z1";
4180
4181           if (DSP_ACC_REG_P (REGNO (dest)))
4182             {
4183               static char retval[] = "mt__\t%z1,%q0";
4184
4185               retval[2] = reg_names[REGNO (dest)][4];
4186               retval[3] = reg_names[REGNO (dest)][5];
4187               return retval;
4188             }
4189
4190           if (FP_REG_P (REGNO (dest)))
4191             return dbl_p ? "dmtc1\t%z1,%0" : "mtc1\t%z1,%0";
4192
4193           if (ALL_COP_REG_P (REGNO (dest)))
4194             {
4195               static char retval[] = "dmtc_\t%z1,%0";
4196
4197               retval[4] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (dest));
4198               return dbl_p ? retval : retval + 1;
4199             }
4200         }
4201       if (dest_code == MEM)
4202         switch (GET_MODE_SIZE (mode))
4203           {
4204           case 1: return "sb\t%z1,%0";
4205           case 2: return "sh\t%z1,%0";
4206           case 4: return "sw\t%z1,%0";
4207           case 8: return "sd\t%z1,%0";
4208           }
4209     }
4210   if (dest_code == REG && GP_REG_P (REGNO (dest)))
4211     {
4212       if (src_code == REG)
4213         {
4214           /* Moves from HI are handled by special .md insns.  */
4215           if (REGNO (src) == LO_REGNUM)
4216             {
4217               /* When generating VR4120 or VR4130 code, we use MACC and
4218                  DMACC instead of MFLO.  This avoids both the normal
4219                  MIPS III HI/LO hazards and the errata related to
4220                  -mfix-vr4130.  */
4221               if (ISA_HAS_MACCHI)
4222                 return dbl_p ? "dmacc\t%0,%.,%." : "macc\t%0,%.,%.";
4223               return "mflo\t%0";
4224             }
4225
4226           if (DSP_ACC_REG_P (REGNO (src)))
4227             {
4228               static char retval[] = "mf__\t%0,%q1";
4229
4230               retval[2] = reg_names[REGNO (src)][4];
4231               retval[3] = reg_names[REGNO (src)][5];
4232               return retval;
4233             }
4234
4235           if (FP_REG_P (REGNO (src)))
4236             return dbl_p ? "dmfc1\t%0,%1" : "mfc1\t%0,%1";
4237
4238           if (ALL_COP_REG_P (REGNO (src)))
4239             {
4240               static char retval[] = "dmfc_\t%0,%1";
4241
4242               retval[4] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (src));
4243               return dbl_p ? retval : retval + 1;
4244             }
4245
4246           if (ST_REG_P (REGNO (src)) && ISA_HAS_8CC)
4247             return "lui\t%0,0x3f80\n\tmovf\t%0,%.,%1";
4248         }
4249
4250       if (src_code == MEM)
4251         switch (GET_MODE_SIZE (mode))
4252           {
4253           case 1: return "lbu\t%0,%1";
4254           case 2: return "lhu\t%0,%1";
4255           case 4: return "lw\t%0,%1";
4256           case 8: return "ld\t%0,%1";
4257           }
4258
4259       if (src_code == CONST_INT)
4260         {
4261           /* Don't use the X format for the operand itself, because that
4262              will give out-of-range numbers for 64-bit hosts and 32-bit
4263              targets.  */
4264           if (!TARGET_MIPS16)
4265             return "li\t%0,%1\t\t\t# %X1";
4266
4267           if (SMALL_OPERAND_UNSIGNED (INTVAL (src)))
4268             return "li\t%0,%1";
4269
4270           if (SMALL_OPERAND_UNSIGNED (-INTVAL (src)))
4271             return "#";
4272         }
4273
4274       if (src_code == HIGH)
4275         return TARGET_MIPS16 ? "#" : "lui\t%0,%h1";
4276
4277       if (CONST_GP_P (src))
4278         return "move\t%0,%1";
4279
4280       if (mips_symbolic_constant_p (src, SYMBOL_CONTEXT_LEA, &symbol_type)
4281           && mips_lo_relocs[symbol_type] != 0)
4282         {
4283           /* A signed 16-bit constant formed by applying a relocation
4284              operator to a symbolic address.  */
4285           gcc_assert (!mips_split_p[symbol_type]);
4286           return "li\t%0,%R1";
4287         }
4288
4289       if (symbolic_operand (src, VOIDmode))
4290         {
4291           gcc_assert (TARGET_MIPS16
4292                       ? TARGET_MIPS16_TEXT_LOADS
4293                       : !TARGET_EXPLICIT_RELOCS);
4294           return dbl_p ? "dla\t%0,%1" : "la\t%0,%1";
4295         }
4296     }
4297   if (src_code == REG && FP_REG_P (REGNO (src)))
4298     {
4299       if (dest_code == REG && FP_REG_P (REGNO (dest)))
4300         {
4301           if (GET_MODE (dest) == V2SFmode)
4302             return "mov.ps\t%0,%1";
4303           else
4304             return dbl_p ? "mov.d\t%0,%1" : "mov.s\t%0,%1";
4305         }
4306
4307       if (dest_code == MEM)
4308         return dbl_p ? "sdc1\t%1,%0" : "swc1\t%1,%0";
4309     }
4310   if (dest_code == REG && FP_REG_P (REGNO (dest)))
4311     {
4312       if (src_code == MEM)
4313         return dbl_p ? "ldc1\t%0,%1" : "lwc1\t%0,%1";
4314     }
4315   if (dest_code == REG && ALL_COP_REG_P (REGNO (dest)) && src_code == MEM)
4316     {
4317       static char retval[] = "l_c_\t%0,%1";
4318
4319       retval[1] = (dbl_p ? 'd' : 'w');
4320       retval[3] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (dest));
4321       return retval;
4322     }
4323   if (dest_code == MEM && src_code == REG && ALL_COP_REG_P (REGNO (src)))
4324     {
4325       static char retval[] = "s_c_\t%1,%0";
4326
4327       retval[1] = (dbl_p ? 'd' : 'w');
4328       retval[3] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (src));
4329       return retval;
4330     }
4331   gcc_unreachable ();
4332 }
4333 \f
4334 /* Return true if CMP1 is a suitable second operand for integer ordering
4335    test CODE.  See also the *sCC patterns in mips.md.  */
4336
4337 static bool
4338 mips_int_order_operand_ok_p (enum rtx_code code, rtx cmp1)
4339 {
4340   switch (code)
4341     {
4342     case GT:
4343     case GTU:
4344       return reg_or_0_operand (cmp1, VOIDmode);
4345
4346     case GE:
4347     case GEU:
4348       return !TARGET_MIPS16 && cmp1 == const1_rtx;
4349
4350     case LT:
4351     case LTU:
4352       return arith_operand (cmp1, VOIDmode);
4353
4354     case LE:
4355       return sle_operand (cmp1, VOIDmode);
4356
4357     case LEU:
4358       return sleu_operand (cmp1, VOIDmode);
4359
4360     default:
4361       gcc_unreachable ();
4362     }
4363 }
4364
4365 /* Return true if *CMP1 (of mode MODE) is a valid second operand for
4366    integer ordering test *CODE, or if an equivalent combination can
4367    be formed by adjusting *CODE and *CMP1.  When returning true, update
4368    *CODE and *CMP1 with the chosen code and operand, otherwise leave
4369    them alone.  */
4370
4371 static bool
4372 mips_canonicalize_int_order_test (enum rtx_code *code, rtx *cmp1,
4373                                   enum machine_mode mode)
4374 {
4375   HOST_WIDE_INT plus_one;
4376
4377   if (mips_int_order_operand_ok_p (*code, *cmp1))
4378     return true;
4379
4380   if (CONST_INT_P (*cmp1))
4381     switch (*code)
4382       {
4383       case LE:
4384         plus_one = trunc_int_for_mode (UINTVAL (*cmp1) + 1, mode);
4385         if (INTVAL (*cmp1) < plus_one)
4386           {
4387             *code = LT;
4388             *cmp1 = force_reg (mode, GEN_INT (plus_one));
4389             return true;
4390           }
4391         break;
4392
4393       case LEU:
4394         plus_one = trunc_int_for_mode (UINTVAL (*cmp1) + 1, mode);
4395         if (plus_one != 0)
4396           {
4397             *code = LTU;
4398             *cmp1 = force_reg (mode, GEN_INT (plus_one));
4399             return true;
4400           }
4401         break;
4402
4403       default:
4404         break;
4405       }
4406   return false;
4407 }
4408
4409 /* Compare CMP0 and CMP1 using ordering test CODE and store the result
4410    in TARGET.  CMP0 and TARGET are register_operands.  If INVERT_PTR
4411    is nonnull, it's OK to set TARGET to the inverse of the result and
4412    flip *INVERT_PTR instead.  */
4413
4414 static void
4415 mips_emit_int_order_test (enum rtx_code code, bool *invert_ptr,
4416                           rtx target, rtx cmp0, rtx cmp1)
4417 {
4418   enum machine_mode mode;
4419
4420   /* First see if there is a MIPS instruction that can do this operation.
4421      If not, try doing the same for the inverse operation.  If that also
4422      fails, force CMP1 into a register and try again.  */
4423   mode = GET_MODE (cmp0);
4424   if (mips_canonicalize_int_order_test (&code, &cmp1, mode))
4425     mips_emit_binary (code, target, cmp0, cmp1);
4426   else
4427     {
4428       enum rtx_code inv_code = reverse_condition (code);
4429       if (!mips_canonicalize_int_order_test (&inv_code, &cmp1, mode))
4430         {
4431           cmp1 = force_reg (mode, cmp1);
4432           mips_emit_int_order_test (code, invert_ptr, target, cmp0, cmp1);
4433         }
4434       else if (invert_ptr == 0)
4435         {
4436           rtx inv_target;
4437
4438           inv_target = mips_force_binary (GET_MODE (target),
4439                                           inv_code, cmp0, cmp1);
4440           mips_emit_binary (XOR, target, inv_target, const1_rtx);
4441         }
4442       else
4443         {
4444           *invert_ptr = !*invert_ptr;
4445           mips_emit_binary (inv_code, target, cmp0, cmp1);
4446         }
4447     }
4448 }
4449
4450 /* Return a register that is zero iff CMP0 and CMP1 are equal.
4451    The register will have the same mode as CMP0.  */
4452
4453 static rtx
4454 mips_zero_if_equal (rtx cmp0, rtx cmp1)
4455 {
4456   if (cmp1 == const0_rtx)
4457     return cmp0;
4458
4459   if (uns_arith_operand (cmp1, VOIDmode))
4460     return expand_binop (GET_MODE (cmp0), xor_optab,
4461                          cmp0, cmp1, 0, 0, OPTAB_DIRECT);
4462
4463   return expand_binop (GET_MODE (cmp0), sub_optab,
4464                        cmp0, cmp1, 0, 0, OPTAB_DIRECT);
4465 }
4466
4467 /* Convert *CODE into a code that can be used in a floating-point
4468    scc instruction (C.cond.fmt).  Return true if the values of
4469    the condition code registers will be inverted, with 0 indicating
4470    that the condition holds.  */
4471
4472 static bool
4473 mips_reversed_fp_cond (enum rtx_code *code)
4474 {
4475   switch (*code)
4476     {
4477     case NE:
4478     case LTGT:
4479     case ORDERED:
4480       *code = reverse_condition_maybe_unordered (*code);
4481       return true;
4482
4483     default:
4484       return false;
4485     }
4486 }
4487
4488 /* Convert a comparison into something that can be used in a branch or
4489    conditional move.  On entry, *OP0 and *OP1 are the values being
4490    compared and *CODE is the code used to compare them.
4491
4492    Update *CODE, *OP0 and *OP1 so that they describe the final comparison.
4493    If NEED_EQ_NE_P, then only EQ or NE comparisons against zero are possible,
4494    otherwise any standard branch condition can be used.  The standard branch
4495    conditions are:
4496
4497       - EQ or NE between two registers.
4498       - any comparison between a register and zero.  */
4499
4500 static void
4501 mips_emit_compare (enum rtx_code *code, rtx *op0, rtx *op1, bool need_eq_ne_p)
4502 {
4503   rtx cmp_op0 = *op0;
4504   rtx cmp_op1 = *op1;
4505
4506   if (GET_MODE_CLASS (GET_MODE (*op0)) == MODE_INT)
4507     {
4508       if (!need_eq_ne_p && *op1 == const0_rtx)
4509         ;
4510       else if (*code == EQ || *code == NE)
4511         {
4512           if (need_eq_ne_p)
4513             {
4514               *op0 = mips_zero_if_equal (cmp_op0, cmp_op1);
4515               *op1 = const0_rtx;
4516             }
4517           else
4518             *op1 = force_reg (GET_MODE (cmp_op0), cmp_op1);
4519         }
4520       else
4521         {
4522           /* The comparison needs a separate scc instruction.  Store the
4523              result of the scc in *OP0 and compare it against zero.  */
4524           bool invert = false;
4525           *op0 = gen_reg_rtx (GET_MODE (cmp_op0));
4526           mips_emit_int_order_test (*code, &invert, *op0, cmp_op0, cmp_op1);
4527           *code = (invert ? EQ : NE);
4528           *op1 = const0_rtx;
4529         }
4530     }
4531   else if (ALL_FIXED_POINT_MODE_P (GET_MODE (cmp_op0)))
4532     {
4533       *op0 = gen_rtx_REG (CCDSPmode, CCDSP_CC_REGNUM);
4534       mips_emit_binary (*code, *op0, cmp_op0, cmp_op1);
4535       *code = NE;
4536       *op1 = const0_rtx;
4537     }
4538   else
4539     {
4540       enum rtx_code cmp_code;
4541
4542       /* Floating-point tests use a separate C.cond.fmt comparison to
4543          set a condition code register.  The branch or conditional move
4544          will then compare that register against zero.
4545
4546          Set CMP_CODE to the code of the comparison instruction and
4547          *CODE to the code that the branch or move should use.  */
4548       cmp_code = *code;
4549       *code = mips_reversed_fp_cond (&cmp_code) ? EQ : NE;
4550       *op0 = (ISA_HAS_8CC
4551               ? gen_reg_rtx (CCmode)
4552               : gen_rtx_REG (CCmode, FPSW_REGNUM));
4553       *op1 = const0_rtx;
4554       mips_emit_binary (cmp_code, *op0, cmp_op0, cmp_op1);
4555     }
4556 }
4557 \f
4558 /* Try performing the comparison in OPERANDS[1], whose arms are OPERANDS[2]
4559    and OPERAND[3].  Store the result in OPERANDS[0].
4560
4561    On 64-bit targets, the mode of the comparison and target will always be
4562    SImode, thus possibly narrower than that of the comparison's operands.  */
4563
4564 void
4565 mips_expand_scc (rtx operands[])
4566 {
4567   rtx target = operands[0];
4568   enum rtx_code code = GET_CODE (operands[1]);
4569   rtx op0 = operands[2];
4570   rtx op1 = operands[3];
4571
4572   gcc_assert (GET_MODE_CLASS (GET_MODE (op0)) == MODE_INT);
4573
4574   if (code == EQ || code == NE)
4575     {
4576       if (ISA_HAS_SEQ_SNE
4577           && reg_imm10_operand (op1, GET_MODE (op1)))
4578         mips_emit_binary (code, target, op0, op1);
4579       else
4580         {
4581           rtx zie = mips_zero_if_equal (op0, op1);
4582           mips_emit_binary (code, target, zie, const0_rtx);
4583         }
4584     }
4585   else
4586     mips_emit_int_order_test (code, 0, target, op0, op1);
4587 }
4588
4589 /* Compare OPERANDS[1] with OPERANDS[2] using comparison code
4590    CODE and jump to OPERANDS[3] if the condition holds.  */
4591
4592 void
4593 mips_expand_conditional_branch (rtx *operands)
4594 {
4595   enum rtx_code code = GET_CODE (operands[0]);
4596   rtx op0 = operands[1];
4597   rtx op1 = operands[2];
4598   rtx condition;
4599
4600   mips_emit_compare (&code, &op0, &op1, TARGET_MIPS16);
4601   condition = gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
4602   emit_jump_insn (gen_condjump (condition, operands[3]));
4603 }
4604
4605 /* Implement:
4606
4607    (set temp (COND:CCV2 CMP_OP0 CMP_OP1))
4608    (set DEST (unspec [TRUE_SRC FALSE_SRC temp] UNSPEC_MOVE_TF_PS))  */
4609
4610 void
4611 mips_expand_vcondv2sf (rtx dest, rtx true_src, rtx false_src,
4612                        enum rtx_code cond, rtx cmp_op0, rtx cmp_op1)
4613 {
4614   rtx cmp_result;
4615   bool reversed_p;
4616
4617   reversed_p = mips_reversed_fp_cond (&cond);
4618   cmp_result = gen_reg_rtx (CCV2mode);
4619   emit_insn (gen_scc_ps (cmp_result,
4620                          gen_rtx_fmt_ee (cond, VOIDmode, cmp_op0, cmp_op1)));
4621   if (reversed_p)
4622     emit_insn (gen_mips_cond_move_tf_ps (dest, false_src, true_src,
4623                                          cmp_result));
4624   else
4625     emit_insn (gen_mips_cond_move_tf_ps (dest, true_src, false_src,
4626                                          cmp_result));
4627 }
4628
4629 /* Perform the comparison in OPERANDS[1].  Move OPERANDS[2] into OPERANDS[0]
4630    if the condition holds, otherwise move OPERANDS[3] into OPERANDS[0].  */
4631
4632 void
4633 mips_expand_conditional_move (rtx *operands)
4634 {
4635   rtx cond;
4636   enum rtx_code code = GET_CODE (operands[1]);
4637   rtx op0 = XEXP (operands[1], 0);
4638   rtx op1 = XEXP (operands[1], 1);
4639
4640   mips_emit_compare (&code, &op0, &op1, true);
4641   cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
4642   emit_insn (gen_rtx_SET (VOIDmode, operands[0],
4643                           gen_rtx_IF_THEN_ELSE (GET_MODE (operands[0]), cond,
4644                                                 operands[2], operands[3])));
4645 }
4646
4647 /* Perform the comparison in COMPARISON, then trap if the condition holds.  */
4648
4649 void
4650 mips_expand_conditional_trap (rtx comparison)
4651 {
4652   rtx op0, op1;
4653   enum machine_mode mode;
4654   enum rtx_code code;
4655
4656   /* MIPS conditional trap instructions don't have GT or LE flavors,
4657      so we must swap the operands and convert to LT and GE respectively.  */
4658   code = GET_CODE (comparison);
4659   switch (code)
4660     {
4661     case GT:
4662     case LE:
4663     case GTU:
4664     case LEU:
4665       code = swap_condition (code);
4666       op0 = XEXP (comparison, 1);
4667       op1 = XEXP (comparison, 0);
4668       break;
4669
4670     default:
4671       op0 = XEXP (comparison, 0);
4672       op1 = XEXP (comparison, 1);
4673       break;
4674     }
4675
4676   mode = GET_MODE (XEXP (comparison, 0));
4677   op0 = force_reg (mode, op0);
4678   if (!arith_operand (op1, mode))
4679     op1 = force_reg (mode, op1);
4680
4681   emit_insn (gen_rtx_TRAP_IF (VOIDmode,
4682                               gen_rtx_fmt_ee (code, mode, op0, op1),
4683                               const0_rtx));
4684 }
4685 \f
4686 /* Initialize *CUM for a call to a function of type FNTYPE.  */
4687
4688 void
4689 mips_init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype)
4690 {
4691   memset (cum, 0, sizeof (*cum));
4692   cum->prototype = (fntype && prototype_p (fntype));
4693   cum->gp_reg_found = (cum->prototype && stdarg_p (fntype));
4694 }
4695
4696 /* Fill INFO with information about a single argument.  CUM is the
4697    cumulative state for earlier arguments.  MODE is the mode of this
4698    argument and TYPE is its type (if known).  NAMED is true if this
4699    is a named (fixed) argument rather than a variable one.  */
4700
4701 static void
4702 mips_get_arg_info (struct mips_arg_info *info, const CUMULATIVE_ARGS *cum,
4703                    enum machine_mode mode, const_tree type, bool named)
4704 {
4705   bool doubleword_aligned_p;
4706   unsigned int num_bytes, num_words, max_regs;
4707
4708   /* Work out the size of the argument.  */
4709   num_bytes = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode);
4710   num_words = (num_bytes + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
4711
4712   /* Decide whether it should go in a floating-point register, assuming
4713      one is free.  Later code checks for availability.
4714
4715      The checks against UNITS_PER_FPVALUE handle the soft-float and
4716      single-float cases.  */
4717   switch (mips_abi)
4718     {
4719     case ABI_EABI:
4720       /* The EABI conventions have traditionally been defined in terms
4721          of TYPE_MODE, regardless of the actual type.  */
4722       info->fpr_p = ((GET_MODE_CLASS (mode) == MODE_FLOAT
4723                       || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
4724                      && GET_MODE_SIZE (mode) <= UNITS_PER_FPVALUE);
4725       break;
4726
4727     case ABI_32:
4728     case ABI_O64:
4729       /* Only leading floating-point scalars are passed in
4730          floating-point registers.  We also handle vector floats the same
4731          say, which is OK because they are not covered by the standard ABI.  */
4732       info->fpr_p = (!cum->gp_reg_found
4733                      && cum->arg_number < 2
4734                      && (type == 0
4735                          || SCALAR_FLOAT_TYPE_P (type)
4736                          || VECTOR_FLOAT_TYPE_P (type))
4737                      && (GET_MODE_CLASS (mode) == MODE_FLOAT
4738                          || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
4739                      && GET_MODE_SIZE (mode) <= UNITS_PER_FPVALUE);
4740       break;
4741
4742     case ABI_N32:
4743     case ABI_64:
4744       /* Scalar, complex and vector floating-point types are passed in
4745          floating-point registers, as long as this is a named rather
4746          than a variable argument.  */
4747       info->fpr_p = (named
4748                      && (type == 0 || FLOAT_TYPE_P (type))
4749                      && (GET_MODE_CLASS (mode) == MODE_FLOAT
4750                          || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT
4751                          || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
4752                      && GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_FPVALUE);
4753
4754       /* ??? According to the ABI documentation, the real and imaginary
4755          parts of complex floats should be passed in individual registers.
4756          The real and imaginary parts of stack arguments are supposed
4757          to be contiguous and there should be an extra word of padding
4758          at the end.
4759
4760          This has two problems.  First, it makes it impossible to use a
4761          single "void *" va_list type, since register and stack arguments
4762          are passed differently.  (At the time of writing, MIPSpro cannot
4763          handle complex float varargs correctly.)  Second, it's unclear
4764          what should happen when there is only one register free.
4765
4766          For now, we assume that named complex floats should go into FPRs
4767          if there are two FPRs free, otherwise they should be passed in the
4768          same way as a struct containing two floats.  */
4769       if (info->fpr_p
4770           && GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT
4771           && GET_MODE_UNIT_SIZE (mode) < UNITS_PER_FPVALUE)
4772         {
4773           if (cum->num_gprs >= MAX_ARGS_IN_REGISTERS - 1)
4774             info->fpr_p = false;
4775           else
4776             num_words = 2;
4777         }
4778       break;
4779
4780     default:
4781       gcc_unreachable ();
4782     }
4783
4784   /* See whether the argument has doubleword alignment.  */
4785   doubleword_aligned_p = (mips_function_arg_boundary (mode, type)
4786                           > BITS_PER_WORD);
4787
4788   /* Set REG_OFFSET to the register count we're interested in.
4789      The EABI allocates the floating-point registers separately,
4790      but the other ABIs allocate them like integer registers.  */
4791   info->reg_offset = (mips_abi == ABI_EABI && info->fpr_p
4792                       ? cum->num_fprs
4793                       : cum->num_gprs);
4794
4795   /* Advance to an even register if the argument is doubleword-aligned.  */
4796   if (doubleword_aligned_p)
4797     info->reg_offset += info->reg_offset & 1;
4798
4799   /* Work out the offset of a stack argument.  */
4800   info->stack_offset = cum->stack_words;
4801   if (doubleword_aligned_p)
4802     info->stack_offset += info->stack_offset & 1;
4803
4804   max_regs = MAX_ARGS_IN_REGISTERS - info->reg_offset;
4805
4806   /* Partition the argument between registers and stack.  */
4807   info->reg_words = MIN (num_words, max_regs);
4808   info->stack_words = num_words - info->reg_words;
4809 }
4810
4811 /* INFO describes a register argument that has the normal format for the
4812    argument's mode.  Return the register it uses, assuming that FPRs are
4813    available if HARD_FLOAT_P.  */
4814
4815 static unsigned int
4816 mips_arg_regno (const struct mips_arg_info *info, bool hard_float_p)
4817 {
4818   if (!info->fpr_p || !hard_float_p)
4819     return GP_ARG_FIRST + info->reg_offset;
4820   else if (mips_abi == ABI_32 && TARGET_DOUBLE_FLOAT && info->reg_offset > 0)
4821     /* In o32, the second argument is always passed in $f14
4822        for TARGET_DOUBLE_FLOAT, regardless of whether the
4823        first argument was a word or doubleword.  */
4824     return FP_ARG_FIRST + 2;
4825   else
4826     return FP_ARG_FIRST + info->reg_offset;
4827 }
4828
4829 /* Implement TARGET_STRICT_ARGUMENT_NAMING.  */
4830
4831 static bool
4832 mips_strict_argument_naming (CUMULATIVE_ARGS *ca ATTRIBUTE_UNUSED)
4833 {
4834   return !TARGET_OLDABI;
4835 }
4836
4837 /* Implement TARGET_FUNCTION_ARG.  */
4838
4839 static rtx
4840 mips_function_arg (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4841                    const_tree type, bool named)
4842 {
4843   struct mips_arg_info info;
4844
4845   /* We will be called with a mode of VOIDmode after the last argument
4846      has been seen.  Whatever we return will be passed to the call expander.
4847      If we need a MIPS16 fp_code, return a REG with the code stored as
4848      the mode.  */
4849   if (mode == VOIDmode)
4850     {
4851       if (TARGET_MIPS16 && cum->fp_code != 0)
4852         return gen_rtx_REG ((enum machine_mode) cum->fp_code, 0);
4853       else
4854         return NULL;
4855     }
4856
4857   mips_get_arg_info (&info, cum, mode, type, named);
4858
4859   /* Return straight away if the whole argument is passed on the stack.  */
4860   if (info.reg_offset == MAX_ARGS_IN_REGISTERS)
4861     return NULL;
4862
4863   /* The n32 and n64 ABIs say that if any 64-bit chunk of the structure
4864      contains a double in its entirety, then that 64-bit chunk is passed
4865      in a floating-point register.  */
4866   if (TARGET_NEWABI
4867       && TARGET_HARD_FLOAT
4868       && named
4869       && type != 0
4870       && TREE_CODE (type) == RECORD_TYPE
4871       && TYPE_SIZE_UNIT (type)
4872       && host_integerp (TYPE_SIZE_UNIT (type), 1))
4873     {
4874       tree field;
4875
4876       /* First check to see if there is any such field.  */
4877       for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4878         if (TREE_CODE (field) == FIELD_DECL
4879             && SCALAR_FLOAT_TYPE_P (TREE_TYPE (field))
4880             && TYPE_PRECISION (TREE_TYPE (field)) == BITS_PER_WORD
4881             && host_integerp (bit_position (field), 0)
4882             && int_bit_position (field) % BITS_PER_WORD == 0)
4883           break;
4884
4885       if (field != 0)
4886         {
4887           /* Now handle the special case by returning a PARALLEL
4888              indicating where each 64-bit chunk goes.  INFO.REG_WORDS
4889              chunks are passed in registers.  */
4890           unsigned int i;
4891           HOST_WIDE_INT bitpos;
4892           rtx ret;
4893
4894           /* assign_parms checks the mode of ENTRY_PARM, so we must
4895              use the actual mode here.  */
4896           ret = gen_rtx_PARALLEL (mode, rtvec_alloc (info.reg_words));
4897
4898           bitpos = 0;
4899           field = TYPE_FIELDS (type);
4900           for (i = 0; i < info.reg_words; i++)
4901             {
4902               rtx reg;
4903
4904               for (; field; field = DECL_CHAIN (field))
4905                 if (TREE_CODE (field) == FIELD_DECL
4906                     && int_bit_position (field) >= bitpos)
4907                   break;
4908
4909               if (field
4910                   && int_bit_position (field) == bitpos
4911                   && SCALAR_FLOAT_TYPE_P (TREE_TYPE (field))
4912                   && TYPE_PRECISION (TREE_TYPE (field)) == BITS_PER_WORD)
4913                 reg = gen_rtx_REG (DFmode, FP_ARG_FIRST + info.reg_offset + i);
4914               else
4915                 reg = gen_rtx_REG (DImode, GP_ARG_FIRST + info.reg_offset + i);
4916
4917               XVECEXP (ret, 0, i)
4918                 = gen_rtx_EXPR_LIST (VOIDmode, reg,
4919                                      GEN_INT (bitpos / BITS_PER_UNIT));
4920
4921               bitpos += BITS_PER_WORD;
4922             }
4923           return ret;
4924         }
4925     }
4926
4927   /* Handle the n32/n64 conventions for passing complex floating-point
4928      arguments in FPR pairs.  The real part goes in the lower register
4929      and the imaginary part goes in the upper register.  */
4930   if (TARGET_NEWABI
4931       && info.fpr_p
4932       && GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
4933     {
4934       rtx real, imag;
4935       enum machine_mode inner;
4936       unsigned int regno;
4937
4938       inner = GET_MODE_INNER (mode);
4939       regno = FP_ARG_FIRST + info.reg_offset;
4940       if (info.reg_words * UNITS_PER_WORD == GET_MODE_SIZE (inner))
4941         {
4942           /* Real part in registers, imaginary part on stack.  */
4943           gcc_assert (info.stack_words == info.reg_words);
4944           return gen_rtx_REG (inner, regno);
4945         }
4946       else
4947         {
4948           gcc_assert (info.stack_words == 0);
4949           real = gen_rtx_EXPR_LIST (VOIDmode,
4950                                     gen_rtx_REG (inner, regno),
4951                                     const0_rtx);
4952           imag = gen_rtx_EXPR_LIST (VOIDmode,
4953                                     gen_rtx_REG (inner,
4954                                                  regno + info.reg_words / 2),
4955                                     GEN_INT (GET_MODE_SIZE (inner)));
4956           return gen_rtx_PARALLEL (mode, gen_rtvec (2, real, imag));
4957         }
4958     }
4959
4960   return gen_rtx_REG (mode, mips_arg_regno (&info, TARGET_HARD_FLOAT));
4961 }
4962
4963 /* Implement TARGET_FUNCTION_ARG_ADVANCE.  */
4964
4965 static void
4966 mips_function_arg_advance (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4967                            const_tree type, bool named)
4968 {
4969   struct mips_arg_info info;
4970
4971   mips_get_arg_info (&info, cum, mode, type, named);
4972
4973   if (!info.fpr_p)
4974     cum->gp_reg_found = true;
4975
4976   /* See the comment above the CUMULATIVE_ARGS structure in mips.h for
4977      an explanation of what this code does.  It assumes that we're using
4978      either the o32 or the o64 ABI, both of which pass at most 2 arguments
4979      in FPRs.  */
4980   if (cum->arg_number < 2 && info.fpr_p)
4981     cum->fp_code += (mode == SFmode ? 1 : 2) << (cum->arg_number * 2);
4982
4983   /* Advance the register count.  This has the effect of setting
4984      num_gprs to MAX_ARGS_IN_REGISTERS if a doubleword-aligned
4985      argument required us to skip the final GPR and pass the whole
4986      argument on the stack.  */
4987   if (mips_abi != ABI_EABI || !info.fpr_p)
4988     cum->num_gprs = info.reg_offset + info.reg_words;
4989   else if (info.reg_words > 0)
4990     cum->num_fprs += MAX_FPRS_PER_FMT;
4991
4992   /* Advance the stack word count.  */
4993   if (info.stack_words > 0)
4994     cum->stack_words = info.stack_offset + info.stack_words;
4995
4996   cum->arg_number++;
4997 }
4998
4999 /* Implement TARGET_ARG_PARTIAL_BYTES.  */
5000
5001 static int
5002 mips_arg_partial_bytes (CUMULATIVE_ARGS *cum,
5003                         enum machine_mode mode, tree type, bool named)
5004 {
5005   struct mips_arg_info info;
5006
5007   mips_get_arg_info (&info, cum, mode, type, named);
5008   return info.stack_words > 0 ? info.reg_words * UNITS_PER_WORD : 0;
5009 }
5010
5011 /* Implement TARGET_FUNCTION_ARG_BOUNDARY.  Every parameter gets at
5012    least PARM_BOUNDARY bits of alignment, but will be given anything up
5013    to STACK_BOUNDARY bits if the type requires it.  */
5014
5015 static unsigned int
5016 mips_function_arg_boundary (enum machine_mode mode, const_tree type)
5017 {
5018   unsigned int alignment;
5019
5020   alignment = type ? TYPE_ALIGN (type) : GET_MODE_ALIGNMENT (mode);
5021   if (alignment < PARM_BOUNDARY)
5022     alignment = PARM_BOUNDARY;
5023   if (alignment > STACK_BOUNDARY)
5024     alignment = STACK_BOUNDARY;
5025   return alignment;
5026 }
5027
5028 /* Return true if FUNCTION_ARG_PADDING (MODE, TYPE) should return
5029    upward rather than downward.  In other words, return true if the
5030    first byte of the stack slot has useful data, false if the last
5031    byte does.  */
5032
5033 bool
5034 mips_pad_arg_upward (enum machine_mode mode, const_tree type)
5035 {
5036   /* On little-endian targets, the first byte of every stack argument
5037      is passed in the first byte of the stack slot.  */
5038   if (!BYTES_BIG_ENDIAN)
5039     return true;
5040
5041   /* Otherwise, integral types are padded downward: the last byte of a
5042      stack argument is passed in the last byte of the stack slot.  */
5043   if (type != 0
5044       ? (INTEGRAL_TYPE_P (type)
5045          || POINTER_TYPE_P (type)
5046          || FIXED_POINT_TYPE_P (type))
5047       : (SCALAR_INT_MODE_P (mode)
5048          || ALL_SCALAR_FIXED_POINT_MODE_P (mode)))
5049     return false;
5050
5051   /* Big-endian o64 pads floating-point arguments downward.  */
5052   if (mips_abi == ABI_O64)
5053     if (type != 0 ? FLOAT_TYPE_P (type) : GET_MODE_CLASS (mode) == MODE_FLOAT)
5054       return false;
5055
5056   /* Other types are padded upward for o32, o64, n32 and n64.  */
5057   if (mips_abi != ABI_EABI)
5058     return true;
5059
5060   /* Arguments smaller than a stack slot are padded downward.  */
5061   if (mode != BLKmode)
5062     return GET_MODE_BITSIZE (mode) >= PARM_BOUNDARY;
5063   else
5064     return int_size_in_bytes (type) >= (PARM_BOUNDARY / BITS_PER_UNIT);
5065 }
5066
5067 /* Likewise BLOCK_REG_PADDING (MODE, TYPE, ...).  Return !BYTES_BIG_ENDIAN
5068    if the least significant byte of the register has useful data.  Return
5069    the opposite if the most significant byte does.  */
5070
5071 bool
5072 mips_pad_reg_upward (enum machine_mode mode, tree type)
5073 {
5074   /* No shifting is required for floating-point arguments.  */
5075   if (type != 0 ? FLOAT_TYPE_P (type) : GET_MODE_CLASS (mode) == MODE_FLOAT)
5076     return !BYTES_BIG_ENDIAN;
5077
5078   /* Otherwise, apply the same padding to register arguments as we do
5079      to stack arguments.  */
5080   return mips_pad_arg_upward (mode, type);
5081 }
5082
5083 /* Return nonzero when an argument must be passed by reference.  */
5084
5085 static bool
5086 mips_pass_by_reference (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
5087                         enum machine_mode mode, const_tree type,
5088                         bool named ATTRIBUTE_UNUSED)
5089 {
5090   if (mips_abi == ABI_EABI)
5091     {
5092       int size;
5093
5094       /* ??? How should SCmode be handled?  */
5095       if (mode == DImode || mode == DFmode
5096           || mode == DQmode || mode == UDQmode
5097           || mode == DAmode || mode == UDAmode)
5098         return 0;
5099
5100       size = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode);
5101       return size == -1 || size > UNITS_PER_WORD;
5102     }
5103   else
5104     {
5105       /* If we have a variable-sized parameter, we have no choice.  */
5106       return targetm.calls.must_pass_in_stack (mode, type);
5107     }
5108 }
5109
5110 /* Implement TARGET_CALLEE_COPIES.  */
5111
5112 static bool
5113 mips_callee_copies (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
5114                     enum machine_mode mode ATTRIBUTE_UNUSED,
5115                     const_tree type ATTRIBUTE_UNUSED, bool named)
5116 {
5117   return mips_abi == ABI_EABI && named;
5118 }
5119 \f
5120 /* See whether VALTYPE is a record whose fields should be returned in
5121    floating-point registers.  If so, return the number of fields and
5122    list them in FIELDS (which should have two elements).  Return 0
5123    otherwise.
5124
5125    For n32 & n64, a structure with one or two fields is returned in
5126    floating-point registers as long as every field has a floating-point
5127    type.  */
5128
5129 static int
5130 mips_fpr_return_fields (const_tree valtype, tree *fields)
5131 {
5132   tree field;
5133   int i;
5134
5135   if (!TARGET_NEWABI)
5136     return 0;
5137
5138   if (TREE_CODE (valtype) != RECORD_TYPE)
5139     return 0;
5140
5141   i = 0;
5142   for (field = TYPE_FIELDS (valtype); field != 0; field = DECL_CHAIN (field))
5143     {
5144       if (TREE_CODE (field) != FIELD_DECL)
5145         continue;
5146
5147       if (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (field)))
5148         return 0;
5149
5150       if (i == 2)
5151         return 0;
5152
5153       fields[i++] = field;
5154     }
5155   return i;
5156 }
5157
5158 /* Implement TARGET_RETURN_IN_MSB.  For n32 & n64, we should return
5159    a value in the most significant part of $2/$3 if:
5160
5161       - the target is big-endian;
5162
5163       - the value has a structure or union type (we generalize this to
5164         cover aggregates from other languages too); and
5165
5166       - the structure is not returned in floating-point registers.  */
5167
5168 static bool
5169 mips_return_in_msb (const_tree valtype)
5170 {
5171   tree fields[2];
5172
5173   return (TARGET_NEWABI
5174           && TARGET_BIG_ENDIAN
5175           && AGGREGATE_TYPE_P (valtype)
5176           && mips_fpr_return_fields (valtype, fields) == 0);
5177 }
5178
5179 /* Return true if the function return value MODE will get returned in a
5180    floating-point register.  */
5181
5182 static bool
5183 mips_return_mode_in_fpr_p (enum machine_mode mode)
5184 {
5185   return ((GET_MODE_CLASS (mode) == MODE_FLOAT
5186            || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT
5187            || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
5188           && GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_HWFPVALUE);
5189 }
5190
5191 /* Return the representation of an FPR return register when the
5192    value being returned in FP_RETURN has mode VALUE_MODE and the
5193    return type itself has mode TYPE_MODE.  On NewABI targets,
5194    the two modes may be different for structures like:
5195
5196        struct __attribute__((packed)) foo { float f; }
5197
5198    where we return the SFmode value of "f" in FP_RETURN, but where
5199    the structure itself has mode BLKmode.  */
5200
5201 static rtx
5202 mips_return_fpr_single (enum machine_mode type_mode,
5203                         enum machine_mode value_mode)
5204 {
5205   rtx x;
5206
5207   x = gen_rtx_REG (value_mode, FP_RETURN);
5208   if (type_mode != value_mode)
5209     {
5210       x = gen_rtx_EXPR_LIST (VOIDmode, x, const0_rtx);
5211       x = gen_rtx_PARALLEL (type_mode, gen_rtvec (1, x));
5212     }
5213   return x;
5214 }
5215
5216 /* Return a composite value in a pair of floating-point registers.
5217    MODE1 and OFFSET1 are the mode and byte offset for the first value,
5218    likewise MODE2 and OFFSET2 for the second.  MODE is the mode of the
5219    complete value.
5220
5221    For n32 & n64, $f0 always holds the first value and $f2 the second.
5222    Otherwise the values are packed together as closely as possible.  */
5223
5224 static rtx
5225 mips_return_fpr_pair (enum machine_mode mode,
5226                       enum machine_mode mode1, HOST_WIDE_INT offset1,
5227                       enum machine_mode mode2, HOST_WIDE_INT offset2)
5228 {
5229   int inc;
5230
5231   inc = (TARGET_NEWABI ? 2 : MAX_FPRS_PER_FMT);
5232   return gen_rtx_PARALLEL
5233     (mode,
5234      gen_rtvec (2,
5235                 gen_rtx_EXPR_LIST (VOIDmode,
5236                                    gen_rtx_REG (mode1, FP_RETURN),
5237                                    GEN_INT (offset1)),
5238                 gen_rtx_EXPR_LIST (VOIDmode,
5239                                    gen_rtx_REG (mode2, FP_RETURN + inc),
5240                                    GEN_INT (offset2))));
5241
5242 }
5243
5244 /* Implement FUNCTION_VALUE and LIBCALL_VALUE.  For normal calls,
5245    VALTYPE is the return type and MODE is VOIDmode.  For libcalls,
5246    VALTYPE is null and MODE is the mode of the return value.  */
5247
5248 rtx
5249 mips_function_value (const_tree valtype, const_tree func, enum machine_mode mode)
5250 {
5251   if (valtype)
5252     {
5253       tree fields[2];
5254       int unsigned_p;
5255
5256       mode = TYPE_MODE (valtype);
5257       unsigned_p = TYPE_UNSIGNED (valtype);
5258
5259       /* Since TARGET_PROMOTE_FUNCTION_MODE unconditionally promotes,
5260          return values, promote the mode here too.  */
5261       mode = promote_function_mode (valtype, mode, &unsigned_p, func, 1);
5262
5263       /* Handle structures whose fields are returned in $f0/$f2.  */
5264       switch (mips_fpr_return_fields (valtype, fields))
5265         {
5266         case 1:
5267           return mips_return_fpr_single (mode,
5268                                          TYPE_MODE (TREE_TYPE (fields[0])));
5269
5270         case 2:
5271           return mips_return_fpr_pair (mode,
5272                                        TYPE_MODE (TREE_TYPE (fields[0])),
5273                                        int_byte_position (fields[0]),
5274                                        TYPE_MODE (TREE_TYPE (fields[1])),
5275                                        int_byte_position (fields[1]));
5276         }
5277
5278       /* If a value is passed in the most significant part of a register, see
5279          whether we have to round the mode up to a whole number of words.  */
5280       if (mips_return_in_msb (valtype))
5281         {
5282           HOST_WIDE_INT size = int_size_in_bytes (valtype);
5283           if (size % UNITS_PER_WORD != 0)
5284             {
5285               size += UNITS_PER_WORD - size % UNITS_PER_WORD;
5286               mode = mode_for_size (size * BITS_PER_UNIT, MODE_INT, 0);
5287             }
5288         }
5289
5290       /* For EABI, the class of return register depends entirely on MODE.
5291          For example, "struct { some_type x; }" and "union { some_type x; }"
5292          are returned in the same way as a bare "some_type" would be.
5293          Other ABIs only use FPRs for scalar, complex or vector types.  */
5294       if (mips_abi != ABI_EABI && !FLOAT_TYPE_P (valtype))
5295         return gen_rtx_REG (mode, GP_RETURN);
5296     }
5297
5298   if (!TARGET_MIPS16)
5299     {
5300       /* Handle long doubles for n32 & n64.  */
5301       if (mode == TFmode)
5302         return mips_return_fpr_pair (mode,
5303                                      DImode, 0,
5304                                      DImode, GET_MODE_SIZE (mode) / 2);
5305
5306       if (mips_return_mode_in_fpr_p (mode))
5307         {
5308           if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
5309             return mips_return_fpr_pair (mode,
5310                                          GET_MODE_INNER (mode), 0,
5311                                          GET_MODE_INNER (mode),
5312                                          GET_MODE_SIZE (mode) / 2);
5313           else
5314             return gen_rtx_REG (mode, FP_RETURN);
5315         }
5316     }
5317
5318   return gen_rtx_REG (mode, GP_RETURN);
5319 }
5320
5321 /* Implement TARGET_RETURN_IN_MEMORY.  Under the o32 and o64 ABIs,
5322    all BLKmode objects are returned in memory.  Under the n32, n64
5323    and embedded ABIs, small structures are returned in a register.
5324    Objects with varying size must still be returned in memory, of
5325    course.  */
5326
5327 static bool
5328 mips_return_in_memory (const_tree type, const_tree fndecl ATTRIBUTE_UNUSED)
5329 {
5330   return (TARGET_OLDABI
5331           ? TYPE_MODE (type) == BLKmode
5332           : !IN_RANGE (int_size_in_bytes (type), 0, 2 * UNITS_PER_WORD));
5333 }
5334 \f
5335 /* Implement TARGET_SETUP_INCOMING_VARARGS.  */
5336
5337 static void
5338 mips_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
5339                              tree type, int *pretend_size ATTRIBUTE_UNUSED,
5340                              int no_rtl)
5341 {
5342   CUMULATIVE_ARGS local_cum;
5343   int gp_saved, fp_saved;
5344
5345   /* The caller has advanced CUM up to, but not beyond, the last named
5346      argument.  Advance a local copy of CUM past the last "real" named
5347      argument, to find out how many registers are left over.  */
5348   local_cum = *cum;
5349   mips_function_arg_advance (&local_cum, mode, type, true);
5350
5351   /* Found out how many registers we need to save.  */
5352   gp_saved = MAX_ARGS_IN_REGISTERS - local_cum.num_gprs;
5353   fp_saved = (EABI_FLOAT_VARARGS_P
5354               ? MAX_ARGS_IN_REGISTERS - local_cum.num_fprs
5355               : 0);
5356
5357   if (!no_rtl)
5358     {
5359       if (gp_saved > 0)
5360         {
5361           rtx ptr, mem;
5362
5363           ptr = plus_constant (virtual_incoming_args_rtx,
5364                                REG_PARM_STACK_SPACE (cfun->decl)
5365                                - gp_saved * UNITS_PER_WORD);
5366           mem = gen_frame_mem (BLKmode, ptr);
5367           set_mem_alias_set (mem, get_varargs_alias_set ());
5368
5369           move_block_from_reg (local_cum.num_gprs + GP_ARG_FIRST,
5370                                mem, gp_saved);
5371         }
5372       if (fp_saved > 0)
5373         {
5374           /* We can't use move_block_from_reg, because it will use
5375              the wrong mode.  */
5376           enum machine_mode mode;
5377           int off, i;
5378
5379           /* Set OFF to the offset from virtual_incoming_args_rtx of
5380              the first float register.  The FP save area lies below
5381              the integer one, and is aligned to UNITS_PER_FPVALUE bytes.  */
5382           off = (-gp_saved * UNITS_PER_WORD) & -UNITS_PER_FPVALUE;
5383           off -= fp_saved * UNITS_PER_FPREG;
5384
5385           mode = TARGET_SINGLE_FLOAT ? SFmode : DFmode;
5386
5387           for (i = local_cum.num_fprs; i < MAX_ARGS_IN_REGISTERS;
5388                i += MAX_FPRS_PER_FMT)
5389             {
5390               rtx ptr, mem;
5391
5392               ptr = plus_constant (virtual_incoming_args_rtx, off);
5393               mem = gen_frame_mem (mode, ptr);
5394               set_mem_alias_set (mem, get_varargs_alias_set ());
5395               mips_emit_move (mem, gen_rtx_REG (mode, FP_ARG_FIRST + i));
5396               off += UNITS_PER_HWFPVALUE;
5397             }
5398         }
5399     }
5400   if (REG_PARM_STACK_SPACE (cfun->decl) == 0)
5401     cfun->machine->varargs_size = (gp_saved * UNITS_PER_WORD
5402                                    + fp_saved * UNITS_PER_FPREG);
5403 }
5404
5405 /* Implement TARGET_BUILTIN_VA_LIST.  */
5406
5407 static tree
5408 mips_build_builtin_va_list (void)
5409 {
5410   if (EABI_FLOAT_VARARGS_P)
5411     {
5412       /* We keep 3 pointers, and two offsets.
5413
5414          Two pointers are to the overflow area, which starts at the CFA.
5415          One of these is constant, for addressing into the GPR save area
5416          below it.  The other is advanced up the stack through the
5417          overflow region.
5418
5419          The third pointer is to the bottom of the GPR save area.
5420          Since the FPR save area is just below it, we can address
5421          FPR slots off this pointer.
5422
5423          We also keep two one-byte offsets, which are to be subtracted
5424          from the constant pointers to yield addresses in the GPR and
5425          FPR save areas.  These are downcounted as float or non-float
5426          arguments are used, and when they get to zero, the argument
5427          must be obtained from the overflow region.  */
5428       tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff, f_res, record;
5429       tree array, index;
5430
5431       record = lang_hooks.types.make_type (RECORD_TYPE);
5432
5433       f_ovfl = build_decl (BUILTINS_LOCATION,
5434                            FIELD_DECL, get_identifier ("__overflow_argptr"),
5435                            ptr_type_node);
5436       f_gtop = build_decl (BUILTINS_LOCATION,
5437                            FIELD_DECL, get_identifier ("__gpr_top"),
5438                            ptr_type_node);
5439       f_ftop = build_decl (BUILTINS_LOCATION,
5440                            FIELD_DECL, get_identifier ("__fpr_top"),
5441                            ptr_type_node);
5442       f_goff = build_decl (BUILTINS_LOCATION,
5443                            FIELD_DECL, get_identifier ("__gpr_offset"),
5444                            unsigned_char_type_node);
5445       f_foff = build_decl (BUILTINS_LOCATION,
5446                            FIELD_DECL, get_identifier ("__fpr_offset"),
5447                            unsigned_char_type_node);
5448       /* Explicitly pad to the size of a pointer, so that -Wpadded won't
5449          warn on every user file.  */
5450       index = build_int_cst (NULL_TREE, GET_MODE_SIZE (ptr_mode) - 2 - 1);
5451       array = build_array_type (unsigned_char_type_node,
5452                                 build_index_type (index));
5453       f_res = build_decl (BUILTINS_LOCATION,
5454                           FIELD_DECL, get_identifier ("__reserved"), array);
5455
5456       DECL_FIELD_CONTEXT (f_ovfl) = record;
5457       DECL_FIELD_CONTEXT (f_gtop) = record;
5458       DECL_FIELD_CONTEXT (f_ftop) = record;
5459       DECL_FIELD_CONTEXT (f_goff) = record;
5460       DECL_FIELD_CONTEXT (f_foff) = record;
5461       DECL_FIELD_CONTEXT (f_res) = record;
5462
5463       TYPE_FIELDS (record) = f_ovfl;
5464       DECL_CHAIN (f_ovfl) = f_gtop;
5465       DECL_CHAIN (f_gtop) = f_ftop;
5466       DECL_CHAIN (f_ftop) = f_goff;
5467       DECL_CHAIN (f_goff) = f_foff;
5468       DECL_CHAIN (f_foff) = f_res;
5469
5470       layout_type (record);
5471       return record;
5472     }
5473   else if (TARGET_IRIX6)
5474     /* On IRIX 6, this type is 'char *'.  */
5475     return build_pointer_type (char_type_node);
5476   else
5477     /* Otherwise, we use 'void *'.  */
5478     return ptr_type_node;
5479 }
5480
5481 /* Implement TARGET_EXPAND_BUILTIN_VA_START.  */
5482
5483 static void
5484 mips_va_start (tree valist, rtx nextarg)
5485 {
5486   if (EABI_FLOAT_VARARGS_P)
5487     {
5488       const CUMULATIVE_ARGS *cum;
5489       tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff;
5490       tree ovfl, gtop, ftop, goff, foff;
5491       tree t;
5492       int gpr_save_area_size;
5493       int fpr_save_area_size;
5494       int fpr_offset;
5495
5496       cum = &crtl->args.info;
5497       gpr_save_area_size
5498         = (MAX_ARGS_IN_REGISTERS - cum->num_gprs) * UNITS_PER_WORD;
5499       fpr_save_area_size
5500         = (MAX_ARGS_IN_REGISTERS - cum->num_fprs) * UNITS_PER_FPREG;
5501
5502       f_ovfl = TYPE_FIELDS (va_list_type_node);
5503       f_gtop = DECL_CHAIN (f_ovfl);
5504       f_ftop = DECL_CHAIN (f_gtop);
5505       f_goff = DECL_CHAIN (f_ftop);
5506       f_foff = DECL_CHAIN (f_goff);
5507
5508       ovfl = build3 (COMPONENT_REF, TREE_TYPE (f_ovfl), valist, f_ovfl,
5509                      NULL_TREE);
5510       gtop = build3 (COMPONENT_REF, TREE_TYPE (f_gtop), valist, f_gtop,
5511                      NULL_TREE);
5512       ftop = build3 (COMPONENT_REF, TREE_TYPE (f_ftop), valist, f_ftop,
5513                      NULL_TREE);
5514       goff = build3 (COMPONENT_REF, TREE_TYPE (f_goff), valist, f_goff,
5515                      NULL_TREE);
5516       foff = build3 (COMPONENT_REF, TREE_TYPE (f_foff), valist, f_foff,
5517                      NULL_TREE);
5518
5519       /* Emit code to initialize OVFL, which points to the next varargs
5520          stack argument.  CUM->STACK_WORDS gives the number of stack
5521          words used by named arguments.  */
5522       t = make_tree (TREE_TYPE (ovfl), virtual_incoming_args_rtx);
5523       if (cum->stack_words > 0)
5524         t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (ovfl), t,
5525                     size_int (cum->stack_words * UNITS_PER_WORD));
5526       t = build2 (MODIFY_EXPR, TREE_TYPE (ovfl), ovfl, t);
5527       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5528
5529       /* Emit code to initialize GTOP, the top of the GPR save area.  */
5530       t = make_tree (TREE_TYPE (gtop), virtual_incoming_args_rtx);
5531       t = build2 (MODIFY_EXPR, TREE_TYPE (gtop), gtop, t);
5532       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5533
5534       /* Emit code to initialize FTOP, the top of the FPR save area.
5535          This address is gpr_save_area_bytes below GTOP, rounded
5536          down to the next fp-aligned boundary.  */
5537       t = make_tree (TREE_TYPE (ftop), virtual_incoming_args_rtx);
5538       fpr_offset = gpr_save_area_size + UNITS_PER_FPVALUE - 1;
5539       fpr_offset &= -UNITS_PER_FPVALUE;
5540       if (fpr_offset)
5541         t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (ftop), t,
5542                     size_int (-fpr_offset));
5543       t = build2 (MODIFY_EXPR, TREE_TYPE (ftop), ftop, t);
5544       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5545
5546       /* Emit code to initialize GOFF, the offset from GTOP of the
5547          next GPR argument.  */
5548       t = build2 (MODIFY_EXPR, TREE_TYPE (goff), goff,
5549                   build_int_cst (TREE_TYPE (goff), gpr_save_area_size));
5550       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5551
5552       /* Likewise emit code to initialize FOFF, the offset from FTOP
5553          of the next FPR argument.  */
5554       t = build2 (MODIFY_EXPR, TREE_TYPE (foff), foff,
5555                   build_int_cst (TREE_TYPE (foff), fpr_save_area_size));
5556       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5557     }
5558   else
5559     {
5560       nextarg = plus_constant (nextarg, -cfun->machine->varargs_size);
5561       std_expand_builtin_va_start (valist, nextarg);
5562     }
5563 }
5564
5565 /* Implement TARGET_GIMPLIFY_VA_ARG_EXPR.  */
5566
5567 static tree
5568 mips_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
5569                            gimple_seq *post_p)
5570 {
5571   tree addr;
5572   bool indirect_p;
5573
5574   indirect_p = pass_by_reference (NULL, TYPE_MODE (type), type, 0);
5575   if (indirect_p)
5576     type = build_pointer_type (type);
5577
5578   if (!EABI_FLOAT_VARARGS_P)
5579     addr = std_gimplify_va_arg_expr (valist, type, pre_p, post_p);
5580   else
5581     {
5582       tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff;
5583       tree ovfl, top, off, align;
5584       HOST_WIDE_INT size, rsize, osize;
5585       tree t, u;
5586
5587       f_ovfl = TYPE_FIELDS (va_list_type_node);
5588       f_gtop = DECL_CHAIN (f_ovfl);
5589       f_ftop = DECL_CHAIN (f_gtop);
5590       f_goff = DECL_CHAIN (f_ftop);
5591       f_foff = DECL_CHAIN (f_goff);
5592
5593       /* Let:
5594
5595          TOP be the top of the GPR or FPR save area;
5596          OFF be the offset from TOP of the next register;
5597          ADDR_RTX be the address of the argument;
5598          SIZE be the number of bytes in the argument type;
5599          RSIZE be the number of bytes used to store the argument
5600            when it's in the register save area; and
5601          OSIZE be the number of bytes used to store it when it's
5602            in the stack overflow area.
5603
5604          The code we want is:
5605
5606          1: off &= -rsize;        // round down
5607          2: if (off != 0)
5608          3:   {
5609          4:     addr_rtx = top - off + (BYTES_BIG_ENDIAN ? RSIZE - SIZE : 0);
5610          5:     off -= rsize;
5611          6:   }
5612          7: else
5613          8:   {
5614          9:     ovfl = ((intptr_t) ovfl + osize - 1) & -osize;
5615          10:    addr_rtx = ovfl + (BYTES_BIG_ENDIAN ? OSIZE - SIZE : 0);
5616          11:    ovfl += osize;
5617          14:  }
5618
5619          [1] and [9] can sometimes be optimized away.  */
5620
5621       ovfl = build3 (COMPONENT_REF, TREE_TYPE (f_ovfl), valist, f_ovfl,
5622                      NULL_TREE);
5623       size = int_size_in_bytes (type);
5624
5625       if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_FLOAT
5626           && GET_MODE_SIZE (TYPE_MODE (type)) <= UNITS_PER_FPVALUE)
5627         {
5628           top = build3 (COMPONENT_REF, TREE_TYPE (f_ftop),
5629                         unshare_expr (valist), f_ftop, NULL_TREE);
5630           off = build3 (COMPONENT_REF, TREE_TYPE (f_foff),
5631                         unshare_expr (valist), f_foff, NULL_TREE);
5632
5633           /* When va_start saves FPR arguments to the stack, each slot
5634              takes up UNITS_PER_HWFPVALUE bytes, regardless of the
5635              argument's precision.  */
5636           rsize = UNITS_PER_HWFPVALUE;
5637
5638           /* Overflow arguments are padded to UNITS_PER_WORD bytes
5639              (= PARM_BOUNDARY bits).  This can be different from RSIZE
5640              in two cases:
5641
5642              (1) On 32-bit targets when TYPE is a structure such as:
5643
5644              struct s { float f; };
5645
5646              Such structures are passed in paired FPRs, so RSIZE
5647              will be 8 bytes.  However, the structure only takes
5648              up 4 bytes of memory, so OSIZE will only be 4.
5649
5650              (2) In combinations such as -mgp64 -msingle-float
5651              -fshort-double.  Doubles passed in registers will then take
5652              up 4 (UNITS_PER_HWFPVALUE) bytes, but those passed on the
5653              stack take up UNITS_PER_WORD bytes.  */
5654           osize = MAX (GET_MODE_SIZE (TYPE_MODE (type)), UNITS_PER_WORD);
5655         }
5656       else
5657         {
5658           top = build3 (COMPONENT_REF, TREE_TYPE (f_gtop),
5659                         unshare_expr (valist), f_gtop, NULL_TREE);
5660           off = build3 (COMPONENT_REF, TREE_TYPE (f_goff),
5661                         unshare_expr (valist), f_goff, NULL_TREE);
5662           rsize = (size + UNITS_PER_WORD - 1) & -UNITS_PER_WORD;
5663           if (rsize > UNITS_PER_WORD)
5664             {
5665               /* [1] Emit code for: off &= -rsize.      */
5666               t = build2 (BIT_AND_EXPR, TREE_TYPE (off), unshare_expr (off),
5667                           build_int_cst (TREE_TYPE (off), -rsize));
5668               gimplify_assign (unshare_expr (off), t, pre_p);
5669             }
5670           osize = rsize;
5671         }
5672
5673       /* [2] Emit code to branch if off == 0.  */
5674       t = build2 (NE_EXPR, boolean_type_node, off,
5675                   build_int_cst (TREE_TYPE (off), 0));
5676       addr = build3 (COND_EXPR, ptr_type_node, t, NULL_TREE, NULL_TREE);
5677
5678       /* [5] Emit code for: off -= rsize.  We do this as a form of
5679          post-decrement not available to C.  */
5680       t = fold_convert (TREE_TYPE (off), build_int_cst (NULL_TREE, rsize));
5681       t = build2 (POSTDECREMENT_EXPR, TREE_TYPE (off), off, t);
5682
5683       /* [4] Emit code for:
5684          addr_rtx = top - off + (BYTES_BIG_ENDIAN ? RSIZE - SIZE : 0).  */
5685       t = fold_convert (sizetype, t);
5686       t = fold_build1 (NEGATE_EXPR, sizetype, t);
5687       t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (top), top, t);
5688       if (BYTES_BIG_ENDIAN && rsize > size)
5689         {
5690           u = size_int (rsize - size);
5691           t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (t), t, u);
5692         }
5693       COND_EXPR_THEN (addr) = t;
5694
5695       if (osize > UNITS_PER_WORD)
5696         {
5697           /* [9] Emit: ovfl = ((intptr_t) ovfl + osize - 1) & -osize.  */
5698           u = size_int (osize - 1);
5699           t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (ovfl),
5700                       unshare_expr (ovfl), u);
5701           t = fold_convert (sizetype, t);
5702           u = size_int (-osize);
5703           t = build2 (BIT_AND_EXPR, sizetype, t, u);
5704           t = fold_convert (TREE_TYPE (ovfl), t);
5705           align = build2 (MODIFY_EXPR, TREE_TYPE (ovfl),
5706                           unshare_expr (ovfl), t);
5707         }
5708       else
5709         align = NULL;
5710
5711       /* [10, 11] Emit code for:
5712          addr_rtx = ovfl + (BYTES_BIG_ENDIAN ? OSIZE - SIZE : 0)
5713          ovfl += osize.  */
5714       u = fold_convert (TREE_TYPE (ovfl), build_int_cst (NULL_TREE, osize));
5715       t = build2 (POSTINCREMENT_EXPR, TREE_TYPE (ovfl), ovfl, u);
5716       if (BYTES_BIG_ENDIAN && osize > size)
5717         {
5718           u = size_int (osize - size);
5719           t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (t), t, u);
5720         }
5721
5722       /* String [9] and [10, 11] together.  */
5723       if (align)
5724         t = build2 (COMPOUND_EXPR, TREE_TYPE (t), align, t);
5725       COND_EXPR_ELSE (addr) = t;
5726
5727       addr = fold_convert (build_pointer_type (type), addr);
5728       addr = build_va_arg_indirect_ref (addr);
5729     }
5730
5731   if (indirect_p)
5732     addr = build_va_arg_indirect_ref (addr);
5733
5734   return addr;
5735 }
5736 \f
5737 /* Start a definition of function NAME.  MIPS16_P indicates whether the
5738    function contains MIPS16 code.  */
5739
5740 static void
5741 mips_start_function_definition (const char *name, bool mips16_p)
5742 {
5743   if (mips16_p)
5744     fprintf (asm_out_file, "\t.set\tmips16\n");
5745   else
5746     fprintf (asm_out_file, "\t.set\tnomips16\n");
5747
5748   if (!flag_inhibit_size_directive)
5749     {
5750       fputs ("\t.ent\t", asm_out_file);
5751       assemble_name (asm_out_file, name);
5752       fputs ("\n", asm_out_file);
5753     }
5754
5755   ASM_OUTPUT_TYPE_DIRECTIVE (asm_out_file, name, "function");
5756
5757   /* Start the definition proper.  */
5758   assemble_name (asm_out_file, name);
5759   fputs (":\n", asm_out_file);
5760 }
5761
5762 /* End a function definition started by mips_start_function_definition.  */
5763
5764 static void
5765 mips_end_function_definition (const char *name)
5766 {
5767   if (!flag_inhibit_size_directive)
5768     {
5769       fputs ("\t.end\t", asm_out_file);
5770       assemble_name (asm_out_file, name);
5771       fputs ("\n", asm_out_file);
5772     }
5773 }
5774 \f
5775 /* Return true if calls to X can use R_MIPS_CALL* relocations.  */
5776
5777 static bool
5778 mips_ok_for_lazy_binding_p (rtx x)
5779 {
5780   return (TARGET_USE_GOT
5781           && GET_CODE (x) == SYMBOL_REF
5782           && !SYMBOL_REF_BIND_NOW_P (x)
5783           && !mips_symbol_binds_local_p (x));
5784 }
5785
5786 /* Load function address ADDR into register DEST.  TYPE is as for
5787    mips_expand_call.  Return true if we used an explicit lazy-binding
5788    sequence.  */
5789
5790 static bool
5791 mips_load_call_address (enum mips_call_type type, rtx dest, rtx addr)
5792 {
5793   /* If we're generating PIC, and this call is to a global function,
5794      try to allow its address to be resolved lazily.  This isn't
5795      possible for sibcalls when $gp is call-saved because the value
5796      of $gp on entry to the stub would be our caller's gp, not ours.  */
5797   if (TARGET_EXPLICIT_RELOCS
5798       && !(type == MIPS_CALL_SIBCALL && TARGET_CALL_SAVED_GP)
5799       && mips_ok_for_lazy_binding_p (addr))
5800     {
5801       addr = mips_got_load (dest, addr, SYMBOL_GOTOFF_CALL);
5802       emit_insn (gen_rtx_SET (VOIDmode, dest, addr));
5803       return true;
5804     }
5805   else
5806     {
5807       mips_emit_move (dest, addr);
5808       return false;
5809     }
5810 }
5811 \f
5812 /* Each locally-defined hard-float MIPS16 function has a local symbol
5813    associated with it.  This hash table maps the function symbol (FUNC)
5814    to the local symbol (LOCAL). */
5815 struct GTY(()) mips16_local_alias {
5816   rtx func;
5817   rtx local;
5818 };
5819 static GTY ((param_is (struct mips16_local_alias))) htab_t mips16_local_aliases;
5820
5821 /* Hash table callbacks for mips16_local_aliases.  */
5822
5823 static hashval_t
5824 mips16_local_aliases_hash (const void *entry)
5825 {
5826   const struct mips16_local_alias *alias;
5827
5828   alias = (const struct mips16_local_alias *) entry;
5829   return htab_hash_string (XSTR (alias->func, 0));
5830 }
5831
5832 static int
5833 mips16_local_aliases_eq (const void *entry1, const void *entry2)
5834 {
5835   const struct mips16_local_alias *alias1, *alias2;
5836
5837   alias1 = (const struct mips16_local_alias *) entry1;
5838   alias2 = (const struct mips16_local_alias *) entry2;
5839   return rtx_equal_p (alias1->func, alias2->func);
5840 }
5841
5842 /* FUNC is the symbol for a locally-defined hard-float MIPS16 function.
5843    Return a local alias for it, creating a new one if necessary.  */
5844
5845 static rtx
5846 mips16_local_alias (rtx func)
5847 {
5848   struct mips16_local_alias *alias, tmp_alias;
5849   void **slot;
5850
5851   /* Create the hash table if this is the first call.  */
5852   if (mips16_local_aliases == NULL)
5853     mips16_local_aliases = htab_create_ggc (37, mips16_local_aliases_hash,
5854                                             mips16_local_aliases_eq, NULL);
5855
5856   /* Look up the function symbol, creating a new entry if need be.  */
5857   tmp_alias.func = func;
5858   slot = htab_find_slot (mips16_local_aliases, &tmp_alias, INSERT);
5859   gcc_assert (slot != NULL);
5860
5861   alias = (struct mips16_local_alias *) *slot;
5862   if (alias == NULL)
5863     {
5864       const char *func_name, *local_name;
5865       rtx local;
5866
5867       /* Create a new SYMBOL_REF for the local symbol.  The choice of
5868          __fn_local_* is based on the __fn_stub_* names that we've
5869          traditionally used for the non-MIPS16 stub.  */
5870       func_name = targetm.strip_name_encoding (XSTR (func, 0));
5871       local_name = ACONCAT (("__fn_local_", func_name, NULL));
5872       local = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (local_name));
5873       SYMBOL_REF_FLAGS (local) = SYMBOL_REF_FLAGS (func) | SYMBOL_FLAG_LOCAL;
5874
5875       /* Create a new structure to represent the mapping.  */
5876       alias = ggc_alloc_mips16_local_alias ();
5877       alias->func = func;
5878       alias->local = local;
5879       *slot = alias;
5880     }
5881   return alias->local;
5882 }
5883 \f
5884 /* A chained list of functions for which mips16_build_call_stub has already
5885    generated a stub.  NAME is the name of the function and FP_RET_P is true
5886    if the function returns a value in floating-point registers.  */
5887 struct mips16_stub {
5888   struct mips16_stub *next;
5889   char *name;
5890   bool fp_ret_p;
5891 };
5892 static struct mips16_stub *mips16_stubs;
5893
5894 /* Return a SYMBOL_REF for a MIPS16 function called NAME.  */
5895
5896 static rtx
5897 mips16_stub_function (const char *name)
5898 {
5899   rtx x;
5900
5901   x = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (name));
5902   SYMBOL_REF_FLAGS (x) |= (SYMBOL_FLAG_EXTERNAL | SYMBOL_FLAG_FUNCTION);
5903   return x;
5904 }
5905
5906 /* Return the two-character string that identifies floating-point
5907    return mode MODE in the name of a MIPS16 function stub.  */
5908
5909 static const char *
5910 mips16_call_stub_mode_suffix (enum machine_mode mode)
5911 {
5912   if (mode == SFmode)
5913     return "sf";
5914   else if (mode == DFmode)
5915     return "df";
5916   else if (mode == SCmode)
5917     return "sc";
5918   else if (mode == DCmode)
5919     return "dc";
5920   else if (mode == V2SFmode)
5921     return "df";
5922   else
5923     gcc_unreachable ();
5924 }
5925
5926 /* Write instructions to move a 32-bit value between general register
5927    GPREG and floating-point register FPREG.  DIRECTION is 't' to move
5928    from GPREG to FPREG and 'f' to move in the opposite direction.  */
5929
5930 static void
5931 mips_output_32bit_xfer (char direction, unsigned int gpreg, unsigned int fpreg)
5932 {
5933   fprintf (asm_out_file, "\tm%cc1\t%s,%s\n", direction,
5934            reg_names[gpreg], reg_names[fpreg]);
5935 }
5936
5937 /* Likewise for 64-bit values.  */
5938
5939 static void
5940 mips_output_64bit_xfer (char direction, unsigned int gpreg, unsigned int fpreg)
5941 {
5942   if (TARGET_64BIT)
5943     fprintf (asm_out_file, "\tdm%cc1\t%s,%s\n", direction,
5944              reg_names[gpreg], reg_names[fpreg]);
5945   else if (TARGET_FLOAT64)
5946     {
5947       fprintf (asm_out_file, "\tm%cc1\t%s,%s\n", direction,
5948                reg_names[gpreg + TARGET_BIG_ENDIAN], reg_names[fpreg]);
5949       fprintf (asm_out_file, "\tm%chc1\t%s,%s\n", direction,
5950                reg_names[gpreg + TARGET_LITTLE_ENDIAN], reg_names[fpreg]);
5951     }
5952   else
5953     {
5954       /* Move the least-significant word.  */
5955       fprintf (asm_out_file, "\tm%cc1\t%s,%s\n", direction,
5956                reg_names[gpreg + TARGET_BIG_ENDIAN], reg_names[fpreg]);
5957       /* ...then the most significant word.  */
5958       fprintf (asm_out_file, "\tm%cc1\t%s,%s\n", direction,
5959                reg_names[gpreg + TARGET_LITTLE_ENDIAN], reg_names[fpreg + 1]);
5960     }
5961 }
5962
5963 /* Write out code to move floating-point arguments into or out of
5964    general registers.  FP_CODE is the code describing which arguments
5965    are present (see the comment above the definition of CUMULATIVE_ARGS
5966    in mips.h).  DIRECTION is as for mips_output_32bit_xfer.  */
5967
5968 static void
5969 mips_output_args_xfer (int fp_code, char direction)
5970 {
5971   unsigned int gparg, fparg, f;
5972   CUMULATIVE_ARGS cum;
5973
5974   /* This code only works for o32 and o64.  */
5975   gcc_assert (TARGET_OLDABI);
5976
5977   mips_init_cumulative_args (&cum, NULL);
5978
5979   for (f = (unsigned int) fp_code; f != 0; f >>= 2)
5980     {
5981       enum machine_mode mode;
5982       struct mips_arg_info info;
5983
5984       if ((f & 3) == 1)
5985         mode = SFmode;
5986       else if ((f & 3) == 2)
5987         mode = DFmode;
5988       else
5989         gcc_unreachable ();
5990
5991       mips_get_arg_info (&info, &cum, mode, NULL, true);
5992       gparg = mips_arg_regno (&info, false);
5993       fparg = mips_arg_regno (&info, true);
5994
5995       if (mode == SFmode)
5996         mips_output_32bit_xfer (direction, gparg, fparg);
5997       else
5998         mips_output_64bit_xfer (direction, gparg, fparg);
5999
6000       mips_function_arg_advance (&cum, mode, NULL, true);
6001     }
6002 }
6003
6004 /* Write a MIPS16 stub for the current function.  This stub is used
6005    for functions which take arguments in the floating-point registers.
6006    It is normal-mode code that moves the floating-point arguments
6007    into the general registers and then jumps to the MIPS16 code.  */
6008
6009 static void
6010 mips16_build_function_stub (void)
6011 {
6012   const char *fnname, *alias_name, *separator;
6013   char *secname, *stubname;
6014   tree stubdecl;
6015   unsigned int f;
6016   rtx symbol, alias;
6017
6018   /* Create the name of the stub, and its unique section.  */
6019   symbol = XEXP (DECL_RTL (current_function_decl), 0);
6020   alias = mips16_local_alias (symbol);
6021
6022   fnname = targetm.strip_name_encoding (XSTR (symbol, 0));
6023   alias_name = targetm.strip_name_encoding (XSTR (alias, 0));
6024   secname = ACONCAT ((".mips16.fn.", fnname, NULL));
6025   stubname = ACONCAT (("__fn_stub_", fnname, NULL));
6026
6027   /* Build a decl for the stub.  */
6028   stubdecl = build_decl (BUILTINS_LOCATION,
6029                          FUNCTION_DECL, get_identifier (stubname),
6030                          build_function_type (void_type_node, NULL_TREE));
6031   DECL_SECTION_NAME (stubdecl) = build_string (strlen (secname), secname);
6032   DECL_RESULT (stubdecl) = build_decl (BUILTINS_LOCATION,
6033                                        RESULT_DECL, NULL_TREE, void_type_node);
6034
6035   /* Output a comment.  */
6036   fprintf (asm_out_file, "\t# Stub function for %s (",
6037            current_function_name ());
6038   separator = "";
6039   for (f = (unsigned int) crtl->args.info.fp_code; f != 0; f >>= 2)
6040     {
6041       fprintf (asm_out_file, "%s%s", separator,
6042                (f & 3) == 1 ? "float" : "double");
6043       separator = ", ";
6044     }
6045   fprintf (asm_out_file, ")\n");
6046
6047   /* Start the function definition.  */
6048   assemble_start_function (stubdecl, stubname);
6049   mips_start_function_definition (stubname, false);
6050
6051   /* If generating pic2 code, either set up the global pointer or
6052      switch to pic0.  */
6053   if (TARGET_ABICALLS_PIC2)
6054     {
6055       if (TARGET_ABSOLUTE_ABICALLS)
6056         fprintf (asm_out_file, "\t.option\tpic0\n");
6057       else
6058         {
6059           output_asm_insn ("%(.cpload\t%^%)", NULL);
6060           /* Emit an R_MIPS_NONE relocation to tell the linker what the
6061              target function is.  Use a local GOT access when loading the
6062              symbol, to cut down on the number of unnecessary GOT entries
6063              for stubs that aren't needed.  */
6064           output_asm_insn (".reloc\t0,R_MIPS_NONE,%0", &symbol);
6065           symbol = alias;
6066         }
6067     }
6068
6069   /* Load the address of the MIPS16 function into $25.  Do this first so
6070      that targets with coprocessor interlocks can use an MFC1 to fill the
6071      delay slot.  */
6072   output_asm_insn ("la\t%^,%0", &symbol);
6073
6074   /* Move the arguments from floating-point registers to general registers.  */
6075   mips_output_args_xfer (crtl->args.info.fp_code, 'f');
6076
6077   /* Jump to the MIPS16 function.  */
6078   output_asm_insn ("jr\t%^", NULL);
6079
6080   if (TARGET_ABICALLS_PIC2 && TARGET_ABSOLUTE_ABICALLS)
6081     fprintf (asm_out_file, "\t.option\tpic2\n");
6082
6083   mips_end_function_definition (stubname);
6084
6085   /* If the linker needs to create a dynamic symbol for the target
6086      function, it will associate the symbol with the stub (which,
6087      unlike the target function, follows the proper calling conventions).
6088      It is therefore useful to have a local alias for the target function,
6089      so that it can still be identified as MIPS16 code.  As an optimization,
6090      this symbol can also be used for indirect MIPS16 references from
6091      within this file.  */
6092   ASM_OUTPUT_DEF (asm_out_file, alias_name, fnname);
6093
6094   switch_to_section (function_section (current_function_decl));
6095 }
6096
6097 /* The current function is a MIPS16 function that returns a value in an FPR.
6098    Copy the return value from its soft-float to its hard-float location.
6099    libgcc2 has special non-MIPS16 helper functions for each case.  */
6100
6101 static void
6102 mips16_copy_fpr_return_value (void)
6103 {
6104   rtx fn, insn, retval;
6105   tree return_type;
6106   enum machine_mode return_mode;
6107   const char *name;
6108
6109   return_type = DECL_RESULT (current_function_decl);
6110   return_mode = DECL_MODE (return_type);
6111
6112   name = ACONCAT (("__mips16_ret_",
6113                    mips16_call_stub_mode_suffix (return_mode),
6114                    NULL));
6115   fn = mips16_stub_function (name);
6116
6117   /* The function takes arguments in $2 (and possibly $3), so calls
6118      to it cannot be lazily bound.  */
6119   SYMBOL_REF_FLAGS (fn) |= SYMBOL_FLAG_BIND_NOW;
6120
6121   /* Model the call as something that takes the GPR return value as
6122      argument and returns an "updated" value.  */
6123   retval = gen_rtx_REG (return_mode, GP_RETURN);
6124   insn = mips_expand_call (MIPS_CALL_EPILOGUE, retval, fn,
6125                            const0_rtx, NULL_RTX, false);
6126   use_reg (&CALL_INSN_FUNCTION_USAGE (insn), retval);
6127 }
6128
6129 /* Consider building a stub for a MIPS16 call to function *FN_PTR.
6130    RETVAL is the location of the return value, or null if this is
6131    a "call" rather than a "call_value".  ARGS_SIZE is the size of the
6132    arguments and FP_CODE is the code built by mips_function_arg;
6133    see the comment before the fp_code field in CUMULATIVE_ARGS for details.
6134
6135    There are three alternatives:
6136
6137    - If a stub was needed, emit the call and return the call insn itself.
6138
6139    - If we can avoid using a stub by redirecting the call, set *FN_PTR
6140      to the new target and return null.
6141
6142    - If *FN_PTR doesn't need a stub, return null and leave *FN_PTR
6143      unmodified.
6144
6145    A stub is needed for calls to functions that, in normal mode,
6146    receive arguments in FPRs or return values in FPRs.  The stub
6147    copies the arguments from their soft-float positions to their
6148    hard-float positions, calls the real function, then copies the
6149    return value from its hard-float position to its soft-float
6150    position.
6151
6152    We can emit a JAL to *FN_PTR even when *FN_PTR might need a stub.
6153    If *FN_PTR turns out to be to a non-MIPS16 function, the linker
6154    automatically redirects the JAL to the stub, otherwise the JAL
6155    continues to call FN directly.  */
6156
6157 static rtx
6158 mips16_build_call_stub (rtx retval, rtx *fn_ptr, rtx args_size, int fp_code)
6159 {
6160   const char *fnname;
6161   bool fp_ret_p;
6162   struct mips16_stub *l;
6163   rtx insn, fn;
6164
6165   /* We don't need to do anything if we aren't in MIPS16 mode, or if
6166      we were invoked with the -msoft-float option.  */
6167   if (!TARGET_MIPS16 || TARGET_SOFT_FLOAT_ABI)
6168     return NULL_RTX;
6169
6170   /* Figure out whether the value might come back in a floating-point
6171      register.  */
6172   fp_ret_p = retval && mips_return_mode_in_fpr_p (GET_MODE (retval));
6173
6174   /* We don't need to do anything if there were no floating-point
6175      arguments and the value will not be returned in a floating-point
6176      register.  */
6177   if (fp_code == 0 && !fp_ret_p)
6178     return NULL_RTX;
6179
6180   /* We don't need to do anything if this is a call to a special
6181      MIPS16 support function.  */
6182   fn = *fn_ptr;
6183   if (mips16_stub_function_p (fn))
6184     return NULL_RTX;
6185
6186   /* This code will only work for o32 and o64 abis.  The other ABI's
6187      require more sophisticated support.  */
6188   gcc_assert (TARGET_OLDABI);
6189
6190   /* If we're calling via a function pointer, use one of the magic
6191      libgcc.a stubs provided for each (FP_CODE, FP_RET_P) combination.
6192      Each stub expects the function address to arrive in register $2.  */
6193   if (GET_CODE (fn) != SYMBOL_REF
6194       || !call_insn_operand (fn, VOIDmode))
6195     {
6196       char buf[30];
6197       rtx stub_fn, insn, addr;
6198       bool lazy_p;
6199
6200       /* If this is a locally-defined and locally-binding function,
6201          avoid the stub by calling the local alias directly.  */
6202       if (mips16_local_function_p (fn))
6203         {
6204           *fn_ptr = mips16_local_alias (fn);
6205           return NULL_RTX;
6206         }
6207
6208       /* Create a SYMBOL_REF for the libgcc.a function.  */
6209       if (fp_ret_p)
6210         sprintf (buf, "__mips16_call_stub_%s_%d",
6211                  mips16_call_stub_mode_suffix (GET_MODE (retval)),
6212                  fp_code);
6213       else
6214         sprintf (buf, "__mips16_call_stub_%d", fp_code);
6215       stub_fn = mips16_stub_function (buf);
6216
6217       /* The function uses $2 as an argument, so calls to it
6218          cannot be lazily bound.  */
6219       SYMBOL_REF_FLAGS (stub_fn) |= SYMBOL_FLAG_BIND_NOW;
6220
6221       /* Load the target function into $2.  */
6222       addr = gen_rtx_REG (Pmode, GP_REG_FIRST + 2);
6223       lazy_p = mips_load_call_address (MIPS_CALL_NORMAL, addr, fn);
6224
6225       /* Emit the call.  */
6226       insn = mips_expand_call (MIPS_CALL_NORMAL, retval, stub_fn,
6227                                args_size, NULL_RTX, lazy_p);
6228
6229       /* Tell GCC that this call does indeed use the value of $2.  */
6230       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), addr);
6231
6232       /* If we are handling a floating-point return value, we need to
6233          save $18 in the function prologue.  Putting a note on the
6234          call will mean that df_regs_ever_live_p ($18) will be true if the
6235          call is not eliminated, and we can check that in the prologue
6236          code.  */
6237       if (fp_ret_p)
6238         CALL_INSN_FUNCTION_USAGE (insn) =
6239           gen_rtx_EXPR_LIST (VOIDmode,
6240                              gen_rtx_CLOBBER (VOIDmode,
6241                                               gen_rtx_REG (word_mode, 18)),
6242                              CALL_INSN_FUNCTION_USAGE (insn));
6243
6244       return insn;
6245     }
6246
6247   /* We know the function we are going to call.  If we have already
6248      built a stub, we don't need to do anything further.  */
6249   fnname = targetm.strip_name_encoding (XSTR (fn, 0));
6250   for (l = mips16_stubs; l != NULL; l = l->next)
6251     if (strcmp (l->name, fnname) == 0)
6252       break;
6253
6254   if (l == NULL)
6255     {
6256       const char *separator;
6257       char *secname, *stubname;
6258       tree stubid, stubdecl;
6259       unsigned int f;
6260
6261       /* If the function does not return in FPRs, the special stub
6262          section is named
6263              .mips16.call.FNNAME
6264
6265          If the function does return in FPRs, the stub section is named
6266              .mips16.call.fp.FNNAME
6267
6268          Build a decl for the stub.  */
6269       secname = ACONCAT ((".mips16.call.", fp_ret_p ? "fp." : "",
6270                           fnname, NULL));
6271       stubname = ACONCAT (("__call_stub_", fp_ret_p ? "fp_" : "",
6272                            fnname, NULL));
6273       stubid = get_identifier (stubname);
6274       stubdecl = build_decl (BUILTINS_LOCATION,
6275                              FUNCTION_DECL, stubid,
6276                              build_function_type (void_type_node, NULL_TREE));
6277       DECL_SECTION_NAME (stubdecl) = build_string (strlen (secname), secname);
6278       DECL_RESULT (stubdecl) = build_decl (BUILTINS_LOCATION,
6279                                            RESULT_DECL, NULL_TREE,
6280                                            void_type_node);
6281
6282       /* Output a comment.  */
6283       fprintf (asm_out_file, "\t# Stub function to call %s%s (",
6284                (fp_ret_p
6285                 ? (GET_MODE (retval) == SFmode ? "float " : "double ")
6286                 : ""),
6287                fnname);
6288       separator = "";
6289       for (f = (unsigned int) fp_code; f != 0; f >>= 2)
6290         {
6291           fprintf (asm_out_file, "%s%s", separator,
6292                    (f & 3) == 1 ? "float" : "double");
6293           separator = ", ";
6294         }
6295       fprintf (asm_out_file, ")\n");
6296
6297       /* Start the function definition.  */
6298       assemble_start_function (stubdecl, stubname);
6299       mips_start_function_definition (stubname, false);
6300
6301       if (!fp_ret_p)
6302         {
6303           /* Load the address of the MIPS16 function into $25.  Do this
6304              first so that targets with coprocessor interlocks can use
6305              an MFC1 to fill the delay slot.  */
6306           if (TARGET_EXPLICIT_RELOCS)
6307             {
6308               output_asm_insn ("lui\t%^,%%hi(%0)", &fn);
6309               output_asm_insn ("addiu\t%^,%^,%%lo(%0)", &fn);
6310             }
6311           else
6312             output_asm_insn ("la\t%^,%0", &fn);
6313         }
6314
6315       /* Move the arguments from general registers to floating-point
6316          registers.  */
6317       mips_output_args_xfer (fp_code, 't');
6318
6319       if (!fp_ret_p)
6320         {
6321           /* Jump to the previously-loaded address.  */
6322           output_asm_insn ("jr\t%^", NULL);
6323         }
6324       else
6325         {
6326           /* Save the return address in $18 and call the non-MIPS16 function.
6327              The stub's caller knows that $18 might be clobbered, even though
6328              $18 is usually a call-saved register.  */
6329           fprintf (asm_out_file, "\tmove\t%s,%s\n",
6330                    reg_names[GP_REG_FIRST + 18], reg_names[RETURN_ADDR_REGNUM]);
6331           output_asm_insn (MIPS_CALL ("jal", &fn, 0, -1), &fn);
6332
6333           /* Move the result from floating-point registers to
6334              general registers.  */
6335           switch (GET_MODE (retval))
6336             {
6337             case SCmode:
6338               mips_output_32bit_xfer ('f', GP_RETURN + TARGET_BIG_ENDIAN,
6339                                       TARGET_BIG_ENDIAN
6340                                       ? FP_REG_FIRST + MAX_FPRS_PER_FMT
6341                                       : FP_REG_FIRST);
6342               mips_output_32bit_xfer ('f', GP_RETURN + TARGET_LITTLE_ENDIAN,
6343                                       TARGET_LITTLE_ENDIAN
6344                                       ? FP_REG_FIRST + MAX_FPRS_PER_FMT
6345                                       : FP_REG_FIRST);
6346               if (GET_MODE (retval) == SCmode && TARGET_64BIT)
6347                 {
6348                   /* On 64-bit targets, complex floats are returned in
6349                      a single GPR, such that "sd" on a suitably-aligned
6350                      target would store the value correctly.  */
6351                   fprintf (asm_out_file, "\tdsll\t%s,%s,32\n",
6352                            reg_names[GP_RETURN + TARGET_BIG_ENDIAN],
6353                            reg_names[GP_RETURN + TARGET_BIG_ENDIAN]);
6354                   fprintf (asm_out_file, "\tdsll\t%s,%s,32\n",
6355                            reg_names[GP_RETURN + TARGET_LITTLE_ENDIAN],
6356                            reg_names[GP_RETURN + TARGET_LITTLE_ENDIAN]);
6357                   fprintf (asm_out_file, "\tdsrl\t%s,%s,32\n",
6358                            reg_names[GP_RETURN + TARGET_BIG_ENDIAN],
6359                            reg_names[GP_RETURN + TARGET_BIG_ENDIAN]);
6360                   fprintf (asm_out_file, "\tor\t%s,%s,%s\n",
6361                            reg_names[GP_RETURN],
6362                            reg_names[GP_RETURN],
6363                            reg_names[GP_RETURN + 1]);
6364                 }
6365               break;
6366
6367             case SFmode:
6368               mips_output_32bit_xfer ('f', GP_RETURN, FP_REG_FIRST);
6369               break;
6370
6371             case DCmode:
6372               mips_output_64bit_xfer ('f', GP_RETURN + (8 / UNITS_PER_WORD),
6373                                       FP_REG_FIRST + MAX_FPRS_PER_FMT);
6374               /* Fall though.  */
6375             case DFmode:
6376             case V2SFmode:
6377               mips_output_64bit_xfer ('f', GP_RETURN, FP_REG_FIRST);
6378               break;
6379
6380             default:
6381               gcc_unreachable ();
6382             }
6383           fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 18]);
6384         }
6385
6386 #ifdef ASM_DECLARE_FUNCTION_SIZE
6387       ASM_DECLARE_FUNCTION_SIZE (asm_out_file, stubname, stubdecl);
6388 #endif
6389
6390       mips_end_function_definition (stubname);
6391
6392       /* Record this stub.  */
6393       l = XNEW (struct mips16_stub);
6394       l->name = xstrdup (fnname);
6395       l->fp_ret_p = fp_ret_p;
6396       l->next = mips16_stubs;
6397       mips16_stubs = l;
6398     }
6399
6400   /* If we expect a floating-point return value, but we've built a
6401      stub which does not expect one, then we're in trouble.  We can't
6402      use the existing stub, because it won't handle the floating-point
6403      value.  We can't build a new stub, because the linker won't know
6404      which stub to use for the various calls in this object file.
6405      Fortunately, this case is illegal, since it means that a function
6406      was declared in two different ways in a single compilation.  */
6407   if (fp_ret_p && !l->fp_ret_p)
6408     error ("cannot handle inconsistent calls to %qs", fnname);
6409
6410   if (retval == NULL_RTX)
6411     insn = gen_call_internal_direct (fn, args_size);
6412   else
6413     insn = gen_call_value_internal_direct (retval, fn, args_size);
6414   insn = mips_emit_call_insn (insn, fn, fn, false);
6415
6416   /* If we are calling a stub which handles a floating-point return
6417      value, we need to arrange to save $18 in the prologue.  We do this
6418      by marking the function call as using the register.  The prologue
6419      will later see that it is used, and emit code to save it.  */
6420   if (fp_ret_p)
6421     CALL_INSN_FUNCTION_USAGE (insn) =
6422       gen_rtx_EXPR_LIST (VOIDmode,
6423                          gen_rtx_CLOBBER (VOIDmode,
6424                                           gen_rtx_REG (word_mode, 18)),
6425                          CALL_INSN_FUNCTION_USAGE (insn));
6426
6427   return insn;
6428 }
6429 \f
6430 /* Expand a call of type TYPE.  RESULT is where the result will go (null
6431    for "call"s and "sibcall"s), ADDR is the address of the function,
6432    ARGS_SIZE is the size of the arguments and AUX is the value passed
6433    to us by mips_function_arg.  LAZY_P is true if this call already
6434    involves a lazily-bound function address (such as when calling
6435    functions through a MIPS16 hard-float stub).
6436
6437    Return the call itself.  */
6438
6439 rtx
6440 mips_expand_call (enum mips_call_type type, rtx result, rtx addr,
6441                   rtx args_size, rtx aux, bool lazy_p)
6442 {
6443   rtx orig_addr, pattern, insn;
6444   int fp_code;
6445
6446   fp_code = aux == 0 ? 0 : (int) GET_MODE (aux);
6447   insn = mips16_build_call_stub (result, &addr, args_size, fp_code);
6448   if (insn)
6449     {
6450       gcc_assert (!lazy_p && type == MIPS_CALL_NORMAL);
6451       return insn;
6452     }
6453                                  ;
6454   orig_addr = addr;
6455   if (!call_insn_operand (addr, VOIDmode))
6456     {
6457       if (type == MIPS_CALL_EPILOGUE)
6458         addr = MIPS_EPILOGUE_TEMP (Pmode);
6459       else
6460         addr = gen_reg_rtx (Pmode);
6461       lazy_p |= mips_load_call_address (type, addr, orig_addr);
6462     }
6463
6464   if (result == 0)
6465     {
6466       rtx (*fn) (rtx, rtx);
6467
6468       if (type == MIPS_CALL_SIBCALL)
6469         fn = gen_sibcall_internal;
6470       else
6471         fn = gen_call_internal;
6472
6473       pattern = fn (addr, args_size);
6474     }
6475   else if (GET_CODE (result) == PARALLEL && XVECLEN (result, 0) == 2)
6476     {
6477       /* Handle return values created by mips_return_fpr_pair.  */
6478       rtx (*fn) (rtx, rtx, rtx, rtx);
6479       rtx reg1, reg2;
6480
6481       if (type == MIPS_CALL_SIBCALL)
6482         fn = gen_sibcall_value_multiple_internal;
6483       else
6484         fn = gen_call_value_multiple_internal;
6485
6486       reg1 = XEXP (XVECEXP (result, 0, 0), 0);
6487       reg2 = XEXP (XVECEXP (result, 0, 1), 0);
6488       pattern = fn (reg1, addr, args_size, reg2);
6489     }
6490   else
6491     {
6492       rtx (*fn) (rtx, rtx, rtx);
6493
6494       if (type == MIPS_CALL_SIBCALL)
6495         fn = gen_sibcall_value_internal;
6496       else
6497         fn = gen_call_value_internal;
6498
6499       /* Handle return values created by mips_return_fpr_single.  */
6500       if (GET_CODE (result) == PARALLEL && XVECLEN (result, 0) == 1)
6501         result = XEXP (XVECEXP (result, 0, 0), 0);
6502       pattern = fn (result, addr, args_size);
6503     }
6504
6505   return mips_emit_call_insn (pattern, orig_addr, addr, lazy_p);
6506 }
6507
6508 /* Split call instruction INSN into a $gp-clobbering call and
6509    (where necessary) an instruction to restore $gp from its save slot.
6510    CALL_PATTERN is the pattern of the new call.  */
6511
6512 void
6513 mips_split_call (rtx insn, rtx call_pattern)
6514 {
6515   emit_call_insn (call_pattern);
6516   if (!find_reg_note (insn, REG_NORETURN, 0))
6517     /* Pick a temporary register that is suitable for both MIPS16 and
6518        non-MIPS16 code.  $4 and $5 are used for returning complex double
6519        values in soft-float code, so $6 is the first suitable candidate.  */
6520     mips_restore_gp_from_cprestore_slot (gen_rtx_REG (Pmode, GP_ARG_FIRST + 2));
6521 }
6522
6523 /* Implement TARGET_FUNCTION_OK_FOR_SIBCALL.  */
6524
6525 static bool
6526 mips_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
6527 {
6528   if (!TARGET_SIBCALLS)
6529     return false;
6530
6531   /* Interrupt handlers need special epilogue code and therefore can't
6532      use sibcalls.  */
6533   if (mips_interrupt_type_p (TREE_TYPE (current_function_decl)))
6534     return false;
6535
6536   /* We can't do a sibcall if the called function is a MIPS16 function
6537      because there is no direct "jx" instruction equivalent to "jalx" to
6538      switch the ISA mode.  We only care about cases where the sibling
6539      and normal calls would both be direct.  */
6540   if (decl
6541       && mips_use_mips16_mode_p (decl)
6542       && const_call_insn_operand (XEXP (DECL_RTL (decl), 0), VOIDmode))
6543     return false;
6544
6545   /* When -minterlink-mips16 is in effect, assume that non-locally-binding
6546      functions could be MIPS16 ones unless an attribute explicitly tells
6547      us otherwise.  */
6548   if (TARGET_INTERLINK_MIPS16
6549       && decl
6550       && (DECL_EXTERNAL (decl) || !targetm.binds_local_p (decl))
6551       && !mips_nomips16_decl_p (decl)
6552       && const_call_insn_operand (XEXP (DECL_RTL (decl), 0), VOIDmode))
6553     return false;
6554
6555   /* Otherwise OK.  */
6556   return true;
6557 }
6558 \f
6559 /* Emit code to move general operand SRC into condition-code
6560    register DEST given that SCRATCH is a scratch TFmode FPR.
6561    The sequence is:
6562
6563         FP1 = SRC
6564         FP2 = 0.0f
6565         DEST = FP2 < FP1
6566
6567    where FP1 and FP2 are single-precision FPRs taken from SCRATCH.  */
6568
6569 void
6570 mips_expand_fcc_reload (rtx dest, rtx src, rtx scratch)
6571 {
6572   rtx fp1, fp2;
6573
6574   /* Change the source to SFmode.  */
6575   if (MEM_P (src))
6576     src = adjust_address (src, SFmode, 0);
6577   else if (REG_P (src) || GET_CODE (src) == SUBREG)
6578     src = gen_rtx_REG (SFmode, true_regnum (src));
6579
6580   fp1 = gen_rtx_REG (SFmode, REGNO (scratch));
6581   fp2 = gen_rtx_REG (SFmode, REGNO (scratch) + MAX_FPRS_PER_FMT);
6582
6583   mips_emit_move (copy_rtx (fp1), src);
6584   mips_emit_move (copy_rtx (fp2), CONST0_RTX (SFmode));
6585   emit_insn (gen_slt_sf (dest, fp2, fp1));
6586 }
6587 \f
6588 /* Emit straight-line code to move LENGTH bytes from SRC to DEST.
6589    Assume that the areas do not overlap.  */
6590
6591 static void
6592 mips_block_move_straight (rtx dest, rtx src, HOST_WIDE_INT length)
6593 {
6594   HOST_WIDE_INT offset, delta;
6595   unsigned HOST_WIDE_INT bits;
6596   int i;
6597   enum machine_mode mode;
6598   rtx *regs;
6599
6600   /* Work out how many bits to move at a time.  If both operands have
6601      half-word alignment, it is usually better to move in half words.
6602      For instance, lh/lh/sh/sh is usually better than lwl/lwr/swl/swr
6603      and lw/lw/sw/sw is usually better than ldl/ldr/sdl/sdr.
6604      Otherwise move word-sized chunks.  */
6605   if (MEM_ALIGN (src) == BITS_PER_WORD / 2
6606       && MEM_ALIGN (dest) == BITS_PER_WORD / 2)
6607     bits = BITS_PER_WORD / 2;
6608   else
6609     bits = BITS_PER_WORD;
6610
6611   mode = mode_for_size (bits, MODE_INT, 0);
6612   delta = bits / BITS_PER_UNIT;
6613
6614   /* Allocate a buffer for the temporary registers.  */
6615   regs = XALLOCAVEC (rtx, length / delta);
6616
6617   /* Load as many BITS-sized chunks as possible.  Use a normal load if
6618      the source has enough alignment, otherwise use left/right pairs.  */
6619   for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
6620     {
6621       regs[i] = gen_reg_rtx (mode);
6622       if (MEM_ALIGN (src) >= bits)
6623         mips_emit_move (regs[i], adjust_address (src, mode, offset));
6624       else
6625         {
6626           rtx part = adjust_address (src, BLKmode, offset);
6627           if (!mips_expand_ext_as_unaligned_load (regs[i], part, bits, 0))
6628             gcc_unreachable ();
6629         }
6630     }
6631
6632   /* Copy the chunks to the destination.  */
6633   for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
6634     if (MEM_ALIGN (dest) >= bits)
6635       mips_emit_move (adjust_address (dest, mode, offset), regs[i]);
6636     else
6637       {
6638         rtx part = adjust_address (dest, BLKmode, offset);
6639         if (!mips_expand_ins_as_unaligned_store (part, regs[i], bits, 0))
6640           gcc_unreachable ();
6641       }
6642
6643   /* Mop up any left-over bytes.  */
6644   if (offset < length)
6645     {
6646       src = adjust_address (src, BLKmode, offset);
6647       dest = adjust_address (dest, BLKmode, offset);
6648       move_by_pieces (dest, src, length - offset,
6649                       MIN (MEM_ALIGN (src), MEM_ALIGN (dest)), 0);
6650     }
6651 }
6652
6653 /* Helper function for doing a loop-based block operation on memory
6654    reference MEM.  Each iteration of the loop will operate on LENGTH
6655    bytes of MEM.
6656
6657    Create a new base register for use within the loop and point it to
6658    the start of MEM.  Create a new memory reference that uses this
6659    register.  Store them in *LOOP_REG and *LOOP_MEM respectively.  */
6660
6661 static void
6662 mips_adjust_block_mem (rtx mem, HOST_WIDE_INT length,
6663                        rtx *loop_reg, rtx *loop_mem)
6664 {
6665   *loop_reg = copy_addr_to_reg (XEXP (mem, 0));
6666
6667   /* Although the new mem does not refer to a known location,
6668      it does keep up to LENGTH bytes of alignment.  */
6669   *loop_mem = change_address (mem, BLKmode, *loop_reg);
6670   set_mem_align (*loop_mem, MIN (MEM_ALIGN (mem), length * BITS_PER_UNIT));
6671 }
6672
6673 /* Move LENGTH bytes from SRC to DEST using a loop that moves BYTES_PER_ITER
6674    bytes at a time.  LENGTH must be at least BYTES_PER_ITER.  Assume that
6675    the memory regions do not overlap.  */
6676
6677 static void
6678 mips_block_move_loop (rtx dest, rtx src, HOST_WIDE_INT length,
6679                       HOST_WIDE_INT bytes_per_iter)
6680 {
6681   rtx label, src_reg, dest_reg, final_src, test;
6682   HOST_WIDE_INT leftover;
6683
6684   leftover = length % bytes_per_iter;
6685   length -= leftover;
6686
6687   /* Create registers and memory references for use within the loop.  */
6688   mips_adjust_block_mem (src, bytes_per_iter, &src_reg, &src);
6689   mips_adjust_block_mem (dest, bytes_per_iter, &dest_reg, &dest);
6690
6691   /* Calculate the value that SRC_REG should have after the last iteration
6692      of the loop.  */
6693   final_src = expand_simple_binop (Pmode, PLUS, src_reg, GEN_INT (length),
6694                                    0, 0, OPTAB_WIDEN);
6695
6696   /* Emit the start of the loop.  */
6697   label = gen_label_rtx ();
6698   emit_label (label);
6699
6700   /* Emit the loop body.  */
6701   mips_block_move_straight (dest, src, bytes_per_iter);
6702
6703   /* Move on to the next block.  */
6704   mips_emit_move (src_reg, plus_constant (src_reg, bytes_per_iter));
6705   mips_emit_move (dest_reg, plus_constant (dest_reg, bytes_per_iter));
6706
6707   /* Emit the loop condition.  */
6708   test = gen_rtx_NE (VOIDmode, src_reg, final_src);
6709   if (Pmode == DImode)
6710     emit_jump_insn (gen_cbranchdi4 (test, src_reg, final_src, label));
6711   else
6712     emit_jump_insn (gen_cbranchsi4 (test, src_reg, final_src, label));
6713
6714   /* Mop up any left-over bytes.  */
6715   if (leftover)
6716     mips_block_move_straight (dest, src, leftover);
6717 }
6718
6719 /* Expand a movmemsi instruction, which copies LENGTH bytes from
6720    memory reference SRC to memory reference DEST.  */
6721
6722 bool
6723 mips_expand_block_move (rtx dest, rtx src, rtx length)
6724 {
6725   if (CONST_INT_P (length))
6726     {
6727       if (INTVAL (length) <= MIPS_MAX_MOVE_BYTES_STRAIGHT)
6728         {
6729           mips_block_move_straight (dest, src, INTVAL (length));
6730           return true;
6731         }
6732       else if (optimize)
6733         {
6734           mips_block_move_loop (dest, src, INTVAL (length),
6735                                 MIPS_MAX_MOVE_BYTES_PER_LOOP_ITER);
6736           return true;
6737         }
6738     }
6739   return false;
6740 }
6741 \f
6742 /* Expand a loop of synci insns for the address range [BEGIN, END).  */
6743
6744 void
6745 mips_expand_synci_loop (rtx begin, rtx end)
6746 {
6747   rtx inc, label, end_label, cmp_result, mask, length;
6748
6749   /* Create end_label.  */
6750   end_label = gen_label_rtx ();
6751
6752   /* Check if begin equals end.  */
6753   cmp_result = gen_rtx_EQ (VOIDmode, begin, end);
6754   emit_jump_insn (gen_condjump (cmp_result, end_label));
6755
6756   /* Load INC with the cache line size (rdhwr INC,$1).  */
6757   inc = gen_reg_rtx (Pmode);
6758   emit_insn (Pmode == SImode
6759              ? gen_rdhwr_synci_step_si (inc)
6760              : gen_rdhwr_synci_step_di (inc));
6761
6762   /* Check if inc is 0.  */
6763   cmp_result = gen_rtx_EQ (VOIDmode, inc, const0_rtx);
6764   emit_jump_insn (gen_condjump (cmp_result, end_label));
6765
6766   /* Calculate mask.  */
6767   mask = mips_force_unary (Pmode, NEG, inc);
6768
6769   /* Mask out begin by mask.  */
6770   begin = mips_force_binary (Pmode, AND, begin, mask);
6771
6772   /* Calculate length.  */
6773   length = mips_force_binary (Pmode, MINUS, end, begin);
6774
6775   /* Loop back to here.  */
6776   label = gen_label_rtx ();
6777   emit_label (label);
6778
6779   emit_insn (gen_synci (begin));
6780
6781   /* Update length.  */
6782   mips_emit_binary (MINUS, length, length, inc);
6783
6784   /* Update begin.  */
6785   mips_emit_binary (PLUS, begin, begin, inc);
6786
6787   /* Check if length is greater than 0.  */
6788   cmp_result = gen_rtx_GT (VOIDmode, length, const0_rtx);
6789   emit_jump_insn (gen_condjump (cmp_result, label));
6790
6791   emit_label (end_label);
6792 }
6793 \f
6794 /* Expand a QI or HI mode atomic memory operation.
6795
6796    GENERATOR contains a pointer to the gen_* function that generates
6797    the SI mode underlying atomic operation using masks that we
6798    calculate.
6799
6800    RESULT is the return register for the operation.  Its value is NULL
6801    if unused.
6802
6803    MEM is the location of the atomic access.
6804
6805    OLDVAL is the first operand for the operation.
6806
6807    NEWVAL is the optional second operand for the operation.  Its value
6808    is NULL if unused.  */
6809
6810 void
6811 mips_expand_atomic_qihi (union mips_gen_fn_ptrs generator,
6812                          rtx result, rtx mem, rtx oldval, rtx newval)
6813 {
6814   rtx orig_addr, memsi_addr, memsi, shift, shiftsi, unshifted_mask;
6815   rtx unshifted_mask_reg, mask, inverted_mask, si_op;
6816   rtx res = NULL;
6817   enum machine_mode mode;
6818
6819   mode = GET_MODE (mem);
6820
6821   /* Compute the address of the containing SImode value.  */
6822   orig_addr = force_reg (Pmode, XEXP (mem, 0));
6823   memsi_addr = mips_force_binary (Pmode, AND, orig_addr,
6824                                   force_reg (Pmode, GEN_INT (-4)));
6825
6826   /* Create a memory reference for it.  */
6827   memsi = gen_rtx_MEM (SImode, memsi_addr);
6828   set_mem_alias_set (memsi, ALIAS_SET_MEMORY_BARRIER);
6829   MEM_VOLATILE_P (memsi) = MEM_VOLATILE_P (mem);
6830
6831   /* Work out the byte offset of the QImode or HImode value,
6832      counting from the least significant byte.  */
6833   shift = mips_force_binary (Pmode, AND, orig_addr, GEN_INT (3));
6834   if (TARGET_BIG_ENDIAN)
6835     mips_emit_binary (XOR, shift, shift, GEN_INT (mode == QImode ? 3 : 2));
6836
6837   /* Multiply by eight to convert the shift value from bytes to bits.  */
6838   mips_emit_binary (ASHIFT, shift, shift, GEN_INT (3));
6839
6840   /* Make the final shift an SImode value, so that it can be used in
6841      SImode operations.  */
6842   shiftsi = force_reg (SImode, gen_lowpart (SImode, shift));
6843
6844   /* Set MASK to an inclusive mask of the QImode or HImode value.  */
6845   unshifted_mask = GEN_INT (GET_MODE_MASK (mode));
6846   unshifted_mask_reg = force_reg (SImode, unshifted_mask);
6847   mask = mips_force_binary (SImode, ASHIFT, unshifted_mask_reg, shiftsi);
6848
6849   /* Compute the equivalent exclusive mask.  */
6850   inverted_mask = gen_reg_rtx (SImode);
6851   emit_insn (gen_rtx_SET (VOIDmode, inverted_mask,
6852                           gen_rtx_NOT (SImode, mask)));
6853
6854   /* Shift the old value into place.  */
6855   if (oldval != const0_rtx)
6856     {
6857       oldval = convert_modes (SImode, mode, oldval, true);
6858       oldval = force_reg (SImode, oldval);
6859       oldval = mips_force_binary (SImode, ASHIFT, oldval, shiftsi);
6860     }
6861
6862   /* Do the same for the new value.  */
6863   if (newval && newval != const0_rtx)
6864     {
6865       newval = convert_modes (SImode, mode, newval, true);
6866       newval = force_reg (SImode, newval);
6867       newval = mips_force_binary (SImode, ASHIFT, newval, shiftsi);
6868     }
6869
6870   /* Do the SImode atomic access.  */
6871   if (result)
6872     res = gen_reg_rtx (SImode);
6873   if (newval)
6874     si_op = generator.fn_6 (res, memsi, mask, inverted_mask, oldval, newval);
6875   else if (result)
6876     si_op = generator.fn_5 (res, memsi, mask, inverted_mask, oldval);
6877   else
6878     si_op = generator.fn_4 (memsi, mask, inverted_mask, oldval);
6879
6880   emit_insn (si_op);
6881
6882   if (result)
6883     {
6884       /* Shift and convert the result.  */
6885       mips_emit_binary (AND, res, res, mask);
6886       mips_emit_binary (LSHIFTRT, res, res, shiftsi);
6887       mips_emit_move (result, gen_lowpart (GET_MODE (result), res));
6888     }
6889 }
6890
6891 /* Return true if it is possible to use left/right accesses for a
6892    bitfield of WIDTH bits starting BITPOS bits into *OP.  When
6893    returning true, update *OP, *LEFT and *RIGHT as follows:
6894
6895    *OP is a BLKmode reference to the whole field.
6896
6897    *LEFT is a QImode reference to the first byte if big endian or
6898    the last byte if little endian.  This address can be used in the
6899    left-side instructions (LWL, SWL, LDL, SDL).
6900
6901    *RIGHT is a QImode reference to the opposite end of the field and
6902    can be used in the patterning right-side instruction.  */
6903
6904 static bool
6905 mips_get_unaligned_mem (rtx *op, HOST_WIDE_INT width, HOST_WIDE_INT bitpos,
6906                         rtx *left, rtx *right)
6907 {
6908   rtx first, last;
6909
6910   /* Check that the operand really is a MEM.  Not all the extv and
6911      extzv predicates are checked.  */
6912   if (!MEM_P (*op))
6913     return false;
6914
6915   /* Check that the size is valid.  */
6916   if (width != 32 && (!TARGET_64BIT || width != 64))
6917     return false;
6918
6919   /* We can only access byte-aligned values.  Since we are always passed
6920      a reference to the first byte of the field, it is not necessary to
6921      do anything with BITPOS after this check.  */
6922   if (bitpos % BITS_PER_UNIT != 0)
6923     return false;
6924
6925   /* Reject aligned bitfields: we want to use a normal load or store
6926      instead of a left/right pair.  */
6927   if (MEM_ALIGN (*op) >= width)
6928     return false;
6929
6930   /* Adjust *OP to refer to the whole field.  This also has the effect
6931      of legitimizing *OP's address for BLKmode, possibly simplifying it.  */
6932   *op = adjust_address (*op, BLKmode, 0);
6933   set_mem_size (*op, GEN_INT (width / BITS_PER_UNIT));
6934
6935   /* Get references to both ends of the field.  We deliberately don't
6936      use the original QImode *OP for FIRST since the new BLKmode one
6937      might have a simpler address.  */
6938   first = adjust_address (*op, QImode, 0);
6939   last = adjust_address (*op, QImode, width / BITS_PER_UNIT - 1);
6940
6941   /* Allocate to LEFT and RIGHT according to endianness.  LEFT should
6942      correspond to the MSB and RIGHT to the LSB.  */
6943   if (TARGET_BIG_ENDIAN)
6944     *left = first, *right = last;
6945   else
6946     *left = last, *right = first;
6947
6948   return true;
6949 }
6950
6951 /* Try to use left/right loads to expand an "extv" or "extzv" pattern.
6952    DEST, SRC, WIDTH and BITPOS are the operands passed to the expander;
6953    the operation is the equivalent of:
6954
6955       (set DEST (*_extract SRC WIDTH BITPOS))
6956
6957    Return true on success.  */
6958
6959 bool
6960 mips_expand_ext_as_unaligned_load (rtx dest, rtx src, HOST_WIDE_INT width,
6961                                    HOST_WIDE_INT bitpos)
6962 {
6963   rtx left, right, temp;
6964
6965   /* If TARGET_64BIT, the destination of a 32-bit "extz" or "extzv" will
6966      be a paradoxical word_mode subreg.  This is the only case in which
6967      we allow the destination to be larger than the source.  */
6968   if (GET_CODE (dest) == SUBREG
6969       && GET_MODE (dest) == DImode
6970       && GET_MODE (SUBREG_REG (dest)) == SImode)
6971     dest = SUBREG_REG (dest);
6972
6973   /* After the above adjustment, the destination must be the same
6974      width as the source.  */
6975   if (GET_MODE_BITSIZE (GET_MODE (dest)) != width)
6976     return false;
6977
6978   if (!mips_get_unaligned_mem (&src, width, bitpos, &left, &right))
6979     return false;
6980
6981   temp = gen_reg_rtx (GET_MODE (dest));
6982   if (GET_MODE (dest) == DImode)
6983     {
6984       emit_insn (gen_mov_ldl (temp, src, left));
6985       emit_insn (gen_mov_ldr (dest, copy_rtx (src), right, temp));
6986     }
6987   else
6988     {
6989       emit_insn (gen_mov_lwl (temp, src, left));
6990       emit_insn (gen_mov_lwr (dest, copy_rtx (src), right, temp));
6991     }
6992   return true;
6993 }
6994
6995 /* Try to use left/right stores to expand an "ins" pattern.  DEST, WIDTH,
6996    BITPOS and SRC are the operands passed to the expander; the operation
6997    is the equivalent of:
6998
6999        (set (zero_extract DEST WIDTH BITPOS) SRC)
7000
7001    Return true on success.  */
7002
7003 bool
7004 mips_expand_ins_as_unaligned_store (rtx dest, rtx src, HOST_WIDE_INT width,
7005                                     HOST_WIDE_INT bitpos)
7006 {
7007   rtx left, right;
7008   enum machine_mode mode;
7009
7010   if (!mips_get_unaligned_mem (&dest, width, bitpos, &left, &right))
7011     return false;
7012
7013   mode = mode_for_size (width, MODE_INT, 0);
7014   src = gen_lowpart (mode, src);
7015   if (mode == DImode)
7016     {
7017       emit_insn (gen_mov_sdl (dest, src, left));
7018       emit_insn (gen_mov_sdr (copy_rtx (dest), copy_rtx (src), right));
7019     }
7020   else
7021     {
7022       emit_insn (gen_mov_swl (dest, src, left));
7023       emit_insn (gen_mov_swr (copy_rtx (dest), copy_rtx (src), right));
7024     }
7025   return true;
7026 }
7027
7028 /* Return true if X is a MEM with the same size as MODE.  */
7029
7030 bool
7031 mips_mem_fits_mode_p (enum machine_mode mode, rtx x)
7032 {
7033   rtx size;
7034
7035   if (!MEM_P (x))
7036     return false;
7037
7038   size = MEM_SIZE (x);
7039   return size && INTVAL (size) == GET_MODE_SIZE (mode);
7040 }
7041
7042 /* Return true if (zero_extract OP WIDTH BITPOS) can be used as the
7043    source of an "ext" instruction or the destination of an "ins"
7044    instruction.  OP must be a register operand and the following
7045    conditions must hold:
7046
7047      0 <= BITPOS < GET_MODE_BITSIZE (GET_MODE (op))
7048      0 < WIDTH <= GET_MODE_BITSIZE (GET_MODE (op))
7049      0 < BITPOS + WIDTH <= GET_MODE_BITSIZE (GET_MODE (op))
7050
7051    Also reject lengths equal to a word as they are better handled
7052    by the move patterns.  */
7053
7054 bool
7055 mips_use_ins_ext_p (rtx op, HOST_WIDE_INT width, HOST_WIDE_INT bitpos)
7056 {
7057   if (!ISA_HAS_EXT_INS
7058       || !register_operand (op, VOIDmode)
7059       || GET_MODE_BITSIZE (GET_MODE (op)) > BITS_PER_WORD)
7060     return false;
7061
7062   if (!IN_RANGE (width, 1, GET_MODE_BITSIZE (GET_MODE (op)) - 1))
7063     return false;
7064
7065   if (bitpos < 0 || bitpos + width > GET_MODE_BITSIZE (GET_MODE (op)))
7066     return false;
7067
7068   return true;
7069 }
7070
7071 /* Check if MASK and SHIFT are valid in mask-low-and-shift-left
7072    operation if MAXLEN is the maxium length of consecutive bits that
7073    can make up MASK.  MODE is the mode of the operation.  See
7074    mask_low_and_shift_len for the actual definition.  */
7075
7076 bool
7077 mask_low_and_shift_p (enum machine_mode mode, rtx mask, rtx shift, int maxlen)
7078 {
7079   return IN_RANGE (mask_low_and_shift_len (mode, mask, shift), 1, maxlen);
7080 }
7081
7082 /* Return true iff OP1 and OP2 are valid operands together for the
7083    *and<MODE>3 and *and<MODE>3_mips16 patterns.  For the cases to consider,
7084    see the table in the comment before the pattern.  */
7085
7086 bool
7087 and_operands_ok (enum machine_mode mode, rtx op1, rtx op2)
7088 {
7089   return (memory_operand (op1, mode)
7090           ? and_load_operand (op2, mode)
7091           : and_reg_operand (op2, mode));
7092 }
7093
7094 /* The canonical form of a mask-low-and-shift-left operation is
7095    (and (ashift X SHIFT) MASK) where MASK has the lower SHIFT number of bits
7096    cleared.  Thus we need to shift MASK to the right before checking if it
7097    is a valid mask value.  MODE is the mode of the operation.  If true
7098    return the length of the mask, otherwise return -1.  */
7099
7100 int
7101 mask_low_and_shift_len (enum machine_mode mode, rtx mask, rtx shift)
7102 {
7103   HOST_WIDE_INT shval;
7104
7105   shval = INTVAL (shift) & (GET_MODE_BITSIZE (mode) - 1);
7106   return exact_log2 ((UINTVAL (mask) >> shval) + 1);
7107 }
7108 \f
7109 /* Return true if -msplit-addresses is selected and should be honored.
7110
7111    -msplit-addresses is a half-way house between explicit relocations
7112    and the traditional assembler macros.  It can split absolute 32-bit
7113    symbolic constants into a high/lo_sum pair but uses macros for other
7114    sorts of access.
7115
7116    Like explicit relocation support for REL targets, it relies
7117    on GNU extensions in the assembler and the linker.
7118
7119    Although this code should work for -O0, it has traditionally
7120    been treated as an optimization.  */
7121
7122 static bool
7123 mips_split_addresses_p (void)
7124 {
7125   return (TARGET_SPLIT_ADDRESSES
7126           && optimize
7127           && !TARGET_MIPS16
7128           && !flag_pic
7129           && !ABI_HAS_64BIT_SYMBOLS);
7130 }
7131
7132 /* (Re-)Initialize mips_split_p, mips_lo_relocs and mips_hi_relocs.  */
7133
7134 static void
7135 mips_init_relocs (void)
7136 {
7137   memset (mips_split_p, '\0', sizeof (mips_split_p));
7138   memset (mips_split_hi_p, '\0', sizeof (mips_split_hi_p));
7139   memset (mips_hi_relocs, '\0', sizeof (mips_hi_relocs));
7140   memset (mips_lo_relocs, '\0', sizeof (mips_lo_relocs));
7141
7142   if (ABI_HAS_64BIT_SYMBOLS)
7143     {
7144       if (TARGET_EXPLICIT_RELOCS)
7145         {
7146           mips_split_p[SYMBOL_64_HIGH] = true;
7147           mips_hi_relocs[SYMBOL_64_HIGH] = "%highest(";
7148           mips_lo_relocs[SYMBOL_64_HIGH] = "%higher(";
7149
7150           mips_split_p[SYMBOL_64_MID] = true;
7151           mips_hi_relocs[SYMBOL_64_MID] = "%higher(";
7152           mips_lo_relocs[SYMBOL_64_MID] = "%hi(";
7153
7154           mips_split_p[SYMBOL_64_LOW] = true;
7155           mips_hi_relocs[SYMBOL_64_LOW] = "%hi(";
7156           mips_lo_relocs[SYMBOL_64_LOW] = "%lo(";
7157
7158           mips_split_p[SYMBOL_ABSOLUTE] = true;
7159           mips_lo_relocs[SYMBOL_ABSOLUTE] = "%lo(";
7160         }
7161     }
7162   else
7163     {
7164       if (TARGET_EXPLICIT_RELOCS || mips_split_addresses_p () || TARGET_MIPS16)
7165         {
7166           mips_split_p[SYMBOL_ABSOLUTE] = true;
7167           mips_hi_relocs[SYMBOL_ABSOLUTE] = "%hi(";
7168           mips_lo_relocs[SYMBOL_ABSOLUTE] = "%lo(";
7169
7170           mips_lo_relocs[SYMBOL_32_HIGH] = "%hi(";
7171         }
7172     }
7173
7174   if (TARGET_MIPS16)
7175     {
7176       /* The high part is provided by a pseudo copy of $gp.  */
7177       mips_split_p[SYMBOL_GP_RELATIVE] = true;
7178       mips_lo_relocs[SYMBOL_GP_RELATIVE] = "%gprel(";
7179     }
7180   else if (TARGET_EXPLICIT_RELOCS)
7181     /* Small data constants are kept whole until after reload,
7182        then lowered by mips_rewrite_small_data.  */
7183     mips_lo_relocs[SYMBOL_GP_RELATIVE] = "%gp_rel(";
7184
7185   if (TARGET_EXPLICIT_RELOCS)
7186     {
7187       mips_split_p[SYMBOL_GOT_PAGE_OFST] = true;
7188       if (TARGET_NEWABI)
7189         {
7190           mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got_page(";
7191           mips_lo_relocs[SYMBOL_GOT_PAGE_OFST] = "%got_ofst(";
7192         }
7193       else
7194         {
7195           mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got(";
7196           mips_lo_relocs[SYMBOL_GOT_PAGE_OFST] = "%lo(";
7197         }
7198       if (TARGET_MIPS16)
7199         /* Expose the use of $28 as soon as possible.  */
7200         mips_split_hi_p[SYMBOL_GOT_PAGE_OFST] = true;
7201
7202       if (TARGET_XGOT)
7203         {
7204           /* The HIGH and LO_SUM are matched by special .md patterns.  */
7205           mips_split_p[SYMBOL_GOT_DISP] = true;
7206
7207           mips_split_p[SYMBOL_GOTOFF_DISP] = true;
7208           mips_hi_relocs[SYMBOL_GOTOFF_DISP] = "%got_hi(";
7209           mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got_lo(";
7210
7211           mips_split_p[SYMBOL_GOTOFF_CALL] = true;
7212           mips_hi_relocs[SYMBOL_GOTOFF_CALL] = "%call_hi(";
7213           mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call_lo(";
7214         }
7215       else
7216         {
7217           if (TARGET_NEWABI)
7218             mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got_disp(";
7219           else
7220             mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got(";
7221           mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call16(";
7222           if (TARGET_MIPS16)
7223             /* Expose the use of $28 as soon as possible.  */
7224             mips_split_p[SYMBOL_GOT_DISP] = true;
7225         }
7226     }
7227
7228   if (TARGET_NEWABI)
7229     {
7230       mips_split_p[SYMBOL_GOTOFF_LOADGP] = true;
7231       mips_hi_relocs[SYMBOL_GOTOFF_LOADGP] = "%hi(%neg(%gp_rel(";
7232       mips_lo_relocs[SYMBOL_GOTOFF_LOADGP] = "%lo(%neg(%gp_rel(";
7233     }
7234
7235   mips_lo_relocs[SYMBOL_TLSGD] = "%tlsgd(";
7236   mips_lo_relocs[SYMBOL_TLSLDM] = "%tlsldm(";
7237
7238   mips_split_p[SYMBOL_DTPREL] = true;
7239   mips_hi_relocs[SYMBOL_DTPREL] = "%dtprel_hi(";
7240   mips_lo_relocs[SYMBOL_DTPREL] = "%dtprel_lo(";
7241
7242   mips_lo_relocs[SYMBOL_GOTTPREL] = "%gottprel(";
7243
7244   mips_split_p[SYMBOL_TPREL] = true;
7245   mips_hi_relocs[SYMBOL_TPREL] = "%tprel_hi(";
7246   mips_lo_relocs[SYMBOL_TPREL] = "%tprel_lo(";
7247
7248   mips_lo_relocs[SYMBOL_HALF] = "%half(";
7249 }
7250
7251 /* Print symbolic operand OP, which is part of a HIGH or LO_SUM
7252    in context CONTEXT.  RELOCS is the array of relocations to use.  */
7253
7254 static void
7255 mips_print_operand_reloc (FILE *file, rtx op, enum mips_symbol_context context,
7256                           const char **relocs)
7257 {
7258   enum mips_symbol_type symbol_type;
7259   const char *p;
7260
7261   symbol_type = mips_classify_symbolic_expression (op, context);
7262   gcc_assert (relocs[symbol_type]);
7263
7264   fputs (relocs[symbol_type], file);
7265   output_addr_const (file, mips_strip_unspec_address (op));
7266   for (p = relocs[symbol_type]; *p != 0; p++)
7267     if (*p == '(')
7268       fputc (')', file);
7269 }
7270
7271 /* Start a new block with the given asm switch enabled.  If we need
7272    to print a directive, emit PREFIX before it and SUFFIX after it.  */
7273
7274 static void
7275 mips_push_asm_switch_1 (struct mips_asm_switch *asm_switch,
7276                         const char *prefix, const char *suffix)
7277 {
7278   if (asm_switch->nesting_level == 0)
7279     fprintf (asm_out_file, "%s.set\tno%s%s", prefix, asm_switch->name, suffix);
7280   asm_switch->nesting_level++;
7281 }
7282
7283 /* Likewise, but end a block.  */
7284
7285 static void
7286 mips_pop_asm_switch_1 (struct mips_asm_switch *asm_switch,
7287                        const char *prefix, const char *suffix)
7288 {
7289   gcc_assert (asm_switch->nesting_level);
7290   asm_switch->nesting_level--;
7291   if (asm_switch->nesting_level == 0)
7292     fprintf (asm_out_file, "%s.set\t%s%s", prefix, asm_switch->name, suffix);
7293 }
7294
7295 /* Wrappers around mips_push_asm_switch_1 and mips_pop_asm_switch_1
7296    that either print a complete line or print nothing.  */
7297
7298 void
7299 mips_push_asm_switch (struct mips_asm_switch *asm_switch)
7300 {
7301   mips_push_asm_switch_1 (asm_switch, "\t", "\n");
7302 }
7303
7304 void
7305 mips_pop_asm_switch (struct mips_asm_switch *asm_switch)
7306 {
7307   mips_pop_asm_switch_1 (asm_switch, "\t", "\n");
7308 }
7309
7310 /* Print the text for PRINT_OPERAND punctation character CH to FILE.
7311    The punctuation characters are:
7312
7313    '('  Start a nested ".set noreorder" block.
7314    ')'  End a nested ".set noreorder" block.
7315    '['  Start a nested ".set noat" block.
7316    ']'  End a nested ".set noat" block.
7317    '<'  Start a nested ".set nomacro" block.
7318    '>'  End a nested ".set nomacro" block.
7319    '*'  Behave like %(%< if generating a delayed-branch sequence.
7320    '#'  Print a nop if in a ".set noreorder" block.
7321    '/'  Like '#', but do nothing within a delayed-branch sequence.
7322    '?'  Print "l" if mips_branch_likely is true
7323    '~'  Print a nop if mips_branch_likely is true
7324    '.'  Print the name of the register with a hard-wired zero (zero or $0).
7325    '@'  Print the name of the assembler temporary register (at or $1).
7326    '^'  Print the name of the pic call-through register (t9 or $25).
7327    '+'  Print the name of the gp register (usually gp or $28).
7328    '$'  Print the name of the stack pointer register (sp or $29).
7329
7330    See also mips_init_print_operand_pucnt.  */
7331
7332 static void
7333 mips_print_operand_punctuation (FILE *file, int ch)
7334 {
7335   switch (ch)
7336     {
7337     case '(':
7338       mips_push_asm_switch_1 (&mips_noreorder, "", "\n\t");
7339       break;
7340
7341     case ')':
7342       mips_pop_asm_switch_1 (&mips_noreorder, "\n\t", "");
7343       break;
7344
7345     case '[':
7346       mips_push_asm_switch_1 (&mips_noat, "", "\n\t");
7347       break;
7348
7349     case ']':
7350       mips_pop_asm_switch_1 (&mips_noat, "\n\t", "");
7351       break;
7352
7353     case '<':
7354       mips_push_asm_switch_1 (&mips_nomacro, "", "\n\t");
7355       break;
7356
7357     case '>':
7358       mips_pop_asm_switch_1 (&mips_nomacro, "\n\t", "");
7359       break;
7360
7361     case '*':
7362       if (final_sequence != 0)
7363         {
7364           mips_print_operand_punctuation (file, '(');
7365           mips_print_operand_punctuation (file, '<');
7366         }
7367       break;
7368
7369     case '#':
7370       if (mips_noreorder.nesting_level > 0)
7371         fputs ("\n\tnop", file);
7372       break;
7373
7374     case '/':
7375       /* Print an extra newline so that the delayed insn is separated
7376          from the following ones.  This looks neater and is consistent
7377          with non-nop delayed sequences.  */
7378       if (mips_noreorder.nesting_level > 0 && final_sequence == 0)
7379         fputs ("\n\tnop\n", file);
7380       break;
7381
7382     case '?':
7383       if (mips_branch_likely)
7384         putc ('l', file);
7385       break;
7386
7387     case '~':
7388       if (mips_branch_likely)
7389         fputs ("\n\tnop", file);
7390       break;
7391
7392     case '.':
7393       fputs (reg_names[GP_REG_FIRST + 0], file);
7394       break;
7395
7396     case '@':
7397       fputs (reg_names[AT_REGNUM], file);
7398       break;
7399
7400     case '^':
7401       fputs (reg_names[PIC_FUNCTION_ADDR_REGNUM], file);
7402       break;
7403
7404     case '+':
7405       fputs (reg_names[PIC_OFFSET_TABLE_REGNUM], file);
7406       break;
7407
7408     case '$':
7409       fputs (reg_names[STACK_POINTER_REGNUM], file);
7410       break;
7411
7412     default:
7413       gcc_unreachable ();
7414       break;
7415     }
7416 }
7417
7418 /* Initialize mips_print_operand_punct.  */
7419
7420 static void
7421 mips_init_print_operand_punct (void)
7422 {
7423   const char *p;
7424
7425   for (p = "()[]<>*#/?~.@^+$"; *p; p++)
7426     mips_print_operand_punct[(unsigned char) *p] = true;
7427 }
7428
7429 /* PRINT_OPERAND prefix LETTER refers to the integer branch instruction
7430    associated with condition CODE.  Print the condition part of the
7431    opcode to FILE.  */
7432
7433 static void
7434 mips_print_int_branch_condition (FILE *file, enum rtx_code code, int letter)
7435 {
7436   switch (code)
7437     {
7438     case EQ:
7439     case NE:
7440     case GT:
7441     case GE:
7442     case LT:
7443     case LE:
7444     case GTU:
7445     case GEU:
7446     case LTU:
7447     case LEU:
7448       /* Conveniently, the MIPS names for these conditions are the same
7449          as their RTL equivalents.  */
7450       fputs (GET_RTX_NAME (code), file);
7451       break;
7452
7453     default:
7454       output_operand_lossage ("'%%%c' is not a valid operand prefix", letter);
7455       break;
7456     }
7457 }
7458
7459 /* Likewise floating-point branches.  */
7460
7461 static void
7462 mips_print_float_branch_condition (FILE *file, enum rtx_code code, int letter)
7463 {
7464   switch (code)
7465     {
7466     case EQ:
7467       fputs ("c1f", file);
7468       break;
7469
7470     case NE:
7471       fputs ("c1t", file);
7472       break;
7473
7474     default:
7475       output_operand_lossage ("'%%%c' is not a valid operand prefix", letter);
7476       break;
7477     }
7478 }
7479
7480 /* Implement TARGET_PRINT_OPERAND_PUNCT_VALID_P.  */
7481
7482 static bool
7483 mips_print_operand_punct_valid_p (unsigned char code)
7484 {
7485   return mips_print_operand_punct[code];
7486 }
7487
7488 /* Implement TARGET_PRINT_OPERAND.  The MIPS-specific operand codes are:
7489
7490    'X'  Print CONST_INT OP in hexadecimal format.
7491    'x'  Print the low 16 bits of CONST_INT OP in hexadecimal format.
7492    'd'  Print CONST_INT OP in decimal.
7493    'm'  Print one less than CONST_INT OP in decimal.
7494    'h'  Print the high-part relocation associated with OP, after stripping
7495           any outermost HIGH.
7496    'R'  Print the low-part relocation associated with OP.
7497    'C'  Print the integer branch condition for comparison OP.
7498    'N'  Print the inverse of the integer branch condition for comparison OP.
7499    'F'  Print the FPU branch condition for comparison OP.
7500    'W'  Print the inverse of the FPU branch condition for comparison OP.
7501    'T'  Print 'f' for (eq:CC ...), 't' for (ne:CC ...),
7502               'z' for (eq:?I ...), 'n' for (ne:?I ...).
7503    't'  Like 'T', but with the EQ/NE cases reversed
7504    'Y'  Print mips_fp_conditions[INTVAL (OP)]
7505    'Z'  Print OP and a comma for ISA_HAS_8CC, otherwise print nothing.
7506    'q'  Print a DSP accumulator register.
7507    'D'  Print the second part of a double-word register or memory operand.
7508    'L'  Print the low-order register in a double-word register operand.
7509    'M'  Print high-order register in a double-word register operand.
7510    'z'  Print $0 if OP is zero, otherwise print OP normally.  */
7511
7512 static void
7513 mips_print_operand (FILE *file, rtx op, int letter)
7514 {
7515   enum rtx_code code;
7516
7517   if (mips_print_operand_punct_valid_p (letter))
7518     {
7519       mips_print_operand_punctuation (file, letter);
7520       return;
7521     }
7522
7523   gcc_assert (op);
7524   code = GET_CODE (op);
7525
7526   switch (letter)
7527     {
7528     case 'X':
7529       if (CONST_INT_P (op))
7530         fprintf (file, HOST_WIDE_INT_PRINT_HEX, INTVAL (op));
7531       else
7532         output_operand_lossage ("invalid use of '%%%c'", letter);
7533       break;
7534
7535     case 'x':
7536       if (CONST_INT_P (op))
7537         fprintf (file, HOST_WIDE_INT_PRINT_HEX, INTVAL (op) & 0xffff);
7538       else
7539         output_operand_lossage ("invalid use of '%%%c'", letter);
7540       break;
7541
7542     case 'd':
7543       if (CONST_INT_P (op))
7544         fprintf (file, HOST_WIDE_INT_PRINT_DEC, INTVAL (op));
7545       else
7546         output_operand_lossage ("invalid use of '%%%c'", letter);
7547       break;
7548
7549     case 'm':
7550       if (CONST_INT_P (op))
7551         fprintf (file, HOST_WIDE_INT_PRINT_DEC, INTVAL (op) - 1);
7552       else
7553         output_operand_lossage ("invalid use of '%%%c'", letter);
7554       break;
7555
7556     case 'h':
7557       if (code == HIGH)
7558         op = XEXP (op, 0);
7559       mips_print_operand_reloc (file, op, SYMBOL_CONTEXT_LEA, mips_hi_relocs);
7560       break;
7561
7562     case 'R':
7563       mips_print_operand_reloc (file, op, SYMBOL_CONTEXT_LEA, mips_lo_relocs);
7564       break;
7565
7566     case 'C':
7567       mips_print_int_branch_condition (file, code, letter);
7568       break;
7569
7570     case 'N':
7571       mips_print_int_branch_condition (file, reverse_condition (code), letter);
7572       break;
7573
7574     case 'F':
7575       mips_print_float_branch_condition (file, code, letter);
7576       break;
7577
7578     case 'W':
7579       mips_print_float_branch_condition (file, reverse_condition (code),
7580                                          letter);
7581       break;
7582
7583     case 'T':
7584     case 't':
7585       {
7586         int truth = (code == NE) == (letter == 'T');
7587         fputc ("zfnt"[truth * 2 + (GET_MODE (op) == CCmode)], file);
7588       }
7589       break;
7590
7591     case 'Y':
7592       if (code == CONST_INT && UINTVAL (op) < ARRAY_SIZE (mips_fp_conditions))
7593         fputs (mips_fp_conditions[UINTVAL (op)], file);
7594       else
7595         output_operand_lossage ("'%%%c' is not a valid operand prefix",
7596                                 letter);
7597       break;
7598
7599     case 'Z':
7600       if (ISA_HAS_8CC)
7601         {
7602           mips_print_operand (file, op, 0);
7603           fputc (',', file);
7604         }
7605       break;
7606
7607     case 'q':
7608       if (code == REG && MD_REG_P (REGNO (op)))
7609         fprintf (file, "$ac0");
7610       else if (code == REG && DSP_ACC_REG_P (REGNO (op)))
7611         fprintf (file, "$ac%c", reg_names[REGNO (op)][3]);
7612       else
7613         output_operand_lossage ("invalid use of '%%%c'", letter);
7614       break;
7615
7616     default:
7617       switch (code)
7618         {
7619         case REG:
7620           {
7621             unsigned int regno = REGNO (op);
7622             if ((letter == 'M' && TARGET_LITTLE_ENDIAN)
7623                 || (letter == 'L' && TARGET_BIG_ENDIAN)
7624                 || letter == 'D')
7625               regno++;
7626             else if (letter && letter != 'z' && letter != 'M' && letter != 'L')
7627               output_operand_lossage ("invalid use of '%%%c'", letter);
7628             /* We need to print $0 .. $31 for COP0 registers.  */
7629             if (COP0_REG_P (regno))
7630               fprintf (file, "$%s", &reg_names[regno][4]);
7631             else
7632               fprintf (file, "%s", reg_names[regno]);
7633           }
7634           break;
7635
7636         case MEM:
7637           if (letter == 'D')
7638             output_address (plus_constant (XEXP (op, 0), 4));
7639           else if (letter && letter != 'z')
7640             output_operand_lossage ("invalid use of '%%%c'", letter);
7641           else
7642             output_address (XEXP (op, 0));
7643           break;
7644
7645         default:
7646           if (letter == 'z' && op == CONST0_RTX (GET_MODE (op)))
7647             fputs (reg_names[GP_REG_FIRST], file);
7648           else if (letter && letter != 'z')
7649             output_operand_lossage ("invalid use of '%%%c'", letter);
7650           else if (CONST_GP_P (op))
7651             fputs (reg_names[GLOBAL_POINTER_REGNUM], file);
7652           else
7653             output_addr_const (file, mips_strip_unspec_address (op));
7654           break;
7655         }
7656     }
7657 }
7658
7659 /* Implement TARGET_PRINT_OPERAND_ADDRESS.  */
7660
7661 static void
7662 mips_print_operand_address (FILE *file, rtx x)
7663 {
7664   struct mips_address_info addr;
7665
7666   if (mips_classify_address (&addr, x, word_mode, true))
7667     switch (addr.type)
7668       {
7669       case ADDRESS_REG:
7670         mips_print_operand (file, addr.offset, 0);
7671         fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
7672         return;
7673
7674       case ADDRESS_LO_SUM:
7675         mips_print_operand_reloc (file, addr.offset, SYMBOL_CONTEXT_MEM,
7676                                   mips_lo_relocs);
7677         fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
7678         return;
7679
7680       case ADDRESS_CONST_INT:
7681         output_addr_const (file, x);
7682         fprintf (file, "(%s)", reg_names[GP_REG_FIRST]);
7683         return;
7684
7685       case ADDRESS_SYMBOLIC:
7686         output_addr_const (file, mips_strip_unspec_address (x));
7687         return;
7688       }
7689   gcc_unreachable ();
7690 }
7691 \f
7692 /* Implement TARGET_ENCODE_SECTION_INFO.  */
7693
7694 static void
7695 mips_encode_section_info (tree decl, rtx rtl, int first)
7696 {
7697   default_encode_section_info (decl, rtl, first);
7698
7699   if (TREE_CODE (decl) == FUNCTION_DECL)
7700     {
7701       rtx symbol = XEXP (rtl, 0);
7702       tree type = TREE_TYPE (decl);
7703
7704       /* Encode whether the symbol is short or long.  */
7705       if ((TARGET_LONG_CALLS && !mips_near_type_p (type))
7706           || mips_far_type_p (type))
7707         SYMBOL_REF_FLAGS (symbol) |= SYMBOL_FLAG_LONG_CALL;
7708     }
7709 }
7710
7711 /* Implement TARGET_SELECT_RTX_SECTION.  */
7712
7713 static section *
7714 mips_select_rtx_section (enum machine_mode mode, rtx x,
7715                          unsigned HOST_WIDE_INT align)
7716 {
7717   /* ??? Consider using mergeable small data sections.  */
7718   if (mips_rtx_constant_in_small_data_p (mode))
7719     return get_named_section (NULL, ".sdata", 0);
7720
7721   return default_elf_select_rtx_section (mode, x, align);
7722 }
7723
7724 /* Implement TARGET_ASM_FUNCTION_RODATA_SECTION.
7725
7726    The complication here is that, with the combination TARGET_ABICALLS
7727    && !TARGET_ABSOLUTE_ABICALLS && !TARGET_GPWORD, jump tables will use
7728    absolute addresses, and should therefore not be included in the
7729    read-only part of a DSO.  Handle such cases by selecting a normal
7730    data section instead of a read-only one.  The logic apes that in
7731    default_function_rodata_section.  */
7732
7733 static section *
7734 mips_function_rodata_section (tree decl)
7735 {
7736   if (!TARGET_ABICALLS || TARGET_ABSOLUTE_ABICALLS || TARGET_GPWORD)
7737     return default_function_rodata_section (decl);
7738
7739   if (decl && DECL_SECTION_NAME (decl))
7740     {
7741       const char *name = TREE_STRING_POINTER (DECL_SECTION_NAME (decl));
7742       if (DECL_ONE_ONLY (decl) && strncmp (name, ".gnu.linkonce.t.", 16) == 0)
7743         {
7744           char *rname = ASTRDUP (name);
7745           rname[14] = 'd';
7746           return get_section (rname, SECTION_LINKONCE | SECTION_WRITE, decl);
7747         }
7748       else if (flag_function_sections
7749                && flag_data_sections
7750                && strncmp (name, ".text.", 6) == 0)
7751         {
7752           char *rname = ASTRDUP (name);
7753           memcpy (rname + 1, "data", 4);
7754           return get_section (rname, SECTION_WRITE, decl);
7755         }
7756     }
7757   return data_section;
7758 }
7759
7760 /* Implement TARGET_IN_SMALL_DATA_P.  */
7761
7762 static bool
7763 mips_in_small_data_p (const_tree decl)
7764 {
7765   unsigned HOST_WIDE_INT size;
7766
7767   if (TREE_CODE (decl) == STRING_CST || TREE_CODE (decl) == FUNCTION_DECL)
7768     return false;
7769
7770   /* We don't yet generate small-data references for -mabicalls
7771      or VxWorks RTP code.  See the related -G handling in
7772      mips_option_override.  */
7773   if (TARGET_ABICALLS || TARGET_VXWORKS_RTP)
7774     return false;
7775
7776   if (TREE_CODE (decl) == VAR_DECL && DECL_SECTION_NAME (decl) != 0)
7777     {
7778       const char *name;
7779
7780       /* Reject anything that isn't in a known small-data section.  */
7781       name = TREE_STRING_POINTER (DECL_SECTION_NAME (decl));
7782       if (strcmp (name, ".sdata") != 0 && strcmp (name, ".sbss") != 0)
7783         return false;
7784
7785       /* If a symbol is defined externally, the assembler will use the
7786          usual -G rules when deciding how to implement macros.  */
7787       if (mips_lo_relocs[SYMBOL_GP_RELATIVE] || !DECL_EXTERNAL (decl))
7788         return true;
7789     }
7790   else if (TARGET_EMBEDDED_DATA)
7791     {
7792       /* Don't put constants into the small data section: we want them
7793          to be in ROM rather than RAM.  */
7794       if (TREE_CODE (decl) != VAR_DECL)
7795         return false;
7796
7797       if (TREE_READONLY (decl)
7798           && !TREE_SIDE_EFFECTS (decl)
7799           && (!DECL_INITIAL (decl) || TREE_CONSTANT (DECL_INITIAL (decl))))
7800         return false;
7801     }
7802
7803   /* Enforce -mlocal-sdata.  */
7804   if (!TARGET_LOCAL_SDATA && !TREE_PUBLIC (decl))
7805     return false;
7806
7807   /* Enforce -mextern-sdata.  */
7808   if (!TARGET_EXTERN_SDATA && DECL_P (decl))
7809     {
7810       if (DECL_EXTERNAL (decl))
7811         return false;
7812       if (DECL_COMMON (decl) && DECL_INITIAL (decl) == NULL)
7813         return false;
7814     }
7815
7816   /* We have traditionally not treated zero-sized objects as small data,
7817      so this is now effectively part of the ABI.  */
7818   size = int_size_in_bytes (TREE_TYPE (decl));
7819   return size > 0 && size <= mips_small_data_threshold;
7820 }
7821
7822 /* Implement TARGET_USE_ANCHORS_FOR_SYMBOL_P.  We don't want to use
7823    anchors for small data: the GP register acts as an anchor in that
7824    case.  We also don't want to use them for PC-relative accesses,
7825    where the PC acts as an anchor.  */
7826
7827 static bool
7828 mips_use_anchors_for_symbol_p (const_rtx symbol)
7829 {
7830   switch (mips_classify_symbol (symbol, SYMBOL_CONTEXT_MEM))
7831     {
7832     case SYMBOL_PC_RELATIVE:
7833     case SYMBOL_GP_RELATIVE:
7834       return false;
7835
7836     default:
7837       return default_use_anchors_for_symbol_p (symbol);
7838     }
7839 }
7840 \f
7841 /* The MIPS debug format wants all automatic variables and arguments
7842    to be in terms of the virtual frame pointer (stack pointer before
7843    any adjustment in the function), while the MIPS 3.0 linker wants
7844    the frame pointer to be the stack pointer after the initial
7845    adjustment.  So, we do the adjustment here.  The arg pointer (which
7846    is eliminated) points to the virtual frame pointer, while the frame
7847    pointer (which may be eliminated) points to the stack pointer after
7848    the initial adjustments.  */
7849
7850 HOST_WIDE_INT
7851 mips_debugger_offset (rtx addr, HOST_WIDE_INT offset)
7852 {
7853   rtx offset2 = const0_rtx;
7854   rtx reg = eliminate_constant_term (addr, &offset2);
7855
7856   if (offset == 0)
7857     offset = INTVAL (offset2);
7858
7859   if (reg == stack_pointer_rtx
7860       || reg == frame_pointer_rtx
7861       || reg == hard_frame_pointer_rtx)
7862     {
7863       offset -= cfun->machine->frame.total_size;
7864       if (reg == hard_frame_pointer_rtx)
7865         offset += cfun->machine->frame.hard_frame_pointer_offset;
7866     }
7867
7868   /* sdbout_parms does not want this to crash for unrecognized cases.  */
7869 #if 0
7870   else if (reg != arg_pointer_rtx)
7871     fatal_insn ("mips_debugger_offset called with non stack/frame/arg pointer",
7872                 addr);
7873 #endif
7874
7875   return offset;
7876 }
7877 \f
7878 /* Implement ASM_OUTPUT_EXTERNAL.  */
7879
7880 void
7881 mips_output_external (FILE *file, tree decl, const char *name)
7882 {
7883   default_elf_asm_output_external (file, decl, name);
7884
7885   /* We output the name if and only if TREE_SYMBOL_REFERENCED is
7886      set in order to avoid putting out names that are never really
7887      used. */
7888   if (TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
7889     {
7890       if (!TARGET_EXPLICIT_RELOCS && mips_in_small_data_p (decl))
7891         {
7892           /* When using assembler macros, emit .extern directives for
7893              all small-data externs so that the assembler knows how
7894              big they are.
7895
7896              In most cases it would be safe (though pointless) to emit
7897              .externs for other symbols too.  One exception is when an
7898              object is within the -G limit but declared by the user to
7899              be in a section other than .sbss or .sdata.  */
7900           fputs ("\t.extern\t", file);
7901           assemble_name (file, name);
7902           fprintf (file, ", " HOST_WIDE_INT_PRINT_DEC "\n",
7903                    int_size_in_bytes (TREE_TYPE (decl)));
7904         }
7905     }
7906 }
7907
7908 /* Implement TARGET_ASM_OUTPUT_SOURCE_FILENAME.  */
7909
7910 static void
7911 mips_output_filename (FILE *stream, const char *name)
7912 {
7913   /* If we are emitting DWARF-2, let dwarf2out handle the ".file"
7914      directives.  */
7915   if (write_symbols == DWARF2_DEBUG)
7916     return;
7917   else if (mips_output_filename_first_time)
7918     {
7919       mips_output_filename_first_time = 0;
7920       num_source_filenames += 1;
7921       current_function_file = name;
7922       fprintf (stream, "\t.file\t%d ", num_source_filenames);
7923       output_quoted_string (stream, name);
7924       putc ('\n', stream);
7925     }
7926   /* If we are emitting stabs, let dbxout.c handle this (except for
7927      the mips_output_filename_first_time case).  */
7928   else if (write_symbols == DBX_DEBUG)
7929     return;
7930   else if (name != current_function_file
7931            && strcmp (name, current_function_file) != 0)
7932     {
7933       num_source_filenames += 1;
7934       current_function_file = name;
7935       fprintf (stream, "\t.file\t%d ", num_source_filenames);
7936       output_quoted_string (stream, name);
7937       putc ('\n', stream);
7938     }
7939 }
7940
7941 /* Implement TARGET_ASM_OUTPUT_DWARF_DTPREL.  */
7942
7943 static void ATTRIBUTE_UNUSED
7944 mips_output_dwarf_dtprel (FILE *file, int size, rtx x)
7945 {
7946   switch (size)
7947     {
7948     case 4:
7949       fputs ("\t.dtprelword\t", file);
7950       break;
7951
7952     case 8:
7953       fputs ("\t.dtpreldword\t", file);
7954       break;
7955
7956     default:
7957       gcc_unreachable ();
7958     }
7959   output_addr_const (file, x);
7960   fputs ("+0x8000", file);
7961 }
7962
7963 /* Implement TARGET_DWARF_REGISTER_SPAN.  */
7964
7965 static rtx
7966 mips_dwarf_register_span (rtx reg)
7967 {
7968   rtx high, low;
7969   enum machine_mode mode;
7970
7971   /* By default, GCC maps increasing register numbers to increasing
7972      memory locations, but paired FPRs are always little-endian,
7973      regardless of the prevailing endianness.  */
7974   mode = GET_MODE (reg);
7975   if (FP_REG_P (REGNO (reg))
7976       && TARGET_BIG_ENDIAN
7977       && MAX_FPRS_PER_FMT > 1
7978       && GET_MODE_SIZE (mode) > UNITS_PER_FPREG)
7979     {
7980       gcc_assert (GET_MODE_SIZE (mode) == UNITS_PER_HWFPVALUE);
7981       high = mips_subword (reg, true);
7982       low = mips_subword (reg, false);
7983       return gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, high, low));
7984     }
7985
7986   return NULL_RTX;
7987 }
7988
7989 /* Implement ASM_OUTPUT_ASCII.  */
7990
7991 void
7992 mips_output_ascii (FILE *stream, const char *string, size_t len)
7993 {
7994   size_t i;
7995   int cur_pos;
7996
7997   cur_pos = 17;
7998   fprintf (stream, "\t.ascii\t\"");
7999   for (i = 0; i < len; i++)
8000     {
8001       int c;
8002
8003       c = (unsigned char) string[i];
8004       if (ISPRINT (c))
8005         {
8006           if (c == '\\' || c == '\"')
8007             {
8008               putc ('\\', stream);
8009               cur_pos++;
8010             }
8011           putc (c, stream);
8012           cur_pos++;
8013         }
8014       else
8015         {
8016           fprintf (stream, "\\%03o", c);
8017           cur_pos += 4;
8018         }
8019
8020       if (cur_pos > 72 && i+1 < len)
8021         {
8022           cur_pos = 17;
8023           fprintf (stream, "\"\n\t.ascii\t\"");
8024         }
8025     }
8026   fprintf (stream, "\"\n");
8027 }
8028
8029 /* Emit either a label, .comm, or .lcomm directive.  When using assembler
8030    macros, mark the symbol as written so that mips_asm_output_external
8031    won't emit an .extern for it.  STREAM is the output file, NAME is the
8032    name of the symbol, INIT_STRING is the string that should be written
8033    before the symbol and FINAL_STRING is the string that should be
8034    written after it.  FINAL_STRING is a printf format that consumes the
8035    remaining arguments.  */
8036
8037 void
8038 mips_declare_object (FILE *stream, const char *name, const char *init_string,
8039                      const char *final_string, ...)
8040 {
8041   va_list ap;
8042
8043   fputs (init_string, stream);
8044   assemble_name (stream, name);
8045   va_start (ap, final_string);
8046   vfprintf (stream, final_string, ap);
8047   va_end (ap);
8048
8049   if (!TARGET_EXPLICIT_RELOCS)
8050     {
8051       tree name_tree = get_identifier (name);
8052       TREE_ASM_WRITTEN (name_tree) = 1;
8053     }
8054 }
8055
8056 /* Declare a common object of SIZE bytes using asm directive INIT_STRING.
8057    NAME is the name of the object and ALIGN is the required alignment
8058    in bytes.  TAKES_ALIGNMENT_P is true if the directive takes a third
8059    alignment argument.  */
8060
8061 void
8062 mips_declare_common_object (FILE *stream, const char *name,
8063                             const char *init_string,
8064                             unsigned HOST_WIDE_INT size,
8065                             unsigned int align, bool takes_alignment_p)
8066 {
8067   if (!takes_alignment_p)
8068     {
8069       size += (align / BITS_PER_UNIT) - 1;
8070       size -= size % (align / BITS_PER_UNIT);
8071       mips_declare_object (stream, name, init_string,
8072                            "," HOST_WIDE_INT_PRINT_UNSIGNED "\n", size);
8073     }
8074   else
8075     mips_declare_object (stream, name, init_string,
8076                          "," HOST_WIDE_INT_PRINT_UNSIGNED ",%u\n",
8077                          size, align / BITS_PER_UNIT);
8078 }
8079
8080 /* Implement ASM_OUTPUT_ALIGNED_DECL_COMMON.  This is usually the same as the
8081    elfos.h version, but we also need to handle -muninit-const-in-rodata.  */
8082
8083 void
8084 mips_output_aligned_decl_common (FILE *stream, tree decl, const char *name,
8085                                  unsigned HOST_WIDE_INT size,
8086                                  unsigned int align)
8087 {
8088   /* If the target wants uninitialized const declarations in
8089      .rdata then don't put them in .comm.  */
8090   if (TARGET_EMBEDDED_DATA
8091       && TARGET_UNINIT_CONST_IN_RODATA
8092       && TREE_CODE (decl) == VAR_DECL
8093       && TREE_READONLY (decl)
8094       && (DECL_INITIAL (decl) == 0 || DECL_INITIAL (decl) == error_mark_node))
8095     {
8096       if (TREE_PUBLIC (decl) && DECL_NAME (decl))
8097         targetm.asm_out.globalize_label (stream, name);
8098
8099       switch_to_section (readonly_data_section);
8100       ASM_OUTPUT_ALIGN (stream, floor_log2 (align / BITS_PER_UNIT));
8101       mips_declare_object (stream, name, "",
8102                            ":\n\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED "\n",
8103                            size);
8104     }
8105   else
8106     mips_declare_common_object (stream, name, "\n\t.comm\t",
8107                                 size, align, true);
8108 }
8109
8110 #ifdef ASM_OUTPUT_SIZE_DIRECTIVE
8111 extern int size_directive_output;
8112
8113 /* Implement ASM_DECLARE_OBJECT_NAME.  This is like most of the standard ELF
8114    definitions except that it uses mips_declare_object to emit the label.  */
8115
8116 void
8117 mips_declare_object_name (FILE *stream, const char *name,
8118                           tree decl ATTRIBUTE_UNUSED)
8119 {
8120 #ifdef ASM_OUTPUT_TYPE_DIRECTIVE
8121   ASM_OUTPUT_TYPE_DIRECTIVE (stream, name, "object");
8122 #endif
8123
8124   size_directive_output = 0;
8125   if (!flag_inhibit_size_directive && DECL_SIZE (decl))
8126     {
8127       HOST_WIDE_INT size;
8128
8129       size_directive_output = 1;
8130       size = int_size_in_bytes (TREE_TYPE (decl));
8131       ASM_OUTPUT_SIZE_DIRECTIVE (stream, name, size);
8132     }
8133
8134   mips_declare_object (stream, name, "", ":\n");
8135 }
8136
8137 /* Implement ASM_FINISH_DECLARE_OBJECT.  This is generic ELF stuff.  */
8138
8139 void
8140 mips_finish_declare_object (FILE *stream, tree decl, int top_level, int at_end)
8141 {
8142   const char *name;
8143
8144   name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
8145   if (!flag_inhibit_size_directive
8146       && DECL_SIZE (decl) != 0
8147       && !at_end
8148       && top_level
8149       && DECL_INITIAL (decl) == error_mark_node
8150       && !size_directive_output)
8151     {
8152       HOST_WIDE_INT size;
8153
8154       size_directive_output = 1;
8155       size = int_size_in_bytes (TREE_TYPE (decl));
8156       ASM_OUTPUT_SIZE_DIRECTIVE (stream, name, size);
8157     }
8158 }
8159 #endif
8160 \f
8161 /* Return the FOO in the name of the ".mdebug.FOO" section associated
8162    with the current ABI.  */
8163
8164 static const char *
8165 mips_mdebug_abi_name (void)
8166 {
8167   switch (mips_abi)
8168     {
8169     case ABI_32:
8170       return "abi32";
8171     case ABI_O64:
8172       return "abiO64";
8173     case ABI_N32:
8174       return "abiN32";
8175     case ABI_64:
8176       return "abi64";
8177     case ABI_EABI:
8178       return TARGET_64BIT ? "eabi64" : "eabi32";
8179     default:
8180       gcc_unreachable ();
8181     }
8182 }
8183
8184 /* Implement TARGET_ASM_FILE_START.  */
8185
8186 static void
8187 mips_file_start (void)
8188 {
8189   default_file_start ();
8190
8191   /* Generate a special section to describe the ABI switches used to
8192      produce the resultant binary.  This is unnecessary on IRIX and
8193      causes unwanted warnings from the native linker.  */
8194   if (!TARGET_IRIX6)
8195     {
8196       /* Record the ABI itself.  Modern versions of binutils encode
8197          this information in the ELF header flags, but GDB needs the
8198          information in order to correctly debug binaries produced by
8199          older binutils.  See the function mips_gdbarch_init in
8200          gdb/mips-tdep.c.  */
8201       fprintf (asm_out_file, "\t.section .mdebug.%s\n\t.previous\n",
8202                mips_mdebug_abi_name ());
8203
8204       /* There is no ELF header flag to distinguish long32 forms of the
8205          EABI from long64 forms.  Emit a special section to help tools
8206          such as GDB.  Do the same for o64, which is sometimes used with
8207          -mlong64.  */
8208       if (mips_abi == ABI_EABI || mips_abi == ABI_O64)
8209         fprintf (asm_out_file, "\t.section .gcc_compiled_long%d\n"
8210                  "\t.previous\n", TARGET_LONG64 ? 64 : 32);
8211
8212 #ifdef HAVE_AS_GNU_ATTRIBUTE
8213       {
8214         int attr;
8215
8216         /* No floating-point operations, -mno-float.  */
8217         if (TARGET_NO_FLOAT)
8218           attr = 0;
8219         /* Soft-float code, -msoft-float.  */
8220         else if (!TARGET_HARD_FLOAT_ABI)
8221           attr = 3;
8222         /* Single-float code, -msingle-float.  */
8223         else if (!TARGET_DOUBLE_FLOAT)
8224           attr = 2;
8225         /* 64-bit FP registers on a 32-bit target, -mips32r2 -mfp64.  */
8226         else if (!TARGET_64BIT && TARGET_FLOAT64)
8227           attr = 4;
8228         /* Regular FP code, FP regs same size as GP regs, -mdouble-float.  */
8229         else
8230           attr = 1;
8231
8232         fprintf (asm_out_file, "\t.gnu_attribute 4, %d\n", attr);
8233       }
8234 #endif
8235     }
8236
8237   /* If TARGET_ABICALLS, tell GAS to generate -KPIC code.  */
8238   if (TARGET_ABICALLS)
8239     {
8240       fprintf (asm_out_file, "\t.abicalls\n");
8241       if (TARGET_ABICALLS_PIC0)
8242         fprintf (asm_out_file, "\t.option\tpic0\n");
8243     }
8244
8245   if (flag_verbose_asm)
8246     fprintf (asm_out_file, "\n%s -G value = %d, Arch = %s, ISA = %d\n",
8247              ASM_COMMENT_START,
8248              mips_small_data_threshold, mips_arch_info->name, mips_isa);
8249 }
8250 \f
8251 /* Make the last instruction frame-related and note that it performs
8252    the operation described by FRAME_PATTERN.  */
8253
8254 static void
8255 mips_set_frame_expr (rtx frame_pattern)
8256 {
8257   rtx insn;
8258
8259   insn = get_last_insn ();
8260   RTX_FRAME_RELATED_P (insn) = 1;
8261   REG_NOTES (insn) = alloc_EXPR_LIST (REG_FRAME_RELATED_EXPR,
8262                                       frame_pattern,
8263                                       REG_NOTES (insn));
8264 }
8265
8266 /* Return a frame-related rtx that stores REG at MEM.
8267    REG must be a single register.  */
8268
8269 static rtx
8270 mips_frame_set (rtx mem, rtx reg)
8271 {
8272   rtx set;
8273
8274   /* If we're saving the return address register and the DWARF return
8275      address column differs from the hard register number, adjust the
8276      note reg to refer to the former.  */
8277   if (REGNO (reg) == RETURN_ADDR_REGNUM
8278       && DWARF_FRAME_RETURN_COLUMN != RETURN_ADDR_REGNUM)
8279     reg = gen_rtx_REG (GET_MODE (reg), DWARF_FRAME_RETURN_COLUMN);
8280
8281   set = gen_rtx_SET (VOIDmode, mem, reg);
8282   RTX_FRAME_RELATED_P (set) = 1;
8283
8284   return set;
8285 }
8286 \f
8287 /* If a MIPS16e SAVE or RESTORE instruction saves or restores register
8288    mips16e_s2_s8_regs[X], it must also save the registers in indexes
8289    X + 1 onwards.  Likewise mips16e_a0_a3_regs.  */
8290 static const unsigned char mips16e_s2_s8_regs[] = {
8291   30, 23, 22, 21, 20, 19, 18
8292 };
8293 static const unsigned char mips16e_a0_a3_regs[] = {
8294   4, 5, 6, 7
8295 };
8296
8297 /* A list of the registers that can be saved by the MIPS16e SAVE instruction,
8298    ordered from the uppermost in memory to the lowest in memory.  */
8299 static const unsigned char mips16e_save_restore_regs[] = {
8300   31, 30, 23, 22, 21, 20, 19, 18, 17, 16, 7, 6, 5, 4
8301 };
8302
8303 /* Return the index of the lowest X in the range [0, SIZE) for which
8304    bit REGS[X] is set in MASK.  Return SIZE if there is no such X.  */
8305
8306 static unsigned int
8307 mips16e_find_first_register (unsigned int mask, const unsigned char *regs,
8308                              unsigned int size)
8309 {
8310   unsigned int i;
8311
8312   for (i = 0; i < size; i++)
8313     if (BITSET_P (mask, regs[i]))
8314       break;
8315
8316   return i;
8317 }
8318
8319 /* *MASK_PTR is a mask of general-purpose registers and *NUM_REGS_PTR
8320    is the number of set bits.  If *MASK_PTR contains REGS[X] for some X
8321    in [0, SIZE), adjust *MASK_PTR and *NUM_REGS_PTR so that the same
8322    is true for all indexes (X, SIZE).  */
8323
8324 static void
8325 mips16e_mask_registers (unsigned int *mask_ptr, const unsigned char *regs,
8326                         unsigned int size, unsigned int *num_regs_ptr)
8327 {
8328   unsigned int i;
8329
8330   i = mips16e_find_first_register (*mask_ptr, regs, size);
8331   for (i++; i < size; i++)
8332     if (!BITSET_P (*mask_ptr, regs[i]))
8333       {
8334         *num_regs_ptr += 1;
8335         *mask_ptr |= 1 << regs[i];
8336       }
8337 }
8338
8339 /* Return a simplified form of X using the register values in REG_VALUES.
8340    REG_VALUES[R] is the last value assigned to hard register R, or null
8341    if R has not been modified.
8342
8343    This function is rather limited, but is good enough for our purposes.  */
8344
8345 static rtx
8346 mips16e_collect_propagate_value (rtx x, rtx *reg_values)
8347 {
8348   x = avoid_constant_pool_reference (x);
8349
8350   if (UNARY_P (x))
8351     {
8352       rtx x0 = mips16e_collect_propagate_value (XEXP (x, 0), reg_values);
8353       return simplify_gen_unary (GET_CODE (x), GET_MODE (x),
8354                                  x0, GET_MODE (XEXP (x, 0)));
8355     }
8356
8357   if (ARITHMETIC_P (x))
8358     {
8359       rtx x0 = mips16e_collect_propagate_value (XEXP (x, 0), reg_values);
8360       rtx x1 = mips16e_collect_propagate_value (XEXP (x, 1), reg_values);
8361       return simplify_gen_binary (GET_CODE (x), GET_MODE (x), x0, x1);
8362     }
8363
8364   if (REG_P (x)
8365       && reg_values[REGNO (x)]
8366       && !rtx_unstable_p (reg_values[REGNO (x)]))
8367     return reg_values[REGNO (x)];
8368
8369   return x;
8370 }
8371
8372 /* Return true if (set DEST SRC) stores an argument register into its
8373    caller-allocated save slot, storing the number of that argument
8374    register in *REGNO_PTR if so.  REG_VALUES is as for
8375    mips16e_collect_propagate_value.  */
8376
8377 static bool
8378 mips16e_collect_argument_save_p (rtx dest, rtx src, rtx *reg_values,
8379                                  unsigned int *regno_ptr)
8380 {
8381   unsigned int argno, regno;
8382   HOST_WIDE_INT offset, required_offset;
8383   rtx addr, base;
8384
8385   /* Check that this is a word-mode store.  */
8386   if (!MEM_P (dest) || !REG_P (src) || GET_MODE (dest) != word_mode)
8387     return false;
8388
8389   /* Check that the register being saved is an unmodified argument
8390      register.  */
8391   regno = REGNO (src);
8392   if (!IN_RANGE (regno, GP_ARG_FIRST, GP_ARG_LAST) || reg_values[regno])
8393     return false;
8394   argno = regno - GP_ARG_FIRST;
8395
8396   /* Check whether the address is an appropriate stack-pointer or
8397      frame-pointer access.  */
8398   addr = mips16e_collect_propagate_value (XEXP (dest, 0), reg_values);
8399   mips_split_plus (addr, &base, &offset);
8400   required_offset = cfun->machine->frame.total_size + argno * UNITS_PER_WORD;
8401   if (base == hard_frame_pointer_rtx)
8402     required_offset -= cfun->machine->frame.hard_frame_pointer_offset;
8403   else if (base != stack_pointer_rtx)
8404     return false;
8405   if (offset != required_offset)
8406     return false;
8407
8408   *regno_ptr = regno;
8409   return true;
8410 }
8411
8412 /* A subroutine of mips_expand_prologue, called only when generating
8413    MIPS16e SAVE instructions.  Search the start of the function for any
8414    instructions that save argument registers into their caller-allocated
8415    save slots.  Delete such instructions and return a value N such that
8416    saving [GP_ARG_FIRST, GP_ARG_FIRST + N) would make all the deleted
8417    instructions redundant.  */
8418
8419 static unsigned int
8420 mips16e_collect_argument_saves (void)
8421 {
8422   rtx reg_values[FIRST_PSEUDO_REGISTER];
8423   rtx insn, next, set, dest, src;
8424   unsigned int nargs, regno;
8425
8426   push_topmost_sequence ();
8427   nargs = 0;
8428   memset (reg_values, 0, sizeof (reg_values));
8429   for (insn = get_insns (); insn; insn = next)
8430     {
8431       next = NEXT_INSN (insn);
8432       if (NOTE_P (insn) || DEBUG_INSN_P (insn))
8433         continue;
8434
8435       if (!INSN_P (insn))
8436         break;
8437
8438       set = PATTERN (insn);
8439       if (GET_CODE (set) != SET)
8440         break;
8441
8442       dest = SET_DEST (set);
8443       src = SET_SRC (set);
8444       if (mips16e_collect_argument_save_p (dest, src, reg_values, &regno))
8445         {
8446           if (!BITSET_P (cfun->machine->frame.mask, regno))
8447             {
8448               delete_insn (insn);
8449               nargs = MAX (nargs, (regno - GP_ARG_FIRST) + 1);
8450             }
8451         }
8452       else if (REG_P (dest) && GET_MODE (dest) == word_mode)
8453         reg_values[REGNO (dest)]
8454           = mips16e_collect_propagate_value (src, reg_values);
8455       else
8456         break;
8457     }
8458   pop_topmost_sequence ();
8459
8460   return nargs;
8461 }
8462
8463 /* Return a move between register REGNO and memory location SP + OFFSET.
8464    Make the move a load if RESTORE_P, otherwise make it a frame-related
8465    store.  */
8466
8467 static rtx
8468 mips16e_save_restore_reg (bool restore_p, HOST_WIDE_INT offset,
8469                           unsigned int regno)
8470 {
8471   rtx reg, mem;
8472
8473   mem = gen_frame_mem (SImode, plus_constant (stack_pointer_rtx, offset));
8474   reg = gen_rtx_REG (SImode, regno);
8475   return (restore_p
8476           ? gen_rtx_SET (VOIDmode, reg, mem)
8477           : mips_frame_set (mem, reg));
8478 }
8479
8480 /* Return RTL for a MIPS16e SAVE or RESTORE instruction; RESTORE_P says which.
8481    The instruction must:
8482
8483      - Allocate or deallocate SIZE bytes in total; SIZE is known
8484        to be nonzero.
8485
8486      - Save or restore as many registers in *MASK_PTR as possible.
8487        The instruction saves the first registers at the top of the
8488        allocated area, with the other registers below it.
8489
8490      - Save NARGS argument registers above the allocated area.
8491
8492    (NARGS is always zero if RESTORE_P.)
8493
8494    The SAVE and RESTORE instructions cannot save and restore all general
8495    registers, so there may be some registers left over for the caller to
8496    handle.  Destructively modify *MASK_PTR so that it contains the registers
8497    that still need to be saved or restored.  The caller can save these
8498    registers in the memory immediately below *OFFSET_PTR, which is a
8499    byte offset from the bottom of the allocated stack area.  */
8500
8501 static rtx
8502 mips16e_build_save_restore (bool restore_p, unsigned int *mask_ptr,
8503                             HOST_WIDE_INT *offset_ptr, unsigned int nargs,
8504                             HOST_WIDE_INT size)
8505 {
8506   rtx pattern, set;
8507   HOST_WIDE_INT offset, top_offset;
8508   unsigned int i, regno;
8509   int n;
8510
8511   gcc_assert (cfun->machine->frame.num_fp == 0);
8512
8513   /* Calculate the number of elements in the PARALLEL.  We need one element
8514      for the stack adjustment, one for each argument register save, and one
8515      for each additional register move.  */
8516   n = 1 + nargs;
8517   for (i = 0; i < ARRAY_SIZE (mips16e_save_restore_regs); i++)
8518     if (BITSET_P (*mask_ptr, mips16e_save_restore_regs[i]))
8519       n++;
8520
8521   /* Create the final PARALLEL.  */
8522   pattern = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (n));
8523   n = 0;
8524
8525   /* Add the stack pointer adjustment.  */
8526   set = gen_rtx_SET (VOIDmode, stack_pointer_rtx,
8527                      plus_constant (stack_pointer_rtx,
8528                                     restore_p ? size : -size));
8529   RTX_FRAME_RELATED_P (set) = 1;
8530   XVECEXP (pattern, 0, n++) = set;
8531
8532   /* Stack offsets in the PARALLEL are relative to the old stack pointer.  */
8533   top_offset = restore_p ? size : 0;
8534
8535   /* Save the arguments.  */
8536   for (i = 0; i < nargs; i++)
8537     {
8538       offset = top_offset + i * UNITS_PER_WORD;
8539       set = mips16e_save_restore_reg (restore_p, offset, GP_ARG_FIRST + i);
8540       XVECEXP (pattern, 0, n++) = set;
8541     }
8542
8543   /* Then fill in the other register moves.  */
8544   offset = top_offset;
8545   for (i = 0; i < ARRAY_SIZE (mips16e_save_restore_regs); i++)
8546     {
8547       regno = mips16e_save_restore_regs[i];
8548       if (BITSET_P (*mask_ptr, regno))
8549         {
8550           offset -= UNITS_PER_WORD;
8551           set = mips16e_save_restore_reg (restore_p, offset, regno);
8552           XVECEXP (pattern, 0, n++) = set;
8553           *mask_ptr &= ~(1 << regno);
8554         }
8555     }
8556
8557   /* Tell the caller what offset it should use for the remaining registers.  */
8558   *offset_ptr = size + (offset - top_offset);
8559
8560   gcc_assert (n == XVECLEN (pattern, 0));
8561
8562   return pattern;
8563 }
8564
8565 /* PATTERN is a PARALLEL whose first element adds ADJUST to the stack
8566    pointer.  Return true if PATTERN matches the kind of instruction
8567    generated by mips16e_build_save_restore.  If INFO is nonnull,
8568    initialize it when returning true.  */
8569
8570 bool
8571 mips16e_save_restore_pattern_p (rtx pattern, HOST_WIDE_INT adjust,
8572                                 struct mips16e_save_restore_info *info)
8573 {
8574   unsigned int i, nargs, mask, extra;
8575   HOST_WIDE_INT top_offset, save_offset, offset;
8576   rtx set, reg, mem, base;
8577   int n;
8578
8579   if (!GENERATE_MIPS16E_SAVE_RESTORE)
8580     return false;
8581
8582   /* Stack offsets in the PARALLEL are relative to the old stack pointer.  */
8583   top_offset = adjust > 0 ? adjust : 0;
8584
8585   /* Interpret all other members of the PARALLEL.  */
8586   save_offset = top_offset - UNITS_PER_WORD;
8587   mask = 0;
8588   nargs = 0;
8589   i = 0;
8590   for (n = 1; n < XVECLEN (pattern, 0); n++)
8591     {
8592       /* Check that we have a SET.  */
8593       set = XVECEXP (pattern, 0, n);
8594       if (GET_CODE (set) != SET)
8595         return false;
8596
8597       /* Check that the SET is a load (if restoring) or a store
8598          (if saving).  */
8599       mem = adjust > 0 ? SET_SRC (set) : SET_DEST (set);
8600       if (!MEM_P (mem))
8601         return false;
8602
8603       /* Check that the address is the sum of the stack pointer and a
8604          possibly-zero constant offset.  */
8605       mips_split_plus (XEXP (mem, 0), &base, &offset);
8606       if (base != stack_pointer_rtx)
8607         return false;
8608
8609       /* Check that SET's other operand is a register.  */
8610       reg = adjust > 0 ? SET_DEST (set) : SET_SRC (set);
8611       if (!REG_P (reg))
8612         return false;
8613
8614       /* Check for argument saves.  */
8615       if (offset == top_offset + nargs * UNITS_PER_WORD
8616           && REGNO (reg) == GP_ARG_FIRST + nargs)
8617         nargs++;
8618       else if (offset == save_offset)
8619         {
8620           while (mips16e_save_restore_regs[i++] != REGNO (reg))
8621             if (i == ARRAY_SIZE (mips16e_save_restore_regs))
8622               return false;
8623
8624           mask |= 1 << REGNO (reg);
8625           save_offset -= UNITS_PER_WORD;
8626         }
8627       else
8628         return false;
8629     }
8630
8631   /* Check that the restrictions on register ranges are met.  */
8632   extra = 0;
8633   mips16e_mask_registers (&mask, mips16e_s2_s8_regs,
8634                           ARRAY_SIZE (mips16e_s2_s8_regs), &extra);
8635   mips16e_mask_registers (&mask, mips16e_a0_a3_regs,
8636                           ARRAY_SIZE (mips16e_a0_a3_regs), &extra);
8637   if (extra != 0)
8638     return false;
8639
8640   /* Make sure that the topmost argument register is not saved twice.
8641      The checks above ensure that the same is then true for the other
8642      argument registers.  */
8643   if (nargs > 0 && BITSET_P (mask, GP_ARG_FIRST + nargs - 1))
8644     return false;
8645
8646   /* Pass back information, if requested.  */
8647   if (info)
8648     {
8649       info->nargs = nargs;
8650       info->mask = mask;
8651       info->size = (adjust > 0 ? adjust : -adjust);
8652     }
8653
8654   return true;
8655 }
8656
8657 /* Add a MIPS16e SAVE or RESTORE register-range argument to string S
8658    for the register range [MIN_REG, MAX_REG].  Return a pointer to
8659    the null terminator.  */
8660
8661 static char *
8662 mips16e_add_register_range (char *s, unsigned int min_reg,
8663                             unsigned int max_reg)
8664 {
8665   if (min_reg != max_reg)
8666     s += sprintf (s, ",%s-%s", reg_names[min_reg], reg_names[max_reg]);
8667   else
8668     s += sprintf (s, ",%s", reg_names[min_reg]);
8669   return s;
8670 }
8671
8672 /* Return the assembly instruction for a MIPS16e SAVE or RESTORE instruction.
8673    PATTERN and ADJUST are as for mips16e_save_restore_pattern_p.  */
8674
8675 const char *
8676 mips16e_output_save_restore (rtx pattern, HOST_WIDE_INT adjust)
8677 {
8678   static char buffer[300];
8679
8680   struct mips16e_save_restore_info info;
8681   unsigned int i, end;
8682   char *s;
8683
8684   /* Parse the pattern.  */
8685   if (!mips16e_save_restore_pattern_p (pattern, adjust, &info))
8686     gcc_unreachable ();
8687
8688   /* Add the mnemonic.  */
8689   s = strcpy (buffer, adjust > 0 ? "restore\t" : "save\t");
8690   s += strlen (s);
8691
8692   /* Save the arguments.  */
8693   if (info.nargs > 1)
8694     s += sprintf (s, "%s-%s,", reg_names[GP_ARG_FIRST],
8695                   reg_names[GP_ARG_FIRST + info.nargs - 1]);
8696   else if (info.nargs == 1)
8697     s += sprintf (s, "%s,", reg_names[GP_ARG_FIRST]);
8698
8699   /* Emit the amount of stack space to allocate or deallocate.  */
8700   s += sprintf (s, "%d", (int) info.size);
8701
8702   /* Save or restore $16.  */
8703   if (BITSET_P (info.mask, 16))
8704     s += sprintf (s, ",%s", reg_names[GP_REG_FIRST + 16]);
8705
8706   /* Save or restore $17.  */
8707   if (BITSET_P (info.mask, 17))
8708     s += sprintf (s, ",%s", reg_names[GP_REG_FIRST + 17]);
8709
8710   /* Save or restore registers in the range $s2...$s8, which
8711      mips16e_s2_s8_regs lists in decreasing order.  Note that this
8712      is a software register range; the hardware registers are not
8713      numbered consecutively.  */
8714   end = ARRAY_SIZE (mips16e_s2_s8_regs);
8715   i = mips16e_find_first_register (info.mask, mips16e_s2_s8_regs, end);
8716   if (i < end)
8717     s = mips16e_add_register_range (s, mips16e_s2_s8_regs[end - 1],
8718                                     mips16e_s2_s8_regs[i]);
8719
8720   /* Save or restore registers in the range $a0...$a3.  */
8721   end = ARRAY_SIZE (mips16e_a0_a3_regs);
8722   i = mips16e_find_first_register (info.mask, mips16e_a0_a3_regs, end);
8723   if (i < end)
8724     s = mips16e_add_register_range (s, mips16e_a0_a3_regs[i],
8725                                     mips16e_a0_a3_regs[end - 1]);
8726
8727   /* Save or restore $31.  */
8728   if (BITSET_P (info.mask, RETURN_ADDR_REGNUM))
8729     s += sprintf (s, ",%s", reg_names[RETURN_ADDR_REGNUM]);
8730
8731   return buffer;
8732 }
8733 \f
8734 /* Return true if the current function returns its value in a floating-point
8735    register in MIPS16 mode.  */
8736
8737 static bool
8738 mips16_cfun_returns_in_fpr_p (void)
8739 {
8740   tree return_type = DECL_RESULT (current_function_decl);
8741   return (TARGET_MIPS16
8742           && TARGET_HARD_FLOAT_ABI
8743           && !aggregate_value_p (return_type, current_function_decl)
8744           && mips_return_mode_in_fpr_p (DECL_MODE (return_type)));
8745 }
8746
8747 /* Return true if predicate PRED is true for at least one instruction.
8748    Cache the result in *CACHE, and assume that the result is true
8749    if *CACHE is already true.  */
8750
8751 static bool
8752 mips_find_gp_ref (bool *cache, bool (*pred) (rtx))
8753 {
8754   rtx insn;
8755
8756   if (!*cache)
8757     {
8758       push_topmost_sequence ();
8759       for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
8760         if (USEFUL_INSN_P (insn) && pred (insn))
8761           {
8762             *cache = true;
8763             break;
8764           }
8765       pop_topmost_sequence ();
8766     }
8767   return *cache;
8768 }
8769
8770 /* Return true if INSN refers to the global pointer in an "inflexible" way.
8771    See mips_cfun_has_inflexible_gp_ref_p for details.  */
8772
8773 static bool
8774 mips_insn_has_inflexible_gp_ref_p (rtx insn)
8775 {
8776   /* Uses of pic_offset_table_rtx in CALL_INSN_FUNCTION_USAGE
8777      indicate that the target could be a traditional MIPS
8778      lazily-binding stub.  */
8779   return find_reg_fusage (insn, USE, pic_offset_table_rtx);
8780 }
8781
8782 /* Return true if the current function refers to the global pointer
8783    in a way that forces $28 to be valid.  This means that we can't
8784    change the choice of global pointer, even for NewABI code.
8785
8786    One example of this (and one which needs several checks) is that
8787    $28 must be valid when calling traditional MIPS lazy-binding stubs.
8788    (This restriction does not apply to PLTs.)  */
8789
8790 static bool
8791 mips_cfun_has_inflexible_gp_ref_p (void)
8792 {
8793   /* If the function has a nonlocal goto, $28 must hold the correct
8794      global pointer for the target function.  That is, the target
8795      of the goto implicitly uses $28.  */
8796   if (crtl->has_nonlocal_goto)
8797     return true;
8798
8799   if (TARGET_ABICALLS_PIC2)
8800     {
8801       /* Symbolic accesses implicitly use the global pointer unless
8802          -mexplicit-relocs is in effect.  JAL macros to symbolic addresses
8803          might go to traditional MIPS lazy-binding stubs.  */
8804       if (!TARGET_EXPLICIT_RELOCS)
8805         return true;
8806
8807       /* FUNCTION_PROFILER includes a JAL to _mcount, which again
8808          can be lazily-bound.  */
8809       if (crtl->profile)
8810         return true;
8811
8812       /* MIPS16 functions that return in FPRs need to call an
8813          external libgcc routine.  This call is only made explict
8814          during mips_expand_epilogue, and it too might be lazily bound.  */
8815       if (mips16_cfun_returns_in_fpr_p ())
8816         return true;
8817     }
8818
8819   return mips_find_gp_ref (&cfun->machine->has_inflexible_gp_insn_p,
8820                            mips_insn_has_inflexible_gp_ref_p);
8821 }
8822
8823 /* Return true if INSN refers to the global pointer in a "flexible" way.
8824    See mips_cfun_has_flexible_gp_ref_p for details.  */
8825
8826 static bool
8827 mips_insn_has_flexible_gp_ref_p (rtx insn)
8828 {
8829   return (get_attr_got (insn) != GOT_UNSET
8830           || mips_small_data_pattern_p (PATTERN (insn))
8831           || reg_overlap_mentioned_p (pic_offset_table_rtx, PATTERN (insn)));
8832 }
8833
8834 /* Return true if the current function references the global pointer,
8835    but if those references do not inherently require the global pointer
8836    to be $28.  Assume !mips_cfun_has_inflexible_gp_ref_p ().  */
8837
8838 static bool
8839 mips_cfun_has_flexible_gp_ref_p (void)
8840 {
8841   /* Reload can sometimes introduce constant pool references
8842      into a function that otherwise didn't need them.  For example,
8843      suppose we have an instruction like:
8844
8845         (set (reg:DF R1) (float:DF (reg:SI R2)))
8846
8847      If R2 turns out to be a constant such as 1, the instruction may
8848      have a REG_EQUAL note saying that R1 == 1.0.  Reload then has
8849      the option of using this constant if R2 doesn't get allocated
8850      to a register.
8851
8852      In cases like these, reload will have added the constant to the
8853      pool but no instruction will yet refer to it.  */
8854   if (TARGET_ABICALLS_PIC2 && !reload_completed && crtl->uses_const_pool)
8855     return true;
8856
8857   return mips_find_gp_ref (&cfun->machine->has_flexible_gp_insn_p,
8858                            mips_insn_has_flexible_gp_ref_p);
8859 }
8860
8861 /* Return the register that should be used as the global pointer
8862    within this function.  Return INVALID_REGNUM if the function
8863    doesn't need a global pointer.  */
8864
8865 static unsigned int
8866 mips_global_pointer (void)
8867 {
8868   unsigned int regno;
8869
8870   /* $gp is always available unless we're using a GOT.  */
8871   if (!TARGET_USE_GOT)
8872     return GLOBAL_POINTER_REGNUM;
8873
8874   /* If there are inflexible references to $gp, we must use the
8875      standard register.  */
8876   if (mips_cfun_has_inflexible_gp_ref_p ())
8877     return GLOBAL_POINTER_REGNUM;
8878
8879   /* If there are no current references to $gp, then the only uses
8880      we can introduce later are those involved in long branches.  */
8881   if (TARGET_ABSOLUTE_JUMPS && !mips_cfun_has_flexible_gp_ref_p ())
8882     return INVALID_REGNUM;
8883
8884   /* If the global pointer is call-saved, try to use a call-clobbered
8885      alternative.  */
8886   if (TARGET_CALL_SAVED_GP && current_function_is_leaf)
8887     for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
8888       if (!df_regs_ever_live_p (regno)
8889           && call_really_used_regs[regno]
8890           && !fixed_regs[regno]
8891           && regno != PIC_FUNCTION_ADDR_REGNUM)
8892         return regno;
8893
8894   return GLOBAL_POINTER_REGNUM;
8895 }
8896
8897 /* Return true if the current function's prologue must load the global
8898    pointer value into pic_offset_table_rtx and store the same value in
8899    the function's cprestore slot (if any).
8900
8901    One problem we have to deal with is that, when emitting GOT-based
8902    position independent code, long-branch sequences will need to load
8903    the address of the branch target from the GOT.  We don't know until
8904    the very end of compilation whether (and where) the function needs
8905    long branches, so we must ensure that _any_ branch can access the
8906    global pointer in some form.  However, we do not want to pessimize
8907    the usual case in which all branches are short.
8908
8909    We handle this as follows:
8910
8911    (1) During reload, we set cfun->machine->global_pointer to
8912        INVALID_REGNUM if we _know_ that the current function
8913        doesn't need a global pointer.  This is only valid if
8914        long branches don't need the GOT.
8915
8916        Otherwise, we assume that we might need a global pointer
8917        and pick an appropriate register.
8918
8919    (2) If cfun->machine->global_pointer != INVALID_REGNUM,
8920        we ensure that the global pointer is available at every
8921        block boundary bar entry and exit.  We do this in one of two ways:
8922
8923        - If the function has a cprestore slot, we ensure that this
8924          slot is valid at every branch.  However, as explained in
8925          point (6) below, there is no guarantee that pic_offset_table_rtx
8926          itself is valid if new uses of the global pointer are introduced
8927          after the first post-epilogue split.
8928
8929          We guarantee that the cprestore slot is valid by loading it
8930          into a fake register, CPRESTORE_SLOT_REGNUM.  We then make
8931          this register live at every block boundary bar function entry
8932          and exit.  It is then invalid to move the load (and thus the
8933          preceding store) across a block boundary.
8934
8935        - If the function has no cprestore slot, we guarantee that
8936          pic_offset_table_rtx itself is valid at every branch.
8937
8938        See mips_eh_uses for the handling of the register liveness.
8939
8940    (3) During prologue and epilogue generation, we emit "ghost"
8941        placeholder instructions to manipulate the global pointer.
8942
8943    (4) During prologue generation, we set cfun->machine->must_initialize_gp_p
8944        and cfun->machine->must_restore_gp_when_clobbered_p if we already know
8945        that the function needs a global pointer.  (There is no need to set
8946        them earlier than this, and doing it as late as possible leads to
8947        fewer false positives.)
8948
8949    (5) If cfun->machine->must_initialize_gp_p is true during a
8950        split_insns pass, we split the ghost instructions into real
8951        instructions.  These split instructions can then be optimized in
8952        the usual way.  Otherwise, we keep the ghost instructions intact,
8953        and optimize for the case where they aren't needed.  We still
8954        have the option of splitting them later, if we need to introduce
8955        new uses of the global pointer.
8956
8957        For example, the scheduler ignores a ghost instruction that
8958        stores $28 to the stack, but it handles the split form of
8959        the ghost instruction as an ordinary store.
8960
8961    (6) [OldABI only.]  If cfun->machine->must_restore_gp_when_clobbered_p
8962        is true during the first post-epilogue split_insns pass, we split
8963        calls and restore_gp patterns into instructions that explicitly
8964        load pic_offset_table_rtx from the cprestore slot.  Otherwise,
8965        we split these patterns into instructions that _don't_ load from
8966        the cprestore slot.
8967
8968        If cfun->machine->must_restore_gp_when_clobbered_p is true at the
8969        time of the split, then any instructions that exist at that time
8970        can make free use of pic_offset_table_rtx.  However, if we want
8971        to introduce new uses of the global pointer after the split,
8972        we must explicitly load the value from the cprestore slot, since
8973        pic_offset_table_rtx itself might not be valid at a given point
8974        in the function.
8975
8976        The idea is that we want to be able to delete redundant
8977        loads from the cprestore slot in the usual case where no
8978        long branches are needed.
8979
8980    (7) If cfun->machine->must_initialize_gp_p is still false at the end
8981        of md_reorg, we decide whether the global pointer is needed for
8982        long branches.  If so, we set cfun->machine->must_initialize_gp_p
8983        to true and split the ghost instructions into real instructions
8984        at that stage.
8985
8986    Note that the ghost instructions must have a zero length for three reasons:
8987
8988    - Giving the length of the underlying $gp sequence might cause
8989      us to use long branches in cases where they aren't really needed.
8990
8991    - They would perturb things like alignment calculations.
8992
8993    - More importantly, the hazard detection in md_reorg relies on
8994      empty instructions having a zero length.
8995
8996    If we find a long branch and split the ghost instructions at the
8997    end of md_reorg, the split could introduce more long branches.
8998    That isn't a problem though, because we still do the split before
8999    the final shorten_branches pass.
9000
9001    This is extremely ugly, but it seems like the best compromise between
9002    correctness and efficiency.  */
9003
9004 bool
9005 mips_must_initialize_gp_p (void)
9006 {
9007   return cfun->machine->must_initialize_gp_p;
9008 }
9009
9010 /* Return true if REGNO is a register that is ordinarily call-clobbered
9011    but must nevertheless be preserved by an interrupt handler.  */
9012
9013 static bool
9014 mips_interrupt_extra_call_saved_reg_p (unsigned int regno)
9015 {
9016   if (MD_REG_P (regno))
9017     return true;
9018
9019   if (TARGET_DSP && DSP_ACC_REG_P (regno))
9020     return true;
9021
9022   if (GP_REG_P (regno) && !cfun->machine->use_shadow_register_set_p)
9023     {
9024       /* $0 is hard-wired.  */
9025       if (regno == GP_REG_FIRST)
9026         return false;
9027
9028       /* The interrupt handler can treat kernel registers as
9029          scratch registers.  */
9030       if (KERNEL_REG_P (regno))
9031         return false;
9032
9033       /* The function will return the stack pointer to its original value
9034          anyway.  */
9035       if (regno == STACK_POINTER_REGNUM)
9036         return false;
9037
9038       /* Otherwise, return true for registers that aren't ordinarily
9039          call-clobbered.  */
9040       return call_really_used_regs[regno];
9041     }
9042
9043   return false;
9044 }
9045
9046 /* Return true if the current function should treat register REGNO
9047    as call-saved.  */
9048
9049 static bool
9050 mips_cfun_call_saved_reg_p (unsigned int regno)
9051 {
9052   /* Interrupt handlers need to save extra registers.  */
9053   if (cfun->machine->interrupt_handler_p
9054       && mips_interrupt_extra_call_saved_reg_p (regno))
9055     return true;
9056
9057   /* call_insns preserve $28 unless they explicitly say otherwise,
9058      so call_really_used_regs[] treats $28 as call-saved.  However,
9059      we want the ABI property rather than the default call_insn
9060      property here.  */
9061   return (regno == GLOBAL_POINTER_REGNUM
9062           ? TARGET_CALL_SAVED_GP
9063           : !call_really_used_regs[regno]);
9064 }
9065
9066 /* Return true if the function body might clobber register REGNO.
9067    We know that REGNO is call-saved.  */
9068
9069 static bool
9070 mips_cfun_might_clobber_call_saved_reg_p (unsigned int regno)
9071 {
9072   /* Some functions should be treated as clobbering all call-saved
9073      registers.  */
9074   if (crtl->saves_all_registers)
9075     return true;
9076
9077   /* DF handles cases where a register is explicitly referenced in
9078      the rtl.  Incoming values are passed in call-clobbered registers,
9079      so we can assume that any live call-saved register is set within
9080      the function.  */
9081   if (df_regs_ever_live_p (regno))
9082     return true;
9083
9084   /* Check for registers that are clobbered by FUNCTION_PROFILER.
9085      These clobbers are not explicit in the rtl.  */
9086   if (crtl->profile && MIPS_SAVE_REG_FOR_PROFILING_P (regno))
9087     return true;
9088
9089   /* If we're using a call-saved global pointer, the function's
9090      prologue will need to set it up.  */
9091   if (cfun->machine->global_pointer == regno)
9092     return true;
9093
9094   /* The function's prologue will need to set the frame pointer if
9095      frame_pointer_needed.  */
9096   if (regno == HARD_FRAME_POINTER_REGNUM && frame_pointer_needed)
9097     return true;
9098
9099   /* If a MIPS16 function returns a value in FPRs, its epilogue
9100      will need to call an external libgcc routine.  This yet-to-be
9101      generated call_insn will clobber $31.  */
9102   if (regno == RETURN_ADDR_REGNUM && mips16_cfun_returns_in_fpr_p ())
9103     return true;
9104
9105   /* If REGNO is ordinarily call-clobbered, we must assume that any
9106      called function could modify it.  */
9107   if (cfun->machine->interrupt_handler_p
9108       && !current_function_is_leaf
9109       && mips_interrupt_extra_call_saved_reg_p (regno))
9110     return true;
9111
9112   return false;
9113 }
9114
9115 /* Return true if the current function must save register REGNO.  */
9116
9117 static bool
9118 mips_save_reg_p (unsigned int regno)
9119 {
9120   if (mips_cfun_call_saved_reg_p (regno))
9121     {
9122       if (mips_cfun_might_clobber_call_saved_reg_p (regno))
9123         return true;
9124
9125       /* Save both registers in an FPR pair if either one is used.  This is
9126          needed for the case when MIN_FPRS_PER_FMT == 1, which allows the odd
9127          register to be used without the even register.  */
9128       if (FP_REG_P (regno)
9129           && MAX_FPRS_PER_FMT == 2
9130           && mips_cfun_might_clobber_call_saved_reg_p (regno + 1))
9131         return true;
9132     }
9133
9134   /* We need to save the incoming return address if __builtin_eh_return
9135      is being used to set a different return address.  */
9136   if (regno == RETURN_ADDR_REGNUM && crtl->calls_eh_return)
9137     return true;
9138
9139   return false;
9140 }
9141
9142 /* Populate the current function's mips_frame_info structure.
9143
9144    MIPS stack frames look like:
9145
9146         +-------------------------------+
9147         |                               |
9148         |  incoming stack arguments     |
9149         |                               |
9150         +-------------------------------+
9151         |                               |
9152         |  caller-allocated save area   |
9153       A |  for register arguments       |
9154         |                               |
9155         +-------------------------------+ <-- incoming stack pointer
9156         |                               |
9157         |  callee-allocated save area   |
9158       B |  for arguments that are       |
9159         |  split between registers and  |
9160         |  the stack                    |
9161         |                               |
9162         +-------------------------------+ <-- arg_pointer_rtx
9163         |                               |
9164       C |  callee-allocated save area   |
9165         |  for register varargs         |
9166         |                               |
9167         +-------------------------------+ <-- frame_pointer_rtx
9168         |                               |       + cop0_sp_offset
9169         |  COP0 reg save area           |       + UNITS_PER_WORD
9170         |                               |
9171         +-------------------------------+ <-- frame_pointer_rtx + acc_sp_offset
9172         |                               |       + UNITS_PER_WORD
9173         |  accumulator save area        |
9174         |                               |
9175         +-------------------------------+ <-- stack_pointer_rtx + fp_sp_offset
9176         |                               |       + UNITS_PER_HWFPVALUE
9177         |  FPR save area                |
9178         |                               |
9179         +-------------------------------+ <-- stack_pointer_rtx + gp_sp_offset
9180         |                               |       + UNITS_PER_WORD
9181         |  GPR save area                |
9182         |                               |
9183         +-------------------------------+ <-- frame_pointer_rtx with
9184         |                               | \     -fstack-protector
9185         |  local variables              |  | var_size
9186         |                               | /
9187         +-------------------------------+
9188         |                               | \
9189         |  $gp save area                |  | cprestore_size
9190         |                               | /
9191       P +-------------------------------+ <-- hard_frame_pointer_rtx for
9192         |                               | \     MIPS16 code
9193         |  outgoing stack arguments     |  |
9194         |                               |  |
9195         +-------------------------------+  | args_size
9196         |                               |  |
9197         |  caller-allocated save area   |  |
9198         |  for register arguments       |  |
9199         |                               | /
9200         +-------------------------------+ <-- stack_pointer_rtx
9201                                               frame_pointer_rtx without
9202                                                 -fstack-protector
9203                                               hard_frame_pointer_rtx for
9204                                                 non-MIPS16 code.
9205
9206    At least two of A, B and C will be empty.
9207
9208    Dynamic stack allocations such as alloca insert data at point P.
9209    They decrease stack_pointer_rtx but leave frame_pointer_rtx and
9210    hard_frame_pointer_rtx unchanged.  */
9211
9212 static void
9213 mips_compute_frame_info (void)
9214 {
9215   struct mips_frame_info *frame;
9216   HOST_WIDE_INT offset, size;
9217   unsigned int regno, i;
9218
9219   /* Set this function's interrupt properties.  */
9220   if (mips_interrupt_type_p (TREE_TYPE (current_function_decl)))
9221     {
9222       if (!ISA_MIPS32R2)
9223         error ("the %<interrupt%> attribute requires a MIPS32r2 processor");
9224       else if (TARGET_HARD_FLOAT)
9225         error ("the %<interrupt%> attribute requires %<-msoft-float%>");
9226       else if (TARGET_MIPS16)
9227         error ("interrupt handlers cannot be MIPS16 functions");
9228       else
9229         {
9230           cfun->machine->interrupt_handler_p = true;
9231           cfun->machine->use_shadow_register_set_p =
9232             mips_use_shadow_register_set_p (TREE_TYPE (current_function_decl));
9233           cfun->machine->keep_interrupts_masked_p =
9234             mips_keep_interrupts_masked_p (TREE_TYPE (current_function_decl));
9235           cfun->machine->use_debug_exception_return_p =
9236             mips_use_debug_exception_return_p (TREE_TYPE
9237                                                (current_function_decl));
9238         }
9239     }
9240
9241   frame = &cfun->machine->frame;
9242   memset (frame, 0, sizeof (*frame));
9243   size = get_frame_size ();
9244
9245   cfun->machine->global_pointer = mips_global_pointer ();
9246
9247   /* The first two blocks contain the outgoing argument area and the $gp save
9248      slot.  This area isn't needed in leaf functions, but if the
9249      target-independent frame size is nonzero, we have already committed to
9250      allocating these in STARTING_FRAME_OFFSET for !FRAME_GROWS_DOWNWARD.  */
9251   if ((size == 0 || FRAME_GROWS_DOWNWARD) && current_function_is_leaf)
9252     {
9253       /* The MIPS 3.0 linker does not like functions that dynamically
9254          allocate the stack and have 0 for STACK_DYNAMIC_OFFSET, since it
9255          looks like we are trying to create a second frame pointer to the
9256          function, so allocate some stack space to make it happy.  */
9257       if (cfun->calls_alloca)
9258         frame->args_size = REG_PARM_STACK_SPACE (cfun->decl);
9259       else
9260         frame->args_size = 0;
9261       frame->cprestore_size = 0;
9262     }
9263   else
9264     {
9265       frame->args_size = crtl->outgoing_args_size;
9266       frame->cprestore_size = MIPS_GP_SAVE_AREA_SIZE;
9267     }
9268   offset = frame->args_size + frame->cprestore_size;
9269
9270   /* Move above the local variables.  */
9271   frame->var_size = MIPS_STACK_ALIGN (size);
9272   offset += frame->var_size;
9273
9274   /* Find out which GPRs we need to save.  */
9275   for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
9276     if (mips_save_reg_p (regno))
9277       {
9278         frame->num_gp++;
9279         frame->mask |= 1 << (regno - GP_REG_FIRST);
9280       }
9281
9282   /* If this function calls eh_return, we must also save and restore the
9283      EH data registers.  */
9284   if (crtl->calls_eh_return)
9285     for (i = 0; EH_RETURN_DATA_REGNO (i) != INVALID_REGNUM; i++)
9286       {
9287         frame->num_gp++;
9288         frame->mask |= 1 << (EH_RETURN_DATA_REGNO (i) - GP_REG_FIRST);
9289       }
9290
9291   /* The MIPS16e SAVE and RESTORE instructions have two ranges of registers:
9292      $a3-$a0 and $s2-$s8.  If we save one register in the range, we must
9293      save all later registers too.  */
9294   if (GENERATE_MIPS16E_SAVE_RESTORE)
9295     {
9296       mips16e_mask_registers (&frame->mask, mips16e_s2_s8_regs,
9297                               ARRAY_SIZE (mips16e_s2_s8_regs), &frame->num_gp);
9298       mips16e_mask_registers (&frame->mask, mips16e_a0_a3_regs,
9299                               ARRAY_SIZE (mips16e_a0_a3_regs), &frame->num_gp);
9300     }
9301
9302   /* Move above the GPR save area.  */
9303   if (frame->num_gp > 0)
9304     {
9305       offset += MIPS_STACK_ALIGN (frame->num_gp * UNITS_PER_WORD);
9306       frame->gp_sp_offset = offset - UNITS_PER_WORD;
9307     }
9308
9309   /* Find out which FPRs we need to save.  This loop must iterate over
9310      the same space as its companion in mips_for_each_saved_gpr_and_fpr.  */
9311   if (TARGET_HARD_FLOAT)
9312     for (regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno += MAX_FPRS_PER_FMT)
9313       if (mips_save_reg_p (regno))
9314         {
9315           frame->num_fp += MAX_FPRS_PER_FMT;
9316           frame->fmask |= ~(~0 << MAX_FPRS_PER_FMT) << (regno - FP_REG_FIRST);
9317         }
9318
9319   /* Move above the FPR save area.  */
9320   if (frame->num_fp > 0)
9321     {
9322       offset += MIPS_STACK_ALIGN (frame->num_fp * UNITS_PER_FPREG);
9323       frame->fp_sp_offset = offset - UNITS_PER_HWFPVALUE;
9324     }
9325
9326   /* Add in space for the interrupt context information.  */
9327   if (cfun->machine->interrupt_handler_p)
9328     {
9329       /* Check HI/LO.  */
9330       if (mips_save_reg_p (LO_REGNUM) || mips_save_reg_p (HI_REGNUM))
9331         {
9332           frame->num_acc++;
9333           frame->acc_mask |= (1 << 0);
9334         }
9335
9336       /* Check accumulators 1, 2, 3.  */
9337       for (i = DSP_ACC_REG_FIRST; i <= DSP_ACC_REG_LAST; i += 2)
9338         if (mips_save_reg_p (i) || mips_save_reg_p (i + 1))
9339           {
9340             frame->num_acc++;
9341             frame->acc_mask |= 1 << (((i - DSP_ACC_REG_FIRST) / 2) + 1);
9342           }
9343
9344       /* All interrupt context functions need space to preserve STATUS.  */
9345       frame->num_cop0_regs++;
9346
9347       /* If we don't keep interrupts masked, we need to save EPC.  */
9348       if (!cfun->machine->keep_interrupts_masked_p)
9349         frame->num_cop0_regs++;
9350     }
9351
9352   /* Move above the accumulator save area.  */
9353   if (frame->num_acc > 0)
9354     {
9355       /* Each accumulator needs 2 words.  */
9356       offset += frame->num_acc * 2 * UNITS_PER_WORD;
9357       frame->acc_sp_offset = offset - UNITS_PER_WORD;
9358     }
9359
9360   /* Move above the COP0 register save area.  */
9361   if (frame->num_cop0_regs > 0)
9362     {
9363       offset += frame->num_cop0_regs * UNITS_PER_WORD;
9364       frame->cop0_sp_offset = offset - UNITS_PER_WORD;
9365     }
9366
9367   /* Move above the callee-allocated varargs save area.  */
9368   offset += MIPS_STACK_ALIGN (cfun->machine->varargs_size);
9369   frame->arg_pointer_offset = offset;
9370
9371   /* Move above the callee-allocated area for pretend stack arguments.  */
9372   offset += crtl->args.pretend_args_size;
9373   frame->total_size = offset;
9374
9375   /* Work out the offsets of the save areas from the top of the frame.  */
9376   if (frame->gp_sp_offset > 0)
9377     frame->gp_save_offset = frame->gp_sp_offset - offset;
9378   if (frame->fp_sp_offset > 0)
9379     frame->fp_save_offset = frame->fp_sp_offset - offset;
9380   if (frame->acc_sp_offset > 0)
9381     frame->acc_save_offset = frame->acc_sp_offset - offset;
9382   if (frame->num_cop0_regs > 0)
9383     frame->cop0_save_offset = frame->cop0_sp_offset - offset;
9384
9385   /* MIPS16 code offsets the frame pointer by the size of the outgoing
9386      arguments.  This tends to increase the chances of using unextended
9387      instructions for local variables and incoming arguments.  */
9388   if (TARGET_MIPS16)
9389     frame->hard_frame_pointer_offset = frame->args_size;
9390 }
9391
9392 /* Return the style of GP load sequence that is being used for the
9393    current function.  */
9394
9395 enum mips_loadgp_style
9396 mips_current_loadgp_style (void)
9397 {
9398   if (!TARGET_USE_GOT || cfun->machine->global_pointer == INVALID_REGNUM)
9399     return LOADGP_NONE;
9400
9401   if (TARGET_RTP_PIC)
9402     return LOADGP_RTP;
9403
9404   if (TARGET_ABSOLUTE_ABICALLS)
9405     return LOADGP_ABSOLUTE;
9406
9407   return TARGET_NEWABI ? LOADGP_NEWABI : LOADGP_OLDABI;
9408 }
9409
9410 /* Implement TARGET_FRAME_POINTER_REQUIRED.  */
9411
9412 static bool
9413 mips_frame_pointer_required (void)
9414 {
9415   /* If the function contains dynamic stack allocations, we need to
9416      use the frame pointer to access the static parts of the frame.  */
9417   if (cfun->calls_alloca)
9418     return true;
9419
9420   /* In MIPS16 mode, we need a frame pointer for a large frame; otherwise,
9421      reload may be unable to compute the address of a local variable,
9422      since there is no way to add a large constant to the stack pointer
9423      without using a second temporary register.  */
9424   if (TARGET_MIPS16)
9425     {
9426       mips_compute_frame_info ();
9427       if (!SMALL_OPERAND (cfun->machine->frame.total_size))
9428         return true;
9429     }
9430
9431   return false;
9432 }
9433
9434 /* Make sure that we're not trying to eliminate to the wrong hard frame
9435    pointer.  */
9436
9437 static bool
9438 mips_can_eliminate (const int from ATTRIBUTE_UNUSED, const int to)
9439 {
9440   return (to == HARD_FRAME_POINTER_REGNUM || to == STACK_POINTER_REGNUM);
9441 }
9442
9443 /* Implement INITIAL_ELIMINATION_OFFSET.  FROM is either the frame pointer
9444    or argument pointer.  TO is either the stack pointer or hard frame
9445    pointer.  */
9446
9447 HOST_WIDE_INT
9448 mips_initial_elimination_offset (int from, int to)
9449 {
9450   HOST_WIDE_INT offset;
9451
9452   mips_compute_frame_info ();
9453
9454   /* Set OFFSET to the offset from the end-of-prologue stack pointer.  */
9455   switch (from)
9456     {
9457     case FRAME_POINTER_REGNUM:
9458       if (FRAME_GROWS_DOWNWARD)
9459         offset = (cfun->machine->frame.args_size
9460                   + cfun->machine->frame.cprestore_size
9461                   + cfun->machine->frame.var_size);
9462       else
9463         offset = 0;
9464       break;
9465
9466     case ARG_POINTER_REGNUM:
9467       offset = cfun->machine->frame.arg_pointer_offset;
9468       break;
9469
9470     default:
9471       gcc_unreachable ();
9472     }
9473
9474   if (to == HARD_FRAME_POINTER_REGNUM)
9475     offset -= cfun->machine->frame.hard_frame_pointer_offset;
9476
9477   return offset;
9478 }
9479 \f
9480 /* Implement TARGET_EXTRA_LIVE_ON_ENTRY.  */
9481
9482 static void
9483 mips_extra_live_on_entry (bitmap regs)
9484 {
9485   if (TARGET_USE_GOT)
9486     {
9487       /* PIC_FUNCTION_ADDR_REGNUM is live if we need it to set up
9488          the global pointer.   */
9489       if (!TARGET_ABSOLUTE_ABICALLS)
9490         bitmap_set_bit (regs, PIC_FUNCTION_ADDR_REGNUM);
9491
9492       /* The prologue may set MIPS16_PIC_TEMP_REGNUM to the value of
9493          the global pointer.  */
9494       if (TARGET_MIPS16)
9495         bitmap_set_bit (regs, MIPS16_PIC_TEMP_REGNUM);
9496
9497       /* See the comment above load_call<mode> for details.  */
9498       bitmap_set_bit (regs, GOT_VERSION_REGNUM);
9499     }
9500 }
9501
9502 /* Implement RETURN_ADDR_RTX.  We do not support moving back to a
9503    previous frame.  */
9504
9505 rtx
9506 mips_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
9507 {
9508   if (count != 0)
9509     return const0_rtx;
9510
9511   return get_hard_reg_initial_val (Pmode, RETURN_ADDR_REGNUM);
9512 }
9513
9514 /* Emit code to change the current function's return address to
9515    ADDRESS.  SCRATCH is available as a scratch register, if needed.
9516    ADDRESS and SCRATCH are both word-mode GPRs.  */
9517
9518 void
9519 mips_set_return_address (rtx address, rtx scratch)
9520 {
9521   rtx slot_address;
9522
9523   gcc_assert (BITSET_P (cfun->machine->frame.mask, RETURN_ADDR_REGNUM));
9524   slot_address = mips_add_offset (scratch, stack_pointer_rtx,
9525                                   cfun->machine->frame.gp_sp_offset);
9526   mips_emit_move (gen_frame_mem (GET_MODE (address), slot_address), address);
9527 }
9528
9529 /* Return true if the current function has a cprestore slot.  */
9530
9531 bool
9532 mips_cfun_has_cprestore_slot_p (void)
9533 {
9534   return (cfun->machine->global_pointer != INVALID_REGNUM
9535           && cfun->machine->frame.cprestore_size > 0);
9536 }
9537
9538 /* Fill *BASE and *OFFSET such that *BASE + *OFFSET refers to the
9539    cprestore slot.  LOAD_P is true if the caller wants to load from
9540    the cprestore slot; it is false if the caller wants to store to
9541    the slot.  */
9542
9543 static void
9544 mips_get_cprestore_base_and_offset (rtx *base, HOST_WIDE_INT *offset,
9545                                     bool load_p)
9546 {
9547   const struct mips_frame_info *frame;
9548
9549   frame = &cfun->machine->frame;
9550   /* .cprestore always uses the stack pointer instead of the frame pointer.
9551      We have a free choice for direct stores for non-MIPS16 functions,
9552      and for MIPS16 functions whose cprestore slot is in range of the
9553      stack pointer.  Using the stack pointer would sometimes give more
9554      (early) scheduling freedom, but using the frame pointer would
9555      sometimes give more (late) scheduling freedom.  It's hard to
9556      predict which applies to a given function, so let's keep things
9557      simple.
9558
9559      Loads must always use the frame pointer in functions that call
9560      alloca, and there's little benefit to using the stack pointer
9561      otherwise.  */
9562   if (frame_pointer_needed && !(TARGET_CPRESTORE_DIRECTIVE && !load_p))
9563     {
9564       *base = hard_frame_pointer_rtx;
9565       *offset = frame->args_size - frame->hard_frame_pointer_offset;
9566     }
9567   else
9568     {
9569       *base = stack_pointer_rtx;
9570       *offset = frame->args_size;
9571     }
9572 }
9573
9574 /* Return true if X is the load or store address of the cprestore slot;
9575    LOAD_P says which.  */
9576
9577 bool
9578 mips_cprestore_address_p (rtx x, bool load_p)
9579 {
9580   rtx given_base, required_base;
9581   HOST_WIDE_INT given_offset, required_offset;
9582
9583   mips_split_plus (x, &given_base, &given_offset);
9584   mips_get_cprestore_base_and_offset (&required_base, &required_offset, load_p);
9585   return given_base == required_base && given_offset == required_offset;
9586 }
9587
9588 /* Return a MEM rtx for the cprestore slot.  LOAD_P is true if we are
9589    going to load from it, false if we are going to store to it.
9590    Use TEMP as a temporary register if need be.  */
9591
9592 static rtx
9593 mips_cprestore_slot (rtx temp, bool load_p)
9594 {
9595   rtx base;
9596   HOST_WIDE_INT offset;
9597
9598   mips_get_cprestore_base_and_offset (&base, &offset, load_p);
9599   return gen_frame_mem (Pmode, mips_add_offset (temp, base, offset));
9600 }
9601
9602 /* Emit instructions to save global pointer value GP into cprestore
9603    slot MEM.  OFFSET is the offset that MEM applies to the base register.
9604
9605    MEM may not be a legitimate address.  If it isn't, TEMP is a
9606    temporary register that can be used, otherwise it is a SCRATCH.  */
9607
9608 void
9609 mips_save_gp_to_cprestore_slot (rtx mem, rtx offset, rtx gp, rtx temp)
9610 {
9611   if (TARGET_CPRESTORE_DIRECTIVE)
9612     {
9613       gcc_assert (gp == pic_offset_table_rtx);
9614       emit_insn (gen_cprestore (mem, offset));
9615     }
9616   else
9617     mips_emit_move (mips_cprestore_slot (temp, false), gp);
9618 }
9619
9620 /* Restore $gp from its save slot, using TEMP as a temporary base register
9621    if need be.  This function is for o32 and o64 abicalls only.
9622
9623    See mips_must_initialize_gp_p for details about how we manage the
9624    global pointer.  */
9625
9626 void
9627 mips_restore_gp_from_cprestore_slot (rtx temp)
9628 {
9629   gcc_assert (TARGET_ABICALLS && TARGET_OLDABI && epilogue_completed);
9630
9631   if (!cfun->machine->must_restore_gp_when_clobbered_p)
9632     {
9633       emit_note (NOTE_INSN_DELETED);
9634       return;
9635     }
9636
9637   if (TARGET_MIPS16)
9638     {
9639       mips_emit_move (temp, mips_cprestore_slot (temp, true));
9640       mips_emit_move (pic_offset_table_rtx, temp);
9641     }
9642   else
9643     mips_emit_move (pic_offset_table_rtx, mips_cprestore_slot (temp, true));
9644   if (!TARGET_EXPLICIT_RELOCS)
9645     emit_insn (gen_blockage ());
9646 }
9647 \f
9648 /* A function to save or store a register.  The first argument is the
9649    register and the second is the stack slot.  */
9650 typedef void (*mips_save_restore_fn) (rtx, rtx);
9651
9652 /* Use FN to save or restore register REGNO.  MODE is the register's
9653    mode and OFFSET is the offset of its save slot from the current
9654    stack pointer.  */
9655
9656 static void
9657 mips_save_restore_reg (enum machine_mode mode, int regno,
9658                        HOST_WIDE_INT offset, mips_save_restore_fn fn)
9659 {
9660   rtx mem;
9661
9662   mem = gen_frame_mem (mode, plus_constant (stack_pointer_rtx, offset));
9663   fn (gen_rtx_REG (mode, regno), mem);
9664 }
9665
9666 /* Call FN for each accumlator that is saved by the current function.
9667    SP_OFFSET is the offset of the current stack pointer from the start
9668    of the frame.  */
9669
9670 static void
9671 mips_for_each_saved_acc (HOST_WIDE_INT sp_offset, mips_save_restore_fn fn)
9672 {
9673   HOST_WIDE_INT offset;
9674   int regno;
9675
9676   offset = cfun->machine->frame.acc_sp_offset - sp_offset;
9677   if (BITSET_P (cfun->machine->frame.acc_mask, 0))
9678     {
9679       mips_save_restore_reg (word_mode, LO_REGNUM, offset, fn);
9680       offset -= UNITS_PER_WORD;
9681       mips_save_restore_reg (word_mode, HI_REGNUM, offset, fn);
9682       offset -= UNITS_PER_WORD;
9683     }
9684
9685   for (regno = DSP_ACC_REG_FIRST; regno <= DSP_ACC_REG_LAST; regno++)
9686     if (BITSET_P (cfun->machine->frame.acc_mask,
9687                   ((regno - DSP_ACC_REG_FIRST) / 2) + 1))
9688       {
9689         mips_save_restore_reg (word_mode, regno, offset, fn);
9690         offset -= UNITS_PER_WORD;
9691       }
9692 }
9693
9694 /* Call FN for each register that is saved by the current function.
9695    SP_OFFSET is the offset of the current stack pointer from the start
9696    of the frame.  */
9697
9698 static void
9699 mips_for_each_saved_gpr_and_fpr (HOST_WIDE_INT sp_offset,
9700                                  mips_save_restore_fn fn)
9701 {
9702   enum machine_mode fpr_mode;
9703   HOST_WIDE_INT offset;
9704   int regno;
9705
9706   /* Save registers starting from high to low.  The debuggers prefer at least
9707      the return register be stored at func+4, and also it allows us not to
9708      need a nop in the epilogue if at least one register is reloaded in
9709      addition to return address.  */
9710   offset = cfun->machine->frame.gp_sp_offset - sp_offset;
9711   for (regno = GP_REG_LAST; regno >= GP_REG_FIRST; regno--)
9712     if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
9713       {
9714         /* Record the ra offset for use by mips_function_profiler.  */
9715         if (regno == RETURN_ADDR_REGNUM)
9716           cfun->machine->frame.ra_fp_offset = offset + sp_offset;
9717         mips_save_restore_reg (word_mode, regno, offset, fn);
9718         offset -= UNITS_PER_WORD;
9719       }
9720
9721   /* This loop must iterate over the same space as its companion in
9722      mips_compute_frame_info.  */
9723   offset = cfun->machine->frame.fp_sp_offset - sp_offset;
9724   fpr_mode = (TARGET_SINGLE_FLOAT ? SFmode : DFmode);
9725   for (regno = FP_REG_LAST - MAX_FPRS_PER_FMT + 1;
9726        regno >= FP_REG_FIRST;
9727        regno -= MAX_FPRS_PER_FMT)
9728     if (BITSET_P (cfun->machine->frame.fmask, regno - FP_REG_FIRST))
9729       {
9730         mips_save_restore_reg (fpr_mode, regno, offset, fn);
9731         offset -= GET_MODE_SIZE (fpr_mode);
9732       }
9733 }
9734
9735 /* Return true if a move between register REGNO and its save slot (MEM)
9736    can be done in a single move.  LOAD_P is true if we are loading
9737    from the slot, false if we are storing to it.  */
9738
9739 static bool
9740 mips_direct_save_slot_move_p (unsigned int regno, rtx mem, bool load_p)
9741 {
9742   /* There is a specific MIPS16 instruction for saving $31 to the stack.  */
9743   if (TARGET_MIPS16 && !load_p && regno == RETURN_ADDR_REGNUM)
9744     return false;
9745
9746   return mips_secondary_reload_class (REGNO_REG_CLASS (regno),
9747                                       GET_MODE (mem), mem, load_p) == NO_REGS;
9748 }
9749
9750 /* Emit a move from SRC to DEST, given that one of them is a register
9751    save slot and that the other is a register.  TEMP is a temporary
9752    GPR of the same mode that is available if need be.  */
9753
9754 void
9755 mips_emit_save_slot_move (rtx dest, rtx src, rtx temp)
9756 {
9757   unsigned int regno;
9758   rtx mem;
9759
9760   if (REG_P (src))
9761     {
9762       regno = REGNO (src);
9763       mem = dest;
9764     }
9765   else
9766     {
9767       regno = REGNO (dest);
9768       mem = src;
9769     }
9770
9771   if (regno == cfun->machine->global_pointer && !mips_must_initialize_gp_p ())
9772     {
9773       /* We don't yet know whether we'll need this instruction or not.
9774          Postpone the decision by emitting a ghost move.  This move
9775          is specifically not frame-related; only the split version is.  */
9776       if (TARGET_64BIT)
9777         emit_insn (gen_move_gpdi (dest, src));
9778       else
9779         emit_insn (gen_move_gpsi (dest, src));
9780       return;
9781     }
9782
9783   if (regno == HI_REGNUM)
9784     {
9785       if (REG_P (dest))
9786         {
9787           mips_emit_move (temp, src);
9788           if (TARGET_64BIT)
9789             emit_insn (gen_mthisi_di (gen_rtx_REG (TImode, MD_REG_FIRST),
9790                                       temp, gen_rtx_REG (DImode, LO_REGNUM)));
9791           else
9792             emit_insn (gen_mthisi_di (gen_rtx_REG (DImode, MD_REG_FIRST),
9793                                       temp, gen_rtx_REG (SImode, LO_REGNUM)));
9794         }
9795       else
9796         {
9797           if (TARGET_64BIT)
9798             emit_insn (gen_mfhidi_ti (temp,
9799                                       gen_rtx_REG (TImode, MD_REG_FIRST)));
9800           else
9801             emit_insn (gen_mfhisi_di (temp,
9802                                       gen_rtx_REG (DImode, MD_REG_FIRST)));
9803           mips_emit_move (dest, temp);
9804         }
9805     }
9806   else if (mips_direct_save_slot_move_p (regno, mem, mem == src))
9807     mips_emit_move (dest, src);
9808   else
9809     {
9810       gcc_assert (!reg_overlap_mentioned_p (dest, temp));
9811       mips_emit_move (temp, src);
9812       mips_emit_move (dest, temp);
9813     }
9814   if (MEM_P (dest))
9815     mips_set_frame_expr (mips_frame_set (dest, src));
9816 }
9817 \f
9818 /* If we're generating n32 or n64 abicalls, and the current function
9819    does not use $28 as its global pointer, emit a cplocal directive.
9820    Use pic_offset_table_rtx as the argument to the directive.  */
9821
9822 static void
9823 mips_output_cplocal (void)
9824 {
9825   if (!TARGET_EXPLICIT_RELOCS
9826       && mips_must_initialize_gp_p ()
9827       && cfun->machine->global_pointer != GLOBAL_POINTER_REGNUM)
9828     output_asm_insn (".cplocal %+", 0);
9829 }
9830
9831 /* Implement TARGET_OUTPUT_FUNCTION_PROLOGUE.  */
9832
9833 static void
9834 mips_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
9835 {
9836   const char *fnname;
9837
9838 #ifdef SDB_DEBUGGING_INFO
9839   if (debug_info_level != DINFO_LEVEL_TERSE && write_symbols == SDB_DEBUG)
9840     SDB_OUTPUT_SOURCE_LINE (file, DECL_SOURCE_LINE (current_function_decl));
9841 #endif
9842
9843   /* In MIPS16 mode, we may need to generate a non-MIPS16 stub to handle
9844      floating-point arguments.  */
9845   if (TARGET_MIPS16
9846       && TARGET_HARD_FLOAT_ABI
9847       && crtl->args.info.fp_code != 0)
9848     mips16_build_function_stub ();
9849
9850   /* Get the function name the same way that toplev.c does before calling
9851      assemble_start_function.  This is needed so that the name used here
9852      exactly matches the name used in ASM_DECLARE_FUNCTION_NAME.  */
9853   fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
9854   mips_start_function_definition (fnname, TARGET_MIPS16);
9855
9856   /* Output MIPS-specific frame information.  */
9857   if (!flag_inhibit_size_directive)
9858     {
9859       const struct mips_frame_info *frame;
9860
9861       frame = &cfun->machine->frame;
9862
9863       /* .frame FRAMEREG, FRAMESIZE, RETREG.  */
9864       fprintf (file,
9865                "\t.frame\t%s," HOST_WIDE_INT_PRINT_DEC ",%s\t\t"
9866                "# vars= " HOST_WIDE_INT_PRINT_DEC
9867                ", regs= %d/%d"
9868                ", args= " HOST_WIDE_INT_PRINT_DEC
9869                ", gp= " HOST_WIDE_INT_PRINT_DEC "\n",
9870                reg_names[frame_pointer_needed
9871                          ? HARD_FRAME_POINTER_REGNUM
9872                          : STACK_POINTER_REGNUM],
9873                (frame_pointer_needed
9874                 ? frame->total_size - frame->hard_frame_pointer_offset
9875                 : frame->total_size),
9876                reg_names[RETURN_ADDR_REGNUM],
9877                frame->var_size,
9878                frame->num_gp, frame->num_fp,
9879                frame->args_size,
9880                frame->cprestore_size);
9881
9882       /* .mask MASK, OFFSET.  */
9883       fprintf (file, "\t.mask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
9884                frame->mask, frame->gp_save_offset);
9885
9886       /* .fmask MASK, OFFSET.  */
9887       fprintf (file, "\t.fmask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
9888                frame->fmask, frame->fp_save_offset);
9889     }
9890
9891   /* Handle the initialization of $gp for SVR4 PIC, if applicable.
9892      Also emit the ".set noreorder; .set nomacro" sequence for functions
9893      that need it.  */
9894   if (mips_must_initialize_gp_p ()
9895       && mips_current_loadgp_style () == LOADGP_OLDABI)
9896     {
9897       if (TARGET_MIPS16)
9898         {
9899           /* This is a fixed-form sequence.  The position of the
9900              first two instructions is important because of the
9901              way _gp_disp is defined.  */
9902           output_asm_insn ("li\t$2,%%hi(_gp_disp)", 0);
9903           output_asm_insn ("addiu\t$3,$pc,%%lo(_gp_disp)", 0);
9904           output_asm_insn ("sll\t$2,16", 0);
9905           output_asm_insn ("addu\t$2,$3", 0);
9906         }
9907       else
9908         {
9909           /* .cpload must be in a .set noreorder but not a
9910              .set nomacro block.  */
9911           mips_push_asm_switch (&mips_noreorder);
9912           output_asm_insn (".cpload\t%^", 0);
9913           if (!cfun->machine->all_noreorder_p)
9914             mips_pop_asm_switch (&mips_noreorder);
9915           else
9916             mips_push_asm_switch (&mips_nomacro);
9917         }
9918     }
9919   else if (cfun->machine->all_noreorder_p)
9920     {
9921       mips_push_asm_switch (&mips_noreorder);
9922       mips_push_asm_switch (&mips_nomacro);
9923     }
9924
9925   /* Tell the assembler which register we're using as the global
9926      pointer.  This is needed for thunks, since they can use either
9927      explicit relocs or assembler macros.  */
9928   mips_output_cplocal ();
9929 }
9930
9931 /* Implement TARGET_OUTPUT_FUNCTION_EPILOGUE.  */
9932
9933 static void
9934 mips_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
9935                                HOST_WIDE_INT size ATTRIBUTE_UNUSED)
9936 {
9937   const char *fnname;
9938
9939   /* Reinstate the normal $gp.  */
9940   SET_REGNO (pic_offset_table_rtx, GLOBAL_POINTER_REGNUM);
9941   mips_output_cplocal ();
9942
9943   if (cfun->machine->all_noreorder_p)
9944     {
9945       mips_pop_asm_switch (&mips_nomacro);
9946       mips_pop_asm_switch (&mips_noreorder);
9947     }
9948
9949   /* Get the function name the same way that toplev.c does before calling
9950      assemble_start_function.  This is needed so that the name used here
9951      exactly matches the name used in ASM_DECLARE_FUNCTION_NAME.  */
9952   fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
9953   mips_end_function_definition (fnname);
9954 }
9955 \f
9956 /* Save register REG to MEM.  Make the instruction frame-related.  */
9957
9958 static void
9959 mips_save_reg (rtx reg, rtx mem)
9960 {
9961   if (GET_MODE (reg) == DFmode && !TARGET_FLOAT64)
9962     {
9963       rtx x1, x2;
9964
9965       if (mips_split_64bit_move_p (mem, reg))
9966         mips_split_doubleword_move (mem, reg);
9967       else
9968         mips_emit_move (mem, reg);
9969
9970       x1 = mips_frame_set (mips_subword (mem, false),
9971                            mips_subword (reg, false));
9972       x2 = mips_frame_set (mips_subword (mem, true),
9973                            mips_subword (reg, true));
9974       mips_set_frame_expr (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, x1, x2)));
9975     }
9976   else
9977     mips_emit_save_slot_move (mem, reg, MIPS_PROLOGUE_TEMP (GET_MODE (reg)));
9978 }
9979
9980 /* The __gnu_local_gp symbol.  */
9981
9982 static GTY(()) rtx mips_gnu_local_gp;
9983
9984 /* If we're generating n32 or n64 abicalls, emit instructions
9985    to set up the global pointer.  */
9986
9987 static void
9988 mips_emit_loadgp (void)
9989 {
9990   rtx addr, offset, incoming_address, base, index, pic_reg;
9991
9992   pic_reg = TARGET_MIPS16 ? MIPS16_PIC_TEMP : pic_offset_table_rtx;
9993   switch (mips_current_loadgp_style ())
9994     {
9995     case LOADGP_ABSOLUTE:
9996       if (mips_gnu_local_gp == NULL)
9997         {
9998           mips_gnu_local_gp = gen_rtx_SYMBOL_REF (Pmode, "__gnu_local_gp");
9999           SYMBOL_REF_FLAGS (mips_gnu_local_gp) |= SYMBOL_FLAG_LOCAL;
10000         }
10001       emit_insn (Pmode == SImode
10002                  ? gen_loadgp_absolute_si (pic_reg, mips_gnu_local_gp)
10003                  : gen_loadgp_absolute_di (pic_reg, mips_gnu_local_gp));
10004       break;
10005
10006     case LOADGP_OLDABI:
10007       /* Added by mips_output_function_prologue.  */
10008       break;
10009
10010     case LOADGP_NEWABI:
10011       addr = XEXP (DECL_RTL (current_function_decl), 0);
10012       offset = mips_unspec_address (addr, SYMBOL_GOTOFF_LOADGP);
10013       incoming_address = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
10014       emit_insn (Pmode == SImode
10015                  ? gen_loadgp_newabi_si (pic_reg, offset, incoming_address)
10016                  : gen_loadgp_newabi_di (pic_reg, offset, incoming_address));
10017       break;
10018
10019     case LOADGP_RTP:
10020       base = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (VXWORKS_GOTT_BASE));
10021       index = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (VXWORKS_GOTT_INDEX));
10022       emit_insn (Pmode == SImode
10023                  ? gen_loadgp_rtp_si (pic_reg, base, index)
10024                  : gen_loadgp_rtp_di (pic_reg, base, index));
10025       break;
10026
10027     default:
10028       return;
10029     }
10030
10031   if (TARGET_MIPS16)
10032     emit_insn (gen_copygp_mips16 (pic_offset_table_rtx, pic_reg));
10033
10034   /* Emit a blockage if there are implicit uses of the GP register.
10035      This includes profiled functions, because FUNCTION_PROFILE uses
10036      a jal macro.  */
10037   if (!TARGET_EXPLICIT_RELOCS || crtl->profile)
10038     emit_insn (gen_loadgp_blockage ());
10039 }
10040
10041 /* A for_each_rtx callback.  Stop the search if *X is a kernel register.  */
10042
10043 static int
10044 mips_kernel_reg_p (rtx *x, void *data ATTRIBUTE_UNUSED)
10045 {
10046   return REG_P (*x) && KERNEL_REG_P (REGNO (*x));
10047 }
10048
10049 /* Expand the "prologue" pattern.  */
10050
10051 void
10052 mips_expand_prologue (void)
10053 {
10054   const struct mips_frame_info *frame;
10055   HOST_WIDE_INT size;
10056   unsigned int nargs;
10057   rtx insn;
10058
10059   if (cfun->machine->global_pointer != INVALID_REGNUM)
10060     {
10061       /* Check whether an insn uses pic_offset_table_rtx, either explicitly
10062          or implicitly.  If so, we can commit to using a global pointer
10063          straight away, otherwise we need to defer the decision.  */
10064       if (mips_cfun_has_inflexible_gp_ref_p ()
10065           || mips_cfun_has_flexible_gp_ref_p ())
10066         {
10067           cfun->machine->must_initialize_gp_p = true;
10068           cfun->machine->must_restore_gp_when_clobbered_p = true;
10069         }
10070
10071       SET_REGNO (pic_offset_table_rtx, cfun->machine->global_pointer);
10072     }
10073
10074   frame = &cfun->machine->frame;
10075   size = frame->total_size;
10076
10077   if (flag_stack_usage)
10078     current_function_static_stack_size = size;
10079
10080   /* Save the registers.  Allocate up to MIPS_MAX_FIRST_STACK_STEP
10081      bytes beforehand; this is enough to cover the register save area
10082      without going out of range.  */
10083   if (((frame->mask | frame->fmask | frame->acc_mask) != 0)
10084       || frame->num_cop0_regs > 0)
10085     {
10086       HOST_WIDE_INT step1;
10087
10088       step1 = MIN (size, MIPS_MAX_FIRST_STACK_STEP);
10089       if (GENERATE_MIPS16E_SAVE_RESTORE)
10090         {
10091           HOST_WIDE_INT offset;
10092           unsigned int mask, regno;
10093
10094           /* Try to merge argument stores into the save instruction.  */
10095           nargs = mips16e_collect_argument_saves ();
10096
10097           /* Build the save instruction.  */
10098           mask = frame->mask;
10099           insn = mips16e_build_save_restore (false, &mask, &offset,
10100                                              nargs, step1);
10101           RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
10102           size -= step1;
10103
10104           /* Check if we need to save other registers.  */
10105           for (regno = GP_REG_FIRST; regno < GP_REG_LAST; regno++)
10106             if (BITSET_P (mask, regno - GP_REG_FIRST))
10107               {
10108                 offset -= UNITS_PER_WORD;
10109                 mips_save_restore_reg (word_mode, regno,
10110                                        offset, mips_save_reg);
10111               }
10112         }
10113       else
10114         {
10115           if (cfun->machine->interrupt_handler_p)
10116             {
10117               HOST_WIDE_INT offset;
10118               rtx mem;
10119
10120               /* If this interrupt is using a shadow register set, we need to
10121                  get the stack pointer from the previous register set.  */
10122               if (cfun->machine->use_shadow_register_set_p)
10123                 emit_insn (gen_mips_rdpgpr (stack_pointer_rtx,
10124                                             stack_pointer_rtx));
10125
10126               if (!cfun->machine->keep_interrupts_masked_p)
10127                 {
10128                   /* Move from COP0 Cause to K0.  */
10129                   emit_insn (gen_cop0_move (gen_rtx_REG (SImode, K0_REG_NUM),
10130                                             gen_rtx_REG (SImode,
10131                                                          COP0_CAUSE_REG_NUM)));
10132                   /* Move from COP0 EPC to K1.  */
10133                   emit_insn (gen_cop0_move (gen_rtx_REG (SImode, K1_REG_NUM),
10134                                             gen_rtx_REG (SImode,
10135                                                          COP0_EPC_REG_NUM)));
10136                 }
10137
10138               /* Allocate the first part of the frame.  */
10139               insn = gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx,
10140                                     GEN_INT (-step1));
10141               RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
10142               size -= step1;
10143
10144               /* Start at the uppermost location for saving.  */
10145               offset = frame->cop0_sp_offset - size;
10146               if (!cfun->machine->keep_interrupts_masked_p)
10147                 {
10148                   /* Push EPC into its stack slot.  */
10149                   mem = gen_frame_mem (word_mode,
10150                                        plus_constant (stack_pointer_rtx,
10151                                                       offset));
10152                   mips_emit_move (mem, gen_rtx_REG (word_mode, K1_REG_NUM));
10153                   offset -= UNITS_PER_WORD;
10154                 }
10155
10156               /* Move from COP0 Status to K1.  */
10157               emit_insn (gen_cop0_move (gen_rtx_REG (SImode, K1_REG_NUM),
10158                                         gen_rtx_REG (SImode,
10159                                                      COP0_STATUS_REG_NUM)));
10160
10161               /* Right justify the RIPL in k0.  */
10162               if (!cfun->machine->keep_interrupts_masked_p)
10163                 emit_insn (gen_lshrsi3 (gen_rtx_REG (SImode, K0_REG_NUM),
10164                                         gen_rtx_REG (SImode, K0_REG_NUM),
10165                                         GEN_INT (CAUSE_IPL)));
10166
10167               /* Push Status into its stack slot.  */
10168               mem = gen_frame_mem (word_mode,
10169                                    plus_constant (stack_pointer_rtx, offset));
10170               mips_emit_move (mem, gen_rtx_REG (word_mode, K1_REG_NUM));
10171               offset -= UNITS_PER_WORD;
10172
10173               /* Insert the RIPL into our copy of SR (k1) as the new IPL.  */
10174               if (!cfun->machine->keep_interrupts_masked_p)
10175                 emit_insn (gen_insvsi (gen_rtx_REG (SImode, K1_REG_NUM),
10176                                        GEN_INT (6),
10177                                        GEN_INT (SR_IPL),
10178                                        gen_rtx_REG (SImode, K0_REG_NUM)));
10179
10180               if (!cfun->machine->keep_interrupts_masked_p)
10181                 /* Enable interrupts by clearing the KSU ERL and EXL bits.
10182                    IE is already the correct value, so we don't have to do
10183                    anything explicit.  */
10184                 emit_insn (gen_insvsi (gen_rtx_REG (SImode, K1_REG_NUM),
10185                                        GEN_INT (4),
10186                                        GEN_INT (SR_EXL),
10187                                        gen_rtx_REG (SImode, GP_REG_FIRST)));
10188               else
10189                 /* Disable interrupts by clearing the KSU, ERL, EXL,
10190                    and IE bits.  */
10191                 emit_insn (gen_insvsi (gen_rtx_REG (SImode, K1_REG_NUM),
10192                                        GEN_INT (5),
10193                                        GEN_INT (SR_IE),
10194                                        gen_rtx_REG (SImode, GP_REG_FIRST)));
10195             }
10196           else
10197             {
10198               insn = gen_add3_insn (stack_pointer_rtx,
10199                                     stack_pointer_rtx,
10200                                     GEN_INT (-step1));
10201               RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
10202               size -= step1;
10203             }
10204           mips_for_each_saved_acc (size, mips_save_reg);
10205           mips_for_each_saved_gpr_and_fpr (size, mips_save_reg);
10206         }
10207     }
10208
10209   /* Allocate the rest of the frame.  */
10210   if (size > 0)
10211     {
10212       if (SMALL_OPERAND (-size))
10213         RTX_FRAME_RELATED_P (emit_insn (gen_add3_insn (stack_pointer_rtx,
10214                                                        stack_pointer_rtx,
10215                                                        GEN_INT (-size)))) = 1;
10216       else
10217         {
10218           mips_emit_move (MIPS_PROLOGUE_TEMP (Pmode), GEN_INT (size));
10219           if (TARGET_MIPS16)
10220             {
10221               /* There are no instructions to add or subtract registers
10222                  from the stack pointer, so use the frame pointer as a
10223                  temporary.  We should always be using a frame pointer
10224                  in this case anyway.  */
10225               gcc_assert (frame_pointer_needed);
10226               mips_emit_move (hard_frame_pointer_rtx, stack_pointer_rtx);
10227               emit_insn (gen_sub3_insn (hard_frame_pointer_rtx,
10228                                         hard_frame_pointer_rtx,
10229                                         MIPS_PROLOGUE_TEMP (Pmode)));
10230               mips_emit_move (stack_pointer_rtx, hard_frame_pointer_rtx);
10231             }
10232           else
10233             emit_insn (gen_sub3_insn (stack_pointer_rtx,
10234                                       stack_pointer_rtx,
10235                                       MIPS_PROLOGUE_TEMP (Pmode)));
10236
10237           /* Describe the combined effect of the previous instructions.  */
10238           mips_set_frame_expr
10239             (gen_rtx_SET (VOIDmode, stack_pointer_rtx,
10240                           plus_constant (stack_pointer_rtx, -size)));
10241         }
10242     }
10243
10244   /* Set up the frame pointer, if we're using one.  */
10245   if (frame_pointer_needed)
10246     {
10247       HOST_WIDE_INT offset;
10248
10249       offset = frame->hard_frame_pointer_offset;
10250       if (offset == 0)
10251         {
10252           insn = mips_emit_move (hard_frame_pointer_rtx, stack_pointer_rtx);
10253           RTX_FRAME_RELATED_P (insn) = 1;
10254         }
10255       else if (SMALL_OPERAND (offset))
10256         {
10257           insn = gen_add3_insn (hard_frame_pointer_rtx,
10258                                 stack_pointer_rtx, GEN_INT (offset));
10259           RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
10260         }
10261       else
10262         {
10263           mips_emit_move (MIPS_PROLOGUE_TEMP (Pmode), GEN_INT (offset));
10264           mips_emit_move (hard_frame_pointer_rtx, stack_pointer_rtx);
10265           emit_insn (gen_add3_insn (hard_frame_pointer_rtx,
10266                                     hard_frame_pointer_rtx,
10267                                     MIPS_PROLOGUE_TEMP (Pmode)));
10268           mips_set_frame_expr
10269             (gen_rtx_SET (VOIDmode, hard_frame_pointer_rtx,
10270                           plus_constant (stack_pointer_rtx, offset)));
10271         }
10272     }
10273
10274   mips_emit_loadgp ();
10275
10276   /* Initialize the $gp save slot.  */
10277   if (mips_cfun_has_cprestore_slot_p ())
10278     {
10279       rtx base, mem, gp, temp;
10280       HOST_WIDE_INT offset;
10281
10282       mips_get_cprestore_base_and_offset (&base, &offset, false);
10283       mem = gen_frame_mem (Pmode, plus_constant (base, offset));
10284       gp = TARGET_MIPS16 ? MIPS16_PIC_TEMP : pic_offset_table_rtx;
10285       temp = (SMALL_OPERAND (offset)
10286               ? gen_rtx_SCRATCH (Pmode)
10287               : MIPS_PROLOGUE_TEMP (Pmode));
10288       emit_insn (gen_potential_cprestore (mem, GEN_INT (offset), gp, temp));
10289
10290       mips_get_cprestore_base_and_offset (&base, &offset, true);
10291       mem = gen_frame_mem (Pmode, plus_constant (base, offset));
10292       emit_insn (gen_use_cprestore (mem));
10293     }
10294
10295   /* We need to search back to the last use of K0 or K1.  */
10296   if (cfun->machine->interrupt_handler_p)
10297     {
10298       for (insn = get_last_insn (); insn != NULL_RTX; insn = PREV_INSN (insn))
10299         if (INSN_P (insn)
10300             && for_each_rtx (&PATTERN (insn), mips_kernel_reg_p, NULL))
10301           break;
10302       /* Emit a move from K1 to COP0 Status after insn.  */
10303       gcc_assert (insn != NULL_RTX);
10304       emit_insn_after (gen_cop0_move (gen_rtx_REG (SImode, COP0_STATUS_REG_NUM),
10305                                       gen_rtx_REG (SImode, K1_REG_NUM)),
10306                        insn);
10307     }
10308
10309   /* If we are profiling, make sure no instructions are scheduled before
10310      the call to mcount.  */
10311   if (crtl->profile)
10312     emit_insn (gen_blockage ());
10313 }
10314 \f
10315 /* Emit instructions to restore register REG from slot MEM.  */
10316
10317 static void
10318 mips_restore_reg (rtx reg, rtx mem)
10319 {
10320   /* There's no MIPS16 instruction to load $31 directly.  Load into
10321      $7 instead and adjust the return insn appropriately.  */
10322   if (TARGET_MIPS16 && REGNO (reg) == RETURN_ADDR_REGNUM)
10323     reg = gen_rtx_REG (GET_MODE (reg), GP_REG_FIRST + 7);
10324
10325   mips_emit_save_slot_move (reg, mem, MIPS_EPILOGUE_TEMP (GET_MODE (reg)));
10326 }
10327
10328 /* Emit any instructions needed before a return.  */
10329
10330 void
10331 mips_expand_before_return (void)
10332 {
10333   /* When using a call-clobbered gp, we start out with unified call
10334      insns that include instructions to restore the gp.  We then split
10335      these unified calls after reload.  These split calls explicitly
10336      clobber gp, so there is no need to define
10337      PIC_OFFSET_TABLE_REG_CALL_CLOBBERED.
10338
10339      For consistency, we should also insert an explicit clobber of $28
10340      before return insns, so that the post-reload optimizers know that
10341      the register is not live on exit.  */
10342   if (TARGET_CALL_CLOBBERED_GP)
10343     emit_clobber (pic_offset_table_rtx);
10344 }
10345
10346 /* Expand an "epilogue" or "sibcall_epilogue" pattern; SIBCALL_P
10347    says which.  */
10348
10349 void
10350 mips_expand_epilogue (bool sibcall_p)
10351 {
10352   const struct mips_frame_info *frame;
10353   HOST_WIDE_INT step1, step2;
10354   rtx base, target, insn;
10355
10356   if (!sibcall_p && mips_can_use_return_insn ())
10357     {
10358       emit_jump_insn (gen_return ());
10359       return;
10360     }
10361
10362   /* In MIPS16 mode, if the return value should go into a floating-point
10363      register, we need to call a helper routine to copy it over.  */
10364   if (mips16_cfun_returns_in_fpr_p ())
10365     mips16_copy_fpr_return_value ();
10366
10367   /* Split the frame into two.  STEP1 is the amount of stack we should
10368      deallocate before restoring the registers.  STEP2 is the amount we
10369      should deallocate afterwards.
10370
10371      Start off by assuming that no registers need to be restored.  */
10372   frame = &cfun->machine->frame;
10373   step1 = frame->total_size;
10374   step2 = 0;
10375
10376   /* Work out which register holds the frame address.  */
10377   if (!frame_pointer_needed)
10378     base = stack_pointer_rtx;
10379   else
10380     {
10381       base = hard_frame_pointer_rtx;
10382       step1 -= frame->hard_frame_pointer_offset;
10383     }
10384
10385   /* If we need to restore registers, deallocate as much stack as
10386      possible in the second step without going out of range.  */
10387   if ((frame->mask | frame->fmask | frame->acc_mask) != 0
10388       || frame->num_cop0_regs > 0)
10389     {
10390       step2 = MIN (step1, MIPS_MAX_FIRST_STACK_STEP);
10391       step1 -= step2;
10392     }
10393
10394   /* Set TARGET to BASE + STEP1.  */
10395   target = base;
10396   if (step1 > 0)
10397     {
10398       rtx adjust;
10399
10400       /* Get an rtx for STEP1 that we can add to BASE.  */
10401       adjust = GEN_INT (step1);
10402       if (!SMALL_OPERAND (step1))
10403         {
10404           mips_emit_move (MIPS_EPILOGUE_TEMP (Pmode), adjust);
10405           adjust = MIPS_EPILOGUE_TEMP (Pmode);
10406         }
10407
10408       /* Normal mode code can copy the result straight into $sp.  */
10409       if (!TARGET_MIPS16)
10410         target = stack_pointer_rtx;
10411
10412       emit_insn (gen_add3_insn (target, base, adjust));
10413     }
10414
10415   /* Copy TARGET into the stack pointer.  */
10416   if (target != stack_pointer_rtx)
10417     mips_emit_move (stack_pointer_rtx, target);
10418
10419   /* If we're using addressing macros, $gp is implicitly used by all
10420      SYMBOL_REFs.  We must emit a blockage insn before restoring $gp
10421      from the stack.  */
10422   if (TARGET_CALL_SAVED_GP && !TARGET_EXPLICIT_RELOCS)
10423     emit_insn (gen_blockage ());
10424
10425   if (GENERATE_MIPS16E_SAVE_RESTORE && frame->mask != 0)
10426     {
10427       unsigned int regno, mask;
10428       HOST_WIDE_INT offset;
10429       rtx restore;
10430
10431       /* Generate the restore instruction.  */
10432       mask = frame->mask;
10433       restore = mips16e_build_save_restore (true, &mask, &offset, 0, step2);
10434
10435       /* Restore any other registers manually.  */
10436       for (regno = GP_REG_FIRST; regno < GP_REG_LAST; regno++)
10437         if (BITSET_P (mask, regno - GP_REG_FIRST))
10438           {
10439             offset -= UNITS_PER_WORD;
10440             mips_save_restore_reg (word_mode, regno, offset, mips_restore_reg);
10441           }
10442
10443       /* Restore the remaining registers and deallocate the final bit
10444          of the frame.  */
10445       emit_insn (restore);
10446     }
10447   else
10448     {
10449       /* Restore the registers.  */
10450       mips_for_each_saved_acc (frame->total_size - step2, mips_restore_reg);
10451       mips_for_each_saved_gpr_and_fpr (frame->total_size - step2,
10452                                        mips_restore_reg);
10453
10454       if (cfun->machine->interrupt_handler_p)
10455         {
10456           HOST_WIDE_INT offset;
10457           rtx mem;
10458
10459           offset = frame->cop0_sp_offset - (frame->total_size - step2);
10460           if (!cfun->machine->keep_interrupts_masked_p)
10461             {
10462               /* Restore the original EPC.  */
10463               mem = gen_frame_mem (word_mode,
10464                                    plus_constant (stack_pointer_rtx, offset));
10465               mips_emit_move (gen_rtx_REG (word_mode, K0_REG_NUM), mem);
10466               offset -= UNITS_PER_WORD;
10467
10468               /* Move to COP0 EPC.  */
10469               emit_insn (gen_cop0_move (gen_rtx_REG (SImode, COP0_EPC_REG_NUM),
10470                                         gen_rtx_REG (SImode, K0_REG_NUM)));
10471             }
10472
10473           /* Restore the original Status.  */
10474           mem = gen_frame_mem (word_mode,
10475                                plus_constant (stack_pointer_rtx, offset));
10476           mips_emit_move (gen_rtx_REG (word_mode, K0_REG_NUM), mem);
10477           offset -= UNITS_PER_WORD;
10478
10479           /* If we don't use shoadow register set, we need to update SP.  */
10480           if (!cfun->machine->use_shadow_register_set_p && step2 > 0)
10481             emit_insn (gen_add3_insn (stack_pointer_rtx,
10482                                       stack_pointer_rtx,
10483                                       GEN_INT (step2)));
10484
10485           /* Move to COP0 Status.  */
10486           emit_insn (gen_cop0_move (gen_rtx_REG (SImode, COP0_STATUS_REG_NUM),
10487                                     gen_rtx_REG (SImode, K0_REG_NUM)));
10488         }
10489       else
10490         {
10491           /* Deallocate the final bit of the frame.  */
10492           if (step2 > 0)
10493             emit_insn (gen_add3_insn (stack_pointer_rtx,
10494                                       stack_pointer_rtx,
10495                                       GEN_INT (step2)));
10496         }
10497     }
10498
10499   /* Add in the __builtin_eh_return stack adjustment.  We need to
10500      use a temporary in MIPS16 code.  */
10501   if (crtl->calls_eh_return)
10502     {
10503       if (TARGET_MIPS16)
10504         {
10505           mips_emit_move (MIPS_EPILOGUE_TEMP (Pmode), stack_pointer_rtx);
10506           emit_insn (gen_add3_insn (MIPS_EPILOGUE_TEMP (Pmode),
10507                                     MIPS_EPILOGUE_TEMP (Pmode),
10508                                     EH_RETURN_STACKADJ_RTX));
10509           mips_emit_move (stack_pointer_rtx, MIPS_EPILOGUE_TEMP (Pmode));
10510         }
10511       else
10512         emit_insn (gen_add3_insn (stack_pointer_rtx,
10513                                   stack_pointer_rtx,
10514                                   EH_RETURN_STACKADJ_RTX));
10515     }
10516
10517   if (!sibcall_p)
10518     {
10519       mips_expand_before_return ();
10520       if (cfun->machine->interrupt_handler_p)
10521         {
10522           /* Interrupt handlers generate eret or deret.  */
10523           if (cfun->machine->use_debug_exception_return_p)
10524             emit_jump_insn (gen_mips_deret ());
10525           else
10526             emit_jump_insn (gen_mips_eret ());
10527         }
10528       else
10529         {
10530           unsigned int regno;
10531
10532           /* When generating MIPS16 code, the normal
10533              mips_for_each_saved_gpr_and_fpr path will restore the return
10534              address into $7 rather than $31.  */
10535           if (TARGET_MIPS16
10536               && !GENERATE_MIPS16E_SAVE_RESTORE
10537               && BITSET_P (frame->mask, RETURN_ADDR_REGNUM))
10538             regno = GP_REG_FIRST + 7;
10539           else
10540             regno = RETURN_ADDR_REGNUM;
10541           emit_jump_insn (gen_return_internal (gen_rtx_REG (Pmode, regno)));
10542         }
10543     }
10544
10545   /* Search from the beginning to the first use of K0 or K1.  */
10546   if (cfun->machine->interrupt_handler_p
10547       && !cfun->machine->keep_interrupts_masked_p)
10548     {
10549       for (insn = get_insns (); insn != NULL_RTX; insn = NEXT_INSN (insn))
10550         if (INSN_P (insn)
10551             && for_each_rtx (&PATTERN(insn), mips_kernel_reg_p, NULL))
10552           break;
10553       gcc_assert (insn != NULL_RTX);
10554       /* Insert disable interrupts before the first use of K0 or K1.  */
10555       emit_insn_before (gen_mips_di (), insn);
10556       emit_insn_before (gen_mips_ehb (), insn);
10557     }
10558 }
10559 \f
10560 /* Return nonzero if this function is known to have a null epilogue.
10561    This allows the optimizer to omit jumps to jumps if no stack
10562    was created.  */
10563
10564 bool
10565 mips_can_use_return_insn (void)
10566 {
10567   /* Interrupt handlers need to go through the epilogue.  */
10568   if (cfun->machine->interrupt_handler_p)
10569     return false;
10570
10571   if (!reload_completed)
10572     return false;
10573
10574   if (crtl->profile)
10575     return false;
10576
10577   /* In MIPS16 mode, a function that returns a floating-point value
10578      needs to arrange to copy the return value into the floating-point
10579      registers.  */
10580   if (mips16_cfun_returns_in_fpr_p ())
10581     return false;
10582
10583   return cfun->machine->frame.total_size == 0;
10584 }
10585 \f
10586 /* Return true if register REGNO can store a value of mode MODE.
10587    The result of this function is cached in mips_hard_regno_mode_ok.  */
10588
10589 static bool
10590 mips_hard_regno_mode_ok_p (unsigned int regno, enum machine_mode mode)
10591 {
10592   unsigned int size;
10593   enum mode_class mclass;
10594
10595   if (mode == CCV2mode)
10596     return (ISA_HAS_8CC
10597             && ST_REG_P (regno)
10598             && (regno - ST_REG_FIRST) % 2 == 0);
10599
10600   if (mode == CCV4mode)
10601     return (ISA_HAS_8CC
10602             && ST_REG_P (regno)
10603             && (regno - ST_REG_FIRST) % 4 == 0);
10604
10605   if (mode == CCmode)
10606     {
10607       if (!ISA_HAS_8CC)
10608         return regno == FPSW_REGNUM;
10609
10610       return (ST_REG_P (regno)
10611               || GP_REG_P (regno)
10612               || FP_REG_P (regno));
10613     }
10614
10615   size = GET_MODE_SIZE (mode);
10616   mclass = GET_MODE_CLASS (mode);
10617
10618   if (GP_REG_P (regno))
10619     return ((regno - GP_REG_FIRST) & 1) == 0 || size <= UNITS_PER_WORD;
10620
10621   if (FP_REG_P (regno)
10622       && (((regno - FP_REG_FIRST) % MAX_FPRS_PER_FMT) == 0
10623           || (MIN_FPRS_PER_FMT == 1 && size <= UNITS_PER_FPREG)))
10624     {
10625       /* Allow TFmode for CCmode reloads.  */
10626       if (mode == TFmode && ISA_HAS_8CC)
10627         return true;
10628
10629       /* Allow 64-bit vector modes for Loongson-2E/2F.  */
10630       if (TARGET_LOONGSON_VECTORS
10631           && (mode == V2SImode
10632               || mode == V4HImode
10633               || mode == V8QImode
10634               || mode == DImode))
10635         return true;
10636
10637       if (mclass == MODE_FLOAT
10638           || mclass == MODE_COMPLEX_FLOAT
10639           || mclass == MODE_VECTOR_FLOAT)
10640         return size <= UNITS_PER_FPVALUE;
10641
10642       /* Allow integer modes that fit into a single register.  We need
10643          to put integers into FPRs when using instructions like CVT
10644          and TRUNC.  There's no point allowing sizes smaller than a word,
10645          because the FPU has no appropriate load/store instructions.  */
10646       if (mclass == MODE_INT)
10647         return size >= MIN_UNITS_PER_WORD && size <= UNITS_PER_FPREG;
10648     }
10649
10650   if (ACC_REG_P (regno)
10651       && (INTEGRAL_MODE_P (mode) || ALL_FIXED_POINT_MODE_P (mode)))
10652     {
10653       if (MD_REG_P (regno))
10654         {
10655           /* After a multiplication or division, clobbering HI makes
10656              the value of LO unpredictable, and vice versa.  This means
10657              that, for all interesting cases, HI and LO are effectively
10658              a single register.
10659
10660              We model this by requiring that any value that uses HI
10661              also uses LO.  */
10662           if (size <= UNITS_PER_WORD * 2)
10663             return regno == (size <= UNITS_PER_WORD ? LO_REGNUM : MD_REG_FIRST);
10664         }
10665       else
10666         {
10667           /* DSP accumulators do not have the same restrictions as
10668              HI and LO, so we can treat them as normal doubleword
10669              registers.  */
10670           if (size <= UNITS_PER_WORD)
10671             return true;
10672
10673           if (size <= UNITS_PER_WORD * 2
10674               && ((regno - DSP_ACC_REG_FIRST) & 1) == 0)
10675             return true;
10676         }
10677     }
10678
10679   if (ALL_COP_REG_P (regno))
10680     return mclass == MODE_INT && size <= UNITS_PER_WORD;
10681
10682   if (regno == GOT_VERSION_REGNUM)
10683     return mode == SImode;
10684
10685   return false;
10686 }
10687
10688 /* Implement HARD_REGNO_NREGS.  */
10689
10690 unsigned int
10691 mips_hard_regno_nregs (int regno, enum machine_mode mode)
10692 {
10693   if (ST_REG_P (regno))
10694     /* The size of FP status registers is always 4, because they only hold
10695        CCmode values, and CCmode is always considered to be 4 bytes wide.  */
10696     return (GET_MODE_SIZE (mode) + 3) / 4;
10697
10698   if (FP_REG_P (regno))
10699     return (GET_MODE_SIZE (mode) + UNITS_PER_FPREG - 1) / UNITS_PER_FPREG;
10700
10701   /* All other registers are word-sized.  */
10702   return (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
10703 }
10704
10705 /* Implement CLASS_MAX_NREGS, taking the maximum of the cases
10706    in mips_hard_regno_nregs.  */
10707
10708 int
10709 mips_class_max_nregs (enum reg_class rclass, enum machine_mode mode)
10710 {
10711   int size;
10712   HARD_REG_SET left;
10713
10714   size = 0x8000;
10715   COPY_HARD_REG_SET (left, reg_class_contents[(int) rclass]);
10716   if (hard_reg_set_intersect_p (left, reg_class_contents[(int) ST_REGS]))
10717     {
10718       size = MIN (size, 4);
10719       AND_COMPL_HARD_REG_SET (left, reg_class_contents[(int) ST_REGS]);
10720     }
10721   if (hard_reg_set_intersect_p (left, reg_class_contents[(int) FP_REGS]))
10722     {
10723       size = MIN (size, UNITS_PER_FPREG);
10724       AND_COMPL_HARD_REG_SET (left, reg_class_contents[(int) FP_REGS]);
10725     }
10726   if (!hard_reg_set_empty_p (left))
10727     size = MIN (size, UNITS_PER_WORD);
10728   return (GET_MODE_SIZE (mode) + size - 1) / size;
10729 }
10730
10731 /* Implement CANNOT_CHANGE_MODE_CLASS.  */
10732
10733 bool
10734 mips_cannot_change_mode_class (enum machine_mode from ATTRIBUTE_UNUSED,
10735                                enum machine_mode to ATTRIBUTE_UNUSED,
10736                                enum reg_class rclass)
10737 {
10738   /* There are several problems with changing the modes of values
10739      in floating-point registers:
10740
10741      - When a multi-word value is stored in paired floating-point
10742        registers, the first register always holds the low word.
10743        We therefore can't allow FPRs to change between single-word
10744        and multi-word modes on big-endian targets.
10745
10746      - GCC assumes that each word of a multiword register can be accessed
10747        individually using SUBREGs.  This is not true for floating-point
10748        registers if they are bigger than a word.
10749
10750      - Loading a 32-bit value into a 64-bit floating-point register
10751        will not sign-extend the value, despite what LOAD_EXTEND_OP says.
10752        We can't allow FPRs to change from SImode to to a wider mode on
10753        64-bit targets.
10754
10755      - If the FPU has already interpreted a value in one format, we must
10756        not ask it to treat the value as having a different format.
10757
10758      We therefore disallow all mode changes involving FPRs.  */
10759   return reg_classes_intersect_p (FP_REGS, rclass);
10760 }
10761
10762 /* Implement target hook small_register_classes_for_mode_p.  */
10763
10764 static bool
10765 mips_small_register_classes_for_mode_p (enum machine_mode mode
10766                                         ATTRIBUTE_UNUSED)
10767 {
10768   return TARGET_MIPS16;
10769 }
10770
10771 /* Return true if moves in mode MODE can use the FPU's mov.fmt instruction.  */
10772
10773 static bool
10774 mips_mode_ok_for_mov_fmt_p (enum machine_mode mode)
10775 {
10776   switch (mode)
10777     {
10778     case SFmode:
10779       return TARGET_HARD_FLOAT;
10780
10781     case DFmode:
10782       return TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT;
10783
10784     case V2SFmode:
10785       return TARGET_HARD_FLOAT && TARGET_PAIRED_SINGLE_FLOAT;
10786
10787     default:
10788       return false;
10789     }
10790 }
10791
10792 /* Implement MODES_TIEABLE_P.  */
10793
10794 bool
10795 mips_modes_tieable_p (enum machine_mode mode1, enum machine_mode mode2)
10796 {
10797   /* FPRs allow no mode punning, so it's not worth tying modes if we'd
10798      prefer to put one of them in FPRs.  */
10799   return (mode1 == mode2
10800           || (!mips_mode_ok_for_mov_fmt_p (mode1)
10801               && !mips_mode_ok_for_mov_fmt_p (mode2)));
10802 }
10803
10804 /* Implement PREFERRED_RELOAD_CLASS.  */
10805
10806 enum reg_class
10807 mips_preferred_reload_class (rtx x, enum reg_class rclass)
10808 {
10809   if (mips_dangerous_for_la25_p (x) && reg_class_subset_p (LEA_REGS, rclass))
10810     return LEA_REGS;
10811
10812   if (reg_class_subset_p (FP_REGS, rclass)
10813       && mips_mode_ok_for_mov_fmt_p (GET_MODE (x)))
10814     return FP_REGS;
10815
10816   if (reg_class_subset_p (GR_REGS, rclass))
10817     rclass = GR_REGS;
10818
10819   if (TARGET_MIPS16 && reg_class_subset_p (M16_REGS, rclass))
10820     rclass = M16_REGS;
10821
10822   return rclass;
10823 }
10824
10825 /* RCLASS is a class involved in a REGISTER_MOVE_COST calculation.
10826    Return a "canonical" class to represent it in later calculations.  */
10827
10828 static reg_class_t
10829 mips_canonicalize_move_class (reg_class_t rclass)
10830 {
10831   /* All moves involving accumulator registers have the same cost.  */
10832   if (reg_class_subset_p (rclass, ACC_REGS))
10833     rclass = ACC_REGS;
10834
10835   /* Likewise promote subclasses of general registers to the most
10836      interesting containing class.  */
10837   if (TARGET_MIPS16 && reg_class_subset_p (rclass, M16_REGS))
10838     rclass = M16_REGS;
10839   else if (reg_class_subset_p (rclass, GENERAL_REGS))
10840     rclass = GENERAL_REGS;
10841
10842   return rclass;
10843 }
10844
10845 /* Return the cost of moving a value of mode MODE from a register of
10846    class FROM to a GPR.  Return 0 for classes that are unions of other
10847    classes handled by this function.  */
10848
10849 static int
10850 mips_move_to_gpr_cost (enum machine_mode mode ATTRIBUTE_UNUSED,
10851                        reg_class_t from)
10852 {
10853   switch (from)
10854     {
10855     case GENERAL_REGS:
10856       /* A MIPS16 MOVE instruction, or a non-MIPS16 MOVE macro.  */
10857       return 2;
10858
10859     case ACC_REGS:
10860       /* MFLO and MFHI.  */
10861       return 6;
10862
10863     case FP_REGS:
10864       /* MFC1, etc.  */
10865       return 4;
10866
10867     case ST_REGS:
10868       /* LUI followed by MOVF.  */
10869       return 4;
10870
10871     case COP0_REGS:
10872     case COP2_REGS:
10873     case COP3_REGS:
10874       /* This choice of value is historical.  */
10875       return 5;
10876
10877     default:
10878       return 0;
10879     }
10880 }
10881
10882 /* Return the cost of moving a value of mode MODE from a GPR to a
10883    register of class TO.  Return 0 for classes that are unions of
10884    other classes handled by this function.  */
10885
10886 static int
10887 mips_move_from_gpr_cost (enum machine_mode mode, reg_class_t to)
10888 {
10889   switch (to)
10890     {
10891     case GENERAL_REGS:
10892       /* A MIPS16 MOVE instruction, or a non-MIPS16 MOVE macro.  */
10893       return 2;
10894
10895     case ACC_REGS:
10896       /* MTLO and MTHI.  */
10897       return 6;
10898
10899     case FP_REGS:
10900       /* MTC1, etc.  */
10901       return 4;
10902
10903     case ST_REGS:
10904       /* A secondary reload through an FPR scratch.  */
10905       return (mips_register_move_cost (mode, GENERAL_REGS, FP_REGS)
10906               + mips_register_move_cost (mode, FP_REGS, ST_REGS));
10907
10908     case COP0_REGS:
10909     case COP2_REGS:
10910     case COP3_REGS:
10911       /* This choice of value is historical.  */
10912       return 5;
10913
10914     default:
10915       return 0;
10916     }
10917 }
10918
10919 /* Implement TARGET_REGISTER_MOVE_COST.  Return 0 for classes that are the
10920    maximum of the move costs for subclasses; regclass will work out
10921    the maximum for us.  */
10922
10923 static int
10924 mips_register_move_cost (enum machine_mode mode,
10925                          reg_class_t from, reg_class_t to)
10926 {
10927   reg_class_t dregs;
10928   int cost1, cost2;
10929
10930   from = mips_canonicalize_move_class (from);
10931   to = mips_canonicalize_move_class (to);
10932
10933   /* Handle moves that can be done without using general-purpose registers.  */
10934   if (from == FP_REGS)
10935     {
10936       if (to == FP_REGS && mips_mode_ok_for_mov_fmt_p (mode))
10937         /* MOV.FMT.  */
10938         return 4;
10939       if (to == ST_REGS)
10940         /* The sequence generated by mips_expand_fcc_reload.  */
10941         return 8;
10942     }
10943
10944   /* Handle cases in which only one class deviates from the ideal.  */
10945   dregs = TARGET_MIPS16 ? M16_REGS : GENERAL_REGS;
10946   if (from == dregs)
10947     return mips_move_from_gpr_cost (mode, to);
10948   if (to == dregs)
10949     return mips_move_to_gpr_cost (mode, from);
10950
10951   /* Handles cases that require a GPR temporary.  */
10952   cost1 = mips_move_to_gpr_cost (mode, from);
10953   if (cost1 != 0)
10954     {
10955       cost2 = mips_move_from_gpr_cost (mode, to);
10956       if (cost2 != 0)
10957         return cost1 + cost2;
10958     }
10959
10960   return 0;
10961 }
10962
10963 /* Implement TARGET_MEMORY_MOVE_COST.  */
10964
10965 static int
10966 mips_memory_move_cost (enum machine_mode mode, reg_class_t rclass, bool in)
10967 {
10968   return (mips_cost->memory_latency
10969           + memory_move_secondary_cost (mode, rclass, in));
10970
10971
10972 /* Implement TARGET_IRA_COVER_CLASSES.  */
10973
10974 static const reg_class_t *
10975 mips_ira_cover_classes (void)
10976 {
10977   static const reg_class_t acc_classes[] = {
10978     GR_AND_ACC_REGS, FP_REGS, COP0_REGS, COP2_REGS, COP3_REGS,
10979     ST_REGS, LIM_REG_CLASSES
10980   };
10981   static const reg_class_t no_acc_classes[] = {
10982     GR_REGS, FP_REGS, COP0_REGS, COP2_REGS, COP3_REGS,
10983     ST_REGS, LIM_REG_CLASSES
10984   };
10985
10986   /* Don't allow the register allocators to use LO and HI in MIPS16 mode,
10987      which has no MTLO or MTHI instructions.  Also, using GR_AND_ACC_REGS
10988      as a cover class only works well when we keep per-register costs.
10989      Using it when not optimizing can cause us to think accumulators
10990      have the same cost as GPRs in cases where GPRs are actually much
10991      cheaper.  */
10992   return TARGET_MIPS16 || !optimize ? no_acc_classes : acc_classes;
10993 }
10994
10995 /* Return the register class required for a secondary register when
10996    copying between one of the registers in RCLASS and value X, which
10997    has mode MODE.  X is the source of the move if IN_P, otherwise it
10998    is the destination.  Return NO_REGS if no secondary register is
10999    needed.  */
11000
11001 enum reg_class
11002 mips_secondary_reload_class (enum reg_class rclass,
11003                              enum machine_mode mode, rtx x, bool in_p)
11004 {
11005   int regno;
11006
11007   /* If X is a constant that cannot be loaded into $25, it must be loaded
11008      into some other GPR.  No other register class allows a direct move.  */
11009   if (mips_dangerous_for_la25_p (x))
11010     return reg_class_subset_p (rclass, LEA_REGS) ? NO_REGS : LEA_REGS;
11011
11012   regno = true_regnum (x);
11013   if (TARGET_MIPS16)
11014     {
11015       /* In MIPS16 mode, every move must involve a member of M16_REGS.  */
11016       if (!reg_class_subset_p (rclass, M16_REGS) && !M16_REG_P (regno))
11017         return M16_REGS;
11018
11019       return NO_REGS;
11020     }
11021
11022   /* Copying from accumulator registers to anywhere other than a general
11023      register requires a temporary general register.  */
11024   if (reg_class_subset_p (rclass, ACC_REGS))
11025     return GP_REG_P (regno) ? NO_REGS : GR_REGS;
11026   if (ACC_REG_P (regno))
11027     return reg_class_subset_p (rclass, GR_REGS) ? NO_REGS : GR_REGS;
11028
11029   /* We can only copy a value to a condition code register from a
11030      floating-point register, and even then we require a scratch
11031      floating-point register.  We can only copy a value out of a
11032      condition-code register into a general register.  */
11033   if (reg_class_subset_p (rclass, ST_REGS))
11034     {
11035       if (in_p)
11036         return FP_REGS;
11037       return GP_REG_P (regno) ? NO_REGS : GR_REGS;
11038     }
11039   if (ST_REG_P (regno))
11040     {
11041       if (!in_p)
11042         return FP_REGS;
11043       return reg_class_subset_p (rclass, GR_REGS) ? NO_REGS : GR_REGS;
11044     }
11045
11046   if (reg_class_subset_p (rclass, FP_REGS))
11047     {
11048       if (MEM_P (x)
11049           && (GET_MODE_SIZE (mode) == 4 || GET_MODE_SIZE (mode) == 8))
11050         /* In this case we can use lwc1, swc1, ldc1 or sdc1.  We'll use
11051            pairs of lwc1s and swc1s if ldc1 and sdc1 are not supported.  */
11052         return NO_REGS;
11053
11054       if (GP_REG_P (regno) || x == CONST0_RTX (mode))
11055         /* In this case we can use mtc1, mfc1, dmtc1 or dmfc1.  */
11056         return NO_REGS;
11057
11058       if (CONSTANT_P (x) && !targetm.cannot_force_const_mem (x))
11059         /* We can force the constant to memory and use lwc1
11060            and ldc1.  As above, we will use pairs of lwc1s if
11061            ldc1 is not supported.  */
11062         return NO_REGS;
11063
11064       if (FP_REG_P (regno) && mips_mode_ok_for_mov_fmt_p (mode))
11065         /* In this case we can use mov.fmt.  */
11066         return NO_REGS;
11067
11068       /* Otherwise, we need to reload through an integer register.  */
11069       return GR_REGS;
11070     }
11071   if (FP_REG_P (regno))
11072     return reg_class_subset_p (rclass, GR_REGS) ? NO_REGS : GR_REGS;
11073
11074   return NO_REGS;
11075 }
11076
11077 /* Implement TARGET_MODE_REP_EXTENDED.  */
11078
11079 static int
11080 mips_mode_rep_extended (enum machine_mode mode, enum machine_mode mode_rep)
11081 {
11082   /* On 64-bit targets, SImode register values are sign-extended to DImode.  */
11083   if (TARGET_64BIT && mode == SImode && mode_rep == DImode)
11084     return SIGN_EXTEND;
11085
11086   return UNKNOWN;
11087 }
11088 \f
11089 /* Implement TARGET_VALID_POINTER_MODE.  */
11090
11091 static bool
11092 mips_valid_pointer_mode (enum machine_mode mode)
11093 {
11094   return mode == SImode || (TARGET_64BIT && mode == DImode);
11095 }
11096
11097 /* Implement TARGET_VECTOR_MODE_SUPPORTED_P.  */
11098
11099 static bool
11100 mips_vector_mode_supported_p (enum machine_mode mode)
11101 {
11102   switch (mode)
11103     {
11104     case V2SFmode:
11105       return TARGET_PAIRED_SINGLE_FLOAT;
11106
11107     case V2HImode:
11108     case V4QImode:
11109     case V2HQmode:
11110     case V2UHQmode:
11111     case V2HAmode:
11112     case V2UHAmode:
11113     case V4QQmode:
11114     case V4UQQmode:
11115       return TARGET_DSP;
11116
11117     case V2SImode:
11118     case V4HImode:
11119     case V8QImode:
11120       return TARGET_LOONGSON_VECTORS;
11121
11122     default:
11123       return false;
11124     }
11125 }
11126
11127 /* Implement TARGET_SCALAR_MODE_SUPPORTED_P.  */
11128
11129 static bool
11130 mips_scalar_mode_supported_p (enum machine_mode mode)
11131 {
11132   if (ALL_FIXED_POINT_MODE_P (mode)
11133       && GET_MODE_PRECISION (mode) <= 2 * BITS_PER_WORD)
11134     return true;
11135
11136   return default_scalar_mode_supported_p (mode);
11137 }
11138 \f
11139 /* Implement TARGET_VECTORIZE_PREFERRED_SIMD_MODE.  */
11140
11141 static enum machine_mode
11142 mips_preferred_simd_mode (enum machine_mode mode ATTRIBUTE_UNUSED)
11143 {
11144   if (TARGET_PAIRED_SINGLE_FLOAT
11145       && mode == SFmode)
11146     return V2SFmode;
11147   return word_mode;
11148 }
11149
11150 /* Implement TARGET_INIT_LIBFUNCS.  */
11151
11152 static void
11153 mips_init_libfuncs (void)
11154 {
11155   if (TARGET_FIX_VR4120)
11156     {
11157       /* Register the special divsi3 and modsi3 functions needed to work
11158          around VR4120 division errata.  */
11159       set_optab_libfunc (sdiv_optab, SImode, "__vr4120_divsi3");
11160       set_optab_libfunc (smod_optab, SImode, "__vr4120_modsi3");
11161     }
11162
11163   if (TARGET_MIPS16 && TARGET_HARD_FLOAT_ABI)
11164     {
11165       /* Register the MIPS16 -mhard-float stubs.  */
11166       set_optab_libfunc (add_optab, SFmode, "__mips16_addsf3");
11167       set_optab_libfunc (sub_optab, SFmode, "__mips16_subsf3");
11168       set_optab_libfunc (smul_optab, SFmode, "__mips16_mulsf3");
11169       set_optab_libfunc (sdiv_optab, SFmode, "__mips16_divsf3");
11170
11171       set_optab_libfunc (eq_optab, SFmode, "__mips16_eqsf2");
11172       set_optab_libfunc (ne_optab, SFmode, "__mips16_nesf2");
11173       set_optab_libfunc (gt_optab, SFmode, "__mips16_gtsf2");
11174       set_optab_libfunc (ge_optab, SFmode, "__mips16_gesf2");
11175       set_optab_libfunc (lt_optab, SFmode, "__mips16_ltsf2");
11176       set_optab_libfunc (le_optab, SFmode, "__mips16_lesf2");
11177       set_optab_libfunc (unord_optab, SFmode, "__mips16_unordsf2");
11178
11179       set_conv_libfunc (sfix_optab, SImode, SFmode, "__mips16_fix_truncsfsi");
11180       set_conv_libfunc (sfloat_optab, SFmode, SImode, "__mips16_floatsisf");
11181       set_conv_libfunc (ufloat_optab, SFmode, SImode, "__mips16_floatunsisf");
11182
11183       if (TARGET_DOUBLE_FLOAT)
11184         {
11185           set_optab_libfunc (add_optab, DFmode, "__mips16_adddf3");
11186           set_optab_libfunc (sub_optab, DFmode, "__mips16_subdf3");
11187           set_optab_libfunc (smul_optab, DFmode, "__mips16_muldf3");
11188           set_optab_libfunc (sdiv_optab, DFmode, "__mips16_divdf3");
11189
11190           set_optab_libfunc (eq_optab, DFmode, "__mips16_eqdf2");
11191           set_optab_libfunc (ne_optab, DFmode, "__mips16_nedf2");
11192           set_optab_libfunc (gt_optab, DFmode, "__mips16_gtdf2");
11193           set_optab_libfunc (ge_optab, DFmode, "__mips16_gedf2");
11194           set_optab_libfunc (lt_optab, DFmode, "__mips16_ltdf2");
11195           set_optab_libfunc (le_optab, DFmode, "__mips16_ledf2");
11196           set_optab_libfunc (unord_optab, DFmode, "__mips16_unorddf2");
11197
11198           set_conv_libfunc (sext_optab, DFmode, SFmode,
11199                             "__mips16_extendsfdf2");
11200           set_conv_libfunc (trunc_optab, SFmode, DFmode,
11201                             "__mips16_truncdfsf2");
11202           set_conv_libfunc (sfix_optab, SImode, DFmode,
11203                             "__mips16_fix_truncdfsi");
11204           set_conv_libfunc (sfloat_optab, DFmode, SImode,
11205                             "__mips16_floatsidf");
11206           set_conv_libfunc (ufloat_optab, DFmode, SImode,
11207                             "__mips16_floatunsidf");
11208         }
11209     }
11210
11211   /* The MIPS16 ISA does not have an encoding for "sync", so we rely
11212      on an external non-MIPS16 routine to implement __sync_synchronize.  */
11213   if (TARGET_MIPS16)
11214     synchronize_libfunc = init_one_libfunc ("__sync_synchronize");
11215 }
11216
11217 /* Build up a multi-insn sequence that loads label TARGET into $AT.  */
11218
11219 static void
11220 mips_process_load_label (rtx target)
11221 {
11222   rtx base, gp, intop;
11223   HOST_WIDE_INT offset;
11224
11225   mips_multi_start ();
11226   switch (mips_abi)
11227     {
11228     case ABI_N32:
11229       mips_multi_add_insn ("lw\t%@,%%got_page(%0)(%+)", target, 0);
11230       mips_multi_add_insn ("addiu\t%@,%@,%%got_ofst(%0)", target, 0);
11231       break;
11232
11233     case ABI_64:
11234       mips_multi_add_insn ("ld\t%@,%%got_page(%0)(%+)", target, 0);
11235       mips_multi_add_insn ("daddiu\t%@,%@,%%got_ofst(%0)", target, 0);
11236       break;
11237
11238     default:
11239       gp = pic_offset_table_rtx;
11240       if (mips_cfun_has_cprestore_slot_p ())
11241         {
11242           gp = gen_rtx_REG (Pmode, AT_REGNUM);
11243           mips_get_cprestore_base_and_offset (&base, &offset, true);
11244           if (!SMALL_OPERAND (offset))
11245             {
11246               intop = GEN_INT (CONST_HIGH_PART (offset));
11247               mips_multi_add_insn ("lui\t%0,%1", gp, intop, 0);
11248               mips_multi_add_insn ("addu\t%0,%0,%1", gp, base, 0);
11249
11250               base = gp;
11251               offset = CONST_LOW_PART (offset);
11252             }
11253           intop = GEN_INT (offset);
11254           if (ISA_HAS_LOAD_DELAY)
11255             mips_multi_add_insn ("lw\t%0,%1(%2)%#", gp, intop, base, 0);
11256           else
11257             mips_multi_add_insn ("lw\t%0,%1(%2)", gp, intop, base, 0);
11258         }
11259       if (ISA_HAS_LOAD_DELAY)
11260         mips_multi_add_insn ("lw\t%@,%%got(%0)(%1)%#", target, gp, 0);
11261       else
11262         mips_multi_add_insn ("lw\t%@,%%got(%0)(%1)", target, gp, 0);
11263       mips_multi_add_insn ("addiu\t%@,%@,%%lo(%0)", target, 0);
11264       break;
11265     }
11266 }
11267
11268 /* Return the number of instructions needed to load a label into $AT.  */
11269
11270 static unsigned int
11271 mips_load_label_num_insns (void)
11272 {
11273   if (cfun->machine->load_label_num_insns == 0)
11274     {
11275       mips_process_load_label (pc_rtx);
11276       cfun->machine->load_label_num_insns = mips_multi_num_insns;
11277     }
11278   return cfun->machine->load_label_num_insns;
11279 }
11280
11281 /* Emit an asm sequence to start a noat block and load the address
11282    of a label into $1.  */
11283
11284 void
11285 mips_output_load_label (rtx target)
11286 {
11287   mips_push_asm_switch (&mips_noat);
11288   if (TARGET_EXPLICIT_RELOCS)
11289     {
11290       mips_process_load_label (target);
11291       mips_multi_write ();
11292     }
11293   else
11294     {
11295       if (Pmode == DImode)
11296         output_asm_insn ("dla\t%@,%0", &target);
11297       else
11298         output_asm_insn ("la\t%@,%0", &target);
11299     }
11300 }
11301
11302 /* Return the length of INSN.  LENGTH is the initial length computed by
11303    attributes in the machine-description file.  */
11304
11305 int
11306 mips_adjust_insn_length (rtx insn, int length)
11307 {
11308   /* mips.md uses MAX_PIC_BRANCH_LENGTH as a placeholder for the length
11309      of a PIC long-branch sequence.  Substitute the correct value.  */
11310   if (length == MAX_PIC_BRANCH_LENGTH
11311       && INSN_CODE (insn) >= 0
11312       && get_attr_type (insn) == TYPE_BRANCH)
11313     {
11314       /* Add the branch-over instruction and its delay slot, if this
11315          is a conditional branch.  */
11316       length = simplejump_p (insn) ? 0 : 8;
11317
11318       /* Load the label into $AT and jump to it.  Ignore the delay
11319          slot of the jump.  */
11320       length += 4 * mips_load_label_num_insns() + 4;
11321     }
11322
11323   /* A unconditional jump has an unfilled delay slot if it is not part
11324      of a sequence.  A conditional jump normally has a delay slot, but
11325      does not on MIPS16.  */
11326   if (CALL_P (insn) || (TARGET_MIPS16 ? simplejump_p (insn) : JUMP_P (insn)))
11327     length += 4;
11328
11329   /* See how many nops might be needed to avoid hardware hazards.  */
11330   if (!cfun->machine->ignore_hazard_length_p && INSN_CODE (insn) >= 0)
11331     switch (get_attr_hazard (insn))
11332       {
11333       case HAZARD_NONE:
11334         break;
11335
11336       case HAZARD_DELAY:
11337         length += 4;
11338         break;
11339
11340       case HAZARD_HILO:
11341         length += 8;
11342         break;
11343       }
11344
11345   /* In order to make it easier to share MIPS16 and non-MIPS16 patterns,
11346      the .md file length attributes are 4-based for both modes.
11347      Adjust the MIPS16 ones here.  */
11348   if (TARGET_MIPS16)
11349     length /= 2;
11350
11351   return length;
11352 }
11353
11354 /* Return the assembly code for INSN, which has the operands given by
11355    OPERANDS, and which branches to OPERANDS[0] if some condition is true.
11356    BRANCH_IF_TRUE is the asm template that should be used if OPERANDS[0]
11357    is in range of a direct branch.  BRANCH_IF_FALSE is an inverted
11358    version of BRANCH_IF_TRUE.  */
11359
11360 const char *
11361 mips_output_conditional_branch (rtx insn, rtx *operands,
11362                                 const char *branch_if_true,
11363                                 const char *branch_if_false)
11364 {
11365   unsigned int length;
11366   rtx taken, not_taken;
11367
11368   gcc_assert (LABEL_P (operands[0]));
11369
11370   length = get_attr_length (insn);
11371   if (length <= 8)
11372     {
11373       /* Just a simple conditional branch.  */
11374       mips_branch_likely = (final_sequence && INSN_ANNULLED_BRANCH_P (insn));
11375       return branch_if_true;
11376     }
11377
11378   /* Generate a reversed branch around a direct jump.  This fallback does
11379      not use branch-likely instructions.  */
11380   mips_branch_likely = false;
11381   not_taken = gen_label_rtx ();
11382   taken = operands[0];
11383
11384   /* Generate the reversed branch to NOT_TAKEN.  */
11385   operands[0] = not_taken;
11386   output_asm_insn (branch_if_false, operands);
11387
11388   /* If INSN has a delay slot, we must provide delay slots for both the
11389      branch to NOT_TAKEN and the conditional jump.  We must also ensure
11390      that INSN's delay slot is executed in the appropriate cases.  */
11391   if (final_sequence)
11392     {
11393       /* This first delay slot will always be executed, so use INSN's
11394          delay slot if is not annulled.  */
11395       if (!INSN_ANNULLED_BRANCH_P (insn))
11396         {
11397           final_scan_insn (XVECEXP (final_sequence, 0, 1),
11398                            asm_out_file, optimize, 1, NULL);
11399           INSN_DELETED_P (XVECEXP (final_sequence, 0, 1)) = 1;
11400         }
11401       else
11402         output_asm_insn ("nop", 0);
11403       fprintf (asm_out_file, "\n");
11404     }
11405
11406   /* Output the unconditional branch to TAKEN.  */
11407   if (TARGET_ABSOLUTE_JUMPS)
11408     output_asm_insn (MIPS_ABSOLUTE_JUMP ("j\t%0%/"), &taken);
11409   else
11410     {
11411       mips_output_load_label (taken);
11412       output_asm_insn ("jr\t%@%]%/", 0);
11413     }
11414
11415   /* Now deal with its delay slot; see above.  */
11416   if (final_sequence)
11417     {
11418       /* This delay slot will only be executed if the branch is taken.
11419          Use INSN's delay slot if is annulled.  */
11420       if (INSN_ANNULLED_BRANCH_P (insn))
11421         {
11422           final_scan_insn (XVECEXP (final_sequence, 0, 1),
11423                            asm_out_file, optimize, 1, NULL);
11424           INSN_DELETED_P (XVECEXP (final_sequence, 0, 1)) = 1;
11425         }
11426       else
11427         output_asm_insn ("nop", 0);
11428       fprintf (asm_out_file, "\n");
11429     }
11430
11431   /* Output NOT_TAKEN.  */
11432   targetm.asm_out.internal_label (asm_out_file, "L",
11433                                   CODE_LABEL_NUMBER (not_taken));
11434   return "";
11435 }
11436
11437 /* Return the assembly code for INSN, which branches to OPERANDS[0]
11438    if some ordering condition is true.  The condition is given by
11439    OPERANDS[1] if !INVERTED_P, otherwise it is the inverse of
11440    OPERANDS[1].  OPERANDS[2] is the comparison's first operand;
11441    its second is always zero.  */
11442
11443 const char *
11444 mips_output_order_conditional_branch (rtx insn, rtx *operands, bool inverted_p)
11445 {
11446   const char *branch[2];
11447
11448   /* Make BRANCH[1] branch to OPERANDS[0] when the condition is true.
11449      Make BRANCH[0] branch on the inverse condition.  */
11450   switch (GET_CODE (operands[1]))
11451     {
11452       /* These cases are equivalent to comparisons against zero.  */
11453     case LEU:
11454       inverted_p = !inverted_p;
11455       /* Fall through.  */
11456     case GTU:
11457       branch[!inverted_p] = MIPS_BRANCH ("bne", "%2,%.,%0");
11458       branch[inverted_p] = MIPS_BRANCH ("beq", "%2,%.,%0");
11459       break;
11460
11461       /* These cases are always true or always false.  */
11462     case LTU:
11463       inverted_p = !inverted_p;
11464       /* Fall through.  */
11465     case GEU:
11466       branch[!inverted_p] = MIPS_BRANCH ("beq", "%.,%.,%0");
11467       branch[inverted_p] = MIPS_BRANCH ("bne", "%.,%.,%0");
11468       break;
11469
11470     default:
11471       branch[!inverted_p] = MIPS_BRANCH ("b%C1z", "%2,%0");
11472       branch[inverted_p] = MIPS_BRANCH ("b%N1z", "%2,%0");
11473       break;
11474     }
11475   return mips_output_conditional_branch (insn, operands, branch[1], branch[0]);
11476 }
11477 \f
11478 /* Start a block of code that needs access to the LL, SC and SYNC
11479    instructions.  */
11480
11481 static void
11482 mips_start_ll_sc_sync_block (void)
11483 {
11484   if (!ISA_HAS_LL_SC)
11485     {
11486       output_asm_insn (".set\tpush", 0);
11487       output_asm_insn (".set\tmips2", 0);
11488     }
11489 }
11490
11491 /* End a block started by mips_start_ll_sc_sync_block.  */
11492
11493 static void
11494 mips_end_ll_sc_sync_block (void)
11495 {
11496   if (!ISA_HAS_LL_SC)
11497     output_asm_insn (".set\tpop", 0);
11498 }
11499
11500 /* Output and/or return the asm template for a sync instruction.  */
11501
11502 const char *
11503 mips_output_sync (void)
11504 {
11505   mips_start_ll_sc_sync_block ();
11506   output_asm_insn ("sync", 0);
11507   mips_end_ll_sc_sync_block ();
11508   return "";
11509 }
11510
11511 /* Return the asm template associated with sync_insn1 value TYPE.
11512    IS_64BIT_P is true if we want a 64-bit rather than 32-bit operation.  */
11513
11514 static const char *
11515 mips_sync_insn1_template (enum attr_sync_insn1 type, bool is_64bit_p)
11516 {
11517   switch (type)
11518     {
11519     case SYNC_INSN1_MOVE:
11520       return "move\t%0,%z2";
11521     case SYNC_INSN1_LI:
11522       return "li\t%0,%2";
11523     case SYNC_INSN1_ADDU:
11524       return is_64bit_p ? "daddu\t%0,%1,%z2" : "addu\t%0,%1,%z2";
11525     case SYNC_INSN1_ADDIU:
11526       return is_64bit_p ? "daddiu\t%0,%1,%2" : "addiu\t%0,%1,%2";
11527     case SYNC_INSN1_SUBU:
11528       return is_64bit_p ? "dsubu\t%0,%1,%z2" : "subu\t%0,%1,%z2";
11529     case SYNC_INSN1_AND:
11530       return "and\t%0,%1,%z2";
11531     case SYNC_INSN1_ANDI:
11532       return "andi\t%0,%1,%2";
11533     case SYNC_INSN1_OR:
11534       return "or\t%0,%1,%z2";
11535     case SYNC_INSN1_ORI:
11536       return "ori\t%0,%1,%2";
11537     case SYNC_INSN1_XOR:
11538       return "xor\t%0,%1,%z2";
11539     case SYNC_INSN1_XORI:
11540       return "xori\t%0,%1,%2";
11541     }
11542   gcc_unreachable ();
11543 }
11544
11545 /* Return the asm template associated with sync_insn2 value TYPE.  */
11546
11547 static const char *
11548 mips_sync_insn2_template (enum attr_sync_insn2 type)
11549 {
11550   switch (type)
11551     {
11552     case SYNC_INSN2_NOP:
11553       gcc_unreachable ();
11554     case SYNC_INSN2_AND:
11555       return "and\t%0,%1,%z2";
11556     case SYNC_INSN2_XOR:
11557       return "xor\t%0,%1,%z2";
11558     case SYNC_INSN2_NOT:
11559       return "nor\t%0,%1,%.";
11560     }
11561   gcc_unreachable ();
11562 }
11563
11564 /* OPERANDS are the operands to a sync loop instruction and INDEX is
11565    the value of the one of the sync_* attributes.  Return the operand
11566    referred to by the attribute, or DEFAULT_VALUE if the insn doesn't
11567    have the associated attribute.  */
11568
11569 static rtx
11570 mips_get_sync_operand (rtx *operands, int index, rtx default_value)
11571 {
11572   if (index > 0)
11573     default_value = operands[index - 1];
11574   return default_value;
11575 }
11576
11577 /* INSN is a sync loop with operands OPERANDS.  Build up a multi-insn
11578    sequence for it.  */
11579
11580 static void
11581 mips_process_sync_loop (rtx insn, rtx *operands)
11582 {
11583   rtx at, mem, oldval, newval, inclusive_mask, exclusive_mask;
11584   rtx required_oldval, insn1_op2, tmp1, tmp2, tmp3;
11585   unsigned int tmp3_insn;
11586   enum attr_sync_insn1 insn1;
11587   enum attr_sync_insn2 insn2;
11588   bool is_64bit_p;
11589
11590   /* Read an operand from the sync_WHAT attribute and store it in
11591      variable WHAT.  DEFAULT is the default value if no attribute
11592      is specified.  */
11593 #define READ_OPERAND(WHAT, DEFAULT) \
11594   WHAT = mips_get_sync_operand (operands, (int) get_attr_sync_##WHAT (insn), \
11595                                 DEFAULT)
11596
11597   /* Read the memory.  */
11598   READ_OPERAND (mem, 0);
11599   gcc_assert (mem);
11600   is_64bit_p = (GET_MODE_BITSIZE (GET_MODE (mem)) == 64);
11601
11602   /* Read the other attributes.  */
11603   at = gen_rtx_REG (GET_MODE (mem), AT_REGNUM);
11604   READ_OPERAND (oldval, at);
11605   READ_OPERAND (newval, at);
11606   READ_OPERAND (inclusive_mask, 0);
11607   READ_OPERAND (exclusive_mask, 0);
11608   READ_OPERAND (required_oldval, 0);
11609   READ_OPERAND (insn1_op2, 0);
11610   insn1 = get_attr_sync_insn1 (insn);
11611   insn2 = get_attr_sync_insn2 (insn);
11612
11613   mips_multi_start ();
11614
11615   /* Output the release side of the memory barrier.  */
11616   if (get_attr_sync_release_barrier (insn) == SYNC_RELEASE_BARRIER_YES)
11617     {
11618       if (required_oldval == 0 && TARGET_OCTEON)
11619         {
11620           /* Octeon doesn't reorder reads, so a full barrier can be
11621              created by using SYNCW to order writes combined with the
11622              write from the following SC.  When the SC successfully
11623              completes, we know that all preceding writes are also
11624              committed to the coherent memory system.  It is possible
11625              for a single SYNCW to fail, but a pair of them will never
11626              fail, so we use two.  */
11627           mips_multi_add_insn ("syncw", NULL);
11628           mips_multi_add_insn ("syncw", NULL);
11629         }
11630       else
11631         mips_multi_add_insn ("sync", NULL);
11632     }
11633
11634   /* Output the branch-back label.  */
11635   mips_multi_add_label ("1:");
11636
11637   /* OLDVAL = *MEM.  */
11638   mips_multi_add_insn (is_64bit_p ? "lld\t%0,%1" : "ll\t%0,%1",
11639                        oldval, mem, NULL);
11640
11641   /* if ((OLDVAL & INCLUSIVE_MASK) != REQUIRED_OLDVAL) goto 2.  */
11642   if (required_oldval)
11643     {
11644       if (inclusive_mask == 0)
11645         tmp1 = oldval;
11646       else
11647         {
11648           gcc_assert (oldval != at);
11649           mips_multi_add_insn ("and\t%0,%1,%2",
11650                                at, oldval, inclusive_mask, NULL);
11651           tmp1 = at;
11652         }
11653       mips_multi_add_insn ("bne\t%0,%z1,2f", tmp1, required_oldval, NULL);
11654     }
11655
11656   /* $TMP1 = OLDVAL & EXCLUSIVE_MASK.  */
11657   if (exclusive_mask == 0)
11658     tmp1 = const0_rtx;
11659   else
11660     {
11661       gcc_assert (oldval != at);
11662       mips_multi_add_insn ("and\t%0,%1,%z2",
11663                            at, oldval, exclusive_mask, NULL);
11664       tmp1 = at;
11665     }
11666
11667   /* $TMP2 = INSN1 (OLDVAL, INSN1_OP2).
11668
11669      We can ignore moves if $TMP4 != INSN1_OP2, since we'll still emit
11670      at least one instruction in that case.  */
11671   if (insn1 == SYNC_INSN1_MOVE
11672       && (tmp1 != const0_rtx || insn2 != SYNC_INSN2_NOP))
11673     tmp2 = insn1_op2;
11674   else
11675     {
11676       mips_multi_add_insn (mips_sync_insn1_template (insn1, is_64bit_p),
11677                            newval, oldval, insn1_op2, NULL);
11678       tmp2 = newval;
11679     }
11680
11681   /* $TMP3 = INSN2 ($TMP2, INCLUSIVE_MASK).  */
11682   if (insn2 == SYNC_INSN2_NOP)
11683     tmp3 = tmp2;
11684   else
11685     {
11686       mips_multi_add_insn (mips_sync_insn2_template (insn2),
11687                            newval, tmp2, inclusive_mask, NULL);
11688       tmp3 = newval;
11689     }
11690   tmp3_insn = mips_multi_last_index ();
11691
11692   /* $AT = $TMP1 | $TMP3.  */
11693   if (tmp1 == const0_rtx || tmp3 == const0_rtx)
11694     {
11695       mips_multi_set_operand (tmp3_insn, 0, at);
11696       tmp3 = at;
11697     }
11698   else
11699     {
11700       gcc_assert (tmp1 != tmp3);
11701       mips_multi_add_insn ("or\t%0,%1,%2", at, tmp1, tmp3, NULL);
11702     }
11703
11704   /* if (!commit (*MEM = $AT)) goto 1.
11705
11706      This will sometimes be a delayed branch; see the write code below
11707      for details.  */
11708   mips_multi_add_insn (is_64bit_p ? "scd\t%0,%1" : "sc\t%0,%1", at, mem, NULL);
11709   mips_multi_add_insn ("beq%?\t%0,%.,1b", at, NULL);
11710
11711   /* if (INSN1 != MOVE && INSN1 != LI) NEWVAL = $TMP3 [delay slot].  */
11712   if (insn1 != SYNC_INSN1_MOVE && insn1 != SYNC_INSN1_LI && tmp3 != newval)
11713     {
11714       mips_multi_copy_insn (tmp3_insn);
11715       mips_multi_set_operand (mips_multi_last_index (), 0, newval);
11716     }
11717   else
11718     mips_multi_add_insn ("nop", NULL);
11719
11720   /* Output the acquire side of the memory barrier.  */
11721   if (TARGET_SYNC_AFTER_SC)
11722     mips_multi_add_insn ("sync", NULL);
11723
11724   /* Output the exit label, if needed.  */
11725   if (required_oldval)
11726     mips_multi_add_label ("2:");
11727
11728 #undef READ_OPERAND
11729 }
11730
11731 /* Output and/or return the asm template for sync loop INSN, which has
11732    the operands given by OPERANDS.  */
11733
11734 const char *
11735 mips_output_sync_loop (rtx insn, rtx *operands)
11736 {
11737   mips_process_sync_loop (insn, operands);
11738
11739   /* Use branch-likely instructions to work around the LL/SC R10000
11740      errata.  */
11741   mips_branch_likely = TARGET_FIX_R10000;
11742
11743   mips_push_asm_switch (&mips_noreorder);
11744   mips_push_asm_switch (&mips_nomacro);
11745   mips_push_asm_switch (&mips_noat);
11746   mips_start_ll_sc_sync_block ();
11747
11748   mips_multi_write ();
11749
11750   mips_end_ll_sc_sync_block ();
11751   mips_pop_asm_switch (&mips_noat);
11752   mips_pop_asm_switch (&mips_nomacro);
11753   mips_pop_asm_switch (&mips_noreorder);
11754
11755   return "";
11756 }
11757
11758 /* Return the number of individual instructions in sync loop INSN,
11759    which has the operands given by OPERANDS.  */
11760
11761 unsigned int
11762 mips_sync_loop_insns (rtx insn, rtx *operands)
11763 {
11764   mips_process_sync_loop (insn, operands);
11765   return mips_multi_num_insns;
11766 }
11767 \f
11768 /* Return the assembly code for DIV or DDIV instruction DIVISION, which has
11769    the operands given by OPERANDS.  Add in a divide-by-zero check if needed.
11770
11771    When working around R4000 and R4400 errata, we need to make sure that
11772    the division is not immediately followed by a shift[1][2].  We also
11773    need to stop the division from being put into a branch delay slot[3].
11774    The easiest way to avoid both problems is to add a nop after the
11775    division.  When a divide-by-zero check is needed, this nop can be
11776    used to fill the branch delay slot.
11777
11778    [1] If a double-word or a variable shift executes immediately
11779        after starting an integer division, the shift may give an
11780        incorrect result.  See quotations of errata #16 and #28 from
11781        "MIPS R4000PC/SC Errata, Processor Revision 2.2 and 3.0"
11782        in mips.md for details.
11783
11784    [2] A similar bug to [1] exists for all revisions of the
11785        R4000 and the R4400 when run in an MC configuration.
11786        From "MIPS R4000MC Errata, Processor Revision 2.2 and 3.0":
11787
11788        "19. In this following sequence:
11789
11790                     ddiv                (or ddivu or div or divu)
11791                     dsll32              (or dsrl32, dsra32)
11792
11793             if an MPT stall occurs, while the divide is slipping the cpu
11794             pipeline, then the following double shift would end up with an
11795             incorrect result.
11796
11797             Workaround: The compiler needs to avoid generating any
11798             sequence with divide followed by extended double shift."
11799
11800        This erratum is also present in "MIPS R4400MC Errata, Processor
11801        Revision 1.0" and "MIPS R4400MC Errata, Processor Revision 2.0
11802        & 3.0" as errata #10 and #4, respectively.
11803
11804    [3] From "MIPS R4000PC/SC Errata, Processor Revision 2.2 and 3.0"
11805        (also valid for MIPS R4000MC processors):
11806
11807        "52. R4000SC: This bug does not apply for the R4000PC.
11808
11809             There are two flavors of this bug:
11810
11811             1) If the instruction just after divide takes an RF exception
11812                (tlb-refill, tlb-invalid) and gets an instruction cache
11813                miss (both primary and secondary) and the line which is
11814                currently in secondary cache at this index had the first
11815                data word, where the bits 5..2 are set, then R4000 would
11816                get a wrong result for the div.
11817
11818             ##1
11819                     nop
11820                     div r8, r9
11821                     -------------------         # end-of page. -tlb-refill
11822                     nop
11823             ##2
11824                     nop
11825                     div r8, r9
11826                     -------------------         # end-of page. -tlb-invalid
11827                     nop
11828
11829             2) If the divide is in the taken branch delay slot, where the
11830                target takes RF exception and gets an I-cache miss for the
11831                exception vector or where I-cache miss occurs for the
11832                target address, under the above mentioned scenarios, the
11833                div would get wrong results.
11834
11835             ##1
11836                     j   r2              # to next page mapped or unmapped
11837                     div r8,r9           # this bug would be there as long
11838                                         # as there is an ICache miss and
11839                     nop                 # the "data pattern" is present
11840
11841             ##2
11842                     beq r0, r0, NextPage        # to Next page
11843                     div r8,r9
11844                     nop
11845
11846             This bug is present for div, divu, ddiv, and ddivu
11847             instructions.
11848
11849             Workaround: For item 1), OS could make sure that the next page
11850             after the divide instruction is also mapped.  For item 2), the
11851             compiler could make sure that the divide instruction is not in
11852             the branch delay slot."
11853
11854        These processors have PRId values of 0x00004220 and 0x00004300 for
11855        the R4000 and 0x00004400, 0x00004500 and 0x00004600 for the R4400.  */
11856
11857 const char *
11858 mips_output_division (const char *division, rtx *operands)
11859 {
11860   const char *s;
11861
11862   s = division;
11863   if (TARGET_FIX_R4000 || TARGET_FIX_R4400)
11864     {
11865       output_asm_insn (s, operands);
11866       s = "nop";
11867     }
11868   if (TARGET_CHECK_ZERO_DIV)
11869     {
11870       if (TARGET_MIPS16)
11871         {
11872           output_asm_insn (s, operands);
11873           s = "bnez\t%2,1f\n\tbreak\t7\n1:";
11874         }
11875       else if (GENERATE_DIVIDE_TRAPS)
11876         {
11877           /* Avoid long replay penalty on load miss by putting the trap before
11878              the divide.  */
11879           if (TUNE_74K)
11880             output_asm_insn ("teq\t%2,%.,7", operands);
11881           else
11882             {
11883               output_asm_insn (s, operands);
11884               s = "teq\t%2,%.,7";
11885             }
11886         }
11887       else
11888         {
11889           output_asm_insn ("%(bne\t%2,%.,1f", operands);
11890           output_asm_insn (s, operands);
11891           s = "break\t7%)\n1:";
11892         }
11893     }
11894   return s;
11895 }
11896 \f
11897 /* Return true if IN_INSN is a multiply-add or multiply-subtract
11898    instruction and if OUT_INSN assigns to the accumulator operand.  */
11899
11900 bool
11901 mips_linked_madd_p (rtx out_insn, rtx in_insn)
11902 {
11903   rtx x;
11904
11905   x = single_set (in_insn);
11906   if (x == 0)
11907     return false;
11908
11909   x = SET_SRC (x);
11910
11911   if (GET_CODE (x) == PLUS
11912       && GET_CODE (XEXP (x, 0)) == MULT
11913       && reg_set_p (XEXP (x, 1), out_insn))
11914     return true;
11915
11916   if (GET_CODE (x) == MINUS
11917       && GET_CODE (XEXP (x, 1)) == MULT
11918       && reg_set_p (XEXP (x, 0), out_insn))
11919     return true;
11920
11921   return false;
11922 }
11923
11924 /* True if the dependency between OUT_INSN and IN_INSN is on the store
11925    data rather than the address.  We need this because the cprestore
11926    pattern is type "store", but is defined using an UNSPEC_VOLATILE,
11927    which causes the default routine to abort.  We just return false
11928    for that case.  */
11929
11930 bool
11931 mips_store_data_bypass_p (rtx out_insn, rtx in_insn)
11932 {
11933   if (GET_CODE (PATTERN (in_insn)) == UNSPEC_VOLATILE)
11934     return false;
11935
11936   return !store_data_bypass_p (out_insn, in_insn);
11937 }
11938 \f
11939
11940 /* Variables and flags used in scheduler hooks when tuning for
11941    Loongson 2E/2F.  */
11942 static struct
11943 {
11944   /* Variables to support Loongson 2E/2F round-robin [F]ALU1/2 dispatch
11945      strategy.  */
11946
11947   /* If true, then next ALU1/2 instruction will go to ALU1.  */
11948   bool alu1_turn_p;
11949
11950   /* If true, then next FALU1/2 unstruction will go to FALU1.  */
11951   bool falu1_turn_p;
11952
11953   /* Codes to query if [f]alu{1,2}_core units are subscribed or not.  */
11954   int alu1_core_unit_code;
11955   int alu2_core_unit_code;
11956   int falu1_core_unit_code;
11957   int falu2_core_unit_code;
11958
11959   /* True if current cycle has a multi instruction.
11960      This flag is used in mips_ls2_dfa_post_advance_cycle.  */
11961   bool cycle_has_multi_p;
11962
11963   /* Instructions to subscribe ls2_[f]alu{1,2}_turn_enabled units.
11964      These are used in mips_ls2_dfa_post_advance_cycle to initialize
11965      DFA state.
11966      E.g., when alu1_turn_enabled_insn is issued it makes next ALU1/2
11967      instruction to go ALU1.  */
11968   rtx alu1_turn_enabled_insn;
11969   rtx alu2_turn_enabled_insn;
11970   rtx falu1_turn_enabled_insn;
11971   rtx falu2_turn_enabled_insn;
11972 } mips_ls2;
11973
11974 /* Implement TARGET_SCHED_ADJUST_COST.  We assume that anti and output
11975    dependencies have no cost, except on the 20Kc where output-dependence
11976    is treated like input-dependence.  */
11977
11978 static int
11979 mips_adjust_cost (rtx insn ATTRIBUTE_UNUSED, rtx link,
11980                   rtx dep ATTRIBUTE_UNUSED, int cost)
11981 {
11982   if (REG_NOTE_KIND (link) == REG_DEP_OUTPUT
11983       && TUNE_20KC)
11984     return cost;
11985   if (REG_NOTE_KIND (link) != 0)
11986     return 0;
11987   return cost;
11988 }
11989
11990 /* Return the number of instructions that can be issued per cycle.  */
11991
11992 static int
11993 mips_issue_rate (void)
11994 {
11995   switch (mips_tune)
11996     {
11997     case PROCESSOR_74KC:
11998     case PROCESSOR_74KF2_1:
11999     case PROCESSOR_74KF1_1:
12000     case PROCESSOR_74KF3_2:
12001       /* The 74k is not strictly quad-issue cpu, but can be seen as one
12002          by the scheduler.  It can issue 1 ALU, 1 AGEN and 2 FPU insns,
12003          but in reality only a maximum of 3 insns can be issued as
12004          floating-point loads and stores also require a slot in the
12005          AGEN pipe.  */
12006     case PROCESSOR_R10000:
12007       /* All R10K Processors are quad-issue (being the first MIPS
12008          processors to support this feature). */
12009       return 4;
12010
12011     case PROCESSOR_20KC:
12012     case PROCESSOR_R4130:
12013     case PROCESSOR_R5400:
12014     case PROCESSOR_R5500:
12015     case PROCESSOR_R7000:
12016     case PROCESSOR_R9000:
12017     case PROCESSOR_OCTEON:
12018       return 2;
12019
12020     case PROCESSOR_SB1:
12021     case PROCESSOR_SB1A:
12022       /* This is actually 4, but we get better performance if we claim 3.
12023          This is partly because of unwanted speculative code motion with the
12024          larger number, and partly because in most common cases we can't
12025          reach the theoretical max of 4.  */
12026       return 3;
12027
12028     case PROCESSOR_LOONGSON_2E:
12029     case PROCESSOR_LOONGSON_2F:
12030     case PROCESSOR_LOONGSON_3A:
12031       return 4;
12032
12033     default:
12034       return 1;
12035     }
12036 }
12037
12038 /* Implement TARGET_SCHED_INIT_DFA_POST_CYCLE_INSN hook for Loongson2.  */
12039
12040 static void
12041 mips_ls2_init_dfa_post_cycle_insn (void)
12042 {
12043   start_sequence ();
12044   emit_insn (gen_ls2_alu1_turn_enabled_insn ());
12045   mips_ls2.alu1_turn_enabled_insn = get_insns ();
12046   end_sequence ();
12047
12048   start_sequence ();
12049   emit_insn (gen_ls2_alu2_turn_enabled_insn ());
12050   mips_ls2.alu2_turn_enabled_insn = get_insns ();
12051   end_sequence ();
12052
12053   start_sequence ();
12054   emit_insn (gen_ls2_falu1_turn_enabled_insn ());
12055   mips_ls2.falu1_turn_enabled_insn = get_insns ();
12056   end_sequence ();
12057
12058   start_sequence ();
12059   emit_insn (gen_ls2_falu2_turn_enabled_insn ());
12060   mips_ls2.falu2_turn_enabled_insn = get_insns ();
12061   end_sequence ();
12062
12063   mips_ls2.alu1_core_unit_code = get_cpu_unit_code ("ls2_alu1_core");
12064   mips_ls2.alu2_core_unit_code = get_cpu_unit_code ("ls2_alu2_core");
12065   mips_ls2.falu1_core_unit_code = get_cpu_unit_code ("ls2_falu1_core");
12066   mips_ls2.falu2_core_unit_code = get_cpu_unit_code ("ls2_falu2_core");
12067 }
12068
12069 /* Implement TARGET_SCHED_INIT_DFA_POST_CYCLE_INSN hook.
12070    Init data used in mips_dfa_post_advance_cycle.  */
12071
12072 static void
12073 mips_init_dfa_post_cycle_insn (void)
12074 {
12075   if (TUNE_LOONGSON_2EF)
12076     mips_ls2_init_dfa_post_cycle_insn ();
12077 }
12078
12079 /* Initialize STATE when scheduling for Loongson 2E/2F.
12080    Support round-robin dispatch scheme by enabling only one of
12081    ALU1/ALU2 and one of FALU1/FALU2 units for ALU1/2 and FALU1/2 instructions
12082    respectively.  */
12083
12084 static void
12085 mips_ls2_dfa_post_advance_cycle (state_t state)
12086 {
12087   if (cpu_unit_reservation_p (state, mips_ls2.alu1_core_unit_code))
12088     {
12089       /* Though there are no non-pipelined ALU1 insns,
12090          we can get an instruction of type 'multi' before reload.  */
12091       gcc_assert (mips_ls2.cycle_has_multi_p);
12092       mips_ls2.alu1_turn_p = false;
12093     }
12094
12095   mips_ls2.cycle_has_multi_p = false;
12096
12097   if (cpu_unit_reservation_p (state, mips_ls2.alu2_core_unit_code))
12098     /* We have a non-pipelined alu instruction in the core,
12099        adjust round-robin counter.  */
12100     mips_ls2.alu1_turn_p = true;
12101
12102   if (mips_ls2.alu1_turn_p)
12103     {
12104       if (state_transition (state, mips_ls2.alu1_turn_enabled_insn) >= 0)
12105         gcc_unreachable ();
12106     }
12107   else
12108     {
12109       if (state_transition (state, mips_ls2.alu2_turn_enabled_insn) >= 0)
12110         gcc_unreachable ();
12111     }
12112
12113   if (cpu_unit_reservation_p (state, mips_ls2.falu1_core_unit_code))
12114     {
12115       /* There are no non-pipelined FALU1 insns.  */
12116       gcc_unreachable ();
12117       mips_ls2.falu1_turn_p = false;
12118     }
12119
12120   if (cpu_unit_reservation_p (state, mips_ls2.falu2_core_unit_code))
12121     /* We have a non-pipelined falu instruction in the core,
12122        adjust round-robin counter.  */
12123     mips_ls2.falu1_turn_p = true;
12124
12125   if (mips_ls2.falu1_turn_p)
12126     {
12127       if (state_transition (state, mips_ls2.falu1_turn_enabled_insn) >= 0)
12128         gcc_unreachable ();
12129     }
12130   else
12131     {
12132       if (state_transition (state, mips_ls2.falu2_turn_enabled_insn) >= 0)
12133         gcc_unreachable ();
12134     }
12135 }
12136
12137 /* Implement TARGET_SCHED_DFA_POST_ADVANCE_CYCLE.
12138    This hook is being called at the start of each cycle.  */
12139
12140 static void
12141 mips_dfa_post_advance_cycle (void)
12142 {
12143   if (TUNE_LOONGSON_2EF)
12144     mips_ls2_dfa_post_advance_cycle (curr_state);
12145 }
12146
12147 /* Implement TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD.  This should
12148    be as wide as the scheduling freedom in the DFA.  */
12149
12150 static int
12151 mips_multipass_dfa_lookahead (void)
12152 {
12153   /* Can schedule up to 4 of the 6 function units in any one cycle.  */
12154   if (TUNE_SB1)
12155     return 4;
12156
12157   if (TUNE_LOONGSON_2EF)
12158     return 4;
12159
12160   if (TUNE_OCTEON)
12161     return 2;
12162
12163   return 0;
12164 }
12165 \f
12166 /* Remove the instruction at index LOWER from ready queue READY and
12167    reinsert it in front of the instruction at index HIGHER.  LOWER must
12168    be <= HIGHER.  */
12169
12170 static void
12171 mips_promote_ready (rtx *ready, int lower, int higher)
12172 {
12173   rtx new_head;
12174   int i;
12175
12176   new_head = ready[lower];
12177   for (i = lower; i < higher; i++)
12178     ready[i] = ready[i + 1];
12179   ready[i] = new_head;
12180 }
12181
12182 /* If the priority of the instruction at POS2 in the ready queue READY
12183    is within LIMIT units of that of the instruction at POS1, swap the
12184    instructions if POS2 is not already less than POS1.  */
12185
12186 static void
12187 mips_maybe_swap_ready (rtx *ready, int pos1, int pos2, int limit)
12188 {
12189   if (pos1 < pos2
12190       && INSN_PRIORITY (ready[pos1]) + limit >= INSN_PRIORITY (ready[pos2]))
12191     {
12192       rtx temp;
12193
12194       temp = ready[pos1];
12195       ready[pos1] = ready[pos2];
12196       ready[pos2] = temp;
12197     }
12198 }
12199 \f
12200 /* Used by TUNE_MACC_CHAINS to record the last scheduled instruction
12201    that may clobber hi or lo.  */
12202 static rtx mips_macc_chains_last_hilo;
12203
12204 /* A TUNE_MACC_CHAINS helper function.  Record that instruction INSN has
12205    been scheduled, updating mips_macc_chains_last_hilo appropriately.  */
12206
12207 static void
12208 mips_macc_chains_record (rtx insn)
12209 {
12210   if (get_attr_may_clobber_hilo (insn))
12211     mips_macc_chains_last_hilo = insn;
12212 }
12213
12214 /* A TUNE_MACC_CHAINS helper function.  Search ready queue READY, which
12215    has NREADY elements, looking for a multiply-add or multiply-subtract
12216    instruction that is cumulative with mips_macc_chains_last_hilo.
12217    If there is one, promote it ahead of anything else that might
12218    clobber hi or lo.  */
12219
12220 static void
12221 mips_macc_chains_reorder (rtx *ready, int nready)
12222 {
12223   int i, j;
12224
12225   if (mips_macc_chains_last_hilo != 0)
12226     for (i = nready - 1; i >= 0; i--)
12227       if (mips_linked_madd_p (mips_macc_chains_last_hilo, ready[i]))
12228         {
12229           for (j = nready - 1; j > i; j--)
12230             if (recog_memoized (ready[j]) >= 0
12231                 && get_attr_may_clobber_hilo (ready[j]))
12232               {
12233                 mips_promote_ready (ready, i, j);
12234                 break;
12235               }
12236           break;
12237         }
12238 }
12239 \f
12240 /* The last instruction to be scheduled.  */
12241 static rtx vr4130_last_insn;
12242
12243 /* A note_stores callback used by vr4130_true_reg_dependence_p.  DATA
12244    points to an rtx that is initially an instruction.  Nullify the rtx
12245    if the instruction uses the value of register X.  */
12246
12247 static void
12248 vr4130_true_reg_dependence_p_1 (rtx x, const_rtx pat ATTRIBUTE_UNUSED,
12249                                 void *data)
12250 {
12251   rtx *insn_ptr;
12252
12253   insn_ptr = (rtx *) data;
12254   if (REG_P (x)
12255       && *insn_ptr != 0
12256       && reg_referenced_p (x, PATTERN (*insn_ptr)))
12257     *insn_ptr = 0;
12258 }
12259
12260 /* Return true if there is true register dependence between vr4130_last_insn
12261    and INSN.  */
12262
12263 static bool
12264 vr4130_true_reg_dependence_p (rtx insn)
12265 {
12266   note_stores (PATTERN (vr4130_last_insn),
12267                vr4130_true_reg_dependence_p_1, &insn);
12268   return insn == 0;
12269 }
12270
12271 /* A TUNE_MIPS4130 helper function.  Given that INSN1 is at the head of
12272    the ready queue and that INSN2 is the instruction after it, return
12273    true if it is worth promoting INSN2 ahead of INSN1.  Look for cases
12274    in which INSN1 and INSN2 can probably issue in parallel, but for
12275    which (INSN2, INSN1) should be less sensitive to instruction
12276    alignment than (INSN1, INSN2).  See 4130.md for more details.  */
12277
12278 static bool
12279 vr4130_swap_insns_p (rtx insn1, rtx insn2)
12280 {
12281   sd_iterator_def sd_it;
12282   dep_t dep;
12283
12284   /* Check for the following case:
12285
12286      1) there is some other instruction X with an anti dependence on INSN1;
12287      2) X has a higher priority than INSN2; and
12288      3) X is an arithmetic instruction (and thus has no unit restrictions).
12289
12290      If INSN1 is the last instruction blocking X, it would better to
12291      choose (INSN1, X) over (INSN2, INSN1).  */
12292   FOR_EACH_DEP (insn1, SD_LIST_FORW, sd_it, dep)
12293     if (DEP_TYPE (dep) == REG_DEP_ANTI
12294         && INSN_PRIORITY (DEP_CON (dep)) > INSN_PRIORITY (insn2)
12295         && recog_memoized (DEP_CON (dep)) >= 0
12296         && get_attr_vr4130_class (DEP_CON (dep)) == VR4130_CLASS_ALU)
12297       return false;
12298
12299   if (vr4130_last_insn != 0
12300       && recog_memoized (insn1) >= 0
12301       && recog_memoized (insn2) >= 0)
12302     {
12303       /* See whether INSN1 and INSN2 use different execution units,
12304          or if they are both ALU-type instructions.  If so, they can
12305          probably execute in parallel.  */
12306       enum attr_vr4130_class class1 = get_attr_vr4130_class (insn1);
12307       enum attr_vr4130_class class2 = get_attr_vr4130_class (insn2);
12308       if (class1 != class2 || class1 == VR4130_CLASS_ALU)
12309         {
12310           /* If only one of the instructions has a dependence on
12311              vr4130_last_insn, prefer to schedule the other one first.  */
12312           bool dep1_p = vr4130_true_reg_dependence_p (insn1);
12313           bool dep2_p = vr4130_true_reg_dependence_p (insn2);
12314           if (dep1_p != dep2_p)
12315             return dep1_p;
12316
12317           /* Prefer to schedule INSN2 ahead of INSN1 if vr4130_last_insn
12318              is not an ALU-type instruction and if INSN1 uses the same
12319              execution unit.  (Note that if this condition holds, we already
12320              know that INSN2 uses a different execution unit.)  */
12321           if (class1 != VR4130_CLASS_ALU
12322               && recog_memoized (vr4130_last_insn) >= 0
12323               && class1 == get_attr_vr4130_class (vr4130_last_insn))
12324             return true;
12325         }
12326     }
12327   return false;
12328 }
12329
12330 /* A TUNE_MIPS4130 helper function.  (READY, NREADY) describes a ready
12331    queue with at least two instructions.  Swap the first two if
12332    vr4130_swap_insns_p says that it could be worthwhile.  */
12333
12334 static void
12335 vr4130_reorder (rtx *ready, int nready)
12336 {
12337   if (vr4130_swap_insns_p (ready[nready - 1], ready[nready - 2]))
12338     mips_promote_ready (ready, nready - 2, nready - 1);
12339 }
12340 \f
12341 /* Record whether last 74k AGEN instruction was a load or store.  */
12342 static enum attr_type mips_last_74k_agen_insn = TYPE_UNKNOWN;
12343
12344 /* Initialize mips_last_74k_agen_insn from INSN.  A null argument
12345    resets to TYPE_UNKNOWN state.  */
12346
12347 static void
12348 mips_74k_agen_init (rtx insn)
12349 {
12350   if (!insn || CALL_P (insn) || JUMP_P (insn))
12351     mips_last_74k_agen_insn = TYPE_UNKNOWN;
12352   else
12353     {
12354       enum attr_type type = get_attr_type (insn);
12355       if (type == TYPE_LOAD || type == TYPE_STORE)
12356         mips_last_74k_agen_insn = type;
12357     }
12358 }
12359
12360 /* A TUNE_74K helper function.  The 74K AGEN pipeline likes multiple
12361    loads to be grouped together, and multiple stores to be grouped
12362    together.  Swap things around in the ready queue to make this happen.  */
12363
12364 static void
12365 mips_74k_agen_reorder (rtx *ready, int nready)
12366 {
12367   int i;
12368   int store_pos, load_pos;
12369
12370   store_pos = -1;
12371   load_pos = -1;
12372
12373   for (i = nready - 1; i >= 0; i--)
12374     {
12375       rtx insn = ready[i];
12376       if (USEFUL_INSN_P (insn))
12377         switch (get_attr_type (insn))
12378           {
12379           case TYPE_STORE:
12380             if (store_pos == -1)
12381               store_pos = i;
12382             break;
12383
12384           case TYPE_LOAD:
12385             if (load_pos == -1)
12386               load_pos = i;
12387             break;
12388
12389           default:
12390             break;
12391           }
12392     }
12393
12394   if (load_pos == -1 || store_pos == -1)
12395     return;
12396
12397   switch (mips_last_74k_agen_insn)
12398     {
12399     case TYPE_UNKNOWN:
12400       /* Prefer to schedule loads since they have a higher latency.  */
12401     case TYPE_LOAD:
12402       /* Swap loads to the front of the queue.  */
12403       mips_maybe_swap_ready (ready, load_pos, store_pos, 4);
12404       break;
12405     case TYPE_STORE:
12406       /* Swap stores to the front of the queue.  */
12407       mips_maybe_swap_ready (ready, store_pos, load_pos, 4);
12408       break;
12409     default:
12410       break;
12411     }
12412 }
12413 \f
12414 /* Implement TARGET_SCHED_INIT.  */
12415
12416 static void
12417 mips_sched_init (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
12418                  int max_ready ATTRIBUTE_UNUSED)
12419 {
12420   mips_macc_chains_last_hilo = 0;
12421   vr4130_last_insn = 0;
12422   mips_74k_agen_init (NULL_RTX);
12423
12424   /* When scheduling for Loongson2, branch instructions go to ALU1,
12425      therefore basic block is most likely to start with round-robin counter
12426      pointed to ALU2.  */
12427   mips_ls2.alu1_turn_p = false;
12428   mips_ls2.falu1_turn_p = true;
12429 }
12430
12431 /* Subroutine used by TARGET_SCHED_REORDER and TARGET_SCHED_REORDER2.  */
12432
12433 static void
12434 mips_sched_reorder_1 (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
12435                       rtx *ready, int *nreadyp, int cycle ATTRIBUTE_UNUSED)
12436 {
12437   if (!reload_completed
12438       && TUNE_MACC_CHAINS
12439       && *nreadyp > 0)
12440     mips_macc_chains_reorder (ready, *nreadyp);
12441
12442   if (reload_completed
12443       && TUNE_MIPS4130
12444       && !TARGET_VR4130_ALIGN
12445       && *nreadyp > 1)
12446     vr4130_reorder (ready, *nreadyp);
12447
12448   if (TUNE_74K)
12449     mips_74k_agen_reorder (ready, *nreadyp);
12450 }
12451
12452 /* Implement TARGET_SCHED_REORDER.  */
12453
12454 static int
12455 mips_sched_reorder (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
12456                     rtx *ready, int *nreadyp, int cycle ATTRIBUTE_UNUSED)
12457 {
12458   mips_sched_reorder_1 (file, verbose, ready, nreadyp, cycle);
12459   return mips_issue_rate ();
12460 }
12461
12462 /* Implement TARGET_SCHED_REORDER2.  */
12463
12464 static int
12465 mips_sched_reorder2 (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
12466                      rtx *ready, int *nreadyp, int cycle ATTRIBUTE_UNUSED)
12467 {
12468   mips_sched_reorder_1 (file, verbose, ready, nreadyp, cycle);
12469   return cached_can_issue_more;
12470 }
12471
12472 /* Update round-robin counters for ALU1/2 and FALU1/2.  */
12473
12474 static void
12475 mips_ls2_variable_issue (rtx insn)
12476 {
12477   if (mips_ls2.alu1_turn_p)
12478     {
12479       if (cpu_unit_reservation_p (curr_state, mips_ls2.alu1_core_unit_code))
12480         mips_ls2.alu1_turn_p = false;
12481     }
12482   else
12483     {
12484       if (cpu_unit_reservation_p (curr_state, mips_ls2.alu2_core_unit_code))
12485         mips_ls2.alu1_turn_p = true;
12486     }
12487
12488   if (mips_ls2.falu1_turn_p)
12489     {
12490       if (cpu_unit_reservation_p (curr_state, mips_ls2.falu1_core_unit_code))
12491         mips_ls2.falu1_turn_p = false;
12492     }
12493   else
12494     {
12495       if (cpu_unit_reservation_p (curr_state, mips_ls2.falu2_core_unit_code))
12496         mips_ls2.falu1_turn_p = true;
12497     }
12498
12499   if (recog_memoized (insn) >= 0)
12500     mips_ls2.cycle_has_multi_p |= (get_attr_type (insn) == TYPE_MULTI);
12501 }
12502
12503 /* Implement TARGET_SCHED_VARIABLE_ISSUE.  */
12504
12505 static int
12506 mips_variable_issue (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
12507                      rtx insn, int more)
12508 {
12509   /* Ignore USEs and CLOBBERs; don't count them against the issue rate.  */
12510   if (USEFUL_INSN_P (insn))
12511     {
12512       if (get_attr_type (insn) != TYPE_GHOST)
12513         more--;
12514       if (!reload_completed && TUNE_MACC_CHAINS)
12515         mips_macc_chains_record (insn);
12516       vr4130_last_insn = insn;
12517       if (TUNE_74K)
12518         mips_74k_agen_init (insn);
12519       else if (TUNE_LOONGSON_2EF)
12520         mips_ls2_variable_issue (insn);
12521     }
12522
12523   /* Instructions of type 'multi' should all be split before
12524      the second scheduling pass.  */
12525   gcc_assert (!reload_completed
12526               || recog_memoized (insn) < 0
12527               || get_attr_type (insn) != TYPE_MULTI);
12528
12529   cached_can_issue_more = more;
12530   return more;
12531 }
12532 \f
12533 /* Given that we have an rtx of the form (prefetch ... WRITE LOCALITY),
12534    return the first operand of the associated PREF or PREFX insn.  */
12535
12536 rtx
12537 mips_prefetch_cookie (rtx write, rtx locality)
12538 {
12539   /* store_streamed / load_streamed.  */
12540   if (INTVAL (locality) <= 0)
12541     return GEN_INT (INTVAL (write) + 4);
12542
12543   /* store / load.  */
12544   if (INTVAL (locality) <= 2)
12545     return write;
12546
12547   /* store_retained / load_retained.  */
12548   return GEN_INT (INTVAL (write) + 6);
12549 }
12550 \f
12551 /* Flags that indicate when a built-in function is available.
12552
12553    BUILTIN_AVAIL_NON_MIPS16
12554         The function is available on the current target, but only
12555         in non-MIPS16 mode.  */
12556 #define BUILTIN_AVAIL_NON_MIPS16 1
12557
12558 /* Declare an availability predicate for built-in functions that
12559    require non-MIPS16 mode and also require COND to be true.
12560    NAME is the main part of the predicate's name.  */
12561 #define AVAIL_NON_MIPS16(NAME, COND)                                    \
12562  static unsigned int                                                    \
12563  mips_builtin_avail_##NAME (void)                                       \
12564  {                                                                      \
12565    return (COND) ? BUILTIN_AVAIL_NON_MIPS16 : 0;                        \
12566  }
12567
12568 /* This structure describes a single built-in function.  */
12569 struct mips_builtin_description {
12570   /* The code of the main .md file instruction.  See mips_builtin_type
12571      for more information.  */
12572   enum insn_code icode;
12573
12574   /* The floating-point comparison code to use with ICODE, if any.  */
12575   enum mips_fp_condition cond;
12576
12577   /* The name of the built-in function.  */
12578   const char *name;
12579
12580   /* Specifies how the function should be expanded.  */
12581   enum mips_builtin_type builtin_type;
12582
12583   /* The function's prototype.  */
12584   enum mips_function_type function_type;
12585
12586   /* Whether the function is available.  */
12587   unsigned int (*avail) (void);
12588 };
12589
12590 AVAIL_NON_MIPS16 (paired_single, TARGET_PAIRED_SINGLE_FLOAT)
12591 AVAIL_NON_MIPS16 (sb1_paired_single, TARGET_SB1 && TARGET_PAIRED_SINGLE_FLOAT)
12592 AVAIL_NON_MIPS16 (mips3d, TARGET_MIPS3D)
12593 AVAIL_NON_MIPS16 (dsp, TARGET_DSP)
12594 AVAIL_NON_MIPS16 (dspr2, TARGET_DSPR2)
12595 AVAIL_NON_MIPS16 (dsp_32, !TARGET_64BIT && TARGET_DSP)
12596 AVAIL_NON_MIPS16 (dspr2_32, !TARGET_64BIT && TARGET_DSPR2)
12597 AVAIL_NON_MIPS16 (loongson, TARGET_LOONGSON_VECTORS)
12598 AVAIL_NON_MIPS16 (cache, TARGET_CACHE_BUILTIN)
12599
12600 /* Construct a mips_builtin_description from the given arguments.
12601
12602    INSN is the name of the associated instruction pattern, without the
12603    leading CODE_FOR_mips_.
12604
12605    CODE is the floating-point condition code associated with the
12606    function.  It can be 'f' if the field is not applicable.
12607
12608    NAME is the name of the function itself, without the leading
12609    "__builtin_mips_".
12610
12611    BUILTIN_TYPE and FUNCTION_TYPE are mips_builtin_description fields.
12612
12613    AVAIL is the name of the availability predicate, without the leading
12614    mips_builtin_avail_.  */
12615 #define MIPS_BUILTIN(INSN, COND, NAME, BUILTIN_TYPE,                    \
12616                      FUNCTION_TYPE, AVAIL)                              \
12617   { CODE_FOR_mips_ ## INSN, MIPS_FP_COND_ ## COND,                      \
12618     "__builtin_mips_" NAME, BUILTIN_TYPE, FUNCTION_TYPE,                \
12619     mips_builtin_avail_ ## AVAIL }
12620
12621 /* Define __builtin_mips_<INSN>, which is a MIPS_BUILTIN_DIRECT function
12622    mapped to instruction CODE_FOR_mips_<INSN>,  FUNCTION_TYPE and AVAIL
12623    are as for MIPS_BUILTIN.  */
12624 #define DIRECT_BUILTIN(INSN, FUNCTION_TYPE, AVAIL)                      \
12625   MIPS_BUILTIN (INSN, f, #INSN, MIPS_BUILTIN_DIRECT, FUNCTION_TYPE, AVAIL)
12626
12627 /* Define __builtin_mips_<INSN>_<COND>_{s,d} functions, both of which
12628    are subject to mips_builtin_avail_<AVAIL>.  */
12629 #define CMP_SCALAR_BUILTINS(INSN, COND, AVAIL)                          \
12630   MIPS_BUILTIN (INSN ## _cond_s, COND, #INSN "_" #COND "_s",            \
12631                 MIPS_BUILTIN_CMP_SINGLE, MIPS_INT_FTYPE_SF_SF, AVAIL),  \
12632   MIPS_BUILTIN (INSN ## _cond_d, COND, #INSN "_" #COND "_d",            \
12633                 MIPS_BUILTIN_CMP_SINGLE, MIPS_INT_FTYPE_DF_DF, AVAIL)
12634
12635 /* Define __builtin_mips_{any,all,upper,lower}_<INSN>_<COND>_ps.
12636    The lower and upper forms are subject to mips_builtin_avail_<AVAIL>
12637    while the any and all forms are subject to mips_builtin_avail_mips3d.  */
12638 #define CMP_PS_BUILTINS(INSN, COND, AVAIL)                              \
12639   MIPS_BUILTIN (INSN ## _cond_ps, COND, "any_" #INSN "_" #COND "_ps",   \
12640                 MIPS_BUILTIN_CMP_ANY, MIPS_INT_FTYPE_V2SF_V2SF,         \
12641                 mips3d),                                                \
12642   MIPS_BUILTIN (INSN ## _cond_ps, COND, "all_" #INSN "_" #COND "_ps",   \
12643                 MIPS_BUILTIN_CMP_ALL, MIPS_INT_FTYPE_V2SF_V2SF,         \
12644                 mips3d),                                                \
12645   MIPS_BUILTIN (INSN ## _cond_ps, COND, "lower_" #INSN "_" #COND "_ps", \
12646                 MIPS_BUILTIN_CMP_LOWER, MIPS_INT_FTYPE_V2SF_V2SF,       \
12647                 AVAIL),                                                 \
12648   MIPS_BUILTIN (INSN ## _cond_ps, COND, "upper_" #INSN "_" #COND "_ps", \
12649                 MIPS_BUILTIN_CMP_UPPER, MIPS_INT_FTYPE_V2SF_V2SF,       \
12650                 AVAIL)
12651
12652 /* Define __builtin_mips_{any,all}_<INSN>_<COND>_4s.  The functions
12653    are subject to mips_builtin_avail_mips3d.  */
12654 #define CMP_4S_BUILTINS(INSN, COND)                                     \
12655   MIPS_BUILTIN (INSN ## _cond_4s, COND, "any_" #INSN "_" #COND "_4s",   \
12656                 MIPS_BUILTIN_CMP_ANY,                                   \
12657                 MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF, mips3d),            \
12658   MIPS_BUILTIN (INSN ## _cond_4s, COND, "all_" #INSN "_" #COND "_4s",   \
12659                 MIPS_BUILTIN_CMP_ALL,                                   \
12660                 MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF, mips3d)
12661
12662 /* Define __builtin_mips_mov{t,f}_<INSN>_<COND>_ps.  The comparison
12663    instruction requires mips_builtin_avail_<AVAIL>.  */
12664 #define MOVTF_BUILTINS(INSN, COND, AVAIL)                               \
12665   MIPS_BUILTIN (INSN ## _cond_ps, COND, "movt_" #INSN "_" #COND "_ps",  \
12666                 MIPS_BUILTIN_MOVT, MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF, \
12667                 AVAIL),                                                 \
12668   MIPS_BUILTIN (INSN ## _cond_ps, COND, "movf_" #INSN "_" #COND "_ps",  \
12669                 MIPS_BUILTIN_MOVF, MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF, \
12670                 AVAIL)
12671
12672 /* Define all the built-in functions related to C.cond.fmt condition COND.  */
12673 #define CMP_BUILTINS(COND)                                              \
12674   MOVTF_BUILTINS (c, COND, paired_single),                              \
12675   MOVTF_BUILTINS (cabs, COND, mips3d),                                  \
12676   CMP_SCALAR_BUILTINS (cabs, COND, mips3d),                             \
12677   CMP_PS_BUILTINS (c, COND, paired_single),                             \
12678   CMP_PS_BUILTINS (cabs, COND, mips3d),                                 \
12679   CMP_4S_BUILTINS (c, COND),                                            \
12680   CMP_4S_BUILTINS (cabs, COND)
12681
12682 /* Define __builtin_mips_<INSN>, which is a MIPS_BUILTIN_DIRECT_NO_TARGET
12683    function mapped to instruction CODE_FOR_mips_<INSN>,  FUNCTION_TYPE
12684    and AVAIL are as for MIPS_BUILTIN.  */
12685 #define DIRECT_NO_TARGET_BUILTIN(INSN, FUNCTION_TYPE, AVAIL)            \
12686   MIPS_BUILTIN (INSN, f, #INSN, MIPS_BUILTIN_DIRECT_NO_TARGET,          \
12687                 FUNCTION_TYPE, AVAIL)
12688
12689 /* Define __builtin_mips_bposge<VALUE>.  <VALUE> is 32 for the MIPS32 DSP
12690    branch instruction.  AVAIL is as for MIPS_BUILTIN.  */
12691 #define BPOSGE_BUILTIN(VALUE, AVAIL)                                    \
12692   MIPS_BUILTIN (bposge, f, "bposge" #VALUE,                             \
12693                 MIPS_BUILTIN_BPOSGE ## VALUE, MIPS_SI_FTYPE_VOID, AVAIL)
12694
12695 /* Define a Loongson MIPS_BUILTIN_DIRECT function __builtin_loongson_<FN_NAME>
12696    for instruction CODE_FOR_loongson_<INSN>.  FUNCTION_TYPE is a
12697    builtin_description field.  */
12698 #define LOONGSON_BUILTIN_ALIAS(INSN, FN_NAME, FUNCTION_TYPE)            \
12699   { CODE_FOR_loongson_ ## INSN, MIPS_FP_COND_f,                         \
12700     "__builtin_loongson_" #FN_NAME, MIPS_BUILTIN_DIRECT,                \
12701     FUNCTION_TYPE, mips_builtin_avail_loongson }
12702
12703 /* Define a Loongson MIPS_BUILTIN_DIRECT function __builtin_loongson_<INSN>
12704    for instruction CODE_FOR_loongson_<INSN>.  FUNCTION_TYPE is a
12705    builtin_description field.  */
12706 #define LOONGSON_BUILTIN(INSN, FUNCTION_TYPE)                           \
12707   LOONGSON_BUILTIN_ALIAS (INSN, INSN, FUNCTION_TYPE)
12708
12709 /* Like LOONGSON_BUILTIN, but add _<SUFFIX> to the end of the function name.
12710    We use functions of this form when the same insn can be usefully applied
12711    to more than one datatype.  */
12712 #define LOONGSON_BUILTIN_SUFFIX(INSN, SUFFIX, FUNCTION_TYPE)            \
12713   LOONGSON_BUILTIN_ALIAS (INSN, INSN ## _ ## SUFFIX, FUNCTION_TYPE)
12714
12715 #define CODE_FOR_mips_sqrt_ps CODE_FOR_sqrtv2sf2
12716 #define CODE_FOR_mips_addq_ph CODE_FOR_addv2hi3
12717 #define CODE_FOR_mips_addu_qb CODE_FOR_addv4qi3
12718 #define CODE_FOR_mips_subq_ph CODE_FOR_subv2hi3
12719 #define CODE_FOR_mips_subu_qb CODE_FOR_subv4qi3
12720 #define CODE_FOR_mips_mul_ph CODE_FOR_mulv2hi3
12721 #define CODE_FOR_mips_mult CODE_FOR_mulsidi3_32bit
12722 #define CODE_FOR_mips_multu CODE_FOR_umulsidi3_32bit
12723
12724 #define CODE_FOR_loongson_packsswh CODE_FOR_vec_pack_ssat_v2si
12725 #define CODE_FOR_loongson_packsshb CODE_FOR_vec_pack_ssat_v4hi
12726 #define CODE_FOR_loongson_packushb CODE_FOR_vec_pack_usat_v4hi
12727 #define CODE_FOR_loongson_paddw CODE_FOR_addv2si3
12728 #define CODE_FOR_loongson_paddh CODE_FOR_addv4hi3
12729 #define CODE_FOR_loongson_paddb CODE_FOR_addv8qi3
12730 #define CODE_FOR_loongson_paddsh CODE_FOR_ssaddv4hi3
12731 #define CODE_FOR_loongson_paddsb CODE_FOR_ssaddv8qi3
12732 #define CODE_FOR_loongson_paddush CODE_FOR_usaddv4hi3
12733 #define CODE_FOR_loongson_paddusb CODE_FOR_usaddv8qi3
12734 #define CODE_FOR_loongson_pmaxsh CODE_FOR_smaxv4hi3
12735 #define CODE_FOR_loongson_pmaxub CODE_FOR_umaxv8qi3
12736 #define CODE_FOR_loongson_pminsh CODE_FOR_sminv4hi3
12737 #define CODE_FOR_loongson_pminub CODE_FOR_uminv8qi3
12738 #define CODE_FOR_loongson_pmulhuh CODE_FOR_umulv4hi3_highpart
12739 #define CODE_FOR_loongson_pmulhh CODE_FOR_smulv4hi3_highpart
12740 #define CODE_FOR_loongson_pmullh CODE_FOR_mulv4hi3
12741 #define CODE_FOR_loongson_psllh CODE_FOR_ashlv4hi3
12742 #define CODE_FOR_loongson_psllw CODE_FOR_ashlv2si3
12743 #define CODE_FOR_loongson_psrlh CODE_FOR_lshrv4hi3
12744 #define CODE_FOR_loongson_psrlw CODE_FOR_lshrv2si3
12745 #define CODE_FOR_loongson_psrah CODE_FOR_ashrv4hi3
12746 #define CODE_FOR_loongson_psraw CODE_FOR_ashrv2si3
12747 #define CODE_FOR_loongson_psubw CODE_FOR_subv2si3
12748 #define CODE_FOR_loongson_psubh CODE_FOR_subv4hi3
12749 #define CODE_FOR_loongson_psubb CODE_FOR_subv8qi3
12750 #define CODE_FOR_loongson_psubsh CODE_FOR_sssubv4hi3
12751 #define CODE_FOR_loongson_psubsb CODE_FOR_sssubv8qi3
12752 #define CODE_FOR_loongson_psubush CODE_FOR_ussubv4hi3
12753 #define CODE_FOR_loongson_psubusb CODE_FOR_ussubv8qi3
12754 #define CODE_FOR_loongson_punpckhbh CODE_FOR_vec_interleave_highv8qi
12755 #define CODE_FOR_loongson_punpckhhw CODE_FOR_vec_interleave_highv4hi
12756 #define CODE_FOR_loongson_punpckhwd CODE_FOR_vec_interleave_highv2si
12757 #define CODE_FOR_loongson_punpcklbh CODE_FOR_vec_interleave_lowv8qi
12758 #define CODE_FOR_loongson_punpcklhw CODE_FOR_vec_interleave_lowv4hi
12759 #define CODE_FOR_loongson_punpcklwd CODE_FOR_vec_interleave_lowv2si
12760
12761 static const struct mips_builtin_description mips_builtins[] = {
12762   DIRECT_BUILTIN (pll_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, paired_single),
12763   DIRECT_BUILTIN (pul_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, paired_single),
12764   DIRECT_BUILTIN (plu_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, paired_single),
12765   DIRECT_BUILTIN (puu_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, paired_single),
12766   DIRECT_BUILTIN (cvt_ps_s, MIPS_V2SF_FTYPE_SF_SF, paired_single),
12767   DIRECT_BUILTIN (cvt_s_pl, MIPS_SF_FTYPE_V2SF, paired_single),
12768   DIRECT_BUILTIN (cvt_s_pu, MIPS_SF_FTYPE_V2SF, paired_single),
12769   DIRECT_BUILTIN (abs_ps, MIPS_V2SF_FTYPE_V2SF, paired_single),
12770
12771   DIRECT_BUILTIN (alnv_ps, MIPS_V2SF_FTYPE_V2SF_V2SF_INT, paired_single),
12772   DIRECT_BUILTIN (addr_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, mips3d),
12773   DIRECT_BUILTIN (mulr_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, mips3d),
12774   DIRECT_BUILTIN (cvt_pw_ps, MIPS_V2SF_FTYPE_V2SF, mips3d),
12775   DIRECT_BUILTIN (cvt_ps_pw, MIPS_V2SF_FTYPE_V2SF, mips3d),
12776
12777   DIRECT_BUILTIN (recip1_s, MIPS_SF_FTYPE_SF, mips3d),
12778   DIRECT_BUILTIN (recip1_d, MIPS_DF_FTYPE_DF, mips3d),
12779   DIRECT_BUILTIN (recip1_ps, MIPS_V2SF_FTYPE_V2SF, mips3d),
12780   DIRECT_BUILTIN (recip2_s, MIPS_SF_FTYPE_SF_SF, mips3d),
12781   DIRECT_BUILTIN (recip2_d, MIPS_DF_FTYPE_DF_DF, mips3d),
12782   DIRECT_BUILTIN (recip2_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, mips3d),
12783
12784   DIRECT_BUILTIN (rsqrt1_s, MIPS_SF_FTYPE_SF, mips3d),
12785   DIRECT_BUILTIN (rsqrt1_d, MIPS_DF_FTYPE_DF, mips3d),
12786   DIRECT_BUILTIN (rsqrt1_ps, MIPS_V2SF_FTYPE_V2SF, mips3d),
12787   DIRECT_BUILTIN (rsqrt2_s, MIPS_SF_FTYPE_SF_SF, mips3d),
12788   DIRECT_BUILTIN (rsqrt2_d, MIPS_DF_FTYPE_DF_DF, mips3d),
12789   DIRECT_BUILTIN (rsqrt2_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, mips3d),
12790
12791   MIPS_FP_CONDITIONS (CMP_BUILTINS),
12792
12793   /* Built-in functions for the SB-1 processor.  */
12794   DIRECT_BUILTIN (sqrt_ps, MIPS_V2SF_FTYPE_V2SF, sb1_paired_single),
12795
12796   /* Built-in functions for the DSP ASE (32-bit and 64-bit).  */
12797   DIRECT_BUILTIN (addq_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
12798   DIRECT_BUILTIN (addq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
12799   DIRECT_BUILTIN (addq_s_w, MIPS_SI_FTYPE_SI_SI, dsp),
12800   DIRECT_BUILTIN (addu_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dsp),
12801   DIRECT_BUILTIN (addu_s_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dsp),
12802   DIRECT_BUILTIN (subq_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
12803   DIRECT_BUILTIN (subq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
12804   DIRECT_BUILTIN (subq_s_w, MIPS_SI_FTYPE_SI_SI, dsp),
12805   DIRECT_BUILTIN (subu_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dsp),
12806   DIRECT_BUILTIN (subu_s_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dsp),
12807   DIRECT_BUILTIN (addsc, MIPS_SI_FTYPE_SI_SI, dsp),
12808   DIRECT_BUILTIN (addwc, MIPS_SI_FTYPE_SI_SI, dsp),
12809   DIRECT_BUILTIN (modsub, MIPS_SI_FTYPE_SI_SI, dsp),
12810   DIRECT_BUILTIN (raddu_w_qb, MIPS_SI_FTYPE_V4QI, dsp),
12811   DIRECT_BUILTIN (absq_s_ph, MIPS_V2HI_FTYPE_V2HI, dsp),
12812   DIRECT_BUILTIN (absq_s_w, MIPS_SI_FTYPE_SI, dsp),
12813   DIRECT_BUILTIN (precrq_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, dsp),
12814   DIRECT_BUILTIN (precrq_ph_w, MIPS_V2HI_FTYPE_SI_SI, dsp),
12815   DIRECT_BUILTIN (precrq_rs_ph_w, MIPS_V2HI_FTYPE_SI_SI, dsp),
12816   DIRECT_BUILTIN (precrqu_s_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, dsp),
12817   DIRECT_BUILTIN (preceq_w_phl, MIPS_SI_FTYPE_V2HI, dsp),
12818   DIRECT_BUILTIN (preceq_w_phr, MIPS_SI_FTYPE_V2HI, dsp),
12819   DIRECT_BUILTIN (precequ_ph_qbl, MIPS_V2HI_FTYPE_V4QI, dsp),
12820   DIRECT_BUILTIN (precequ_ph_qbr, MIPS_V2HI_FTYPE_V4QI, dsp),
12821   DIRECT_BUILTIN (precequ_ph_qbla, MIPS_V2HI_FTYPE_V4QI, dsp),
12822   DIRECT_BUILTIN (precequ_ph_qbra, MIPS_V2HI_FTYPE_V4QI, dsp),
12823   DIRECT_BUILTIN (preceu_ph_qbl, MIPS_V2HI_FTYPE_V4QI, dsp),
12824   DIRECT_BUILTIN (preceu_ph_qbr, MIPS_V2HI_FTYPE_V4QI, dsp),
12825   DIRECT_BUILTIN (preceu_ph_qbla, MIPS_V2HI_FTYPE_V4QI, dsp),
12826   DIRECT_BUILTIN (preceu_ph_qbra, MIPS_V2HI_FTYPE_V4QI, dsp),
12827   DIRECT_BUILTIN (shll_qb, MIPS_V4QI_FTYPE_V4QI_SI, dsp),
12828   DIRECT_BUILTIN (shll_ph, MIPS_V2HI_FTYPE_V2HI_SI, dsp),
12829   DIRECT_BUILTIN (shll_s_ph, MIPS_V2HI_FTYPE_V2HI_SI, dsp),
12830   DIRECT_BUILTIN (shll_s_w, MIPS_SI_FTYPE_SI_SI, dsp),
12831   DIRECT_BUILTIN (shrl_qb, MIPS_V4QI_FTYPE_V4QI_SI, dsp),
12832   DIRECT_BUILTIN (shra_ph, MIPS_V2HI_FTYPE_V2HI_SI, dsp),
12833   DIRECT_BUILTIN (shra_r_ph, MIPS_V2HI_FTYPE_V2HI_SI, dsp),
12834   DIRECT_BUILTIN (shra_r_w, MIPS_SI_FTYPE_SI_SI, dsp),
12835   DIRECT_BUILTIN (muleu_s_ph_qbl, MIPS_V2HI_FTYPE_V4QI_V2HI, dsp),
12836   DIRECT_BUILTIN (muleu_s_ph_qbr, MIPS_V2HI_FTYPE_V4QI_V2HI, dsp),
12837   DIRECT_BUILTIN (mulq_rs_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
12838   DIRECT_BUILTIN (muleq_s_w_phl, MIPS_SI_FTYPE_V2HI_V2HI, dsp),
12839   DIRECT_BUILTIN (muleq_s_w_phr, MIPS_SI_FTYPE_V2HI_V2HI, dsp),
12840   DIRECT_BUILTIN (bitrev, MIPS_SI_FTYPE_SI, dsp),
12841   DIRECT_BUILTIN (insv, MIPS_SI_FTYPE_SI_SI, dsp),
12842   DIRECT_BUILTIN (repl_qb, MIPS_V4QI_FTYPE_SI, dsp),
12843   DIRECT_BUILTIN (repl_ph, MIPS_V2HI_FTYPE_SI, dsp),
12844   DIRECT_NO_TARGET_BUILTIN (cmpu_eq_qb, MIPS_VOID_FTYPE_V4QI_V4QI, dsp),
12845   DIRECT_NO_TARGET_BUILTIN (cmpu_lt_qb, MIPS_VOID_FTYPE_V4QI_V4QI, dsp),
12846   DIRECT_NO_TARGET_BUILTIN (cmpu_le_qb, MIPS_VOID_FTYPE_V4QI_V4QI, dsp),
12847   DIRECT_BUILTIN (cmpgu_eq_qb, MIPS_SI_FTYPE_V4QI_V4QI, dsp),
12848   DIRECT_BUILTIN (cmpgu_lt_qb, MIPS_SI_FTYPE_V4QI_V4QI, dsp),
12849   DIRECT_BUILTIN (cmpgu_le_qb, MIPS_SI_FTYPE_V4QI_V4QI, dsp),
12850   DIRECT_NO_TARGET_BUILTIN (cmp_eq_ph, MIPS_VOID_FTYPE_V2HI_V2HI, dsp),
12851   DIRECT_NO_TARGET_BUILTIN (cmp_lt_ph, MIPS_VOID_FTYPE_V2HI_V2HI, dsp),
12852   DIRECT_NO_TARGET_BUILTIN (cmp_le_ph, MIPS_VOID_FTYPE_V2HI_V2HI, dsp),
12853   DIRECT_BUILTIN (pick_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dsp),
12854   DIRECT_BUILTIN (pick_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
12855   DIRECT_BUILTIN (packrl_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dsp),
12856   DIRECT_NO_TARGET_BUILTIN (wrdsp, MIPS_VOID_FTYPE_SI_SI, dsp),
12857   DIRECT_BUILTIN (rddsp, MIPS_SI_FTYPE_SI, dsp),
12858   DIRECT_BUILTIN (lbux, MIPS_SI_FTYPE_POINTER_SI, dsp),
12859   DIRECT_BUILTIN (lhx, MIPS_SI_FTYPE_POINTER_SI, dsp),
12860   DIRECT_BUILTIN (lwx, MIPS_SI_FTYPE_POINTER_SI, dsp),
12861   BPOSGE_BUILTIN (32, dsp),
12862
12863   /* The following are for the MIPS DSP ASE REV 2 (32-bit and 64-bit).  */
12864   DIRECT_BUILTIN (absq_s_qb, MIPS_V4QI_FTYPE_V4QI, dspr2),
12865   DIRECT_BUILTIN (addu_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12866   DIRECT_BUILTIN (addu_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12867   DIRECT_BUILTIN (adduh_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dspr2),
12868   DIRECT_BUILTIN (adduh_r_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dspr2),
12869   DIRECT_BUILTIN (append, MIPS_SI_FTYPE_SI_SI_SI, dspr2),
12870   DIRECT_BUILTIN (balign, MIPS_SI_FTYPE_SI_SI_SI, dspr2),
12871   DIRECT_BUILTIN (cmpgdu_eq_qb, MIPS_SI_FTYPE_V4QI_V4QI, dspr2),
12872   DIRECT_BUILTIN (cmpgdu_lt_qb, MIPS_SI_FTYPE_V4QI_V4QI, dspr2),
12873   DIRECT_BUILTIN (cmpgdu_le_qb, MIPS_SI_FTYPE_V4QI_V4QI, dspr2),
12874   DIRECT_BUILTIN (mul_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12875   DIRECT_BUILTIN (mul_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12876   DIRECT_BUILTIN (mulq_rs_w, MIPS_SI_FTYPE_SI_SI, dspr2),
12877   DIRECT_BUILTIN (mulq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12878   DIRECT_BUILTIN (mulq_s_w, MIPS_SI_FTYPE_SI_SI, dspr2),
12879   DIRECT_BUILTIN (precr_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, dspr2),
12880   DIRECT_BUILTIN (precr_sra_ph_w, MIPS_V2HI_FTYPE_SI_SI_SI, dspr2),
12881   DIRECT_BUILTIN (precr_sra_r_ph_w, MIPS_V2HI_FTYPE_SI_SI_SI, dspr2),
12882   DIRECT_BUILTIN (prepend, MIPS_SI_FTYPE_SI_SI_SI, dspr2),
12883   DIRECT_BUILTIN (shra_qb, MIPS_V4QI_FTYPE_V4QI_SI, dspr2),
12884   DIRECT_BUILTIN (shra_r_qb, MIPS_V4QI_FTYPE_V4QI_SI, dspr2),
12885   DIRECT_BUILTIN (shrl_ph, MIPS_V2HI_FTYPE_V2HI_SI, dspr2),
12886   DIRECT_BUILTIN (subu_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12887   DIRECT_BUILTIN (subu_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12888   DIRECT_BUILTIN (subuh_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dspr2),
12889   DIRECT_BUILTIN (subuh_r_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, dspr2),
12890   DIRECT_BUILTIN (addqh_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12891   DIRECT_BUILTIN (addqh_r_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12892   DIRECT_BUILTIN (addqh_w, MIPS_SI_FTYPE_SI_SI, dspr2),
12893   DIRECT_BUILTIN (addqh_r_w, MIPS_SI_FTYPE_SI_SI, dspr2),
12894   DIRECT_BUILTIN (subqh_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12895   DIRECT_BUILTIN (subqh_r_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, dspr2),
12896   DIRECT_BUILTIN (subqh_w, MIPS_SI_FTYPE_SI_SI, dspr2),
12897   DIRECT_BUILTIN (subqh_r_w, MIPS_SI_FTYPE_SI_SI, dspr2),
12898
12899   /* Built-in functions for the DSP ASE (32-bit only).  */
12900   DIRECT_BUILTIN (dpau_h_qbl, MIPS_DI_FTYPE_DI_V4QI_V4QI, dsp_32),
12901   DIRECT_BUILTIN (dpau_h_qbr, MIPS_DI_FTYPE_DI_V4QI_V4QI, dsp_32),
12902   DIRECT_BUILTIN (dpsu_h_qbl, MIPS_DI_FTYPE_DI_V4QI_V4QI, dsp_32),
12903   DIRECT_BUILTIN (dpsu_h_qbr, MIPS_DI_FTYPE_DI_V4QI_V4QI, dsp_32),
12904   DIRECT_BUILTIN (dpaq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
12905   DIRECT_BUILTIN (dpsq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
12906   DIRECT_BUILTIN (mulsaq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
12907   DIRECT_BUILTIN (dpaq_sa_l_w, MIPS_DI_FTYPE_DI_SI_SI, dsp_32),
12908   DIRECT_BUILTIN (dpsq_sa_l_w, MIPS_DI_FTYPE_DI_SI_SI, dsp_32),
12909   DIRECT_BUILTIN (maq_s_w_phl, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
12910   DIRECT_BUILTIN (maq_s_w_phr, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
12911   DIRECT_BUILTIN (maq_sa_w_phl, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
12912   DIRECT_BUILTIN (maq_sa_w_phr, MIPS_DI_FTYPE_DI_V2HI_V2HI, dsp_32),
12913   DIRECT_BUILTIN (extr_w, MIPS_SI_FTYPE_DI_SI, dsp_32),
12914   DIRECT_BUILTIN (extr_r_w, MIPS_SI_FTYPE_DI_SI, dsp_32),
12915   DIRECT_BUILTIN (extr_rs_w, MIPS_SI_FTYPE_DI_SI, dsp_32),
12916   DIRECT_BUILTIN (extr_s_h, MIPS_SI_FTYPE_DI_SI, dsp_32),
12917   DIRECT_BUILTIN (extp, MIPS_SI_FTYPE_DI_SI, dsp_32),
12918   DIRECT_BUILTIN (extpdp, MIPS_SI_FTYPE_DI_SI, dsp_32),
12919   DIRECT_BUILTIN (shilo, MIPS_DI_FTYPE_DI_SI, dsp_32),
12920   DIRECT_BUILTIN (mthlip, MIPS_DI_FTYPE_DI_SI, dsp_32),
12921   DIRECT_BUILTIN (madd, MIPS_DI_FTYPE_DI_SI_SI, dsp_32),
12922   DIRECT_BUILTIN (maddu, MIPS_DI_FTYPE_DI_USI_USI, dsp_32),
12923   DIRECT_BUILTIN (msub, MIPS_DI_FTYPE_DI_SI_SI, dsp_32),
12924   DIRECT_BUILTIN (msubu, MIPS_DI_FTYPE_DI_USI_USI, dsp_32),
12925   DIRECT_BUILTIN (mult, MIPS_DI_FTYPE_SI_SI, dsp_32),
12926   DIRECT_BUILTIN (multu, MIPS_DI_FTYPE_USI_USI, dsp_32),
12927
12928   /* The following are for the MIPS DSP ASE REV 2 (32-bit only).  */
12929   DIRECT_BUILTIN (dpa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
12930   DIRECT_BUILTIN (dps_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
12931   DIRECT_BUILTIN (mulsa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
12932   DIRECT_BUILTIN (dpax_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
12933   DIRECT_BUILTIN (dpsx_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
12934   DIRECT_BUILTIN (dpaqx_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
12935   DIRECT_BUILTIN (dpaqx_sa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
12936   DIRECT_BUILTIN (dpsqx_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
12937   DIRECT_BUILTIN (dpsqx_sa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, dspr2_32),
12938
12939   /* Builtin functions for ST Microelectronics Loongson-2E/2F cores.  */
12940   LOONGSON_BUILTIN (packsswh, MIPS_V4HI_FTYPE_V2SI_V2SI),
12941   LOONGSON_BUILTIN (packsshb, MIPS_V8QI_FTYPE_V4HI_V4HI),
12942   LOONGSON_BUILTIN (packushb, MIPS_UV8QI_FTYPE_UV4HI_UV4HI),
12943   LOONGSON_BUILTIN_SUFFIX (paddw, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
12944   LOONGSON_BUILTIN_SUFFIX (paddh, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12945   LOONGSON_BUILTIN_SUFFIX (paddb, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
12946   LOONGSON_BUILTIN_SUFFIX (paddw, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
12947   LOONGSON_BUILTIN_SUFFIX (paddh, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
12948   LOONGSON_BUILTIN_SUFFIX (paddb, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
12949   LOONGSON_BUILTIN_SUFFIX (paddd, u, MIPS_UDI_FTYPE_UDI_UDI),
12950   LOONGSON_BUILTIN_SUFFIX (paddd, s, MIPS_DI_FTYPE_DI_DI),
12951   LOONGSON_BUILTIN (paddsh, MIPS_V4HI_FTYPE_V4HI_V4HI),
12952   LOONGSON_BUILTIN (paddsb, MIPS_V8QI_FTYPE_V8QI_V8QI),
12953   LOONGSON_BUILTIN (paddush, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12954   LOONGSON_BUILTIN (paddusb, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
12955   LOONGSON_BUILTIN_ALIAS (pandn_d, pandn_ud, MIPS_UDI_FTYPE_UDI_UDI),
12956   LOONGSON_BUILTIN_ALIAS (pandn_w, pandn_uw, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
12957   LOONGSON_BUILTIN_ALIAS (pandn_h, pandn_uh, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12958   LOONGSON_BUILTIN_ALIAS (pandn_b, pandn_ub, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
12959   LOONGSON_BUILTIN_ALIAS (pandn_d, pandn_sd, MIPS_DI_FTYPE_DI_DI),
12960   LOONGSON_BUILTIN_ALIAS (pandn_w, pandn_sw, MIPS_V2SI_FTYPE_V2SI_V2SI),
12961   LOONGSON_BUILTIN_ALIAS (pandn_h, pandn_sh, MIPS_V4HI_FTYPE_V4HI_V4HI),
12962   LOONGSON_BUILTIN_ALIAS (pandn_b, pandn_sb, MIPS_V8QI_FTYPE_V8QI_V8QI),
12963   LOONGSON_BUILTIN (pavgh, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12964   LOONGSON_BUILTIN (pavgb, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
12965   LOONGSON_BUILTIN_SUFFIX (pcmpeqw, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
12966   LOONGSON_BUILTIN_SUFFIX (pcmpeqh, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12967   LOONGSON_BUILTIN_SUFFIX (pcmpeqb, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
12968   LOONGSON_BUILTIN_SUFFIX (pcmpeqw, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
12969   LOONGSON_BUILTIN_SUFFIX (pcmpeqh, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
12970   LOONGSON_BUILTIN_SUFFIX (pcmpeqb, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
12971   LOONGSON_BUILTIN_SUFFIX (pcmpgtw, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
12972   LOONGSON_BUILTIN_SUFFIX (pcmpgth, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12973   LOONGSON_BUILTIN_SUFFIX (pcmpgtb, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
12974   LOONGSON_BUILTIN_SUFFIX (pcmpgtw, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
12975   LOONGSON_BUILTIN_SUFFIX (pcmpgth, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
12976   LOONGSON_BUILTIN_SUFFIX (pcmpgtb, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
12977   LOONGSON_BUILTIN_SUFFIX (pextrh, u, MIPS_UV4HI_FTYPE_UV4HI_USI),
12978   LOONGSON_BUILTIN_SUFFIX (pextrh, s, MIPS_V4HI_FTYPE_V4HI_USI),
12979   LOONGSON_BUILTIN_SUFFIX (pinsrh_0, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12980   LOONGSON_BUILTIN_SUFFIX (pinsrh_1, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12981   LOONGSON_BUILTIN_SUFFIX (pinsrh_2, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12982   LOONGSON_BUILTIN_SUFFIX (pinsrh_3, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12983   LOONGSON_BUILTIN_SUFFIX (pinsrh_0, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
12984   LOONGSON_BUILTIN_SUFFIX (pinsrh_1, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
12985   LOONGSON_BUILTIN_SUFFIX (pinsrh_2, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
12986   LOONGSON_BUILTIN_SUFFIX (pinsrh_3, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
12987   LOONGSON_BUILTIN (pmaddhw, MIPS_V2SI_FTYPE_V4HI_V4HI),
12988   LOONGSON_BUILTIN (pmaxsh, MIPS_V4HI_FTYPE_V4HI_V4HI),
12989   LOONGSON_BUILTIN (pmaxub, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
12990   LOONGSON_BUILTIN (pminsh, MIPS_V4HI_FTYPE_V4HI_V4HI),
12991   LOONGSON_BUILTIN (pminub, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
12992   LOONGSON_BUILTIN_SUFFIX (pmovmskb, u, MIPS_UV8QI_FTYPE_UV8QI),
12993   LOONGSON_BUILTIN_SUFFIX (pmovmskb, s, MIPS_V8QI_FTYPE_V8QI),
12994   LOONGSON_BUILTIN (pmulhuh, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
12995   LOONGSON_BUILTIN (pmulhh, MIPS_V4HI_FTYPE_V4HI_V4HI),
12996   LOONGSON_BUILTIN (pmullh, MIPS_V4HI_FTYPE_V4HI_V4HI),
12997   LOONGSON_BUILTIN (pmuluw, MIPS_UDI_FTYPE_UV2SI_UV2SI),
12998   LOONGSON_BUILTIN (pasubub, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
12999   LOONGSON_BUILTIN (biadd, MIPS_UV4HI_FTYPE_UV8QI),
13000   LOONGSON_BUILTIN (psadbh, MIPS_UV4HI_FTYPE_UV8QI_UV8QI),
13001   LOONGSON_BUILTIN_SUFFIX (pshufh, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI_UQI),
13002   LOONGSON_BUILTIN_SUFFIX (pshufh, s, MIPS_V4HI_FTYPE_V4HI_V4HI_UQI),
13003   LOONGSON_BUILTIN_SUFFIX (psllh, u, MIPS_UV4HI_FTYPE_UV4HI_UQI),
13004   LOONGSON_BUILTIN_SUFFIX (psllh, s, MIPS_V4HI_FTYPE_V4HI_UQI),
13005   LOONGSON_BUILTIN_SUFFIX (psllw, u, MIPS_UV2SI_FTYPE_UV2SI_UQI),
13006   LOONGSON_BUILTIN_SUFFIX (psllw, s, MIPS_V2SI_FTYPE_V2SI_UQI),
13007   LOONGSON_BUILTIN_SUFFIX (psrah, u, MIPS_UV4HI_FTYPE_UV4HI_UQI),
13008   LOONGSON_BUILTIN_SUFFIX (psrah, s, MIPS_V4HI_FTYPE_V4HI_UQI),
13009   LOONGSON_BUILTIN_SUFFIX (psraw, u, MIPS_UV2SI_FTYPE_UV2SI_UQI),
13010   LOONGSON_BUILTIN_SUFFIX (psraw, s, MIPS_V2SI_FTYPE_V2SI_UQI),
13011   LOONGSON_BUILTIN_SUFFIX (psrlh, u, MIPS_UV4HI_FTYPE_UV4HI_UQI),
13012   LOONGSON_BUILTIN_SUFFIX (psrlh, s, MIPS_V4HI_FTYPE_V4HI_UQI),
13013   LOONGSON_BUILTIN_SUFFIX (psrlw, u, MIPS_UV2SI_FTYPE_UV2SI_UQI),
13014   LOONGSON_BUILTIN_SUFFIX (psrlw, s, MIPS_V2SI_FTYPE_V2SI_UQI),
13015   LOONGSON_BUILTIN_SUFFIX (psubw, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
13016   LOONGSON_BUILTIN_SUFFIX (psubh, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
13017   LOONGSON_BUILTIN_SUFFIX (psubb, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
13018   LOONGSON_BUILTIN_SUFFIX (psubw, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
13019   LOONGSON_BUILTIN_SUFFIX (psubh, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
13020   LOONGSON_BUILTIN_SUFFIX (psubb, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
13021   LOONGSON_BUILTIN_SUFFIX (psubd, u, MIPS_UDI_FTYPE_UDI_UDI),
13022   LOONGSON_BUILTIN_SUFFIX (psubd, s, MIPS_DI_FTYPE_DI_DI),
13023   LOONGSON_BUILTIN (psubsh, MIPS_V4HI_FTYPE_V4HI_V4HI),
13024   LOONGSON_BUILTIN (psubsb, MIPS_V8QI_FTYPE_V8QI_V8QI),
13025   LOONGSON_BUILTIN (psubush, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
13026   LOONGSON_BUILTIN (psubusb, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
13027   LOONGSON_BUILTIN_SUFFIX (punpckhbh, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
13028   LOONGSON_BUILTIN_SUFFIX (punpckhhw, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
13029   LOONGSON_BUILTIN_SUFFIX (punpckhwd, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
13030   LOONGSON_BUILTIN_SUFFIX (punpckhbh, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
13031   LOONGSON_BUILTIN_SUFFIX (punpckhhw, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
13032   LOONGSON_BUILTIN_SUFFIX (punpckhwd, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
13033   LOONGSON_BUILTIN_SUFFIX (punpcklbh, u, MIPS_UV8QI_FTYPE_UV8QI_UV8QI),
13034   LOONGSON_BUILTIN_SUFFIX (punpcklhw, u, MIPS_UV4HI_FTYPE_UV4HI_UV4HI),
13035   LOONGSON_BUILTIN_SUFFIX (punpcklwd, u, MIPS_UV2SI_FTYPE_UV2SI_UV2SI),
13036   LOONGSON_BUILTIN_SUFFIX (punpcklbh, s, MIPS_V8QI_FTYPE_V8QI_V8QI),
13037   LOONGSON_BUILTIN_SUFFIX (punpcklhw, s, MIPS_V4HI_FTYPE_V4HI_V4HI),
13038   LOONGSON_BUILTIN_SUFFIX (punpcklwd, s, MIPS_V2SI_FTYPE_V2SI_V2SI),
13039
13040   /* Sundry other built-in functions.  */
13041   DIRECT_NO_TARGET_BUILTIN (cache, MIPS_VOID_FTYPE_SI_CVPOINTER, cache)
13042 };
13043
13044 /* Index I is the function declaration for mips_builtins[I], or null if the
13045    function isn't defined on this target.  */
13046 static GTY(()) tree mips_builtin_decls[ARRAY_SIZE (mips_builtins)];
13047
13048 /* MODE is a vector mode whose elements have type TYPE.  Return the type
13049    of the vector itself.  */
13050
13051 static tree
13052 mips_builtin_vector_type (tree type, enum machine_mode mode)
13053 {
13054   static tree types[2 * (int) MAX_MACHINE_MODE];
13055   int mode_index;
13056
13057   mode_index = (int) mode;
13058
13059   if (TREE_CODE (type) == INTEGER_TYPE && TYPE_UNSIGNED (type))
13060     mode_index += MAX_MACHINE_MODE;
13061
13062   if (types[mode_index] == NULL_TREE)
13063     types[mode_index] = build_vector_type_for_mode (type, mode);
13064   return types[mode_index];
13065 }
13066
13067 /* Return a type for 'const volatile void *'.  */
13068
13069 static tree
13070 mips_build_cvpointer_type (void)
13071 {
13072   static tree cache;
13073
13074   if (cache == NULL_TREE)
13075     cache = build_pointer_type (build_qualified_type
13076                                 (void_type_node,
13077                                  TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE));
13078   return cache;
13079 }
13080
13081 /* Source-level argument types.  */
13082 #define MIPS_ATYPE_VOID void_type_node
13083 #define MIPS_ATYPE_INT integer_type_node
13084 #define MIPS_ATYPE_POINTER ptr_type_node
13085 #define MIPS_ATYPE_CVPOINTER mips_build_cvpointer_type ()
13086
13087 /* Standard mode-based argument types.  */
13088 #define MIPS_ATYPE_UQI unsigned_intQI_type_node
13089 #define MIPS_ATYPE_SI intSI_type_node
13090 #define MIPS_ATYPE_USI unsigned_intSI_type_node
13091 #define MIPS_ATYPE_DI intDI_type_node
13092 #define MIPS_ATYPE_UDI unsigned_intDI_type_node
13093 #define MIPS_ATYPE_SF float_type_node
13094 #define MIPS_ATYPE_DF double_type_node
13095
13096 /* Vector argument types.  */
13097 #define MIPS_ATYPE_V2SF mips_builtin_vector_type (float_type_node, V2SFmode)
13098 #define MIPS_ATYPE_V2HI mips_builtin_vector_type (intHI_type_node, V2HImode)
13099 #define MIPS_ATYPE_V2SI mips_builtin_vector_type (intSI_type_node, V2SImode)
13100 #define MIPS_ATYPE_V4QI mips_builtin_vector_type (intQI_type_node, V4QImode)
13101 #define MIPS_ATYPE_V4HI mips_builtin_vector_type (intHI_type_node, V4HImode)
13102 #define MIPS_ATYPE_V8QI mips_builtin_vector_type (intQI_type_node, V8QImode)
13103 #define MIPS_ATYPE_UV2SI                                        \
13104   mips_builtin_vector_type (unsigned_intSI_type_node, V2SImode)
13105 #define MIPS_ATYPE_UV4HI                                        \
13106   mips_builtin_vector_type (unsigned_intHI_type_node, V4HImode)
13107 #define MIPS_ATYPE_UV8QI                                        \
13108   mips_builtin_vector_type (unsigned_intQI_type_node, V8QImode)
13109
13110 /* MIPS_FTYPE_ATYPESN takes N MIPS_FTYPES-like type codes and lists
13111    their associated MIPS_ATYPEs.  */
13112 #define MIPS_FTYPE_ATYPES1(A, B) \
13113   MIPS_ATYPE_##A, MIPS_ATYPE_##B
13114
13115 #define MIPS_FTYPE_ATYPES2(A, B, C) \
13116   MIPS_ATYPE_##A, MIPS_ATYPE_##B, MIPS_ATYPE_##C
13117
13118 #define MIPS_FTYPE_ATYPES3(A, B, C, D) \
13119   MIPS_ATYPE_##A, MIPS_ATYPE_##B, MIPS_ATYPE_##C, MIPS_ATYPE_##D
13120
13121 #define MIPS_FTYPE_ATYPES4(A, B, C, D, E) \
13122   MIPS_ATYPE_##A, MIPS_ATYPE_##B, MIPS_ATYPE_##C, MIPS_ATYPE_##D, \
13123   MIPS_ATYPE_##E
13124
13125 /* Return the function type associated with function prototype TYPE.  */
13126
13127 static tree
13128 mips_build_function_type (enum mips_function_type type)
13129 {
13130   static tree types[(int) MIPS_MAX_FTYPE_MAX];
13131
13132   if (types[(int) type] == NULL_TREE)
13133     switch (type)
13134       {
13135 #define DEF_MIPS_FTYPE(NUM, ARGS)                                       \
13136   case MIPS_FTYPE_NAME##NUM ARGS:                                       \
13137     types[(int) type]                                                   \
13138       = build_function_type_list (MIPS_FTYPE_ATYPES##NUM ARGS,          \
13139                                   NULL_TREE);                           \
13140     break;
13141 #include "config/mips/mips-ftypes.def"
13142 #undef DEF_MIPS_FTYPE
13143       default:
13144         gcc_unreachable ();
13145       }
13146
13147   return types[(int) type];
13148 }
13149
13150 /* Implement TARGET_INIT_BUILTINS.  */
13151
13152 static void
13153 mips_init_builtins (void)
13154 {
13155   const struct mips_builtin_description *d;
13156   unsigned int i;
13157
13158   /* Iterate through all of the bdesc arrays, initializing all of the
13159      builtin functions.  */
13160   for (i = 0; i < ARRAY_SIZE (mips_builtins); i++)
13161     {
13162       d = &mips_builtins[i];
13163       if (d->avail ())
13164         mips_builtin_decls[i]
13165           = add_builtin_function (d->name,
13166                                   mips_build_function_type (d->function_type),
13167                                   i, BUILT_IN_MD, NULL, NULL);
13168     }
13169 }
13170
13171 /* Implement TARGET_BUILTIN_DECL.  */
13172
13173 static tree
13174 mips_builtin_decl (unsigned int code, bool initialize_p ATTRIBUTE_UNUSED)
13175 {
13176   if (code >= ARRAY_SIZE (mips_builtins))
13177     return error_mark_node;
13178   return mips_builtin_decls[code];
13179 }
13180
13181 /* Take argument ARGNO from EXP's argument list and convert it into a
13182    form suitable for input operand OPNO of instruction ICODE.  Return the
13183    value.  */
13184
13185 static rtx
13186 mips_prepare_builtin_arg (enum insn_code icode,
13187                           unsigned int opno, tree exp, unsigned int argno)
13188 {
13189   tree arg;
13190   rtx value;
13191   enum machine_mode mode;
13192
13193   arg = CALL_EXPR_ARG (exp, argno);
13194   value = expand_normal (arg);
13195   mode = insn_data[icode].operand[opno].mode;
13196   if (!insn_data[icode].operand[opno].predicate (value, mode))
13197     {
13198       /* We need to get the mode from ARG for two reasons:
13199
13200            - to cope with address operands, where MODE is the mode of the
13201              memory, rather than of VALUE itself.
13202
13203            - to cope with special predicates like pmode_register_operand,
13204              where MODE is VOIDmode.  */
13205       value = copy_to_mode_reg (TYPE_MODE (TREE_TYPE (arg)), value);
13206
13207       /* Check the predicate again.  */
13208       if (!insn_data[icode].operand[opno].predicate (value, mode))
13209         {
13210           error ("invalid argument to built-in function");
13211           return const0_rtx;
13212         }
13213     }
13214
13215   return value;
13216 }
13217
13218 /* Return an rtx suitable for output operand OP of instruction ICODE.
13219    If TARGET is non-null, try to use it where possible.  */
13220
13221 static rtx
13222 mips_prepare_builtin_target (enum insn_code icode, unsigned int op, rtx target)
13223 {
13224   enum machine_mode mode;
13225
13226   mode = insn_data[icode].operand[op].mode;
13227   if (target == 0 || !insn_data[icode].operand[op].predicate (target, mode))
13228     target = gen_reg_rtx (mode);
13229
13230   return target;
13231 }
13232
13233 /* Expand a MIPS_BUILTIN_DIRECT or MIPS_BUILTIN_DIRECT_NO_TARGET function;
13234    HAS_TARGET_P says which.  EXP is the CALL_EXPR that calls the function
13235    and ICODE is the code of the associated .md pattern.  TARGET, if nonnull,
13236    suggests a good place to put the result.  */
13237
13238 static rtx
13239 mips_expand_builtin_direct (enum insn_code icode, rtx target, tree exp,
13240                             bool has_target_p)
13241 {
13242   rtx ops[MAX_RECOG_OPERANDS];
13243   int opno, argno;
13244
13245   /* Map any target to operand 0.  */
13246   opno = 0;
13247   if (has_target_p)
13248     {
13249       target = mips_prepare_builtin_target (icode, opno, target);
13250       ops[opno] = target;
13251       opno++;
13252     }
13253
13254   /* Map the arguments to the other operands.  The n_operands value
13255      for an expander includes match_dups and match_scratches as well as
13256      match_operands, so n_operands is only an upper bound on the number
13257      of arguments to the expander function.  */
13258   gcc_assert (opno + call_expr_nargs (exp) <= insn_data[icode].n_operands);
13259   for (argno = 0; argno < call_expr_nargs (exp); argno++, opno++)
13260     ops[opno] = mips_prepare_builtin_arg (icode, opno, exp, argno);
13261
13262   switch (opno)
13263     {
13264     case 2:
13265       emit_insn (GEN_FCN (icode) (ops[0], ops[1]));
13266       break;
13267
13268     case 3:
13269       emit_insn (GEN_FCN (icode) (ops[0], ops[1], ops[2]));
13270       break;
13271
13272     case 4:
13273       emit_insn (GEN_FCN (icode) (ops[0], ops[1], ops[2], ops[3]));
13274       break;
13275
13276     default:
13277       gcc_unreachable ();
13278     }
13279   return target;
13280 }
13281
13282 /* Expand a __builtin_mips_movt_*_ps or __builtin_mips_movf_*_ps
13283    function; TYPE says which.  EXP is the CALL_EXPR that calls the
13284    function, ICODE is the instruction that should be used to compare
13285    the first two arguments, and COND is the condition it should test.
13286    TARGET, if nonnull, suggests a good place to put the result.  */
13287
13288 static rtx
13289 mips_expand_builtin_movtf (enum mips_builtin_type type,
13290                            enum insn_code icode, enum mips_fp_condition cond,
13291                            rtx target, tree exp)
13292 {
13293   rtx cmp_result, op0, op1;
13294
13295   cmp_result = mips_prepare_builtin_target (icode, 0, 0);
13296   op0 = mips_prepare_builtin_arg (icode, 1, exp, 0);
13297   op1 = mips_prepare_builtin_arg (icode, 2, exp, 1);
13298   emit_insn (GEN_FCN (icode) (cmp_result, op0, op1, GEN_INT (cond)));
13299
13300   icode = CODE_FOR_mips_cond_move_tf_ps;
13301   target = mips_prepare_builtin_target (icode, 0, target);
13302   if (type == MIPS_BUILTIN_MOVT)
13303     {
13304       op1 = mips_prepare_builtin_arg (icode, 2, exp, 2);
13305       op0 = mips_prepare_builtin_arg (icode, 1, exp, 3);
13306     }
13307   else
13308     {
13309       op0 = mips_prepare_builtin_arg (icode, 1, exp, 2);
13310       op1 = mips_prepare_builtin_arg (icode, 2, exp, 3);
13311     }
13312   emit_insn (gen_mips_cond_move_tf_ps (target, op0, op1, cmp_result));
13313   return target;
13314 }
13315
13316 /* Move VALUE_IF_TRUE into TARGET if CONDITION is true; move VALUE_IF_FALSE
13317    into TARGET otherwise.  Return TARGET.  */
13318
13319 static rtx
13320 mips_builtin_branch_and_move (rtx condition, rtx target,
13321                               rtx value_if_true, rtx value_if_false)
13322 {
13323   rtx true_label, done_label;
13324
13325   true_label = gen_label_rtx ();
13326   done_label = gen_label_rtx ();
13327
13328   /* First assume that CONDITION is false.  */
13329   mips_emit_move (target, value_if_false);
13330
13331   /* Branch to TRUE_LABEL if CONDITION is true and DONE_LABEL otherwise.  */
13332   emit_jump_insn (gen_condjump (condition, true_label));
13333   emit_jump_insn (gen_jump (done_label));
13334   emit_barrier ();
13335
13336   /* Fix TARGET if CONDITION is true.  */
13337   emit_label (true_label);
13338   mips_emit_move (target, value_if_true);
13339
13340   emit_label (done_label);
13341   return target;
13342 }
13343
13344 /* Expand a comparison built-in function of type BUILTIN_TYPE.  EXP is
13345    the CALL_EXPR that calls the function, ICODE is the code of the
13346    comparison instruction, and COND is the condition it should test.
13347    TARGET, if nonnull, suggests a good place to put the boolean result.  */
13348
13349 static rtx
13350 mips_expand_builtin_compare (enum mips_builtin_type builtin_type,
13351                              enum insn_code icode, enum mips_fp_condition cond,
13352                              rtx target, tree exp)
13353 {
13354   rtx offset, condition, cmp_result, args[MAX_RECOG_OPERANDS];
13355   int argno;
13356
13357   if (target == 0 || GET_MODE (target) != SImode)
13358     target = gen_reg_rtx (SImode);
13359
13360   /* The instruction should have a target operand, an operand for each
13361      argument, and an operand for COND.  */
13362   gcc_assert (call_expr_nargs (exp) + 2 == insn_data[icode].n_operands);
13363
13364   /* Prepare the operands to the comparison.  */
13365   cmp_result = mips_prepare_builtin_target (icode, 0, 0);
13366   for (argno = 0; argno < call_expr_nargs (exp); argno++)
13367     args[argno] = mips_prepare_builtin_arg (icode, argno + 1, exp, argno);
13368
13369   switch (insn_data[icode].n_operands)
13370     {
13371     case 4:
13372       emit_insn (GEN_FCN (icode) (cmp_result, args[0], args[1],
13373                                   GEN_INT (cond)));
13374       break;
13375
13376     case 6:
13377       emit_insn (GEN_FCN (icode) (cmp_result, args[0], args[1],
13378                                   args[2], args[3], GEN_INT (cond)));
13379       break;
13380
13381     default:
13382       gcc_unreachable ();
13383     }
13384
13385   /* If the comparison sets more than one register, we define the result
13386      to be 0 if all registers are false and -1 if all registers are true.
13387      The value of the complete result is indeterminate otherwise.  */
13388   switch (builtin_type)
13389     {
13390     case MIPS_BUILTIN_CMP_ALL:
13391       condition = gen_rtx_NE (VOIDmode, cmp_result, constm1_rtx);
13392       return mips_builtin_branch_and_move (condition, target,
13393                                            const0_rtx, const1_rtx);
13394
13395     case MIPS_BUILTIN_CMP_UPPER:
13396     case MIPS_BUILTIN_CMP_LOWER:
13397       offset = GEN_INT (builtin_type == MIPS_BUILTIN_CMP_UPPER);
13398       condition = gen_single_cc (cmp_result, offset);
13399       return mips_builtin_branch_and_move (condition, target,
13400                                            const1_rtx, const0_rtx);
13401
13402     default:
13403       condition = gen_rtx_NE (VOIDmode, cmp_result, const0_rtx);
13404       return mips_builtin_branch_and_move (condition, target,
13405                                            const1_rtx, const0_rtx);
13406     }
13407 }
13408
13409 /* Expand a bposge built-in function of type BUILTIN_TYPE.  TARGET,
13410    if nonnull, suggests a good place to put the boolean result.  */
13411
13412 static rtx
13413 mips_expand_builtin_bposge (enum mips_builtin_type builtin_type, rtx target)
13414 {
13415   rtx condition, cmp_result;
13416   int cmp_value;
13417
13418   if (target == 0 || GET_MODE (target) != SImode)
13419     target = gen_reg_rtx (SImode);
13420
13421   cmp_result = gen_rtx_REG (CCDSPmode, CCDSP_PO_REGNUM);
13422
13423   if (builtin_type == MIPS_BUILTIN_BPOSGE32)
13424     cmp_value = 32;
13425   else
13426     gcc_assert (0);
13427
13428   condition = gen_rtx_GE (VOIDmode, cmp_result, GEN_INT (cmp_value));
13429   return mips_builtin_branch_and_move (condition, target,
13430                                        const1_rtx, const0_rtx);
13431 }
13432
13433 /* Implement TARGET_EXPAND_BUILTIN.  */
13434
13435 static rtx
13436 mips_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
13437                      enum machine_mode mode, int ignore)
13438 {
13439   tree fndecl;
13440   unsigned int fcode, avail;
13441   const struct mips_builtin_description *d;
13442
13443   fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
13444   fcode = DECL_FUNCTION_CODE (fndecl);
13445   gcc_assert (fcode < ARRAY_SIZE (mips_builtins));
13446   d = &mips_builtins[fcode];
13447   avail = d->avail ();
13448   gcc_assert (avail != 0);
13449   if (TARGET_MIPS16)
13450     {
13451       error ("built-in function %qE not supported for MIPS16",
13452              DECL_NAME (fndecl));
13453       return ignore ? const0_rtx : CONST0_RTX (mode);
13454     }
13455   switch (d->builtin_type)
13456     {
13457     case MIPS_BUILTIN_DIRECT:
13458       return mips_expand_builtin_direct (d->icode, target, exp, true);
13459
13460     case MIPS_BUILTIN_DIRECT_NO_TARGET:
13461       return mips_expand_builtin_direct (d->icode, target, exp, false);
13462
13463     case MIPS_BUILTIN_MOVT:
13464     case MIPS_BUILTIN_MOVF:
13465       return mips_expand_builtin_movtf (d->builtin_type, d->icode,
13466                                         d->cond, target, exp);
13467
13468     case MIPS_BUILTIN_CMP_ANY:
13469     case MIPS_BUILTIN_CMP_ALL:
13470     case MIPS_BUILTIN_CMP_UPPER:
13471     case MIPS_BUILTIN_CMP_LOWER:
13472     case MIPS_BUILTIN_CMP_SINGLE:
13473       return mips_expand_builtin_compare (d->builtin_type, d->icode,
13474                                           d->cond, target, exp);
13475
13476     case MIPS_BUILTIN_BPOSGE32:
13477       return mips_expand_builtin_bposge (d->builtin_type, target);
13478     }
13479   gcc_unreachable ();
13480 }
13481 \f
13482 /* An entry in the MIPS16 constant pool.  VALUE is the pool constant,
13483    MODE is its mode, and LABEL is the CODE_LABEL associated with it.  */
13484 struct mips16_constant {
13485   struct mips16_constant *next;
13486   rtx value;
13487   rtx label;
13488   enum machine_mode mode;
13489 };
13490
13491 /* Information about an incomplete MIPS16 constant pool.  FIRST is the
13492    first constant, HIGHEST_ADDRESS is the highest address that the first
13493    byte of the pool can have, and INSN_ADDRESS is the current instruction
13494    address.  */
13495 struct mips16_constant_pool {
13496   struct mips16_constant *first;
13497   int highest_address;
13498   int insn_address;
13499 };
13500
13501 /* Add constant VALUE to POOL and return its label.  MODE is the
13502    value's mode (used for CONST_INTs, etc.).  */
13503
13504 static rtx
13505 mips16_add_constant (struct mips16_constant_pool *pool,
13506                      rtx value, enum machine_mode mode)
13507 {
13508   struct mips16_constant **p, *c;
13509   bool first_of_size_p;
13510
13511   /* See whether the constant is already in the pool.  If so, return the
13512      existing label, otherwise leave P pointing to the place where the
13513      constant should be added.
13514
13515      Keep the pool sorted in increasing order of mode size so that we can
13516      reduce the number of alignments needed.  */
13517   first_of_size_p = true;
13518   for (p = &pool->first; *p != 0; p = &(*p)->next)
13519     {
13520       if (mode == (*p)->mode && rtx_equal_p (value, (*p)->value))
13521         return (*p)->label;
13522       if (GET_MODE_SIZE (mode) < GET_MODE_SIZE ((*p)->mode))
13523         break;
13524       if (GET_MODE_SIZE (mode) == GET_MODE_SIZE ((*p)->mode))
13525         first_of_size_p = false;
13526     }
13527
13528   /* In the worst case, the constant needed by the earliest instruction
13529      will end up at the end of the pool.  The entire pool must then be
13530      accessible from that instruction.
13531
13532      When adding the first constant, set the pool's highest address to
13533      the address of the first out-of-range byte.  Adjust this address
13534      downwards each time a new constant is added.  */
13535   if (pool->first == 0)
13536     /* For LWPC, ADDIUPC and DADDIUPC, the base PC value is the address
13537        of the instruction with the lowest two bits clear.  The base PC
13538        value for LDPC has the lowest three bits clear.  Assume the worst
13539        case here; namely that the PC-relative instruction occupies the
13540        last 2 bytes in an aligned word.  */
13541     pool->highest_address = pool->insn_address - (UNITS_PER_WORD - 2) + 0x8000;
13542   pool->highest_address -= GET_MODE_SIZE (mode);
13543   if (first_of_size_p)
13544     /* Take into account the worst possible padding due to alignment.  */
13545     pool->highest_address -= GET_MODE_SIZE (mode) - 1;
13546
13547   /* Create a new entry.  */
13548   c = XNEW (struct mips16_constant);
13549   c->value = value;
13550   c->mode = mode;
13551   c->label = gen_label_rtx ();
13552   c->next = *p;
13553   *p = c;
13554
13555   return c->label;
13556 }
13557
13558 /* Output constant VALUE after instruction INSN and return the last
13559    instruction emitted.  MODE is the mode of the constant.  */
13560
13561 static rtx
13562 mips16_emit_constants_1 (enum machine_mode mode, rtx value, rtx insn)
13563 {
13564   if (SCALAR_INT_MODE_P (mode) || ALL_SCALAR_FIXED_POINT_MODE_P (mode))
13565     {
13566       rtx size = GEN_INT (GET_MODE_SIZE (mode));
13567       return emit_insn_after (gen_consttable_int (value, size), insn);
13568     }
13569
13570   if (SCALAR_FLOAT_MODE_P (mode))
13571     return emit_insn_after (gen_consttable_float (value), insn);
13572
13573   if (VECTOR_MODE_P (mode))
13574     {
13575       int i;
13576
13577       for (i = 0; i < CONST_VECTOR_NUNITS (value); i++)
13578         insn = mips16_emit_constants_1 (GET_MODE_INNER (mode),
13579                                         CONST_VECTOR_ELT (value, i), insn);
13580       return insn;
13581     }
13582
13583   gcc_unreachable ();
13584 }
13585
13586 /* Dump out the constants in CONSTANTS after INSN.  */
13587
13588 static void
13589 mips16_emit_constants (struct mips16_constant *constants, rtx insn)
13590 {
13591   struct mips16_constant *c, *next;
13592   int align;
13593
13594   align = 0;
13595   for (c = constants; c != NULL; c = next)
13596     {
13597       /* If necessary, increase the alignment of PC.  */
13598       if (align < GET_MODE_SIZE (c->mode))
13599         {
13600           int align_log = floor_log2 (GET_MODE_SIZE (c->mode));
13601           insn = emit_insn_after (gen_align (GEN_INT (align_log)), insn);
13602         }
13603       align = GET_MODE_SIZE (c->mode);
13604
13605       insn = emit_label_after (c->label, insn);
13606       insn = mips16_emit_constants_1 (c->mode, c->value, insn);
13607
13608       next = c->next;
13609       free (c);
13610     }
13611
13612   emit_barrier_after (insn);
13613 }
13614
13615 /* Return the length of instruction INSN.  */
13616
13617 static int
13618 mips16_insn_length (rtx insn)
13619 {
13620   if (JUMP_P (insn))
13621     {
13622       rtx body = PATTERN (insn);
13623       if (GET_CODE (body) == ADDR_VEC)
13624         return GET_MODE_SIZE (GET_MODE (body)) * XVECLEN (body, 0);
13625       if (GET_CODE (body) == ADDR_DIFF_VEC)
13626         return GET_MODE_SIZE (GET_MODE (body)) * XVECLEN (body, 1);
13627     }
13628   return get_attr_length (insn);
13629 }
13630
13631 /* If *X is a symbolic constant that refers to the constant pool, add
13632    the constant to POOL and rewrite *X to use the constant's label.  */
13633
13634 static void
13635 mips16_rewrite_pool_constant (struct mips16_constant_pool *pool, rtx *x)
13636 {
13637   rtx base, offset, label;
13638
13639   split_const (*x, &base, &offset);
13640   if (GET_CODE (base) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (base))
13641     {
13642       label = mips16_add_constant (pool, get_pool_constant (base),
13643                                    get_pool_mode (base));
13644       base = gen_rtx_LABEL_REF (Pmode, label);
13645       *x = mips_unspec_address_offset (base, offset, SYMBOL_PC_RELATIVE);
13646     }
13647 }
13648
13649 /* This structure is used to communicate with mips16_rewrite_pool_refs.
13650    INSN is the instruction we're rewriting and POOL points to the current
13651    constant pool.  */
13652 struct mips16_rewrite_pool_refs_info {
13653   rtx insn;
13654   struct mips16_constant_pool *pool;
13655 };
13656
13657 /* Rewrite *X so that constant pool references refer to the constant's
13658    label instead.  DATA points to a mips16_rewrite_pool_refs_info
13659    structure.  */
13660
13661 static int
13662 mips16_rewrite_pool_refs (rtx *x, void *data)
13663 {
13664   struct mips16_rewrite_pool_refs_info *info =
13665     (struct mips16_rewrite_pool_refs_info *) data;
13666
13667   if (force_to_mem_operand (*x, Pmode))
13668     {
13669       rtx mem = force_const_mem (GET_MODE (*x), *x);
13670       validate_change (info->insn, x, mem, false);
13671     }
13672
13673   if (MEM_P (*x))
13674     {
13675       mips16_rewrite_pool_constant (info->pool, &XEXP (*x, 0));
13676       return -1;
13677     }
13678
13679   if (TARGET_MIPS16_TEXT_LOADS)
13680     mips16_rewrite_pool_constant (info->pool, x);
13681
13682   return GET_CODE (*x) == CONST ? -1 : 0;
13683 }
13684
13685 /* Return whether CFG is used in mips_reorg.  */
13686
13687 static bool
13688 mips_cfg_in_reorg (void)
13689 {
13690   return (mips_r10k_cache_barrier != R10K_CACHE_BARRIER_NONE
13691           || TARGET_RELAX_PIC_CALLS);
13692 }
13693
13694 /* Build MIPS16 constant pools.  */
13695
13696 static void
13697 mips16_lay_out_constants (void)
13698 {
13699   struct mips16_constant_pool pool;
13700   struct mips16_rewrite_pool_refs_info info;
13701   rtx insn, barrier;
13702
13703   if (!TARGET_MIPS16_PCREL_LOADS)
13704     return;
13705
13706   if (mips_cfg_in_reorg ())
13707     split_all_insns ();
13708   else
13709     split_all_insns_noflow ();
13710   barrier = 0;
13711   memset (&pool, 0, sizeof (pool));
13712   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
13713     {
13714       /* Rewrite constant pool references in INSN.  */
13715       if (USEFUL_INSN_P (insn))
13716         {
13717           info.insn = insn;
13718           info.pool = &pool;
13719           for_each_rtx (&PATTERN (insn), mips16_rewrite_pool_refs, &info);
13720         }
13721
13722       pool.insn_address += mips16_insn_length (insn);
13723
13724       if (pool.first != NULL)
13725         {
13726           /* If there are no natural barriers between the first user of
13727              the pool and the highest acceptable address, we'll need to
13728              create a new instruction to jump around the constant pool.
13729              In the worst case, this instruction will be 4 bytes long.
13730
13731              If it's too late to do this transformation after INSN,
13732              do it immediately before INSN.  */
13733           if (barrier == 0 && pool.insn_address + 4 > pool.highest_address)
13734             {
13735               rtx label, jump;
13736
13737               label = gen_label_rtx ();
13738
13739               jump = emit_jump_insn_before (gen_jump (label), insn);
13740               JUMP_LABEL (jump) = label;
13741               LABEL_NUSES (label) = 1;
13742               barrier = emit_barrier_after (jump);
13743
13744               emit_label_after (label, barrier);
13745               pool.insn_address += 4;
13746             }
13747
13748           /* See whether the constant pool is now out of range of the first
13749              user.  If so, output the constants after the previous barrier.
13750              Note that any instructions between BARRIER and INSN (inclusive)
13751              will use negative offsets to refer to the pool.  */
13752           if (pool.insn_address > pool.highest_address)
13753             {
13754               mips16_emit_constants (pool.first, barrier);
13755               pool.first = NULL;
13756               barrier = 0;
13757             }
13758           else if (BARRIER_P (insn))
13759             barrier = insn;
13760         }
13761     }
13762   mips16_emit_constants (pool.first, get_last_insn ());
13763 }
13764 \f
13765 /* Return true if it is worth r10k_simplify_address's while replacing
13766    an address with X.  We are looking for constants, and for addresses
13767    at a known offset from the incoming stack pointer.  */
13768
13769 static bool
13770 r10k_simplified_address_p (rtx x)
13771 {
13772   if (GET_CODE (x) == PLUS && CONST_INT_P (XEXP (x, 1)))
13773     x = XEXP (x, 0);
13774   return x == virtual_incoming_args_rtx || CONSTANT_P (x);
13775 }
13776
13777 /* X is an expression that appears in INSN.  Try to use the UD chains
13778    to simplify it, returning the simplified form on success and the
13779    original form otherwise.  Replace the incoming value of $sp with
13780    virtual_incoming_args_rtx (which should never occur in X otherwise).  */
13781
13782 static rtx
13783 r10k_simplify_address (rtx x, rtx insn)
13784 {
13785   rtx newx, op0, op1, set, def_insn, note;
13786   df_ref use, def;
13787   struct df_link *defs;
13788
13789   newx = NULL_RTX;
13790   if (UNARY_P (x))
13791     {
13792       op0 = r10k_simplify_address (XEXP (x, 0), insn);
13793       if (op0 != XEXP (x, 0))
13794         newx = simplify_gen_unary (GET_CODE (x), GET_MODE (x),
13795                                    op0, GET_MODE (XEXP (x, 0)));
13796     }
13797   else if (BINARY_P (x))
13798     {
13799       op0 = r10k_simplify_address (XEXP (x, 0), insn);
13800       op1 = r10k_simplify_address (XEXP (x, 1), insn);
13801       if (op0 != XEXP (x, 0) || op1 != XEXP (x, 1))
13802         newx = simplify_gen_binary (GET_CODE (x), GET_MODE (x), op0, op1);
13803     }
13804   else if (GET_CODE (x) == LO_SUM)
13805     {
13806       /* LO_SUMs can be offset from HIGHs, if we know they won't
13807          overflow.  See mips_classify_address for the rationale behind
13808          the lax check.  */
13809       op0 = r10k_simplify_address (XEXP (x, 0), insn);
13810       if (GET_CODE (op0) == HIGH)
13811         newx = XEXP (x, 1);
13812     }
13813   else if (REG_P (x))
13814     {
13815       /* Uses are recorded by regno_reg_rtx, not X itself.  */
13816       use = df_find_use (insn, regno_reg_rtx[REGNO (x)]);
13817       gcc_assert (use);
13818       defs = DF_REF_CHAIN (use);
13819
13820       /* Require a single definition.  */
13821       if (defs && defs->next == NULL)
13822         {
13823           def = defs->ref;
13824           if (DF_REF_IS_ARTIFICIAL (def))
13825             {
13826               /* Replace the incoming value of $sp with
13827                  virtual_incoming_args_rtx.  */
13828               if (x == stack_pointer_rtx
13829                   && DF_REF_BB (def) == ENTRY_BLOCK_PTR)
13830                 newx = virtual_incoming_args_rtx;
13831             }
13832           else if (dominated_by_p (CDI_DOMINATORS, DF_REF_BB (use),
13833                                    DF_REF_BB (def)))
13834             {
13835               /* Make sure that DEF_INSN is a single set of REG.  */
13836               def_insn = DF_REF_INSN (def);
13837               if (NONJUMP_INSN_P (def_insn))
13838                 {
13839                   set = single_set (def_insn);
13840                   if (set && rtx_equal_p (SET_DEST (set), x))
13841                     {
13842                       /* Prefer to use notes, since the def-use chains
13843                          are often shorter.  */
13844                       note = find_reg_equal_equiv_note (def_insn);
13845                       if (note)
13846                         newx = XEXP (note, 0);
13847                       else
13848                         newx = SET_SRC (set);
13849                       newx = r10k_simplify_address (newx, def_insn);
13850                     }
13851                 }
13852             }
13853         }
13854     }
13855   if (newx && r10k_simplified_address_p (newx))
13856     return newx;
13857   return x;
13858 }
13859
13860 /* Return true if ADDRESS is known to be an uncached address
13861    on R10K systems.  */
13862
13863 static bool
13864 r10k_uncached_address_p (unsigned HOST_WIDE_INT address)
13865 {
13866   unsigned HOST_WIDE_INT upper;
13867
13868   /* Check for KSEG1.  */
13869   if (address + 0x60000000 < 0x20000000)
13870     return true;
13871
13872   /* Check for uncached XKPHYS addresses.  */
13873   if (Pmode == DImode)
13874     {
13875       upper = (address >> 40) & 0xf9ffff;
13876       if (upper == 0x900000 || upper == 0xb80000)
13877         return true;
13878     }
13879   return false;
13880 }
13881
13882 /* Return true if we can prove that an access to address X in instruction
13883    INSN would be safe from R10K speculation.  This X is a general
13884    expression; it might not be a legitimate address.  */
13885
13886 static bool
13887 r10k_safe_address_p (rtx x, rtx insn)
13888 {
13889   rtx base, offset;
13890   HOST_WIDE_INT offset_val;
13891
13892   x = r10k_simplify_address (x, insn);
13893
13894   /* Check for references to the stack frame.  It doesn't really matter
13895      how much of the frame has been allocated at INSN; -mr10k-cache-barrier
13896      allows us to assume that accesses to any part of the eventual frame
13897      is safe from speculation at any point in the function.  */
13898   mips_split_plus (x, &base, &offset_val);
13899   if (base == virtual_incoming_args_rtx
13900       && offset_val >= -cfun->machine->frame.total_size
13901       && offset_val < cfun->machine->frame.args_size)
13902     return true;
13903
13904   /* Check for uncached addresses.  */
13905   if (CONST_INT_P (x))
13906     return r10k_uncached_address_p (INTVAL (x));
13907
13908   /* Check for accesses to a static object.  */
13909   split_const (x, &base, &offset);
13910   return offset_within_block_p (base, INTVAL (offset));
13911 }
13912
13913 /* Return true if a MEM with MEM_EXPR EXPR and MEM_OFFSET OFFSET is
13914    an in-range access to an automatic variable, or to an object with
13915    a link-time-constant address.  */
13916
13917 static bool
13918 r10k_safe_mem_expr_p (tree expr, rtx offset)
13919 {
13920   if (expr == NULL_TREE
13921       || offset == NULL_RTX
13922       || !CONST_INT_P (offset)
13923       || INTVAL (offset) < 0
13924       || INTVAL (offset) >= int_size_in_bytes (TREE_TYPE (expr)))
13925     return false;
13926
13927   while (TREE_CODE (expr) == COMPONENT_REF)
13928     {
13929       expr = TREE_OPERAND (expr, 0);
13930       if (expr == NULL_TREE)
13931         return false;
13932     }
13933
13934   return DECL_P (expr);
13935 }
13936
13937 /* A for_each_rtx callback for which DATA points to the instruction
13938    containing *X.  Stop the search if we find a MEM that is not safe
13939    from R10K speculation.  */
13940
13941 static int
13942 r10k_needs_protection_p_1 (rtx *loc, void *data)
13943 {
13944   rtx mem;
13945
13946   mem = *loc;
13947   if (!MEM_P (mem))
13948     return 0;
13949
13950   if (r10k_safe_mem_expr_p (MEM_EXPR (mem), MEM_OFFSET (mem)))
13951     return -1;
13952
13953   if (r10k_safe_address_p (XEXP (mem, 0), (rtx) data))
13954     return -1;
13955
13956   return 1;
13957 }
13958
13959 /* A note_stores callback for which DATA points to an instruction pointer.
13960    If *DATA is nonnull, make it null if it X contains a MEM that is not
13961    safe from R10K speculation.  */
13962
13963 static void
13964 r10k_needs_protection_p_store (rtx x, const_rtx pat ATTRIBUTE_UNUSED,
13965                                void *data)
13966 {
13967   rtx *insn_ptr;
13968
13969   insn_ptr = (rtx *) data;
13970   if (*insn_ptr && for_each_rtx (&x, r10k_needs_protection_p_1, *insn_ptr))
13971     *insn_ptr = NULL_RTX;
13972 }
13973
13974 /* A for_each_rtx callback that iterates over the pattern of a CALL_INSN.
13975    Return nonzero if the call is not to a declared function.  */
13976
13977 static int
13978 r10k_needs_protection_p_call (rtx *loc, void *data ATTRIBUTE_UNUSED)
13979 {
13980   rtx x;
13981
13982   x = *loc;
13983   if (!MEM_P (x))
13984     return 0;
13985
13986   x = XEXP (x, 0);
13987   if (GET_CODE (x) == SYMBOL_REF && SYMBOL_REF_DECL (x))
13988     return -1;
13989
13990   return 1;
13991 }
13992
13993 /* Return true if instruction INSN needs to be protected by an R10K
13994    cache barrier.  */
13995
13996 static bool
13997 r10k_needs_protection_p (rtx insn)
13998 {
13999   if (CALL_P (insn))
14000     return for_each_rtx (&PATTERN (insn), r10k_needs_protection_p_call, NULL);
14001
14002   if (mips_r10k_cache_barrier == R10K_CACHE_BARRIER_STORE)
14003     {
14004       note_stores (PATTERN (insn), r10k_needs_protection_p_store, &insn);
14005       return insn == NULL_RTX;
14006     }
14007
14008   return for_each_rtx (&PATTERN (insn), r10k_needs_protection_p_1, insn);
14009 }
14010
14011 /* Return true if BB is only reached by blocks in PROTECTED_BBS and if every
14012    edge is unconditional.  */
14013
14014 static bool
14015 r10k_protected_bb_p (basic_block bb, sbitmap protected_bbs)
14016 {
14017   edge_iterator ei;
14018   edge e;
14019
14020   FOR_EACH_EDGE (e, ei, bb->preds)
14021     if (!single_succ_p (e->src)
14022         || !TEST_BIT (protected_bbs, e->src->index)
14023         || (e->flags & EDGE_COMPLEX) != 0)
14024       return false;
14025   return true;
14026 }
14027
14028 /* Implement -mr10k-cache-barrier= for the current function.  */
14029
14030 static void
14031 r10k_insert_cache_barriers (void)
14032 {
14033   int *rev_post_order;
14034   unsigned int i, n;
14035   basic_block bb;
14036   sbitmap protected_bbs;
14037   rtx insn, end, unprotected_region;
14038
14039   if (TARGET_MIPS16)
14040     {
14041       sorry ("%qs does not support MIPS16 code", "-mr10k-cache-barrier");
14042       return;
14043     }
14044
14045   /* Calculate dominators.  */
14046   calculate_dominance_info (CDI_DOMINATORS);
14047
14048   /* Bit X of PROTECTED_BBS is set if the last operation in basic block
14049      X is protected by a cache barrier.  */
14050   protected_bbs = sbitmap_alloc (last_basic_block);
14051   sbitmap_zero (protected_bbs);
14052
14053   /* Iterate over the basic blocks in reverse post-order.  */
14054   rev_post_order = XNEWVEC (int, last_basic_block);
14055   n = pre_and_rev_post_order_compute (NULL, rev_post_order, false);
14056   for (i = 0; i < n; i++)
14057     {
14058       bb = BASIC_BLOCK (rev_post_order[i]);
14059
14060       /* If this block is only reached by unconditional edges, and if the
14061          source of every edge is protected, the beginning of the block is
14062          also protected.  */
14063       if (r10k_protected_bb_p (bb, protected_bbs))
14064         unprotected_region = NULL_RTX;
14065       else
14066         unprotected_region = pc_rtx;
14067       end = NEXT_INSN (BB_END (bb));
14068
14069       /* UNPROTECTED_REGION is:
14070
14071          - null if we are processing a protected region,
14072          - pc_rtx if we are processing an unprotected region but have
14073            not yet found the first instruction in it
14074          - the first instruction in an unprotected region otherwise.  */
14075       for (insn = BB_HEAD (bb); insn != end; insn = NEXT_INSN (insn))
14076         {
14077           if (unprotected_region && USEFUL_INSN_P (insn))
14078             {
14079               if (recog_memoized (insn) == CODE_FOR_mips_cache)
14080                 /* This CACHE instruction protects the following code.  */
14081                 unprotected_region = NULL_RTX;
14082               else
14083                 {
14084                   /* See if INSN is the first instruction in this
14085                      unprotected region.  */
14086                   if (unprotected_region == pc_rtx)
14087                     unprotected_region = insn;
14088
14089                   /* See if INSN needs to be protected.  If so,
14090                      we must insert a cache barrier somewhere between
14091                      PREV_INSN (UNPROTECTED_REGION) and INSN.  It isn't
14092                      clear which position is better performance-wise,
14093                      but as a tie-breaker, we assume that it is better
14094                      to allow delay slots to be back-filled where
14095                      possible, and that it is better not to insert
14096                      barriers in the middle of already-scheduled code.
14097                      We therefore insert the barrier at the beginning
14098                      of the region.  */
14099                   if (r10k_needs_protection_p (insn))
14100                     {
14101                       emit_insn_before (gen_r10k_cache_barrier (),
14102                                         unprotected_region);
14103                       unprotected_region = NULL_RTX;
14104                     }
14105                 }
14106             }
14107
14108           if (CALL_P (insn))
14109             /* The called function is not required to protect the exit path.
14110                The code that follows a call is therefore unprotected.  */
14111             unprotected_region = pc_rtx;
14112         }
14113
14114       /* Record whether the end of this block is protected.  */
14115       if (unprotected_region == NULL_RTX)
14116         SET_BIT (protected_bbs, bb->index);
14117     }
14118   XDELETEVEC (rev_post_order);
14119
14120   sbitmap_free (protected_bbs);
14121
14122   free_dominance_info (CDI_DOMINATORS);
14123 }
14124 \f
14125 /* If INSN is a call, return the underlying CALL expr.  Return NULL_RTX
14126    otherwise.  If INSN has two call rtx, then store the second one in
14127    SECOND_CALL.  */
14128
14129 static rtx
14130 mips_call_expr_from_insn (rtx insn, rtx *second_call)
14131 {
14132   rtx x;
14133   rtx x2;
14134
14135   if (!CALL_P (insn))
14136     return NULL_RTX;
14137
14138   x = PATTERN (insn);
14139   if (GET_CODE (x) == PARALLEL)
14140     {
14141       /* Calls returning complex values have two CALL rtx.  Look for the second
14142          one here, and return it via the SECOND_CALL arg.  */
14143       x2 = XVECEXP (x, 0, 1);
14144       if (GET_CODE (x2) == SET)
14145         x2 = XEXP (x2, 1);
14146       if (GET_CODE (x2) == CALL)
14147         *second_call = x2;
14148
14149       x = XVECEXP (x, 0, 0);
14150     }
14151   if (GET_CODE (x) == SET)
14152     x = XEXP (x, 1);
14153   gcc_assert (GET_CODE (x) == CALL);
14154
14155   return x;
14156 }
14157
14158 /* REG is set in DEF.  See if the definition is one of the ways we load a
14159    register with a symbol address for a mips_use_pic_fn_addr_reg_p call.  If
14160    it is return the symbol reference of the function, otherwise return
14161    NULL_RTX.  */
14162
14163 static rtx
14164 mips_pic_call_symbol_from_set (df_ref def, rtx reg)
14165 {
14166   rtx def_insn, set;
14167
14168   if (DF_REF_IS_ARTIFICIAL (def))
14169     return NULL_RTX;
14170
14171   def_insn = DF_REF_INSN (def);
14172   set = single_set (def_insn);
14173   if (set && rtx_equal_p (SET_DEST (set), reg))
14174     {
14175       rtx note, src, symbol;
14176
14177       /* First, look at REG_EQUAL/EQUIV notes.  */
14178       note = find_reg_equal_equiv_note (def_insn);
14179       if (note && GET_CODE (XEXP (note, 0)) == SYMBOL_REF)
14180         return XEXP (note, 0);
14181
14182       /* For %call16 references we don't have REG_EQUAL.  */
14183       src = SET_SRC (set);
14184       symbol = mips_strip_unspec_call (src);
14185       if (symbol)
14186         {
14187           gcc_assert (GET_CODE (symbol) == SYMBOL_REF);
14188           return symbol;
14189         }
14190
14191       /* Follow simple register copies.  */
14192       if (REG_P (src))
14193         return mips_find_pic_call_symbol (def_insn, src);
14194     }
14195
14196   return NULL_RTX;
14197 }
14198
14199 /* Find the definition of the use of REG in INSN.  See if the definition is
14200    one of the ways we load a register with a symbol address for a
14201    mips_use_pic_fn_addr_reg_p call.  If it is return the symbol reference of
14202    the function, otherwise return NULL_RTX.  */
14203
14204 static rtx
14205 mips_find_pic_call_symbol (rtx insn, rtx reg)
14206 {
14207   df_ref use;
14208   struct df_link *defs;
14209   rtx symbol;
14210
14211   use = df_find_use (insn, regno_reg_rtx[REGNO (reg)]);
14212   if (!use)
14213     return NULL_RTX;
14214   defs = DF_REF_CHAIN (use);
14215   if (!defs)
14216     return NULL_RTX;
14217   symbol = mips_pic_call_symbol_from_set (defs->ref, reg);
14218   if (!symbol)
14219     return NULL_RTX;
14220
14221   /* If we have more than one definition, they need to be identical.  */
14222   for (defs = defs->next; defs; defs = defs->next)
14223     {
14224       rtx other;
14225
14226       other = mips_pic_call_symbol_from_set (defs->ref, reg);
14227       if (!rtx_equal_p (symbol, other))
14228         return NULL_RTX;
14229     }
14230
14231   return symbol;
14232 }
14233
14234 /* Replace the args_size operand of the call expression CALL with the
14235    call-attribute UNSPEC and fill in SYMBOL as the function symbol.  */
14236
14237 static void
14238 mips_annotate_pic_call_expr (rtx call, rtx symbol)
14239 {
14240   rtx args_size;
14241
14242   args_size = XEXP (call, 1);
14243   XEXP (call, 1) = gen_rtx_UNSPEC (GET_MODE (args_size),
14244                                    gen_rtvec (2, args_size, symbol),
14245                                    UNSPEC_CALL_ATTR);
14246 }
14247
14248 /* OPERANDS[ARGS_SIZE_OPNO] is the arg_size operand of a CALL expression.  See
14249    if instead of the arg_size argument it contains the call attributes.  If
14250    yes return true along with setting OPERANDS[ARGS_SIZE_OPNO] to the function
14251    symbol from the call attributes.  Also return false if ARGS_SIZE_OPNO is
14252    -1.  */
14253
14254 bool
14255 mips_get_pic_call_symbol (rtx *operands, int args_size_opno)
14256 {
14257   rtx args_size, symbol;
14258
14259   if (!TARGET_RELAX_PIC_CALLS || args_size_opno == -1)
14260     return false;
14261
14262   args_size = operands[args_size_opno];
14263   if (GET_CODE (args_size) != UNSPEC)
14264     return false;
14265   gcc_assert (XINT (args_size, 1) == UNSPEC_CALL_ATTR);
14266
14267   symbol = XVECEXP (args_size, 0, 1);
14268   gcc_assert (GET_CODE (symbol) == SYMBOL_REF);
14269
14270   operands[args_size_opno] = symbol;
14271   return true;
14272 }
14273
14274 /* Use DF to annotate PIC indirect calls with the function symbol they
14275    dispatch to.  */
14276
14277 static void
14278 mips_annotate_pic_calls (void)
14279 {
14280   basic_block bb;
14281   rtx insn;
14282
14283   FOR_EACH_BB (bb)
14284     FOR_BB_INSNS (bb, insn)
14285     {
14286       rtx call, reg, symbol, second_call;
14287
14288       second_call = 0;
14289       call = mips_call_expr_from_insn (insn, &second_call);
14290       if (!call)
14291         continue;
14292       gcc_assert (MEM_P (XEXP (call, 0)));
14293       reg = XEXP (XEXP (call, 0), 0);
14294       if (!REG_P (reg))
14295         continue;
14296
14297       symbol = mips_find_pic_call_symbol (insn, reg);
14298       if (symbol)
14299         {
14300           mips_annotate_pic_call_expr (call, symbol);
14301           if (second_call)
14302             mips_annotate_pic_call_expr (second_call, symbol);
14303         }
14304     }
14305 }
14306 \f
14307 /* A temporary variable used by for_each_rtx callbacks, etc.  */
14308 static rtx mips_sim_insn;
14309
14310 /* A structure representing the state of the processor pipeline.
14311    Used by the mips_sim_* family of functions.  */
14312 struct mips_sim {
14313   /* The maximum number of instructions that can be issued in a cycle.
14314      (Caches mips_issue_rate.)  */
14315   unsigned int issue_rate;
14316
14317   /* The current simulation time.  */
14318   unsigned int time;
14319
14320   /* How many more instructions can be issued in the current cycle.  */
14321   unsigned int insns_left;
14322
14323   /* LAST_SET[X].INSN is the last instruction to set register X.
14324      LAST_SET[X].TIME is the time at which that instruction was issued.
14325      INSN is null if no instruction has yet set register X.  */
14326   struct {
14327     rtx insn;
14328     unsigned int time;
14329   } last_set[FIRST_PSEUDO_REGISTER];
14330
14331   /* The pipeline's current DFA state.  */
14332   state_t dfa_state;
14333 };
14334
14335 /* Reset STATE to the initial simulation state.  */
14336
14337 static void
14338 mips_sim_reset (struct mips_sim *state)
14339 {
14340   state->time = 0;
14341   state->insns_left = state->issue_rate;
14342   memset (&state->last_set, 0, sizeof (state->last_set));
14343   state_reset (state->dfa_state);
14344 }
14345
14346 /* Initialize STATE before its first use.  DFA_STATE points to an
14347    allocated but uninitialized DFA state.  */
14348
14349 static void
14350 mips_sim_init (struct mips_sim *state, state_t dfa_state)
14351 {
14352   state->issue_rate = mips_issue_rate ();
14353   state->dfa_state = dfa_state;
14354   mips_sim_reset (state);
14355 }
14356
14357 /* Advance STATE by one clock cycle.  */
14358
14359 static void
14360 mips_sim_next_cycle (struct mips_sim *state)
14361 {
14362   state->time++;
14363   state->insns_left = state->issue_rate;
14364   state_transition (state->dfa_state, 0);
14365 }
14366
14367 /* Advance simulation state STATE until instruction INSN can read
14368    register REG.  */
14369
14370 static void
14371 mips_sim_wait_reg (struct mips_sim *state, rtx insn, rtx reg)
14372 {
14373   unsigned int regno, end_regno;
14374
14375   end_regno = END_REGNO (reg);
14376   for (regno = REGNO (reg); regno < end_regno; regno++)
14377     if (state->last_set[regno].insn != 0)
14378       {
14379         unsigned int t;
14380
14381         t = (state->last_set[regno].time
14382              + insn_latency (state->last_set[regno].insn, insn));
14383         while (state->time < t)
14384           mips_sim_next_cycle (state);
14385     }
14386 }
14387
14388 /* A for_each_rtx callback.  If *X is a register, advance simulation state
14389    DATA until mips_sim_insn can read the register's value.  */
14390
14391 static int
14392 mips_sim_wait_regs_2 (rtx *x, void *data)
14393 {
14394   if (REG_P (*x))
14395     mips_sim_wait_reg ((struct mips_sim *) data, mips_sim_insn, *x);
14396   return 0;
14397 }
14398
14399 /* Call mips_sim_wait_regs_2 (R, DATA) for each register R mentioned in *X.  */
14400
14401 static void
14402 mips_sim_wait_regs_1 (rtx *x, void *data)
14403 {
14404   for_each_rtx (x, mips_sim_wait_regs_2, data);
14405 }
14406
14407 /* Advance simulation state STATE until all of INSN's register
14408    dependencies are satisfied.  */
14409
14410 static void
14411 mips_sim_wait_regs (struct mips_sim *state, rtx insn)
14412 {
14413   mips_sim_insn = insn;
14414   note_uses (&PATTERN (insn), mips_sim_wait_regs_1, state);
14415 }
14416
14417 /* Advance simulation state STATE until the units required by
14418    instruction INSN are available.  */
14419
14420 static void
14421 mips_sim_wait_units (struct mips_sim *state, rtx insn)
14422 {
14423   state_t tmp_state;
14424
14425   tmp_state = alloca (state_size ());
14426   while (state->insns_left == 0
14427          || (memcpy (tmp_state, state->dfa_state, state_size ()),
14428              state_transition (tmp_state, insn) >= 0))
14429     mips_sim_next_cycle (state);
14430 }
14431
14432 /* Advance simulation state STATE until INSN is ready to issue.  */
14433
14434 static void
14435 mips_sim_wait_insn (struct mips_sim *state, rtx insn)
14436 {
14437   mips_sim_wait_regs (state, insn);
14438   mips_sim_wait_units (state, insn);
14439 }
14440
14441 /* mips_sim_insn has just set X.  Update the LAST_SET array
14442    in simulation state DATA.  */
14443
14444 static void
14445 mips_sim_record_set (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
14446 {
14447   struct mips_sim *state;
14448
14449   state = (struct mips_sim *) data;
14450   if (REG_P (x))
14451     {
14452       unsigned int regno, end_regno;
14453
14454       end_regno = END_REGNO (x);
14455       for (regno = REGNO (x); regno < end_regno; regno++)
14456         {
14457           state->last_set[regno].insn = mips_sim_insn;
14458           state->last_set[regno].time = state->time;
14459         }
14460     }
14461 }
14462
14463 /* Issue instruction INSN in scheduler state STATE.  Assume that INSN
14464    can issue immediately (i.e., that mips_sim_wait_insn has already
14465    been called).  */
14466
14467 static void
14468 mips_sim_issue_insn (struct mips_sim *state, rtx insn)
14469 {
14470   state_transition (state->dfa_state, insn);
14471   state->insns_left--;
14472
14473   mips_sim_insn = insn;
14474   note_stores (PATTERN (insn), mips_sim_record_set, state);
14475 }
14476
14477 /* Simulate issuing a NOP in state STATE.  */
14478
14479 static void
14480 mips_sim_issue_nop (struct mips_sim *state)
14481 {
14482   if (state->insns_left == 0)
14483     mips_sim_next_cycle (state);
14484   state->insns_left--;
14485 }
14486
14487 /* Update simulation state STATE so that it's ready to accept the instruction
14488    after INSN.  INSN should be part of the main rtl chain, not a member of a
14489    SEQUENCE.  */
14490
14491 static void
14492 mips_sim_finish_insn (struct mips_sim *state, rtx insn)
14493 {
14494   /* If INSN is a jump with an implicit delay slot, simulate a nop.  */
14495   if (JUMP_P (insn))
14496     mips_sim_issue_nop (state);
14497
14498   switch (GET_CODE (SEQ_BEGIN (insn)))
14499     {
14500     case CODE_LABEL:
14501     case CALL_INSN:
14502       /* We can't predict the processor state after a call or label.  */
14503       mips_sim_reset (state);
14504       break;
14505
14506     case JUMP_INSN:
14507       /* The delay slots of branch likely instructions are only executed
14508          when the branch is taken.  Therefore, if the caller has simulated
14509          the delay slot instruction, STATE does not really reflect the state
14510          of the pipeline for the instruction after the delay slot.  Also,
14511          branch likely instructions tend to incur a penalty when not taken,
14512          so there will probably be an extra delay between the branch and
14513          the instruction after the delay slot.  */
14514       if (INSN_ANNULLED_BRANCH_P (SEQ_BEGIN (insn)))
14515         mips_sim_reset (state);
14516       break;
14517
14518     default:
14519       break;
14520     }
14521 }
14522 \f
14523 /* The VR4130 pipeline issues aligned pairs of instructions together,
14524    but it stalls the second instruction if it depends on the first.
14525    In order to cut down the amount of logic required, this dependence
14526    check is not based on a full instruction decode.  Instead, any non-SPECIAL
14527    instruction is assumed to modify the register specified by bits 20-16
14528    (which is usually the "rt" field).
14529
14530    In BEQ, BEQL, BNE and BNEL instructions, the rt field is actually an
14531    input, so we can end up with a false dependence between the branch
14532    and its delay slot.  If this situation occurs in instruction INSN,
14533    try to avoid it by swapping rs and rt.  */
14534
14535 static void
14536 vr4130_avoid_branch_rt_conflict (rtx insn)
14537 {
14538   rtx first, second;
14539
14540   first = SEQ_BEGIN (insn);
14541   second = SEQ_END (insn);
14542   if (JUMP_P (first)
14543       && NONJUMP_INSN_P (second)
14544       && GET_CODE (PATTERN (first)) == SET
14545       && GET_CODE (SET_DEST (PATTERN (first))) == PC
14546       && GET_CODE (SET_SRC (PATTERN (first))) == IF_THEN_ELSE)
14547     {
14548       /* Check for the right kind of condition.  */
14549       rtx cond = XEXP (SET_SRC (PATTERN (first)), 0);
14550       if ((GET_CODE (cond) == EQ || GET_CODE (cond) == NE)
14551           && REG_P (XEXP (cond, 0))
14552           && REG_P (XEXP (cond, 1))
14553           && reg_referenced_p (XEXP (cond, 1), PATTERN (second))
14554           && !reg_referenced_p (XEXP (cond, 0), PATTERN (second)))
14555         {
14556           /* SECOND mentions the rt register but not the rs register.  */
14557           rtx tmp = XEXP (cond, 0);
14558           XEXP (cond, 0) = XEXP (cond, 1);
14559           XEXP (cond, 1) = tmp;
14560         }
14561     }
14562 }
14563
14564 /* Implement -mvr4130-align.  Go through each basic block and simulate the
14565    processor pipeline.  If we find that a pair of instructions could execute
14566    in parallel, and the first of those instructions is not 8-byte aligned,
14567    insert a nop to make it aligned.  */
14568
14569 static void
14570 vr4130_align_insns (void)
14571 {
14572   struct mips_sim state;
14573   rtx insn, subinsn, last, last2, next;
14574   bool aligned_p;
14575
14576   dfa_start ();
14577
14578   /* LAST is the last instruction before INSN to have a nonzero length.
14579      LAST2 is the last such instruction before LAST.  */
14580   last = 0;
14581   last2 = 0;
14582
14583   /* ALIGNED_P is true if INSN is known to be at an aligned address.  */
14584   aligned_p = true;
14585
14586   mips_sim_init (&state, alloca (state_size ()));
14587   for (insn = get_insns (); insn != 0; insn = next)
14588     {
14589       unsigned int length;
14590
14591       next = NEXT_INSN (insn);
14592
14593       /* See the comment above vr4130_avoid_branch_rt_conflict for details.
14594          This isn't really related to the alignment pass, but we do it on
14595          the fly to avoid a separate instruction walk.  */
14596       vr4130_avoid_branch_rt_conflict (insn);
14597
14598       if (USEFUL_INSN_P (insn))
14599         FOR_EACH_SUBINSN (subinsn, insn)
14600           {
14601             mips_sim_wait_insn (&state, subinsn);
14602
14603             /* If we want this instruction to issue in parallel with the
14604                previous one, make sure that the previous instruction is
14605                aligned.  There are several reasons why this isn't worthwhile
14606                when the second instruction is a call:
14607
14608                   - Calls are less likely to be performance critical,
14609                   - There's a good chance that the delay slot can execute
14610                     in parallel with the call.
14611                   - The return address would then be unaligned.
14612
14613                In general, if we're going to insert a nop between instructions
14614                X and Y, it's better to insert it immediately after X.  That
14615                way, if the nop makes Y aligned, it will also align any labels
14616                between X and Y.  */
14617             if (state.insns_left != state.issue_rate
14618                 && !CALL_P (subinsn))
14619               {
14620                 if (subinsn == SEQ_BEGIN (insn) && aligned_p)
14621                   {
14622                     /* SUBINSN is the first instruction in INSN and INSN is
14623                        aligned.  We want to align the previous instruction
14624                        instead, so insert a nop between LAST2 and LAST.
14625
14626                        Note that LAST could be either a single instruction
14627                        or a branch with a delay slot.  In the latter case,
14628                        LAST, like INSN, is already aligned, but the delay
14629                        slot must have some extra delay that stops it from
14630                        issuing at the same time as the branch.  We therefore
14631                        insert a nop before the branch in order to align its
14632                        delay slot.  */
14633                     emit_insn_after (gen_nop (), last2);
14634                     aligned_p = false;
14635                   }
14636                 else if (subinsn != SEQ_BEGIN (insn) && !aligned_p)
14637                   {
14638                     /* SUBINSN is the delay slot of INSN, but INSN is
14639                        currently unaligned.  Insert a nop between
14640                        LAST and INSN to align it.  */
14641                     emit_insn_after (gen_nop (), last);
14642                     aligned_p = true;
14643                   }
14644               }
14645             mips_sim_issue_insn (&state, subinsn);
14646           }
14647       mips_sim_finish_insn (&state, insn);
14648
14649       /* Update LAST, LAST2 and ALIGNED_P for the next instruction.  */
14650       length = get_attr_length (insn);
14651       if (length > 0)
14652         {
14653           /* If the instruction is an asm statement or multi-instruction
14654              mips.md patern, the length is only an estimate.  Insert an
14655              8 byte alignment after it so that the following instructions
14656              can be handled correctly.  */
14657           if (NONJUMP_INSN_P (SEQ_BEGIN (insn))
14658               && (recog_memoized (insn) < 0 || length >= 8))
14659             {
14660               next = emit_insn_after (gen_align (GEN_INT (3)), insn);
14661               next = NEXT_INSN (next);
14662               mips_sim_next_cycle (&state);
14663               aligned_p = true;
14664             }
14665           else if (length & 4)
14666             aligned_p = !aligned_p;
14667           last2 = last;
14668           last = insn;
14669         }
14670
14671       /* See whether INSN is an aligned label.  */
14672       if (LABEL_P (insn) && label_to_alignment (insn) >= 3)
14673         aligned_p = true;
14674     }
14675   dfa_finish ();
14676 }
14677 \f
14678 /* This structure records that the current function has a LO_SUM
14679    involving SYMBOL_REF or LABEL_REF BASE and that MAX_OFFSET is
14680    the largest offset applied to BASE by all such LO_SUMs.  */
14681 struct mips_lo_sum_offset {
14682   rtx base;
14683   HOST_WIDE_INT offset;
14684 };
14685
14686 /* Return a hash value for SYMBOL_REF or LABEL_REF BASE.  */
14687
14688 static hashval_t
14689 mips_hash_base (rtx base)
14690 {
14691   int do_not_record_p;
14692
14693   return hash_rtx (base, GET_MODE (base), &do_not_record_p, NULL, false);
14694 }
14695
14696 /* Hash-table callbacks for mips_lo_sum_offsets.  */
14697
14698 static hashval_t
14699 mips_lo_sum_offset_hash (const void *entry)
14700 {
14701   return mips_hash_base (((const struct mips_lo_sum_offset *) entry)->base);
14702 }
14703
14704 static int
14705 mips_lo_sum_offset_eq (const void *entry, const void *value)
14706 {
14707   return rtx_equal_p (((const struct mips_lo_sum_offset *) entry)->base,
14708                       (const_rtx) value);
14709 }
14710
14711 /* Look up symbolic constant X in HTAB, which is a hash table of
14712    mips_lo_sum_offsets.  If OPTION is NO_INSERT, return true if X can be
14713    paired with a recorded LO_SUM, otherwise record X in the table.  */
14714
14715 static bool
14716 mips_lo_sum_offset_lookup (htab_t htab, rtx x, enum insert_option option)
14717 {
14718   rtx base, offset;
14719   void **slot;
14720   struct mips_lo_sum_offset *entry;
14721
14722   /* Split X into a base and offset.  */
14723   split_const (x, &base, &offset);
14724   if (UNSPEC_ADDRESS_P (base))
14725     base = UNSPEC_ADDRESS (base);
14726
14727   /* Look up the base in the hash table.  */
14728   slot = htab_find_slot_with_hash (htab, base, mips_hash_base (base), option);
14729   if (slot == NULL)
14730     return false;
14731
14732   entry = (struct mips_lo_sum_offset *) *slot;
14733   if (option == INSERT)
14734     {
14735       if (entry == NULL)
14736         {
14737           entry = XNEW (struct mips_lo_sum_offset);
14738           entry->base = base;
14739           entry->offset = INTVAL (offset);
14740           *slot = entry;
14741         }
14742       else
14743         {
14744           if (INTVAL (offset) > entry->offset)
14745             entry->offset = INTVAL (offset);
14746         }
14747     }
14748   return INTVAL (offset) <= entry->offset;
14749 }
14750
14751 /* A for_each_rtx callback for which DATA is a mips_lo_sum_offset hash table.
14752    Record every LO_SUM in *LOC.  */
14753
14754 static int
14755 mips_record_lo_sum (rtx *loc, void *data)
14756 {
14757   if (GET_CODE (*loc) == LO_SUM)
14758     mips_lo_sum_offset_lookup ((htab_t) data, XEXP (*loc, 1), INSERT);
14759   return 0;
14760 }
14761
14762 /* Return true if INSN is a SET of an orphaned high-part relocation.
14763    HTAB is a hash table of mips_lo_sum_offsets that describes all the
14764    LO_SUMs in the current function.  */
14765
14766 static bool
14767 mips_orphaned_high_part_p (htab_t htab, rtx insn)
14768 {
14769   enum mips_symbol_type type;
14770   rtx x, set;
14771
14772   set = single_set (insn);
14773   if (set)
14774     {
14775       /* Check for %his.  */
14776       x = SET_SRC (set);
14777       if (GET_CODE (x) == HIGH
14778           && absolute_symbolic_operand (XEXP (x, 0), VOIDmode))
14779         return !mips_lo_sum_offset_lookup (htab, XEXP (x, 0), NO_INSERT);
14780
14781       /* Check for local %gots (and %got_pages, which is redundant but OK).  */
14782       if (GET_CODE (x) == UNSPEC
14783           && XINT (x, 1) == UNSPEC_LOAD_GOT
14784           && mips_symbolic_constant_p (XVECEXP (x, 0, 1),
14785                                        SYMBOL_CONTEXT_LEA, &type)
14786           && type == SYMBOL_GOTOFF_PAGE)
14787         return !mips_lo_sum_offset_lookup (htab, XVECEXP (x, 0, 1), NO_INSERT);
14788     }
14789   return false;
14790 }
14791
14792 /* Subroutine of mips_reorg_process_insns.  If there is a hazard between
14793    INSN and a previous instruction, avoid it by inserting nops after
14794    instruction AFTER.
14795
14796    *DELAYED_REG and *HILO_DELAY describe the hazards that apply at
14797    this point.  If *DELAYED_REG is non-null, INSN must wait a cycle
14798    before using the value of that register.  *HILO_DELAY counts the
14799    number of instructions since the last hilo hazard (that is,
14800    the number of instructions since the last MFLO or MFHI).
14801
14802    After inserting nops for INSN, update *DELAYED_REG and *HILO_DELAY
14803    for the next instruction.
14804
14805    LO_REG is an rtx for the LO register, used in dependence checking.  */
14806
14807 static void
14808 mips_avoid_hazard (rtx after, rtx insn, int *hilo_delay,
14809                    rtx *delayed_reg, rtx lo_reg)
14810 {
14811   rtx pattern, set;
14812   int nops, ninsns;
14813
14814   pattern = PATTERN (insn);
14815
14816   /* Do not put the whole function in .set noreorder if it contains
14817      an asm statement.  We don't know whether there will be hazards
14818      between the asm statement and the gcc-generated code.  */
14819   if (GET_CODE (pattern) == ASM_INPUT || asm_noperands (pattern) >= 0)
14820     cfun->machine->all_noreorder_p = false;
14821
14822   /* Ignore zero-length instructions (barriers and the like).  */
14823   ninsns = get_attr_length (insn) / 4;
14824   if (ninsns == 0)
14825     return;
14826
14827   /* Work out how many nops are needed.  Note that we only care about
14828      registers that are explicitly mentioned in the instruction's pattern.
14829      It doesn't matter that calls use the argument registers or that they
14830      clobber hi and lo.  */
14831   if (*hilo_delay < 2 && reg_set_p (lo_reg, pattern))
14832     nops = 2 - *hilo_delay;
14833   else if (*delayed_reg != 0 && reg_referenced_p (*delayed_reg, pattern))
14834     nops = 1;
14835   else
14836     nops = 0;
14837
14838   /* Insert the nops between this instruction and the previous one.
14839      Each new nop takes us further from the last hilo hazard.  */
14840   *hilo_delay += nops;
14841   while (nops-- > 0)
14842     emit_insn_after (gen_hazard_nop (), after);
14843
14844   /* Set up the state for the next instruction.  */
14845   *hilo_delay += ninsns;
14846   *delayed_reg = 0;
14847   if (INSN_CODE (insn) >= 0)
14848     switch (get_attr_hazard (insn))
14849       {
14850       case HAZARD_NONE:
14851         break;
14852
14853       case HAZARD_HILO:
14854         *hilo_delay = 0;
14855         break;
14856
14857       case HAZARD_DELAY:
14858         set = single_set (insn);
14859         gcc_assert (set);
14860         *delayed_reg = SET_DEST (set);
14861         break;
14862       }
14863 }
14864
14865 /* Go through the instruction stream and insert nops where necessary.
14866    Also delete any high-part relocations whose partnering low parts
14867    are now all dead.  See if the whole function can then be put into
14868    .set noreorder and .set nomacro.  */
14869
14870 static void
14871 mips_reorg_process_insns (void)
14872 {
14873   rtx insn, last_insn, subinsn, next_insn, lo_reg, delayed_reg;
14874   int hilo_delay;
14875   htab_t htab;
14876
14877   /* Force all instructions to be split into their final form.  */
14878   split_all_insns_noflow ();
14879
14880   /* Recalculate instruction lengths without taking nops into account.  */
14881   cfun->machine->ignore_hazard_length_p = true;
14882   shorten_branches (get_insns ());
14883
14884   cfun->machine->all_noreorder_p = true;
14885
14886   /* We don't track MIPS16 PC-relative offsets closely enough to make
14887      a good job of "set .noreorder" code in MIPS16 mode.  */
14888   if (TARGET_MIPS16)
14889     cfun->machine->all_noreorder_p = false;
14890
14891   /* Code that doesn't use explicit relocs can't be ".set nomacro".  */
14892   if (!TARGET_EXPLICIT_RELOCS)
14893     cfun->machine->all_noreorder_p = false;
14894
14895   /* Profiled functions can't be all noreorder because the profiler
14896      support uses assembler macros.  */
14897   if (crtl->profile)
14898     cfun->machine->all_noreorder_p = false;
14899
14900   /* Code compiled with -mfix-vr4120 can't be all noreorder because
14901      we rely on the assembler to work around some errata.  */
14902   if (TARGET_FIX_VR4120)
14903     cfun->machine->all_noreorder_p = false;
14904
14905   /* The same is true for -mfix-vr4130 if we might generate MFLO or
14906      MFHI instructions.  Note that we avoid using MFLO and MFHI if
14907      the VR4130 MACC and DMACC instructions are available instead;
14908      see the *mfhilo_{si,di}_macc patterns.  */
14909   if (TARGET_FIX_VR4130 && !ISA_HAS_MACCHI)
14910     cfun->machine->all_noreorder_p = false;
14911
14912   htab = htab_create (37, mips_lo_sum_offset_hash,
14913                       mips_lo_sum_offset_eq, free);
14914
14915   /* Make a first pass over the instructions, recording all the LO_SUMs.  */
14916   for (insn = get_insns (); insn != 0; insn = NEXT_INSN (insn))
14917     FOR_EACH_SUBINSN (subinsn, insn)
14918       if (USEFUL_INSN_P (subinsn))
14919         for_each_rtx (&PATTERN (subinsn), mips_record_lo_sum, htab);
14920
14921   last_insn = 0;
14922   hilo_delay = 2;
14923   delayed_reg = 0;
14924   lo_reg = gen_rtx_REG (SImode, LO_REGNUM);
14925
14926   /* Make a second pass over the instructions.  Delete orphaned
14927      high-part relocations or turn them into NOPs.  Avoid hazards
14928      by inserting NOPs.  */
14929   for (insn = get_insns (); insn != 0; insn = next_insn)
14930     {
14931       next_insn = NEXT_INSN (insn);
14932       if (USEFUL_INSN_P (insn))
14933         {
14934           if (GET_CODE (PATTERN (insn)) == SEQUENCE)
14935             {
14936               /* If we find an orphaned high-part relocation in a delay
14937                  slot, it's easier to turn that instruction into a NOP than
14938                  to delete it.  The delay slot will be a NOP either way.  */
14939               FOR_EACH_SUBINSN (subinsn, insn)
14940                 if (INSN_P (subinsn))
14941                   {
14942                     if (mips_orphaned_high_part_p (htab, subinsn))
14943                       {
14944                         PATTERN (subinsn) = gen_nop ();
14945                         INSN_CODE (subinsn) = CODE_FOR_nop;
14946                       }
14947                     mips_avoid_hazard (last_insn, subinsn, &hilo_delay,
14948                                        &delayed_reg, lo_reg);
14949                   }
14950               last_insn = insn;
14951             }
14952           else
14953             {
14954               /* INSN is a single instruction.  Delete it if it's an
14955                  orphaned high-part relocation.  */
14956               if (mips_orphaned_high_part_p (htab, insn))
14957                 delete_insn (insn);
14958               /* Also delete cache barriers if the last instruction
14959                  was an annulled branch.  INSN will not be speculatively
14960                  executed.  */
14961               else if (recog_memoized (insn) == CODE_FOR_r10k_cache_barrier
14962                        && last_insn
14963                        && INSN_ANNULLED_BRANCH_P (SEQ_BEGIN (last_insn)))
14964                 delete_insn (insn);
14965               else
14966                 {
14967                   mips_avoid_hazard (last_insn, insn, &hilo_delay,
14968                                      &delayed_reg, lo_reg);
14969                   last_insn = insn;
14970                 }
14971             }
14972         }
14973     }
14974
14975   htab_delete (htab);
14976 }
14977
14978 /* If we are using a GOT, but have not decided to use a global pointer yet,
14979    see whether we need one to implement long branches.  Convert the ghost
14980    global-pointer instructions into real ones if so.  */
14981
14982 static bool
14983 mips_expand_ghost_gp_insns (void)
14984 {
14985   rtx insn;
14986   int normal_length;
14987
14988   /* Quick exit if we already know that we will or won't need a
14989      global pointer.  */
14990   if (!TARGET_USE_GOT
14991       || cfun->machine->global_pointer == INVALID_REGNUM
14992       || mips_must_initialize_gp_p ())
14993     return false;
14994
14995   shorten_branches (get_insns ());
14996
14997   /* Look for a branch that is longer than normal.  The normal length for
14998      non-MIPS16 branches is 8, because the length includes the delay slot.
14999      It is 4 for MIPS16, because MIPS16 branches are extended instructions,
15000      but they have no delay slot.  */
15001   normal_length = (TARGET_MIPS16 ? 4 : 8);
15002   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
15003     if (JUMP_P (insn)
15004         && USEFUL_INSN_P (insn)
15005         && get_attr_length (insn) > normal_length)
15006       break;
15007
15008   if (insn == NULL_RTX)
15009     return false;
15010
15011   /* We've now established that we need $gp.  */
15012   cfun->machine->must_initialize_gp_p = true;
15013   split_all_insns_noflow ();
15014
15015   return true;
15016 }
15017
15018 /* Subroutine of mips_reorg to manage passes that require DF.  */
15019
15020 static void
15021 mips_df_reorg (void)
15022 {
15023   /* Create def-use chains.  */
15024   df_set_flags (DF_EQ_NOTES);
15025   df_chain_add_problem (DF_UD_CHAIN);
15026   df_analyze ();
15027
15028   if (TARGET_RELAX_PIC_CALLS)
15029     mips_annotate_pic_calls ();
15030
15031   if (mips_r10k_cache_barrier != R10K_CACHE_BARRIER_NONE)
15032     r10k_insert_cache_barriers ();
15033
15034   df_finish_pass (false);
15035 }
15036
15037 /* Implement TARGET_MACHINE_DEPENDENT_REORG.  */
15038
15039 static void
15040 mips_reorg (void)
15041 {
15042   /* Restore the BLOCK_FOR_INSN pointers, which are needed by DF.  Also during
15043      insn splitting in mips16_lay_out_constants, DF insn info is only kept up
15044      to date if the CFG is available.  */
15045   if (mips_cfg_in_reorg ())
15046     compute_bb_for_insn ();
15047   mips16_lay_out_constants ();
15048   if (mips_cfg_in_reorg ())
15049     {
15050       mips_df_reorg ();
15051       free_bb_for_insn ();
15052     }
15053
15054   if (optimize > 0 && flag_delayed_branch)
15055     dbr_schedule (get_insns ());
15056   mips_reorg_process_insns ();
15057   if (!TARGET_MIPS16
15058       && TARGET_EXPLICIT_RELOCS
15059       && TUNE_MIPS4130
15060       && TARGET_VR4130_ALIGN)
15061     vr4130_align_insns ();
15062   if (mips_expand_ghost_gp_insns ())
15063     /* The expansion could invalidate some of the VR4130 alignment
15064        optimizations, but this should be an extremely rare case anyhow.  */
15065     mips_reorg_process_insns ();
15066 }
15067 \f
15068 /* Implement TARGET_ASM_OUTPUT_MI_THUNK.  Generate rtl rather than asm text
15069    in order to avoid duplicating too much logic from elsewhere.  */
15070
15071 static void
15072 mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
15073                       HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
15074                       tree function)
15075 {
15076   rtx this_rtx, temp1, temp2, insn, fnaddr;
15077   bool use_sibcall_p;
15078
15079   /* Pretend to be a post-reload pass while generating rtl.  */
15080   reload_completed = 1;
15081
15082   /* Mark the end of the (empty) prologue.  */
15083   emit_note (NOTE_INSN_PROLOGUE_END);
15084
15085   /* Determine if we can use a sibcall to call FUNCTION directly.  */
15086   fnaddr = XEXP (DECL_RTL (function), 0);
15087   use_sibcall_p = (mips_function_ok_for_sibcall (function, NULL)
15088                    && const_call_insn_operand (fnaddr, Pmode));
15089
15090   /* Determine if we need to load FNADDR from the GOT.  */
15091   if (!use_sibcall_p
15092       && (mips_got_symbol_type_p
15093           (mips_classify_symbol (fnaddr, SYMBOL_CONTEXT_LEA))))
15094     {
15095       /* Pick a global pointer.  Use a call-clobbered register if
15096          TARGET_CALL_SAVED_GP.  */
15097       cfun->machine->global_pointer
15098         = TARGET_CALL_SAVED_GP ? 15 : GLOBAL_POINTER_REGNUM;
15099       cfun->machine->must_initialize_gp_p = true;
15100       SET_REGNO (pic_offset_table_rtx, cfun->machine->global_pointer);
15101
15102       /* Set up the global pointer for n32 or n64 abicalls.  */
15103       mips_emit_loadgp ();
15104     }
15105
15106   /* We need two temporary registers in some cases.  */
15107   temp1 = gen_rtx_REG (Pmode, 2);
15108   temp2 = gen_rtx_REG (Pmode, 3);
15109
15110   /* Find out which register contains the "this" pointer.  */
15111   if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
15112     this_rtx = gen_rtx_REG (Pmode, GP_ARG_FIRST + 1);
15113   else
15114     this_rtx = gen_rtx_REG (Pmode, GP_ARG_FIRST);
15115
15116   /* Add DELTA to THIS_RTX.  */
15117   if (delta != 0)
15118     {
15119       rtx offset = GEN_INT (delta);
15120       if (!SMALL_OPERAND (delta))
15121         {
15122           mips_emit_move (temp1, offset);
15123           offset = temp1;
15124         }
15125       emit_insn (gen_add3_insn (this_rtx, this_rtx, offset));
15126     }
15127
15128   /* If needed, add *(*THIS_RTX + VCALL_OFFSET) to THIS_RTX.  */
15129   if (vcall_offset != 0)
15130     {
15131       rtx addr;
15132
15133       /* Set TEMP1 to *THIS_RTX.  */
15134       mips_emit_move (temp1, gen_rtx_MEM (Pmode, this_rtx));
15135
15136       /* Set ADDR to a legitimate address for *THIS_RTX + VCALL_OFFSET.  */
15137       addr = mips_add_offset (temp2, temp1, vcall_offset);
15138
15139       /* Load the offset and add it to THIS_RTX.  */
15140       mips_emit_move (temp1, gen_rtx_MEM (Pmode, addr));
15141       emit_insn (gen_add3_insn (this_rtx, this_rtx, temp1));
15142     }
15143
15144   /* Jump to the target function.  Use a sibcall if direct jumps are
15145      allowed, otherwise load the address into a register first.  */
15146   if (use_sibcall_p)
15147     {
15148       insn = emit_call_insn (gen_sibcall_internal (fnaddr, const0_rtx));
15149       SIBLING_CALL_P (insn) = 1;
15150     }
15151   else
15152     {
15153       /* This is messy.  GAS treats "la $25,foo" as part of a call
15154          sequence and may allow a global "foo" to be lazily bound.
15155          The general move patterns therefore reject this combination.
15156
15157          In this context, lazy binding would actually be OK
15158          for TARGET_CALL_CLOBBERED_GP, but it's still wrong for
15159          TARGET_CALL_SAVED_GP; see mips_load_call_address.
15160          We must therefore load the address via a temporary
15161          register if mips_dangerous_for_la25_p.
15162
15163          If we jump to the temporary register rather than $25,
15164          the assembler can use the move insn to fill the jump's
15165          delay slot.
15166
15167          We can use the same technique for MIPS16 code, where $25
15168          is not a valid JR register.  */
15169       if (TARGET_USE_PIC_FN_ADDR_REG
15170           && !TARGET_MIPS16
15171           && !mips_dangerous_for_la25_p (fnaddr))
15172         temp1 = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
15173       mips_load_call_address (MIPS_CALL_SIBCALL, temp1, fnaddr);
15174
15175       if (TARGET_USE_PIC_FN_ADDR_REG
15176           && REGNO (temp1) != PIC_FUNCTION_ADDR_REGNUM)
15177         mips_emit_move (gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM), temp1);
15178       emit_jump_insn (gen_indirect_jump (temp1));
15179     }
15180
15181   /* Run just enough of rest_of_compilation.  This sequence was
15182      "borrowed" from alpha.c.  */
15183   insn = get_insns ();
15184   insn_locators_alloc ();
15185   split_all_insns_noflow ();
15186   mips16_lay_out_constants ();
15187   shorten_branches (insn);
15188   final_start_function (insn, file, 1);
15189   final (insn, file, 1);
15190   final_end_function ();
15191
15192   /* Clean up the vars set above.  Note that final_end_function resets
15193      the global pointer for us.  */
15194   reload_completed = 0;
15195 }
15196 \f
15197 /* The last argument passed to mips_set_mips16_mode, or negative if the
15198    function hasn't been called yet.
15199
15200    There are two copies of this information.  One is saved and restored
15201    by the PCH process while the other is specific to this compiler
15202    invocation.  The information calculated by mips_set_mips16_mode
15203    is invalid unless the two variables are the same.  */
15204 static int was_mips16_p = -1;
15205 static GTY(()) int was_mips16_pch_p = -1;
15206
15207 /* Set up the target-dependent global state so that it matches the
15208    current function's ISA mode.  */
15209
15210 static void
15211 mips_set_mips16_mode (int mips16_p)
15212 {
15213   if (mips16_p == was_mips16_p
15214       && mips16_p == was_mips16_pch_p)
15215     return;
15216
15217   /* Restore base settings of various flags.  */
15218   target_flags = mips_base_target_flags;
15219   flag_schedule_insns = mips_base_schedule_insns;
15220   flag_reorder_blocks_and_partition = mips_base_reorder_blocks_and_partition;
15221   flag_move_loop_invariants = mips_base_move_loop_invariants;
15222   align_loops = mips_base_align_loops;
15223   align_jumps = mips_base_align_jumps;
15224   align_functions = mips_base_align_functions;
15225
15226   if (mips16_p)
15227     {
15228       /* Switch to MIPS16 mode.  */
15229       target_flags |= MASK_MIPS16;
15230
15231       /* Don't run the scheduler before reload, since it tends to
15232          increase register pressure.  */
15233       flag_schedule_insns = 0;
15234
15235       /* Don't do hot/cold partitioning.  mips16_lay_out_constants expects
15236          the whole function to be in a single section.  */
15237       flag_reorder_blocks_and_partition = 0;
15238
15239       /* Don't move loop invariants, because it tends to increase
15240          register pressure.  It also introduces an extra move in cases
15241          where the constant is the first operand in a two-operand binary
15242          instruction, or when it forms a register argument to a functon
15243          call.  */
15244       flag_move_loop_invariants = 0;
15245
15246       target_flags |= MASK_EXPLICIT_RELOCS;
15247
15248       /* Experiments suggest we get the best overall section-anchor
15249          results from using the range of an unextended LW or SW.  Code
15250          that makes heavy use of byte or short accesses can do better
15251          with ranges of 0...31 and 0...63 respectively, but most code is
15252          sensitive to the range of LW and SW instead.  */
15253       targetm.min_anchor_offset = 0;
15254       targetm.max_anchor_offset = 127;
15255
15256       targetm.const_anchor = 0;
15257
15258       /* MIPS16 has no BAL instruction.  */
15259       target_flags &= ~MASK_RELAX_PIC_CALLS;
15260
15261       if (flag_pic && !TARGET_OLDABI)
15262         sorry ("MIPS16 PIC for ABIs other than o32 and o64");
15263
15264       if (TARGET_XGOT)
15265         sorry ("MIPS16 -mxgot code");
15266
15267       if (TARGET_HARD_FLOAT_ABI && !TARGET_OLDABI)
15268         sorry ("hard-float MIPS16 code for ABIs other than o32 and o64");
15269     }
15270   else
15271     {
15272       /* Switch to normal (non-MIPS16) mode.  */
15273       target_flags &= ~MASK_MIPS16;
15274
15275       /* Provide default values for align_* for 64-bit targets.  */
15276       if (TARGET_64BIT)
15277         {
15278           if (align_loops == 0)
15279             align_loops = 8;
15280           if (align_jumps == 0)
15281             align_jumps = 8;
15282           if (align_functions == 0)
15283             align_functions = 8;
15284         }
15285
15286       targetm.min_anchor_offset = -32768;
15287       targetm.max_anchor_offset = 32767;
15288
15289       targetm.const_anchor = 0x8000;
15290     }
15291
15292   /* (Re)initialize MIPS target internals for new ISA.  */
15293   mips_init_relocs ();
15294
15295   if (mips16_p)
15296     {
15297       if (!mips16_globals)
15298         mips16_globals = save_target_globals ();
15299       else
15300         restore_target_globals (mips16_globals);
15301     }
15302   else
15303     restore_target_globals (&default_target_globals);
15304
15305   was_mips16_p = mips16_p;
15306   was_mips16_pch_p = mips16_p;
15307 }
15308
15309 /* Implement TARGET_SET_CURRENT_FUNCTION.  Decide whether the current
15310    function should use the MIPS16 ISA and switch modes accordingly.  */
15311
15312 static void
15313 mips_set_current_function (tree fndecl)
15314 {
15315   mips_set_mips16_mode (mips_use_mips16_mode_p (fndecl));
15316 }
15317 \f
15318 /* Allocate a chunk of memory for per-function machine-dependent data.  */
15319
15320 static struct machine_function *
15321 mips_init_machine_status (void)
15322 {
15323   return ggc_alloc_cleared_machine_function ();
15324 }
15325
15326 /* Return the processor associated with the given ISA level, or null
15327    if the ISA isn't valid.  */
15328
15329 static const struct mips_cpu_info *
15330 mips_cpu_info_from_isa (int isa)
15331 {
15332   unsigned int i;
15333
15334   for (i = 0; i < ARRAY_SIZE (mips_cpu_info_table); i++)
15335     if (mips_cpu_info_table[i].isa == isa)
15336       return mips_cpu_info_table + i;
15337
15338   return NULL;
15339 }
15340
15341 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
15342    with a final "000" replaced by "k".  Ignore case.
15343
15344    Note: this function is shared between GCC and GAS.  */
15345
15346 static bool
15347 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
15348 {
15349   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
15350     given++, canonical++;
15351
15352   return ((*given == 0 && *canonical == 0)
15353           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
15354 }
15355
15356 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
15357    CPU name.  We've traditionally allowed a lot of variation here.
15358
15359    Note: this function is shared between GCC and GAS.  */
15360
15361 static bool
15362 mips_matching_cpu_name_p (const char *canonical, const char *given)
15363 {
15364   /* First see if the name matches exactly, or with a final "000"
15365      turned into "k".  */
15366   if (mips_strict_matching_cpu_name_p (canonical, given))
15367     return true;
15368
15369   /* If not, try comparing based on numerical designation alone.
15370      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
15371   if (TOLOWER (*given) == 'r')
15372     given++;
15373   if (!ISDIGIT (*given))
15374     return false;
15375
15376   /* Skip over some well-known prefixes in the canonical name,
15377      hoping to find a number there too.  */
15378   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
15379     canonical += 2;
15380   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
15381     canonical += 2;
15382   else if (TOLOWER (canonical[0]) == 'r')
15383     canonical += 1;
15384
15385   return mips_strict_matching_cpu_name_p (canonical, given);
15386 }
15387
15388 /* Return the mips_cpu_info entry for the processor or ISA given
15389    by CPU_STRING.  Return null if the string isn't recognized.
15390
15391    A similar function exists in GAS.  */
15392
15393 static const struct mips_cpu_info *
15394 mips_parse_cpu (const char *cpu_string)
15395 {
15396   unsigned int i;
15397   const char *s;
15398
15399   /* In the past, we allowed upper-case CPU names, but it doesn't
15400      work well with the multilib machinery.  */
15401   for (s = cpu_string; *s != 0; s++)
15402     if (ISUPPER (*s))
15403       {
15404         warning (0, "CPU names must be lower case");
15405         break;
15406       }
15407
15408   /* 'from-abi' selects the most compatible architecture for the given
15409      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
15410      EABIs, we have to decide whether we're using the 32-bit or 64-bit
15411      version.  */
15412   if (strcasecmp (cpu_string, "from-abi") == 0)
15413     return mips_cpu_info_from_isa (ABI_NEEDS_32BIT_REGS ? 1
15414                                    : ABI_NEEDS_64BIT_REGS ? 3
15415                                    : (TARGET_64BIT ? 3 : 1));
15416
15417   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
15418   if (strcasecmp (cpu_string, "default") == 0)
15419     return NULL;
15420
15421   for (i = 0; i < ARRAY_SIZE (mips_cpu_info_table); i++)
15422     if (mips_matching_cpu_name_p (mips_cpu_info_table[i].name, cpu_string))
15423       return mips_cpu_info_table + i;
15424
15425   return NULL;
15426 }
15427
15428 /* Set up globals to generate code for the ISA or processor
15429    described by INFO.  */
15430
15431 static void
15432 mips_set_architecture (const struct mips_cpu_info *info)
15433 {
15434   if (info != 0)
15435     {
15436       mips_arch_info = info;
15437       mips_arch = info->cpu;
15438       mips_isa = info->isa;
15439     }
15440 }
15441
15442 /* Likewise for tuning.  */
15443
15444 static void
15445 mips_set_tune (const struct mips_cpu_info *info)
15446 {
15447   if (info != 0)
15448     {
15449       mips_tune_info = info;
15450       mips_tune = info->cpu;
15451     }
15452 }
15453
15454 /* Implement TARGET_HANDLE_OPTION.  */
15455
15456 static bool
15457 mips_handle_option (size_t code, const char *arg, int value ATTRIBUTE_UNUSED)
15458 {
15459   switch (code)
15460     {
15461     case OPT_mabi_:
15462       if (strcmp (arg, "32") == 0)
15463         mips_abi = ABI_32;
15464       else if (strcmp (arg, "o64") == 0)
15465         mips_abi = ABI_O64;
15466       else if (strcmp (arg, "n32") == 0)
15467         mips_abi = ABI_N32;
15468       else if (strcmp (arg, "64") == 0)
15469         mips_abi = ABI_64;
15470       else if (strcmp (arg, "eabi") == 0)
15471         mips_abi = ABI_EABI;
15472       else
15473         return false;
15474       return true;
15475
15476     case OPT_march_:
15477     case OPT_mtune_:
15478       return mips_parse_cpu (arg) != 0;
15479
15480     case OPT_mips:
15481       mips_isa_option_info = mips_parse_cpu (ACONCAT (("mips", arg, NULL)));
15482       return mips_isa_option_info != 0;
15483
15484     case OPT_mno_flush_func:
15485       mips_cache_flush_func = NULL;
15486       return true;
15487
15488     case OPT_mcode_readable_:
15489       if (strcmp (arg, "yes") == 0)
15490         mips_code_readable = CODE_READABLE_YES;
15491       else if (strcmp (arg, "pcrel") == 0)
15492         mips_code_readable = CODE_READABLE_PCREL;
15493       else if (strcmp (arg, "no") == 0)
15494         mips_code_readable = CODE_READABLE_NO;
15495       else
15496         return false;
15497       return true;
15498
15499     case OPT_mr10k_cache_barrier_:
15500       if (strcmp (arg, "load-store") == 0)
15501         mips_r10k_cache_barrier = R10K_CACHE_BARRIER_LOAD_STORE;
15502       else if (strcmp (arg, "store") == 0)
15503         mips_r10k_cache_barrier = R10K_CACHE_BARRIER_STORE;
15504       else if (strcmp (arg, "none") == 0)
15505         mips_r10k_cache_barrier = R10K_CACHE_BARRIER_NONE;
15506       else
15507         return false;
15508       return true;
15509
15510     default:
15511       return true;
15512     }
15513 }
15514
15515 /* Implement TARGET_OPTION_OVERRIDE.  */
15516
15517 static void
15518 mips_option_override (void)
15519 {
15520   int i, start, regno, mode;
15521
15522   /* Process flags as though we were generating non-MIPS16 code.  */
15523   mips_base_mips16 = TARGET_MIPS16;
15524   target_flags &= ~MASK_MIPS16;
15525
15526 #ifdef SUBTARGET_OVERRIDE_OPTIONS
15527   SUBTARGET_OVERRIDE_OPTIONS;
15528 #endif
15529
15530   /* -mno-float overrides -mhard-float and -msoft-float.  */
15531   if (TARGET_NO_FLOAT)
15532     {
15533       target_flags |= MASK_SOFT_FLOAT_ABI;
15534       target_flags_explicit |= MASK_SOFT_FLOAT_ABI;
15535     }
15536
15537   if (TARGET_FLIP_MIPS16)
15538     TARGET_INTERLINK_MIPS16 = 1;
15539
15540   /* Set the small data limit.  */
15541   mips_small_data_threshold = (global_options_set.x_g_switch_value
15542                                ? g_switch_value
15543                                : MIPS_DEFAULT_GVALUE);
15544
15545   /* The following code determines the architecture and register size.
15546      Similar code was added to GAS 2.14 (see tc-mips.c:md_after_parse_args()).
15547      The GAS and GCC code should be kept in sync as much as possible.  */
15548
15549   if (mips_arch_string != 0)
15550     mips_set_architecture (mips_parse_cpu (mips_arch_string));
15551
15552   if (mips_isa_option_info != 0)
15553     {
15554       if (mips_arch_info == 0)
15555         mips_set_architecture (mips_isa_option_info);
15556       else if (mips_arch_info->isa != mips_isa_option_info->isa)
15557         error ("%<-%s%> conflicts with the other architecture options, "
15558                "which specify a %s processor",
15559                mips_isa_option_info->name,
15560                mips_cpu_info_from_isa (mips_arch_info->isa)->name);
15561     }
15562
15563   if (mips_arch_info == 0)
15564     {
15565 #ifdef MIPS_CPU_STRING_DEFAULT
15566       mips_set_architecture (mips_parse_cpu (MIPS_CPU_STRING_DEFAULT));
15567 #else
15568       mips_set_architecture (mips_cpu_info_from_isa (MIPS_ISA_DEFAULT));
15569 #endif
15570     }
15571
15572   if (ABI_NEEDS_64BIT_REGS && !ISA_HAS_64BIT_REGS)
15573     error ("%<-march=%s%> is not compatible with the selected ABI",
15574            mips_arch_info->name);
15575
15576   /* Optimize for mips_arch, unless -mtune selects a different processor.  */
15577   if (mips_tune_string != 0)
15578     mips_set_tune (mips_parse_cpu (mips_tune_string));
15579
15580   if (mips_tune_info == 0)
15581     mips_set_tune (mips_arch_info);
15582
15583   if ((target_flags_explicit & MASK_64BIT) != 0)
15584     {
15585       /* The user specified the size of the integer registers.  Make sure
15586          it agrees with the ABI and ISA.  */
15587       if (TARGET_64BIT && !ISA_HAS_64BIT_REGS)
15588         error ("%<-mgp64%> used with a 32-bit processor");
15589       else if (!TARGET_64BIT && ABI_NEEDS_64BIT_REGS)
15590         error ("%<-mgp32%> used with a 64-bit ABI");
15591       else if (TARGET_64BIT && ABI_NEEDS_32BIT_REGS)
15592         error ("%<-mgp64%> used with a 32-bit ABI");
15593     }
15594   else
15595     {
15596       /* Infer the integer register size from the ABI and processor.
15597          Restrict ourselves to 32-bit registers if that's all the
15598          processor has, or if the ABI cannot handle 64-bit registers.  */
15599       if (ABI_NEEDS_32BIT_REGS || !ISA_HAS_64BIT_REGS)
15600         target_flags &= ~MASK_64BIT;
15601       else
15602         target_flags |= MASK_64BIT;
15603     }
15604
15605   if ((target_flags_explicit & MASK_FLOAT64) != 0)
15606     {
15607       if (TARGET_SINGLE_FLOAT && TARGET_FLOAT64)
15608         error ("unsupported combination: %s", "-mfp64 -msingle-float");
15609       else if (TARGET_64BIT && TARGET_DOUBLE_FLOAT && !TARGET_FLOAT64)
15610         error ("unsupported combination: %s", "-mgp64 -mfp32 -mdouble-float");
15611       else if (!TARGET_64BIT && TARGET_FLOAT64)
15612         {
15613           if (!ISA_HAS_MXHC1)
15614             error ("%<-mgp32%> and %<-mfp64%> can only be combined if"
15615                    " the target supports the mfhc1 and mthc1 instructions");
15616           else if (mips_abi != ABI_32)
15617             error ("%<-mgp32%> and %<-mfp64%> can only be combined when using"
15618                    " the o32 ABI");
15619         }
15620     }
15621   else
15622     {
15623       /* -msingle-float selects 32-bit float registers.  Otherwise the
15624          float registers should be the same size as the integer ones.  */
15625       if (TARGET_64BIT && TARGET_DOUBLE_FLOAT)
15626         target_flags |= MASK_FLOAT64;
15627       else
15628         target_flags &= ~MASK_FLOAT64;
15629     }
15630
15631   /* End of code shared with GAS.  */
15632
15633   /* If no -mlong* option was given, infer it from the other options.  */
15634   if ((target_flags_explicit & MASK_LONG64) == 0)
15635     {
15636       if ((mips_abi == ABI_EABI && TARGET_64BIT) || mips_abi == ABI_64)
15637         target_flags |= MASK_LONG64;
15638       else
15639         target_flags &= ~MASK_LONG64;
15640     }
15641
15642   if (!TARGET_OLDABI)
15643     flag_pcc_struct_return = 0;
15644
15645   /* Decide which rtx_costs structure to use.  */
15646   if (optimize_size)
15647     mips_cost = &mips_rtx_cost_optimize_size;
15648   else
15649     mips_cost = &mips_rtx_cost_data[mips_tune];
15650
15651   /* If the user hasn't specified a branch cost, use the processor's
15652      default.  */
15653   if (mips_branch_cost == 0)
15654     mips_branch_cost = mips_cost->branch_cost;
15655
15656   /* If neither -mbranch-likely nor -mno-branch-likely was given
15657      on the command line, set MASK_BRANCHLIKELY based on the target
15658      architecture and tuning flags.  Annulled delay slots are a
15659      size win, so we only consider the processor-specific tuning
15660      for !optimize_size.  */
15661   if ((target_flags_explicit & MASK_BRANCHLIKELY) == 0)
15662     {
15663       if (ISA_HAS_BRANCHLIKELY
15664           && (optimize_size
15665               || (mips_tune_info->tune_flags & PTF_AVOID_BRANCHLIKELY) == 0))
15666         target_flags |= MASK_BRANCHLIKELY;
15667       else
15668         target_flags &= ~MASK_BRANCHLIKELY;
15669     }
15670   else if (TARGET_BRANCHLIKELY && !ISA_HAS_BRANCHLIKELY)
15671     warning (0, "the %qs architecture does not support branch-likely"
15672              " instructions", mips_arch_info->name);
15673
15674   /* The effect of -mabicalls isn't defined for the EABI.  */
15675   if (mips_abi == ABI_EABI && TARGET_ABICALLS)
15676     {
15677       error ("unsupported combination: %s", "-mabicalls -mabi=eabi");
15678       target_flags &= ~MASK_ABICALLS;
15679     }
15680
15681   if (TARGET_ABICALLS_PIC2)
15682     /* We need to set flag_pic for executables as well as DSOs
15683        because we may reference symbols that are not defined in
15684        the final executable.  (MIPS does not use things like
15685        copy relocs, for example.)
15686
15687        There is a body of code that uses __PIC__ to distinguish
15688        between -mabicalls and -mno-abicalls code.  The non-__PIC__
15689        variant is usually appropriate for TARGET_ABICALLS_PIC0, as
15690        long as any indirect jumps use $25.  */
15691     flag_pic = 1;
15692
15693   /* -mvr4130-align is a "speed over size" optimization: it usually produces
15694      faster code, but at the expense of more nops.  Enable it at -O3 and
15695      above.  */
15696   if (optimize > 2 && (target_flags_explicit & MASK_VR4130_ALIGN) == 0)
15697     target_flags |= MASK_VR4130_ALIGN;
15698
15699   /* Prefer a call to memcpy over inline code when optimizing for size,
15700      though see MOVE_RATIO in mips.h.  */
15701   if (optimize_size && (target_flags_explicit & MASK_MEMCPY) == 0)
15702     target_flags |= MASK_MEMCPY;
15703
15704   /* If we have a nonzero small-data limit, check that the -mgpopt
15705      setting is consistent with the other target flags.  */
15706   if (mips_small_data_threshold > 0)
15707     {
15708       if (!TARGET_GPOPT)
15709         {
15710           if (!TARGET_EXPLICIT_RELOCS)
15711             error ("%<-mno-gpopt%> needs %<-mexplicit-relocs%>");
15712
15713           TARGET_LOCAL_SDATA = false;
15714           TARGET_EXTERN_SDATA = false;
15715         }
15716       else
15717         {
15718           if (TARGET_VXWORKS_RTP)
15719             warning (0, "cannot use small-data accesses for %qs", "-mrtp");
15720
15721           if (TARGET_ABICALLS)
15722             warning (0, "cannot use small-data accesses for %qs",
15723                      "-mabicalls");
15724         }
15725     }
15726
15727 #ifdef MIPS_TFMODE_FORMAT
15728   REAL_MODE_FORMAT (TFmode) = &MIPS_TFMODE_FORMAT;
15729 #endif
15730
15731   /* Make sure that the user didn't turn off paired single support when
15732      MIPS-3D support is requested.  */
15733   if (TARGET_MIPS3D
15734       && (target_flags_explicit & MASK_PAIRED_SINGLE_FLOAT)
15735       && !TARGET_PAIRED_SINGLE_FLOAT)
15736     error ("%<-mips3d%> requires %<-mpaired-single%>");
15737
15738   /* If TARGET_MIPS3D, enable MASK_PAIRED_SINGLE_FLOAT.  */
15739   if (TARGET_MIPS3D)
15740     target_flags |= MASK_PAIRED_SINGLE_FLOAT;
15741
15742   /* Make sure that when TARGET_PAIRED_SINGLE_FLOAT is true, TARGET_FLOAT64
15743      and TARGET_HARD_FLOAT_ABI are both true.  */
15744   if (TARGET_PAIRED_SINGLE_FLOAT && !(TARGET_FLOAT64 && TARGET_HARD_FLOAT_ABI))
15745     error ("%qs must be used with %qs",
15746            TARGET_MIPS3D ? "-mips3d" : "-mpaired-single",
15747            TARGET_HARD_FLOAT_ABI ? "-mfp64" : "-mhard-float");
15748
15749   /* Make sure that the ISA supports TARGET_PAIRED_SINGLE_FLOAT when it is
15750      enabled.  */
15751   if (TARGET_PAIRED_SINGLE_FLOAT && !ISA_HAS_PAIRED_SINGLE)
15752     warning (0, "the %qs architecture does not support paired-single"
15753              " instructions", mips_arch_info->name);
15754
15755   if (mips_r10k_cache_barrier != R10K_CACHE_BARRIER_NONE
15756       && !TARGET_CACHE_BUILTIN)
15757     {
15758       error ("%qs requires a target that provides the %qs instruction",
15759              "-mr10k-cache-barrier", "cache");
15760       mips_r10k_cache_barrier = R10K_CACHE_BARRIER_NONE;
15761     }
15762
15763   /* If TARGET_DSPR2, enable MASK_DSP.  */
15764   if (TARGET_DSPR2)
15765     target_flags |= MASK_DSP;
15766
15767   /* .eh_frame addresses should be the same width as a C pointer.
15768      Most MIPS ABIs support only one pointer size, so the assembler
15769      will usually know exactly how big an .eh_frame address is.
15770
15771      Unfortunately, this is not true of the 64-bit EABI.  The ABI was
15772      originally defined to use 64-bit pointers (i.e. it is LP64), and
15773      this is still the default mode.  However, we also support an n32-like
15774      ILP32 mode, which is selected by -mlong32.  The problem is that the
15775      assembler has traditionally not had an -mlong option, so it has
15776      traditionally not known whether we're using the ILP32 or LP64 form.
15777
15778      As it happens, gas versions up to and including 2.19 use _32-bit_
15779      addresses for EABI64 .cfi_* directives.  This is wrong for the
15780      default LP64 mode, so we can't use the directives by default.
15781      Moreover, since gas's current behavior is at odds with gcc's
15782      default behavior, it seems unwise to rely on future versions
15783      of gas behaving the same way.  We therefore avoid using .cfi
15784      directives for -mlong32 as well.  */
15785   if (mips_abi == ABI_EABI && TARGET_64BIT)
15786     flag_dwarf2_cfi_asm = 0;
15787
15788   /* .cfi_* directives generate a read-only section, so fall back on
15789      manual .eh_frame creation if we need the section to be writable.  */
15790   if (TARGET_WRITABLE_EH_FRAME)
15791     flag_dwarf2_cfi_asm = 0;
15792
15793   mips_init_print_operand_punct ();
15794
15795   /* Set up array to map GCC register number to debug register number.
15796      Ignore the special purpose register numbers.  */
15797
15798   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
15799     {
15800       mips_dbx_regno[i] = INVALID_REGNUM;
15801       if (GP_REG_P (i) || FP_REG_P (i) || ALL_COP_REG_P (i))
15802         mips_dwarf_regno[i] = i;
15803       else
15804         mips_dwarf_regno[i] = INVALID_REGNUM;
15805     }
15806
15807   start = GP_DBX_FIRST - GP_REG_FIRST;
15808   for (i = GP_REG_FIRST; i <= GP_REG_LAST; i++)
15809     mips_dbx_regno[i] = i + start;
15810
15811   start = FP_DBX_FIRST - FP_REG_FIRST;
15812   for (i = FP_REG_FIRST; i <= FP_REG_LAST; i++)
15813     mips_dbx_regno[i] = i + start;
15814
15815   /* Accumulator debug registers use big-endian ordering.  */
15816   mips_dbx_regno[HI_REGNUM] = MD_DBX_FIRST + 0;
15817   mips_dbx_regno[LO_REGNUM] = MD_DBX_FIRST + 1;
15818   mips_dwarf_regno[HI_REGNUM] = MD_REG_FIRST + 0;
15819   mips_dwarf_regno[LO_REGNUM] = MD_REG_FIRST + 1;
15820   for (i = DSP_ACC_REG_FIRST; i <= DSP_ACC_REG_LAST; i += 2)
15821     {
15822       mips_dwarf_regno[i + TARGET_LITTLE_ENDIAN] = i;
15823       mips_dwarf_regno[i + TARGET_BIG_ENDIAN] = i + 1;
15824     }
15825
15826   /* Set up mips_hard_regno_mode_ok.  */
15827   for (mode = 0; mode < MAX_MACHINE_MODE; mode++)
15828     for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
15829       mips_hard_regno_mode_ok[mode][regno]
15830         = mips_hard_regno_mode_ok_p (regno, (enum machine_mode) mode);
15831
15832   /* Function to allocate machine-dependent function status.  */
15833   init_machine_status = &mips_init_machine_status;
15834
15835   /* Default to working around R4000 errata only if the processor
15836      was selected explicitly.  */
15837   if ((target_flags_explicit & MASK_FIX_R4000) == 0
15838       && mips_matching_cpu_name_p (mips_arch_info->name, "r4000"))
15839     target_flags |= MASK_FIX_R4000;
15840
15841   /* Default to working around R4400 errata only if the processor
15842      was selected explicitly.  */
15843   if ((target_flags_explicit & MASK_FIX_R4400) == 0
15844       && mips_matching_cpu_name_p (mips_arch_info->name, "r4400"))
15845     target_flags |= MASK_FIX_R4400;
15846
15847   /* Default to working around R10000 errata only if the processor
15848      was selected explicitly.  */
15849   if ((target_flags_explicit & MASK_FIX_R10000) == 0
15850       && mips_matching_cpu_name_p (mips_arch_info->name, "r10000"))
15851     target_flags |= MASK_FIX_R10000;
15852
15853   /* Make sure that branch-likely instructions available when using
15854      -mfix-r10000.  The instructions are not available if either:
15855
15856         1. -mno-branch-likely was passed.
15857         2. The selected ISA does not support branch-likely and
15858            the command line does not include -mbranch-likely.  */
15859   if (TARGET_FIX_R10000
15860       && ((target_flags_explicit & MASK_BRANCHLIKELY) == 0
15861           ? !ISA_HAS_BRANCHLIKELY
15862           : !TARGET_BRANCHLIKELY))
15863     sorry ("%qs requires branch-likely instructions", "-mfix-r10000");
15864
15865   if (TARGET_SYNCI && !ISA_HAS_SYNCI)
15866     {
15867       warning (0, "the %qs architecture does not support the synci "
15868                "instruction", mips_arch_info->name);
15869       target_flags &= ~MASK_SYNCI;
15870     }
15871
15872   /* Only optimize PIC indirect calls if they are actually required.  */
15873   if (!TARGET_USE_GOT || !TARGET_EXPLICIT_RELOCS)
15874     target_flags &= ~MASK_RELAX_PIC_CALLS;
15875
15876   /* Save base state of options.  */
15877   mips_base_target_flags = target_flags;
15878   mips_base_schedule_insns = flag_schedule_insns;
15879   mips_base_reorder_blocks_and_partition = flag_reorder_blocks_and_partition;
15880   mips_base_move_loop_invariants = flag_move_loop_invariants;
15881   mips_base_align_loops = align_loops;
15882   mips_base_align_jumps = align_jumps;
15883   mips_base_align_functions = align_functions;
15884
15885   /* Now select the ISA mode.
15886
15887      Do all CPP-sensitive stuff in non-MIPS16 mode; we'll switch to
15888      MIPS16 mode afterwards if need be.  */
15889   mips_set_mips16_mode (false);
15890 }
15891
15892 /* Implement TARGET_OPTION_OPTIMIZATION_TABLE.  */
15893 static const struct default_options mips_option_optimization_table[] =
15894   {
15895     { OPT_LEVELS_1_PLUS, OPT_fomit_frame_pointer, NULL, 1 },
15896     { OPT_LEVELS_NONE, 0, NULL, 0 }
15897   };
15898
15899 /* Swap the register information for registers I and I + 1, which
15900    currently have the wrong endianness.  Note that the registers'
15901    fixedness and call-clobberedness might have been set on the
15902    command line.  */
15903
15904 static void
15905 mips_swap_registers (unsigned int i)
15906 {
15907   int tmpi;
15908   const char *tmps;
15909
15910 #define SWAP_INT(X, Y) (tmpi = (X), (X) = (Y), (Y) = tmpi)
15911 #define SWAP_STRING(X, Y) (tmps = (X), (X) = (Y), (Y) = tmps)
15912
15913   SWAP_INT (fixed_regs[i], fixed_regs[i + 1]);
15914   SWAP_INT (call_used_regs[i], call_used_regs[i + 1]);
15915   SWAP_INT (call_really_used_regs[i], call_really_used_regs[i + 1]);
15916   SWAP_STRING (reg_names[i], reg_names[i + 1]);
15917
15918 #undef SWAP_STRING
15919 #undef SWAP_INT
15920 }
15921
15922 /* Implement TARGET_CONDITIONAL_REGISTER_USAGE.  */
15923
15924 static void
15925 mips_conditional_register_usage (void)
15926 {
15927
15928   if (ISA_HAS_DSP)
15929     {
15930       /* These DSP control register fields are global.  */
15931       global_regs[CCDSP_PO_REGNUM] = 1;
15932       global_regs[CCDSP_SC_REGNUM] = 1;
15933     }
15934   else 
15935     {
15936       int regno;
15937
15938       for (regno = DSP_ACC_REG_FIRST; regno <= DSP_ACC_REG_LAST; regno++)
15939         fixed_regs[regno] = call_used_regs[regno] = 1;
15940     }
15941   if (!TARGET_HARD_FLOAT)
15942     {
15943       int regno;
15944
15945       for (regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
15946         fixed_regs[regno] = call_used_regs[regno] = 1;
15947       for (regno = ST_REG_FIRST; regno <= ST_REG_LAST; regno++)
15948         fixed_regs[regno] = call_used_regs[regno] = 1;
15949     }
15950   else if (! ISA_HAS_8CC)
15951     {
15952       int regno;
15953
15954       /* We only have a single condition-code register.  We implement
15955          this by fixing all the condition-code registers and generating
15956          RTL that refers directly to ST_REG_FIRST.  */
15957       for (regno = ST_REG_FIRST; regno <= ST_REG_LAST; regno++)
15958         fixed_regs[regno] = call_used_regs[regno] = 1;
15959     }
15960   /* In MIPS16 mode, we permit the $t temporary registers to be used
15961      for reload.  We prohibit the unused $s registers, since they
15962      are call-saved, and saving them via a MIPS16 register would
15963      probably waste more time than just reloading the value.  */
15964   if (TARGET_MIPS16)
15965     {
15966       fixed_regs[18] = call_used_regs[18] = 1;
15967       fixed_regs[19] = call_used_regs[19] = 1;
15968       fixed_regs[20] = call_used_regs[20] = 1;
15969       fixed_regs[21] = call_used_regs[21] = 1;
15970       fixed_regs[22] = call_used_regs[22] = 1;
15971       fixed_regs[23] = call_used_regs[23] = 1;
15972       fixed_regs[26] = call_used_regs[26] = 1;
15973       fixed_regs[27] = call_used_regs[27] = 1;
15974       fixed_regs[30] = call_used_regs[30] = 1;
15975     }
15976   /* $f20-$f23 are call-clobbered for n64.  */
15977   if (mips_abi == ABI_64)
15978     {
15979       int regno;
15980       for (regno = FP_REG_FIRST + 20; regno < FP_REG_FIRST + 24; regno++)
15981         call_really_used_regs[regno] = call_used_regs[regno] = 1;
15982     }
15983   /* Odd registers in the range $f21-$f31 (inclusive) are call-clobbered
15984      for n32.  */
15985   if (mips_abi == ABI_N32)
15986     {
15987       int regno;
15988       for (regno = FP_REG_FIRST + 21; regno <= FP_REG_FIRST + 31; regno+=2)
15989         call_really_used_regs[regno] = call_used_regs[regno] = 1;
15990     }
15991   /* Make sure that double-register accumulator values are correctly
15992      ordered for the current endianness.  */
15993   if (TARGET_LITTLE_ENDIAN)
15994     {
15995       unsigned int regno;
15996
15997       mips_swap_registers (MD_REG_FIRST);
15998       for (regno = DSP_ACC_REG_FIRST; regno <= DSP_ACC_REG_LAST; regno += 2)
15999         mips_swap_registers (regno);
16000     }
16001 }
16002
16003 /* Initialize vector TARGET to VALS.  */
16004
16005 void
16006 mips_expand_vector_init (rtx target, rtx vals)
16007 {
16008   enum machine_mode mode;
16009   enum machine_mode inner;
16010   unsigned int i, n_elts;
16011   rtx mem;
16012
16013   mode = GET_MODE (target);
16014   inner = GET_MODE_INNER (mode);
16015   n_elts = GET_MODE_NUNITS (mode);
16016
16017   gcc_assert (VECTOR_MODE_P (mode));
16018
16019   mem = assign_stack_temp (mode, GET_MODE_SIZE (mode), 0);
16020   for (i = 0; i < n_elts; i++)
16021     emit_move_insn (adjust_address_nv (mem, inner, i * GET_MODE_SIZE (inner)),
16022                     XVECEXP (vals, 0, i));
16023
16024   emit_move_insn (target, mem);
16025 }
16026
16027 /* When generating MIPS16 code, we want to allocate $24 (T_REG) before
16028    other registers for instructions for which it is possible.  This
16029    encourages the compiler to use CMP in cases where an XOR would
16030    require some register shuffling.  */
16031
16032 void
16033 mips_order_regs_for_local_alloc (void)
16034 {
16035   int i;
16036
16037   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
16038     reg_alloc_order[i] = i;
16039
16040   if (TARGET_MIPS16)
16041     {
16042       /* It really doesn't matter where we put register 0, since it is
16043          a fixed register anyhow.  */
16044       reg_alloc_order[0] = 24;
16045       reg_alloc_order[24] = 0;
16046     }
16047 }
16048
16049 /* Implement EH_USES.  */
16050
16051 bool
16052 mips_eh_uses (unsigned int regno)
16053 {
16054   if (reload_completed && !TARGET_ABSOLUTE_JUMPS)
16055     {
16056       /* We need to force certain registers to be live in order to handle
16057          PIC long branches correctly.  See mips_must_initialize_gp_p for
16058          details.  */
16059       if (mips_cfun_has_cprestore_slot_p ())
16060         {
16061           if (regno == CPRESTORE_SLOT_REGNUM)
16062             return true;
16063         }
16064       else
16065         {
16066           if (cfun->machine->global_pointer == regno)
16067             return true;
16068         }
16069     }
16070
16071   return false;
16072 }
16073
16074 /* Implement EPILOGUE_USES.  */
16075
16076 bool
16077 mips_epilogue_uses (unsigned int regno)
16078 {
16079   /* Say that the epilogue uses the return address register.  Note that
16080      in the case of sibcalls, the values "used by the epilogue" are
16081      considered live at the start of the called function.  */
16082   if (regno == RETURN_ADDR_REGNUM)
16083     return true;
16084
16085   /* If using a GOT, say that the epilogue also uses GOT_VERSION_REGNUM.
16086      See the comment above load_call<mode> for details.  */
16087   if (TARGET_USE_GOT && (regno) == GOT_VERSION_REGNUM)
16088     return true;
16089
16090   /* An interrupt handler must preserve some registers that are
16091      ordinarily call-clobbered.  */
16092   if (cfun->machine->interrupt_handler_p
16093       && mips_interrupt_extra_call_saved_reg_p (regno))
16094     return true;
16095
16096   return false;
16097 }
16098
16099 /* A for_each_rtx callback.  Stop the search if *X is an AT register.  */
16100
16101 static int
16102 mips_at_reg_p (rtx *x, void *data ATTRIBUTE_UNUSED)
16103 {
16104   return REG_P (*x) && REGNO (*x) == AT_REGNUM;
16105 }
16106
16107 /* Return true if INSN needs to be wrapped in ".set noat".
16108    INSN has NOPERANDS operands, stored in OPVEC.  */
16109
16110 static bool
16111 mips_need_noat_wrapper_p (rtx insn, rtx *opvec, int noperands)
16112 {
16113   int i;
16114
16115   if (recog_memoized (insn) >= 0)
16116     for (i = 0; i < noperands; i++)
16117       if (for_each_rtx (&opvec[i], mips_at_reg_p, NULL))
16118         return true;
16119   return false;
16120 }
16121
16122 /* Implement FINAL_PRESCAN_INSN.  */
16123
16124 void
16125 mips_final_prescan_insn (rtx insn, rtx *opvec, int noperands)
16126 {
16127   if (mips_need_noat_wrapper_p (insn, opvec, noperands))
16128     mips_push_asm_switch (&mips_noat);
16129 }
16130
16131 /* Implement TARGET_ASM_FINAL_POSTSCAN_INSN.  */
16132
16133 static void
16134 mips_final_postscan_insn (FILE *file ATTRIBUTE_UNUSED, rtx insn,
16135                           rtx *opvec, int noperands)
16136 {
16137   if (mips_need_noat_wrapper_p (insn, opvec, noperands))
16138     mips_pop_asm_switch (&mips_noat);
16139 }
16140
16141 /* Return the function that is used to expand the <u>mulsidi3 pattern.
16142    EXT_CODE is the code of the extension used.  Return NULL if widening
16143    multiplication shouldn't be used.  */
16144
16145 mulsidi3_gen_fn
16146 mips_mulsidi3_gen_fn (enum rtx_code ext_code)
16147 {
16148   bool signed_p;
16149
16150   signed_p = ext_code == SIGN_EXTEND;
16151   if (TARGET_64BIT)
16152     {
16153       /* Don't use widening multiplication with MULT when we have DMUL.  Even
16154          with the extension of its input operands DMUL is faster.  Note that
16155          the extension is not needed for signed multiplication.  In order to
16156          ensure that we always remove the redundant sign-extension in this
16157          case we still expand mulsidi3 for DMUL.  */
16158       if (ISA_HAS_DMUL3)
16159         return signed_p ? gen_mulsidi3_64bit_dmul : NULL;
16160       if (TARGET_FIX_R4000)
16161         return NULL;
16162       return signed_p ? gen_mulsidi3_64bit : gen_umulsidi3_64bit;
16163     }
16164   else
16165     {
16166       if (TARGET_FIX_R4000 && !ISA_HAS_DSP)
16167         return signed_p ? gen_mulsidi3_32bit_r4000 : gen_umulsidi3_32bit_r4000;
16168       return signed_p ? gen_mulsidi3_32bit : gen_umulsidi3_32bit;
16169     }
16170 }
16171 \f
16172 /* Return the size in bytes of the trampoline code, padded to
16173    TRAMPOLINE_ALIGNMENT bits.  The static chain pointer and target
16174    function address immediately follow.  */
16175
16176 int
16177 mips_trampoline_code_size (void)
16178 {
16179   if (TARGET_USE_PIC_FN_ADDR_REG)
16180     return 4 * 4;
16181   else if (ptr_mode == DImode)
16182     return 8 * 4;
16183   else if (ISA_HAS_LOAD_DELAY)
16184     return 6 * 4;
16185   else
16186     return 4 * 4;
16187 }
16188
16189 /* Implement TARGET_TRAMPOLINE_INIT.  */
16190
16191 static void
16192 mips_trampoline_init (rtx m_tramp, tree fndecl, rtx chain_value)
16193 {
16194   rtx addr, end_addr, high, low, opcode, mem;
16195   rtx trampoline[8];
16196   unsigned int i, j;
16197   HOST_WIDE_INT end_addr_offset, static_chain_offset, target_function_offset;
16198
16199   /* Work out the offsets of the pointers from the start of the
16200      trampoline code.  */
16201   end_addr_offset = mips_trampoline_code_size ();
16202   static_chain_offset = end_addr_offset;
16203   target_function_offset = static_chain_offset + GET_MODE_SIZE (ptr_mode);
16204
16205   /* Get pointers to the beginning and end of the code block.  */
16206   addr = force_reg (Pmode, XEXP (m_tramp, 0));
16207   end_addr = mips_force_binary (Pmode, PLUS, addr, GEN_INT (end_addr_offset));
16208
16209 #define OP(X) gen_int_mode (X, SImode)
16210
16211   /* Build up the code in TRAMPOLINE.  */
16212   i = 0;
16213   if (TARGET_USE_PIC_FN_ADDR_REG)
16214     {
16215       /* $25 contains the address of the trampoline.  Emit code of the form:
16216
16217              l[wd]    $1, target_function_offset($25)
16218              l[wd]    $static_chain, static_chain_offset($25)
16219              jr       $1
16220              move     $25,$1.  */
16221       trampoline[i++] = OP (MIPS_LOAD_PTR (AT_REGNUM,
16222                                            target_function_offset,
16223                                            PIC_FUNCTION_ADDR_REGNUM));
16224       trampoline[i++] = OP (MIPS_LOAD_PTR (STATIC_CHAIN_REGNUM,
16225                                            static_chain_offset,
16226                                            PIC_FUNCTION_ADDR_REGNUM));
16227       trampoline[i++] = OP (MIPS_JR (AT_REGNUM));
16228       trampoline[i++] = OP (MIPS_MOVE (PIC_FUNCTION_ADDR_REGNUM, AT_REGNUM));
16229     }
16230   else if (ptr_mode == DImode)
16231     {
16232       /* It's too cumbersome to create the full 64-bit address, so let's
16233          instead use:
16234
16235              move    $1, $31
16236              bal     1f
16237              nop
16238          1:  l[wd]   $25, target_function_offset - 12($31)
16239              l[wd]   $static_chain, static_chain_offset - 12($31)
16240              jr      $25
16241              move    $31, $1
16242
16243         where 12 is the offset of "1:" from the start of the code block.  */
16244       trampoline[i++] = OP (MIPS_MOVE (AT_REGNUM, RETURN_ADDR_REGNUM));
16245       trampoline[i++] = OP (MIPS_BAL (1));
16246       trampoline[i++] = OP (MIPS_NOP);
16247       trampoline[i++] = OP (MIPS_LOAD_PTR (PIC_FUNCTION_ADDR_REGNUM,
16248                                            target_function_offset - 12,
16249                                            RETURN_ADDR_REGNUM));
16250       trampoline[i++] = OP (MIPS_LOAD_PTR (STATIC_CHAIN_REGNUM,
16251                                            static_chain_offset - 12,
16252                                            RETURN_ADDR_REGNUM));
16253       trampoline[i++] = OP (MIPS_JR (PIC_FUNCTION_ADDR_REGNUM));
16254       trampoline[i++] = OP (MIPS_MOVE (RETURN_ADDR_REGNUM, AT_REGNUM));
16255     }
16256   else
16257     {
16258       /* If the target has load delays, emit:
16259
16260              lui     $1, %hi(end_addr)
16261              lw      $25, %lo(end_addr + ...)($1)
16262              lw      $static_chain, %lo(end_addr + ...)($1)
16263              jr      $25
16264              nop
16265
16266          Otherwise emit:
16267
16268              lui     $1, %hi(end_addr)
16269              lw      $25, %lo(end_addr + ...)($1)
16270              jr      $25
16271              lw      $static_chain, %lo(end_addr + ...)($1).  */
16272
16273       /* Split END_ADDR into %hi and %lo values.  Trampolines are aligned
16274          to 64 bits, so the %lo value will have the bottom 3 bits clear.  */
16275       high = expand_simple_binop (SImode, PLUS, end_addr, GEN_INT (0x8000),
16276                                   NULL, false, OPTAB_WIDEN);
16277       high = expand_simple_binop (SImode, LSHIFTRT, high, GEN_INT (16),
16278                                   NULL, false, OPTAB_WIDEN);
16279       low = convert_to_mode (SImode, gen_lowpart (HImode, end_addr), true);
16280
16281       /* Emit the LUI.  */
16282       opcode = OP (MIPS_LUI (AT_REGNUM, 0));
16283       trampoline[i++] = expand_simple_binop (SImode, IOR, opcode, high,
16284                                              NULL, false, OPTAB_WIDEN);
16285
16286       /* Emit the load of the target function.  */
16287       opcode = OP (MIPS_LOAD_PTR (PIC_FUNCTION_ADDR_REGNUM,
16288                                   target_function_offset - end_addr_offset,
16289                                   AT_REGNUM));
16290       trampoline[i++] = expand_simple_binop (SImode, IOR, opcode, low,
16291                                              NULL, false, OPTAB_WIDEN);
16292
16293       /* Emit the JR here, if we can.  */
16294       if (!ISA_HAS_LOAD_DELAY)
16295         trampoline[i++] = OP (MIPS_JR (PIC_FUNCTION_ADDR_REGNUM));
16296
16297       /* Emit the load of the static chain register.  */
16298       opcode = OP (MIPS_LOAD_PTR (STATIC_CHAIN_REGNUM,
16299                                   static_chain_offset - end_addr_offset,
16300                                   AT_REGNUM));
16301       trampoline[i++] = expand_simple_binop (SImode, IOR, opcode, low,
16302                                              NULL, false, OPTAB_WIDEN);
16303
16304       /* Emit the JR, if we couldn't above.  */
16305       if (ISA_HAS_LOAD_DELAY)
16306         {
16307           trampoline[i++] = OP (MIPS_JR (PIC_FUNCTION_ADDR_REGNUM));
16308           trampoline[i++] = OP (MIPS_NOP);
16309         }
16310     }
16311
16312 #undef OP
16313
16314   /* Copy the trampoline code.  Leave any padding uninitialized.  */
16315   for (j = 0; j < i; j++)
16316     {
16317       mem = adjust_address (m_tramp, SImode, j * GET_MODE_SIZE (SImode));
16318       mips_emit_move (mem, trampoline[j]);
16319     }
16320
16321   /* Set up the static chain pointer field.  */
16322   mem = adjust_address (m_tramp, ptr_mode, static_chain_offset);
16323   mips_emit_move (mem, chain_value);
16324
16325   /* Set up the target function field.  */
16326   mem = adjust_address (m_tramp, ptr_mode, target_function_offset);
16327   mips_emit_move (mem, XEXP (DECL_RTL (fndecl), 0));
16328
16329   /* Flush the code part of the trampoline.  */
16330   emit_insn (gen_add3_insn (end_addr, addr, GEN_INT (TRAMPOLINE_SIZE)));
16331   emit_insn (gen_clear_cache (addr, end_addr));
16332 }
16333
16334 /* Implement FUNCTION_PROFILER.  */
16335
16336 void mips_function_profiler (FILE *file)
16337 {
16338   if (TARGET_MIPS16)
16339     sorry ("mips16 function profiling");
16340   if (TARGET_LONG_CALLS)
16341     {
16342       /* For TARGET_LONG_CALLS use $3 for the address of _mcount.  */
16343       if (Pmode == DImode)
16344         fprintf (file, "\tdla\t%s,_mcount\n", reg_names[3]);
16345       else
16346         fprintf (file, "\tla\t%s,_mcount\n", reg_names[3]);
16347     }
16348   mips_push_asm_switch (&mips_noat);
16349   fprintf (file, "\tmove\t%s,%s\t\t# save current return address\n",
16350            reg_names[AT_REGNUM], reg_names[RETURN_ADDR_REGNUM]);
16351   /* _mcount treats $2 as the static chain register.  */
16352   if (cfun->static_chain_decl != NULL)
16353     fprintf (file, "\tmove\t%s,%s\n", reg_names[2],
16354              reg_names[STATIC_CHAIN_REGNUM]);
16355   if (TARGET_MCOUNT_RA_ADDRESS)
16356     {
16357       /* If TARGET_MCOUNT_RA_ADDRESS load $12 with the address of the
16358          ra save location.  */
16359       if (cfun->machine->frame.ra_fp_offset == 0)
16360         /* ra not saved, pass zero.  */
16361         fprintf (file, "\tmove\t%s,%s\n", reg_names[12], reg_names[0]);
16362       else
16363         fprintf (file, "\t%s\t%s," HOST_WIDE_INT_PRINT_DEC "(%s)\n",
16364                  Pmode == DImode ? "dla" : "la", reg_names[12],
16365                  cfun->machine->frame.ra_fp_offset,
16366                  reg_names[STACK_POINTER_REGNUM]);
16367     }
16368   if (!TARGET_NEWABI)
16369     fprintf (file,
16370              "\t%s\t%s,%s,%d\t\t# _mcount pops 2 words from  stack\n",
16371              TARGET_64BIT ? "dsubu" : "subu",
16372              reg_names[STACK_POINTER_REGNUM],
16373              reg_names[STACK_POINTER_REGNUM],
16374              Pmode == DImode ? 16 : 8);
16375
16376   if (TARGET_LONG_CALLS)
16377     fprintf (file, "\tjalr\t%s\n", reg_names[3]);
16378   else
16379     fprintf (file, "\tjal\t_mcount\n");
16380   mips_pop_asm_switch (&mips_noat);
16381   /* _mcount treats $2 as the static chain register.  */
16382   if (cfun->static_chain_decl != NULL)
16383     fprintf (file, "\tmove\t%s,%s\n", reg_names[STATIC_CHAIN_REGNUM],
16384              reg_names[2]);
16385 }
16386
16387 /* Implement TARGET_SHIFT_TRUNCATION_MASK.  We want to keep the default
16388    behaviour of TARGET_SHIFT_TRUNCATION_MASK for non-vector modes even
16389    when TARGET_LOONGSON_2EF is true.  */
16390
16391 static unsigned HOST_WIDE_INT
16392 mips_shift_truncation_mask (enum machine_mode mode)
16393 {
16394   if (TARGET_LOONGSON_2EF && VECTOR_MODE_P (mode))
16395     return 0;
16396
16397   return GET_MODE_BITSIZE (mode) - 1;
16398 }
16399
16400 \f
16401 /* Initialize the GCC target structure.  */
16402 #undef TARGET_ASM_ALIGNED_HI_OP
16403 #define TARGET_ASM_ALIGNED_HI_OP "\t.half\t"
16404 #undef TARGET_ASM_ALIGNED_SI_OP
16405 #define TARGET_ASM_ALIGNED_SI_OP "\t.word\t"
16406 #undef TARGET_ASM_ALIGNED_DI_OP
16407 #define TARGET_ASM_ALIGNED_DI_OP "\t.dword\t"
16408
16409 #undef TARGET_OPTION_OVERRIDE
16410 #define TARGET_OPTION_OVERRIDE mips_option_override
16411 #undef TARGET_OPTION_OPTIMIZATION_TABLE
16412 #define TARGET_OPTION_OPTIMIZATION_TABLE mips_option_optimization_table
16413
16414 #undef TARGET_LEGITIMIZE_ADDRESS
16415 #define TARGET_LEGITIMIZE_ADDRESS mips_legitimize_address
16416
16417 #undef TARGET_ASM_FUNCTION_PROLOGUE
16418 #define TARGET_ASM_FUNCTION_PROLOGUE mips_output_function_prologue
16419 #undef TARGET_ASM_FUNCTION_EPILOGUE
16420 #define TARGET_ASM_FUNCTION_EPILOGUE mips_output_function_epilogue
16421 #undef TARGET_ASM_SELECT_RTX_SECTION
16422 #define TARGET_ASM_SELECT_RTX_SECTION mips_select_rtx_section
16423 #undef TARGET_ASM_FUNCTION_RODATA_SECTION
16424 #define TARGET_ASM_FUNCTION_RODATA_SECTION mips_function_rodata_section
16425
16426 #undef TARGET_SCHED_INIT
16427 #define TARGET_SCHED_INIT mips_sched_init
16428 #undef TARGET_SCHED_REORDER
16429 #define TARGET_SCHED_REORDER mips_sched_reorder
16430 #undef TARGET_SCHED_REORDER2
16431 #define TARGET_SCHED_REORDER2 mips_sched_reorder2
16432 #undef TARGET_SCHED_VARIABLE_ISSUE
16433 #define TARGET_SCHED_VARIABLE_ISSUE mips_variable_issue
16434 #undef TARGET_SCHED_ADJUST_COST
16435 #define TARGET_SCHED_ADJUST_COST mips_adjust_cost
16436 #undef TARGET_SCHED_ISSUE_RATE
16437 #define TARGET_SCHED_ISSUE_RATE mips_issue_rate
16438 #undef TARGET_SCHED_INIT_DFA_POST_CYCLE_INSN
16439 #define TARGET_SCHED_INIT_DFA_POST_CYCLE_INSN mips_init_dfa_post_cycle_insn
16440 #undef TARGET_SCHED_DFA_POST_ADVANCE_CYCLE
16441 #define TARGET_SCHED_DFA_POST_ADVANCE_CYCLE mips_dfa_post_advance_cycle
16442 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
16443 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD \
16444   mips_multipass_dfa_lookahead
16445 #undef TARGET_SMALL_REGISTER_CLASSES_FOR_MODE_P
16446 #define TARGET_SMALL_REGISTER_CLASSES_FOR_MODE_P \
16447   mips_small_register_classes_for_mode_p
16448
16449 #undef TARGET_DEFAULT_TARGET_FLAGS
16450 #define TARGET_DEFAULT_TARGET_FLAGS             \
16451   (TARGET_DEFAULT                               \
16452    | TARGET_CPU_DEFAULT                         \
16453    | TARGET_ENDIAN_DEFAULT                      \
16454    | TARGET_FP_EXCEPTIONS_DEFAULT               \
16455    | MASK_CHECK_ZERO_DIV                        \
16456    | MASK_FUSED_MADD)
16457 #undef TARGET_HANDLE_OPTION
16458 #define TARGET_HANDLE_OPTION mips_handle_option
16459
16460 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
16461 #define TARGET_FUNCTION_OK_FOR_SIBCALL mips_function_ok_for_sibcall
16462
16463 #undef TARGET_INSERT_ATTRIBUTES
16464 #define TARGET_INSERT_ATTRIBUTES mips_insert_attributes
16465 #undef TARGET_MERGE_DECL_ATTRIBUTES
16466 #define TARGET_MERGE_DECL_ATTRIBUTES mips_merge_decl_attributes
16467 #undef TARGET_SET_CURRENT_FUNCTION
16468 #define TARGET_SET_CURRENT_FUNCTION mips_set_current_function
16469
16470 #undef TARGET_VALID_POINTER_MODE
16471 #define TARGET_VALID_POINTER_MODE mips_valid_pointer_mode
16472 #undef TARGET_REGISTER_MOVE_COST
16473 #define TARGET_REGISTER_MOVE_COST mips_register_move_cost
16474 #undef TARGET_MEMORY_MOVE_COST
16475 #define TARGET_MEMORY_MOVE_COST mips_memory_move_cost
16476 #undef TARGET_RTX_COSTS
16477 #define TARGET_RTX_COSTS mips_rtx_costs
16478 #undef TARGET_ADDRESS_COST
16479 #define TARGET_ADDRESS_COST mips_address_cost
16480
16481 #undef TARGET_IN_SMALL_DATA_P
16482 #define TARGET_IN_SMALL_DATA_P mips_in_small_data_p
16483
16484 #undef TARGET_MACHINE_DEPENDENT_REORG
16485 #define TARGET_MACHINE_DEPENDENT_REORG mips_reorg
16486
16487 #undef TARGET_ASM_FILE_START
16488 #define TARGET_ASM_FILE_START mips_file_start
16489 #undef TARGET_ASM_FILE_START_FILE_DIRECTIVE
16490 #define TARGET_ASM_FILE_START_FILE_DIRECTIVE true
16491
16492 #undef TARGET_INIT_LIBFUNCS
16493 #define TARGET_INIT_LIBFUNCS mips_init_libfuncs
16494
16495 #undef TARGET_BUILD_BUILTIN_VA_LIST
16496 #define TARGET_BUILD_BUILTIN_VA_LIST mips_build_builtin_va_list
16497 #undef TARGET_EXPAND_BUILTIN_VA_START
16498 #define TARGET_EXPAND_BUILTIN_VA_START mips_va_start
16499 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
16500 #define TARGET_GIMPLIFY_VA_ARG_EXPR mips_gimplify_va_arg_expr
16501
16502 #undef  TARGET_PROMOTE_FUNCTION_MODE
16503 #define TARGET_PROMOTE_FUNCTION_MODE default_promote_function_mode_always_promote
16504 #undef TARGET_PROMOTE_PROTOTYPES
16505 #define TARGET_PROMOTE_PROTOTYPES hook_bool_const_tree_true
16506
16507 #undef TARGET_RETURN_IN_MEMORY
16508 #define TARGET_RETURN_IN_MEMORY mips_return_in_memory
16509 #undef TARGET_RETURN_IN_MSB
16510 #define TARGET_RETURN_IN_MSB mips_return_in_msb
16511
16512 #undef TARGET_ASM_OUTPUT_MI_THUNK
16513 #define TARGET_ASM_OUTPUT_MI_THUNK mips_output_mi_thunk
16514 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
16515 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
16516
16517 #undef TARGET_PRINT_OPERAND
16518 #define TARGET_PRINT_OPERAND mips_print_operand
16519 #undef TARGET_PRINT_OPERAND_ADDRESS
16520 #define TARGET_PRINT_OPERAND_ADDRESS mips_print_operand_address
16521 #undef TARGET_PRINT_OPERAND_PUNCT_VALID_P
16522 #define TARGET_PRINT_OPERAND_PUNCT_VALID_P mips_print_operand_punct_valid_p
16523
16524 #undef TARGET_SETUP_INCOMING_VARARGS
16525 #define TARGET_SETUP_INCOMING_VARARGS mips_setup_incoming_varargs
16526 #undef TARGET_STRICT_ARGUMENT_NAMING
16527 #define TARGET_STRICT_ARGUMENT_NAMING mips_strict_argument_naming
16528 #undef TARGET_MUST_PASS_IN_STACK
16529 #define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
16530 #undef TARGET_PASS_BY_REFERENCE
16531 #define TARGET_PASS_BY_REFERENCE mips_pass_by_reference
16532 #undef TARGET_CALLEE_COPIES
16533 #define TARGET_CALLEE_COPIES mips_callee_copies
16534 #undef TARGET_ARG_PARTIAL_BYTES
16535 #define TARGET_ARG_PARTIAL_BYTES mips_arg_partial_bytes
16536 #undef TARGET_FUNCTION_ARG
16537 #define TARGET_FUNCTION_ARG mips_function_arg
16538 #undef TARGET_FUNCTION_ARG_ADVANCE
16539 #define TARGET_FUNCTION_ARG_ADVANCE mips_function_arg_advance
16540 #undef TARGET_FUNCTION_ARG_BOUNDARY
16541 #define TARGET_FUNCTION_ARG_BOUNDARY mips_function_arg_boundary
16542
16543 #undef TARGET_MODE_REP_EXTENDED
16544 #define TARGET_MODE_REP_EXTENDED mips_mode_rep_extended
16545
16546 #undef TARGET_VECTOR_MODE_SUPPORTED_P
16547 #define TARGET_VECTOR_MODE_SUPPORTED_P mips_vector_mode_supported_p
16548
16549 #undef TARGET_SCALAR_MODE_SUPPORTED_P
16550 #define TARGET_SCALAR_MODE_SUPPORTED_P mips_scalar_mode_supported_p
16551
16552 #undef TARGET_VECTORIZE_PREFERRED_SIMD_MODE
16553 #define TARGET_VECTORIZE_PREFERRED_SIMD_MODE mips_preferred_simd_mode
16554
16555 #undef TARGET_INIT_BUILTINS
16556 #define TARGET_INIT_BUILTINS mips_init_builtins
16557 #undef TARGET_BUILTIN_DECL
16558 #define TARGET_BUILTIN_DECL mips_builtin_decl
16559 #undef TARGET_EXPAND_BUILTIN
16560 #define TARGET_EXPAND_BUILTIN mips_expand_builtin
16561
16562 #undef TARGET_HAVE_TLS
16563 #define TARGET_HAVE_TLS HAVE_AS_TLS
16564
16565 #undef TARGET_CANNOT_FORCE_CONST_MEM
16566 #define TARGET_CANNOT_FORCE_CONST_MEM mips_cannot_force_const_mem
16567
16568 #undef TARGET_ENCODE_SECTION_INFO
16569 #define TARGET_ENCODE_SECTION_INFO mips_encode_section_info
16570
16571 #undef TARGET_ATTRIBUTE_TABLE
16572 #define TARGET_ATTRIBUTE_TABLE mips_attribute_table
16573 /* All our function attributes are related to how out-of-line copies should
16574    be compiled or called.  They don't in themselves prevent inlining.  */
16575 #undef TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P
16576 #define TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P hook_bool_const_tree_true
16577
16578 #undef TARGET_EXTRA_LIVE_ON_ENTRY
16579 #define TARGET_EXTRA_LIVE_ON_ENTRY mips_extra_live_on_entry
16580
16581 #undef TARGET_USE_BLOCKS_FOR_CONSTANT_P
16582 #define TARGET_USE_BLOCKS_FOR_CONSTANT_P mips_use_blocks_for_constant_p
16583 #undef TARGET_USE_ANCHORS_FOR_SYMBOL_P
16584 #define TARGET_USE_ANCHORS_FOR_SYMBOL_P mips_use_anchors_for_symbol_p
16585
16586 #undef  TARGET_COMP_TYPE_ATTRIBUTES
16587 #define TARGET_COMP_TYPE_ATTRIBUTES mips_comp_type_attributes
16588
16589 #ifdef HAVE_AS_DTPRELWORD
16590 #undef TARGET_ASM_OUTPUT_DWARF_DTPREL
16591 #define TARGET_ASM_OUTPUT_DWARF_DTPREL mips_output_dwarf_dtprel
16592 #endif
16593 #undef TARGET_DWARF_REGISTER_SPAN
16594 #define TARGET_DWARF_REGISTER_SPAN mips_dwarf_register_span
16595
16596 #undef TARGET_IRA_COVER_CLASSES
16597 #define TARGET_IRA_COVER_CLASSES mips_ira_cover_classes
16598
16599 #undef TARGET_ASM_FINAL_POSTSCAN_INSN
16600 #define TARGET_ASM_FINAL_POSTSCAN_INSN mips_final_postscan_insn
16601
16602 #undef TARGET_LEGITIMATE_ADDRESS_P
16603 #define TARGET_LEGITIMATE_ADDRESS_P     mips_legitimate_address_p
16604
16605 #undef TARGET_FRAME_POINTER_REQUIRED
16606 #define TARGET_FRAME_POINTER_REQUIRED mips_frame_pointer_required
16607
16608 #undef TARGET_CAN_ELIMINATE
16609 #define TARGET_CAN_ELIMINATE mips_can_eliminate
16610
16611 #undef TARGET_CONDITIONAL_REGISTER_USAGE
16612 #define TARGET_CONDITIONAL_REGISTER_USAGE mips_conditional_register_usage
16613
16614 #undef TARGET_TRAMPOLINE_INIT
16615 #define TARGET_TRAMPOLINE_INIT mips_trampoline_init
16616
16617 #undef TARGET_ASM_OUTPUT_SOURCE_FILENAME
16618 #define TARGET_ASM_OUTPUT_SOURCE_FILENAME mips_output_filename
16619
16620 #undef TARGET_SHIFT_TRUNCATION_MASK
16621 #define TARGET_SHIFT_TRUNCATION_MASK mips_shift_truncation_mask
16622
16623 struct gcc_target targetm = TARGET_INITIALIZER;
16624 \f
16625 #include "gt-mips.h"