OSDN Git Service

* config/sh/sh-protos.h (sh_legitimate_index_p): Declare.
[pf3gnuchains/gcc-fork.git] / gcc / config / sh / sh.c
1 /* Output routines for GCC for Renesas / SuperH SH.
2    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
4    Contributed by Steve Chamberlain (sac@cygnus.com).
5    Improved by Jim Wilson (wilson@cygnus.com).
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "insn-config.h"
28 #include "rtl.h"
29 #include "tree.h"
30 #include "flags.h"
31 #include "expr.h"
32 #include "optabs.h"
33 #include "function.h"
34 #include "regs.h"
35 #include "hard-reg-set.h"
36 #include "output.h"
37 #include "insn-attr.h"
38 #include "toplev.h"
39 #include "recog.h"
40 #include "integrate.h"
41 #include "dwarf2.h"
42 #include "tm_p.h"
43 #include "target.h"
44 #include "target-def.h"
45 #include "real.h"
46 #include "langhooks.h"
47 #include "basic-block.h"
48 #include "df.h"
49 #include "cfglayout.h"
50 #include "intl.h"
51 #include "sched-int.h"
52 #include "ggc.h"
53 #include "gimple.h"
54 #include "cfgloop.h"
55 #include "alloc-pool.h"
56 #include "tm-constrs.h"
57
58
59 int code_for_indirect_jump_scratch = CODE_FOR_indirect_jump_scratch;
60
61 #define MSW (TARGET_LITTLE_ENDIAN ? 1 : 0)
62 #define LSW (TARGET_LITTLE_ENDIAN ? 0 : 1)
63
64 /* These are some macros to abstract register modes.  */
65 #define CONST_OK_FOR_ADD(size) \
66   (TARGET_SHMEDIA ? CONST_OK_FOR_I10 (size) : CONST_OK_FOR_I08 (size))
67 #define GEN_MOV (*(TARGET_SHMEDIA64 ? gen_movdi : gen_movsi))
68 #define GEN_ADD3 (*(TARGET_SHMEDIA64 ? gen_adddi3 : gen_addsi3))
69 #define GEN_SUB3 (*(TARGET_SHMEDIA64 ? gen_subdi3 : gen_subsi3))
70
71 /* Used to simplify the logic below.  Find the attributes wherever
72    they may be.  */
73 #define SH_ATTRIBUTES(decl) \
74   (TYPE_P (decl)) ? TYPE_ATTRIBUTES (decl) \
75                   : DECL_ATTRIBUTES (decl) \
76                   ? (DECL_ATTRIBUTES (decl)) \
77                   : TYPE_ATTRIBUTES (TREE_TYPE (decl))
78
79 /* Set to 1 by expand_prologue() when the function is an interrupt handler.  */
80 int current_function_interrupt;
81
82 tree sh_deferred_function_attributes;
83 tree *sh_deferred_function_attributes_tail = &sh_deferred_function_attributes;
84
85 /* Global variables for machine-dependent things.  */
86
87 /* Which cpu are we scheduling for.  */
88 enum processor_type sh_cpu;
89
90 /* Definitions used in ready queue reordering for first scheduling pass.  */
91
92 /* Reg weights arrays for modes SFmode and SImode, indexed by insn LUID.  */
93 static short *regmode_weight[2];
94
95 /* Total SFmode and SImode weights of scheduled insns.  */
96 static int curr_regmode_pressure[2];
97
98 /* Number of r0 life regions.  */
99 static int r0_life_regions;
100
101 /* If true, skip cycles for Q -> R movement.  */
102 static int skip_cycles = 0;
103
104 /* Cached value of can_issue_more. This is cached in sh_variable_issue hook
105    and returned from sh_reorder2.  */
106 static short cached_can_issue_more;
107
108 /* Provides the class number of the smallest class containing
109    reg number.  */
110
111 enum reg_class regno_reg_class[FIRST_PSEUDO_REGISTER] =
112 {
113   R0_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
114   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
115   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
116   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
117   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
118   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
119   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
120   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
121   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
122   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
123   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
124   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
125   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
126   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
127   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
128   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
129   FP0_REGS,FP_REGS, FP_REGS, FP_REGS,
130   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
131   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
132   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
133   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
134   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
135   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
136   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
137   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
138   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
139   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
140   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
141   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
142   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
143   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
144   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
145   TARGET_REGS, TARGET_REGS, TARGET_REGS, TARGET_REGS,
146   TARGET_REGS, TARGET_REGS, TARGET_REGS, TARGET_REGS,
147   DF_REGS, DF_REGS, DF_REGS, DF_REGS,
148   DF_REGS, DF_REGS, DF_REGS, DF_REGS,
149   NO_REGS, GENERAL_REGS, PR_REGS, T_REGS,
150   MAC_REGS, MAC_REGS, FPUL_REGS, FPSCR_REGS,
151   GENERAL_REGS, GENERAL_REGS,
152 };
153
154 char sh_register_names[FIRST_PSEUDO_REGISTER] \
155   [MAX_REGISTER_NAME_LENGTH + 1] = SH_REGISTER_NAMES_INITIALIZER;
156
157 char sh_additional_register_names[ADDREGNAMES_SIZE] \
158   [MAX_ADDITIONAL_REGISTER_NAME_LENGTH + 1]
159   = SH_ADDITIONAL_REGISTER_NAMES_INITIALIZER;
160
161 int assembler_dialect;
162
163 static bool shmedia_space_reserved_for_target_registers;
164
165 static bool sh_handle_option (size_t, const char *, int);
166 static void split_branches (rtx);
167 static int branch_dest (rtx);
168 static void force_into (rtx, rtx);
169 static void print_slot (rtx);
170 static rtx add_constant (rtx, enum machine_mode, rtx);
171 static void dump_table (rtx, rtx);
172 static int hi_const (rtx);
173 static int broken_move (rtx);
174 static int mova_p (rtx);
175 static rtx find_barrier (int, rtx, rtx);
176 static int noncall_uses_reg (rtx, rtx, rtx *);
177 static rtx gen_block_redirect (rtx, int, int);
178 static void sh_reorg (void);
179 static void output_stack_adjust (int, rtx, int, HARD_REG_SET *);
180 static rtx frame_insn (rtx);
181 static rtx push (int);
182 static void pop (int);
183 static void push_regs (HARD_REG_SET *, int);
184 static int calc_live_regs (HARD_REG_SET *);
185 static HOST_WIDE_INT rounded_frame_size (int);
186 static rtx mark_constant_pool_use (rtx);
187 const struct attribute_spec sh_attribute_table[];
188 static tree sh_handle_interrupt_handler_attribute (tree *, tree, tree, int, bool *);
189 static tree sh_handle_resbank_handler_attribute (tree *, tree,
190                                                  tree, int, bool *);
191 static tree sh2a_handle_function_vector_handler_attribute (tree *, tree,
192                                                            tree, int, bool *);
193 static tree sh_handle_sp_switch_attribute (tree *, tree, tree, int, bool *);
194 static tree sh_handle_trap_exit_attribute (tree *, tree, tree, int, bool *);
195 static tree sh_handle_renesas_attribute (tree *, tree, tree, int, bool *);
196 static void sh_output_function_epilogue (FILE *, HOST_WIDE_INT);
197 static void sh_insert_attributes (tree, tree *);
198 static const char *sh_check_pch_target_flags (int);
199 static int sh_adjust_cost (rtx, rtx, rtx, int);
200 static int sh_issue_rate (void);
201 static int sh_dfa_new_cycle (FILE *, int, rtx, int, int, int *sort_p);
202 static short find_set_regmode_weight (rtx, enum machine_mode);
203 static short find_insn_regmode_weight (rtx, enum machine_mode);
204 static void find_regmode_weight (basic_block, enum machine_mode);
205 static int find_r0_life_regions (basic_block);
206 static void  sh_md_init_global (FILE *, int, int);
207 static void  sh_md_finish_global (FILE *, int);
208 static int rank_for_reorder (const void *, const void *);
209 static void swap_reorder (rtx *, int);
210 static void ready_reorder (rtx *, int);
211 static short high_pressure (enum machine_mode);
212 static int sh_reorder (FILE *, int, rtx *, int *, int);
213 static int sh_reorder2 (FILE *, int, rtx *, int *, int);
214 static void sh_md_init (FILE *, int, int);
215 static int sh_variable_issue (FILE *, int, rtx, int);
216
217 static bool sh_function_ok_for_sibcall (tree, tree);
218
219 static bool sh_cannot_modify_jumps_p (void);
220 static enum reg_class sh_target_reg_class (void);
221 static bool sh_optimize_target_register_callee_saved (bool);
222 static bool sh_ms_bitfield_layout_p (const_tree);
223
224 static void sh_init_builtins (void);
225 static void sh_media_init_builtins (void);
226 static rtx sh_expand_builtin (tree, rtx, rtx, enum machine_mode, int);
227 static void sh_output_mi_thunk (FILE *, tree, HOST_WIDE_INT, HOST_WIDE_INT, tree);
228 static void sh_file_start (void);
229 static int flow_dependent_p (rtx, rtx);
230 static void flow_dependent_p_1 (rtx, const_rtx, void *);
231 static int shiftcosts (rtx);
232 static int andcosts (rtx);
233 static int addsubcosts (rtx);
234 static int multcosts (rtx);
235 static bool unspec_caller_rtx_p (rtx);
236 static bool sh_cannot_copy_insn_p (rtx);
237 static bool sh_rtx_costs (rtx, int, int, int *, bool);
238 static int sh_address_cost (rtx, bool);
239 static int sh_pr_n_sets (void);
240 static rtx sh_allocate_initial_value (rtx);
241 static rtx sh_legitimize_address (rtx, rtx, enum machine_mode);
242 static int shmedia_target_regs_stack_space (HARD_REG_SET *);
243 static int shmedia_reserve_space_for_target_registers_p (int, HARD_REG_SET *);
244 static int shmedia_target_regs_stack_adjust (HARD_REG_SET *);
245 static int scavenge_reg (HARD_REG_SET *s);
246 struct save_schedule_s;
247 static struct save_entry_s *sh5_schedule_saves (HARD_REG_SET *,
248                                                 struct save_schedule_s *, int);
249
250 static rtx sh_struct_value_rtx (tree, int);
251 static bool sh_return_in_memory (const_tree, const_tree);
252 static rtx sh_builtin_saveregs (void);
253 static void sh_setup_incoming_varargs (CUMULATIVE_ARGS *, enum machine_mode, tree, int *, int);
254 static bool sh_strict_argument_naming (CUMULATIVE_ARGS *);
255 static bool sh_pretend_outgoing_varargs_named (CUMULATIVE_ARGS *);
256 static tree sh_build_builtin_va_list (void);
257 static void sh_va_start (tree, rtx);
258 static tree sh_gimplify_va_arg_expr (tree, tree, gimple_seq *, gimple_seq *);
259 static bool sh_pass_by_reference (CUMULATIVE_ARGS *, enum machine_mode,
260                                   const_tree, bool);
261 static bool sh_callee_copies (CUMULATIVE_ARGS *, enum machine_mode,
262                               const_tree, bool);
263 static int sh_arg_partial_bytes (CUMULATIVE_ARGS *, enum machine_mode,
264                                  tree, bool);
265 static bool sh_scalar_mode_supported_p (enum machine_mode);
266 static int sh_dwarf_calling_convention (const_tree);
267 static void sh_encode_section_info (tree, rtx, int);
268 static int sh2a_function_vector_p (tree);
269
270 \f
271 /* Initialize the GCC target structure.  */
272 #undef TARGET_ATTRIBUTE_TABLE
273 #define TARGET_ATTRIBUTE_TABLE sh_attribute_table
274
275 /* The next two are used for debug info when compiling with -gdwarf.  */
276 #undef TARGET_ASM_UNALIGNED_HI_OP
277 #define TARGET_ASM_UNALIGNED_HI_OP "\t.uaword\t"
278 #undef TARGET_ASM_UNALIGNED_SI_OP
279 #define TARGET_ASM_UNALIGNED_SI_OP "\t.ualong\t"
280
281 /* These are NULLed out on non-SH5 in OVERRIDE_OPTIONS.  */
282 #undef TARGET_ASM_UNALIGNED_DI_OP
283 #define TARGET_ASM_UNALIGNED_DI_OP "\t.uaquad\t"
284 #undef TARGET_ASM_ALIGNED_DI_OP
285 #define TARGET_ASM_ALIGNED_DI_OP "\t.quad\t"
286
287 #undef TARGET_ASM_FUNCTION_EPILOGUE
288 #define TARGET_ASM_FUNCTION_EPILOGUE sh_output_function_epilogue
289
290 #undef TARGET_ASM_OUTPUT_MI_THUNK
291 #define TARGET_ASM_OUTPUT_MI_THUNK sh_output_mi_thunk
292
293 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
294 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
295
296 #undef TARGET_ASM_FILE_START
297 #define TARGET_ASM_FILE_START sh_file_start
298 #undef TARGET_ASM_FILE_START_FILE_DIRECTIVE
299 #define TARGET_ASM_FILE_START_FILE_DIRECTIVE true
300
301 #undef TARGET_DEFAULT_TARGET_FLAGS
302 #define TARGET_DEFAULT_TARGET_FLAGS TARGET_DEFAULT
303 #undef TARGET_HANDLE_OPTION
304 #define TARGET_HANDLE_OPTION sh_handle_option
305
306 #undef TARGET_INSERT_ATTRIBUTES
307 #define TARGET_INSERT_ATTRIBUTES sh_insert_attributes
308
309 #undef TARGET_SCHED_ADJUST_COST
310 #define TARGET_SCHED_ADJUST_COST sh_adjust_cost
311
312 #undef TARGET_SCHED_ISSUE_RATE
313 #define TARGET_SCHED_ISSUE_RATE sh_issue_rate
314
315 /* The next 5 hooks have been implemented for reenabling sched1.  With the
316    help of these macros we are limiting the movement of insns in sched1 to
317    reduce the register pressure.  The overall idea is to keep count of SImode
318    and SFmode regs required by already scheduled insns. When these counts
319    cross some threshold values; give priority to insns that free registers.
320    The insn that frees registers is most likely to be the insn with lowest
321    LUID (original insn order); but such an insn might be there in the stalled
322    queue (Q) instead of the ready queue (R).  To solve this, we skip cycles
323    upto a max of 8 cycles so that such insns may move from Q -> R.
324
325    The description of the hooks are as below:
326
327    TARGET_SCHED_INIT_GLOBAL: Added a new target hook in the generic
328    scheduler; it is called inside the sched_init function just after
329    find_insn_reg_weights function call. It is used to calculate the SImode
330    and SFmode weights of insns of basic blocks; much similar to what
331    find_insn_reg_weights does.
332    TARGET_SCHED_FINISH_GLOBAL: Corresponding cleanup hook.
333
334    TARGET_SCHED_DFA_NEW_CYCLE: Skip cycles if high register pressure is
335    indicated by TARGET_SCHED_REORDER2; doing this may move insns from
336    (Q)->(R).
337
338    TARGET_SCHED_REORDER: If the register pressure for SImode or SFmode is
339    high; reorder the ready queue so that the insn with lowest LUID will be
340    issued next.
341
342    TARGET_SCHED_REORDER2: If the register pressure is high, indicate to
343    TARGET_SCHED_DFA_NEW_CYCLE to skip cycles.
344
345    TARGET_SCHED_VARIABLE_ISSUE: Cache the value of can_issue_more so that it
346    can be returned from TARGET_SCHED_REORDER2.
347
348    TARGET_SCHED_INIT: Reset the register pressure counting variables.  */
349
350 #undef TARGET_SCHED_DFA_NEW_CYCLE
351 #define TARGET_SCHED_DFA_NEW_CYCLE sh_dfa_new_cycle
352
353 #undef TARGET_SCHED_INIT_GLOBAL
354 #define TARGET_SCHED_INIT_GLOBAL sh_md_init_global
355
356 #undef TARGET_SCHED_FINISH_GLOBAL
357 #define TARGET_SCHED_FINISH_GLOBAL sh_md_finish_global
358
359 #undef TARGET_SCHED_VARIABLE_ISSUE
360 #define TARGET_SCHED_VARIABLE_ISSUE sh_variable_issue
361
362 #undef TARGET_SCHED_REORDER
363 #define TARGET_SCHED_REORDER sh_reorder
364
365 #undef TARGET_SCHED_REORDER2
366 #define TARGET_SCHED_REORDER2 sh_reorder2
367
368 #undef TARGET_SCHED_INIT
369 #define TARGET_SCHED_INIT sh_md_init
370
371 #undef TARGET_LEGITIMIZE_ADDRESS
372 #define TARGET_LEGITIMIZE_ADDRESS sh_legitimize_address
373
374 #undef TARGET_CANNOT_MODIFY_JUMPS_P
375 #define TARGET_CANNOT_MODIFY_JUMPS_P sh_cannot_modify_jumps_p
376 #undef TARGET_BRANCH_TARGET_REGISTER_CLASS
377 #define TARGET_BRANCH_TARGET_REGISTER_CLASS sh_target_reg_class
378 #undef TARGET_BRANCH_TARGET_REGISTER_CALLEE_SAVED
379 #define TARGET_BRANCH_TARGET_REGISTER_CALLEE_SAVED \
380  sh_optimize_target_register_callee_saved
381
382 #undef TARGET_MS_BITFIELD_LAYOUT_P
383 #define TARGET_MS_BITFIELD_LAYOUT_P sh_ms_bitfield_layout_p
384
385 #undef TARGET_INIT_BUILTINS
386 #define TARGET_INIT_BUILTINS sh_init_builtins
387 #undef TARGET_EXPAND_BUILTIN
388 #define TARGET_EXPAND_BUILTIN sh_expand_builtin
389
390 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
391 #define TARGET_FUNCTION_OK_FOR_SIBCALL sh_function_ok_for_sibcall
392
393 #undef TARGET_CANNOT_COPY_INSN_P
394 #define TARGET_CANNOT_COPY_INSN_P sh_cannot_copy_insn_p
395 #undef TARGET_RTX_COSTS
396 #define TARGET_RTX_COSTS sh_rtx_costs
397 #undef TARGET_ADDRESS_COST
398 #define TARGET_ADDRESS_COST sh_address_cost
399 #undef TARGET_ALLOCATE_INITIAL_VALUE
400 #define TARGET_ALLOCATE_INITIAL_VALUE sh_allocate_initial_value
401
402 #undef TARGET_MACHINE_DEPENDENT_REORG
403 #define TARGET_MACHINE_DEPENDENT_REORG sh_reorg
404
405 #undef TARGET_DWARF_REGISTER_SPAN
406 #define TARGET_DWARF_REGISTER_SPAN sh_dwarf_register_span
407
408 #ifdef HAVE_AS_TLS
409 #undef TARGET_HAVE_TLS
410 #define TARGET_HAVE_TLS true
411 #endif
412
413 #undef TARGET_PROMOTE_PROTOTYPES
414 #define TARGET_PROMOTE_PROTOTYPES sh_promote_prototypes
415 #undef TARGET_PROMOTE_FUNCTION_ARGS
416 #define TARGET_PROMOTE_FUNCTION_ARGS sh_promote_prototypes
417 #undef TARGET_PROMOTE_FUNCTION_RETURN
418 #define TARGET_PROMOTE_FUNCTION_RETURN sh_promote_prototypes
419
420 #undef TARGET_STRUCT_VALUE_RTX
421 #define TARGET_STRUCT_VALUE_RTX sh_struct_value_rtx
422 #undef TARGET_RETURN_IN_MEMORY
423 #define TARGET_RETURN_IN_MEMORY sh_return_in_memory
424
425 #undef TARGET_EXPAND_BUILTIN_SAVEREGS
426 #define TARGET_EXPAND_BUILTIN_SAVEREGS sh_builtin_saveregs
427 #undef TARGET_SETUP_INCOMING_VARARGS
428 #define TARGET_SETUP_INCOMING_VARARGS sh_setup_incoming_varargs
429 #undef TARGET_STRICT_ARGUMENT_NAMING
430 #define TARGET_STRICT_ARGUMENT_NAMING sh_strict_argument_naming
431 #undef TARGET_PRETEND_OUTGOING_VARARGS_NAMED
432 #define TARGET_PRETEND_OUTGOING_VARARGS_NAMED sh_pretend_outgoing_varargs_named
433 #undef TARGET_MUST_PASS_IN_STACK
434 #define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
435 #undef TARGET_PASS_BY_REFERENCE
436 #define TARGET_PASS_BY_REFERENCE sh_pass_by_reference
437 #undef TARGET_CALLEE_COPIES
438 #define TARGET_CALLEE_COPIES sh_callee_copies
439 #undef TARGET_ARG_PARTIAL_BYTES
440 #define TARGET_ARG_PARTIAL_BYTES sh_arg_partial_bytes
441
442 #undef TARGET_BUILD_BUILTIN_VA_LIST
443 #define TARGET_BUILD_BUILTIN_VA_LIST sh_build_builtin_va_list
444 #undef TARGET_EXPAND_BUILTIN_VA_START
445 #define TARGET_EXPAND_BUILTIN_VA_START sh_va_start
446 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
447 #define TARGET_GIMPLIFY_VA_ARG_EXPR sh_gimplify_va_arg_expr
448
449 #undef TARGET_SCALAR_MODE_SUPPORTED_P
450 #define TARGET_SCALAR_MODE_SUPPORTED_P sh_scalar_mode_supported_p
451 #undef TARGET_VECTOR_MODE_SUPPORTED_P
452 #define TARGET_VECTOR_MODE_SUPPORTED_P sh_vector_mode_supported_p
453
454 #undef TARGET_CHECK_PCH_TARGET_FLAGS
455 #define TARGET_CHECK_PCH_TARGET_FLAGS sh_check_pch_target_flags
456
457 #undef TARGET_DWARF_CALLING_CONVENTION
458 #define TARGET_DWARF_CALLING_CONVENTION sh_dwarf_calling_convention
459
460 /* Return regmode weight for insn.  */
461 #define INSN_REGMODE_WEIGHT(INSN, MODE)  regmode_weight[((MODE) == SImode) ? 0 : 1][INSN_UID (INSN)]
462
463 /* Return current register pressure for regmode.  */
464 #define CURR_REGMODE_PRESSURE(MODE)     curr_regmode_pressure[((MODE) == SImode) ? 0 : 1]
465
466 #undef  TARGET_ENCODE_SECTION_INFO
467 #define TARGET_ENCODE_SECTION_INFO      sh_encode_section_info
468
469 #ifdef SYMBIAN
470
471 #undef  TARGET_ENCODE_SECTION_INFO
472 #define TARGET_ENCODE_SECTION_INFO      sh_symbian_encode_section_info
473 #undef  TARGET_STRIP_NAME_ENCODING
474 #define TARGET_STRIP_NAME_ENCODING      sh_symbian_strip_name_encoding
475 #undef  TARGET_CXX_IMPORT_EXPORT_CLASS
476 #define TARGET_CXX_IMPORT_EXPORT_CLASS  symbian_import_export_class
477
478 #endif /* SYMBIAN */
479
480 #undef TARGET_SECONDARY_RELOAD
481 #define TARGET_SECONDARY_RELOAD sh_secondary_reload
482
483 /* Machine-specific symbol_ref flags.  */
484 #define SYMBOL_FLAG_FUNCVEC_FUNCTION    (SYMBOL_FLAG_MACH_DEP << 0)
485
486 struct gcc_target targetm = TARGET_INITIALIZER;
487 \f
488 /* Implement TARGET_HANDLE_OPTION.  */
489
490 static bool
491 sh_handle_option (size_t code, const char *arg ATTRIBUTE_UNUSED,
492                   int value ATTRIBUTE_UNUSED)
493 {
494   switch (code)
495     {
496     case OPT_m1:
497       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH1;
498       return true;
499
500     case OPT_m2:
501       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH2;
502       return true;
503
504     case OPT_m2a:
505       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH2A;
506       return true;
507
508     case OPT_m2a_nofpu:
509       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH2A_NOFPU;
510       return true;
511
512     case OPT_m2a_single:
513       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH2A_SINGLE;
514       return true;
515
516     case OPT_m2a_single_only:
517       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH2A_SINGLE_ONLY;
518       return true;
519
520     case OPT_m2e:
521       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH2E;
522       return true;
523
524     case OPT_m3:
525       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH3;
526       return true;
527
528     case OPT_m3e:
529       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH3E;
530       return true;
531
532     case OPT_m4:
533     case OPT_m4_100:
534     case OPT_m4_200:
535     case OPT_m4_300:
536       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH4;
537       return true;
538
539     case OPT_m4_nofpu:
540     case OPT_m4_100_nofpu:
541     case OPT_m4_200_nofpu:
542     case OPT_m4_300_nofpu:
543     case OPT_m4_340:
544     case OPT_m4_400:
545     case OPT_m4_500:
546       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH4_NOFPU;
547       return true;
548
549     case OPT_m4_single:
550     case OPT_m4_100_single:
551     case OPT_m4_200_single:
552     case OPT_m4_300_single:
553       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH4_SINGLE;
554       return true;
555
556     case OPT_m4_single_only:
557     case OPT_m4_100_single_only:
558     case OPT_m4_200_single_only:
559     case OPT_m4_300_single_only:
560       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH4_SINGLE_ONLY;
561       return true;
562
563     case OPT_m4a:
564       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH4A;
565       return true;
566
567     case OPT_m4a_nofpu:
568     case OPT_m4al:
569       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH4A_NOFPU;
570       return true;
571
572     case OPT_m4a_single:
573       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH4A_SINGLE;
574       return true;
575
576     case OPT_m4a_single_only:
577       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH4A_SINGLE_ONLY;
578       return true;
579
580     case OPT_m5_32media:
581       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH5_32MEDIA;
582       return true;
583
584     case OPT_m5_32media_nofpu:
585       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH5_32MEDIA_NOFPU;
586       return true;
587
588     case OPT_m5_64media:
589       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH5_64MEDIA;
590       return true;
591
592     case OPT_m5_64media_nofpu:
593       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH5_64MEDIA_NOFPU;
594       return true;
595
596     case OPT_m5_compact:
597       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH5_COMPACT;
598       return true;
599
600     case OPT_m5_compact_nofpu:
601       target_flags = (target_flags & ~MASK_ARCH) | SELECT_SH5_COMPACT_NOFPU;
602       return true;
603
604     default:
605       return true;
606     }
607 }
608 \f
609 /* Print the operand address in x to the stream.  */
610
611 void
612 print_operand_address (FILE *stream, rtx x)
613 {
614   switch (GET_CODE (x))
615     {
616     case REG:
617     case SUBREG:
618       fprintf (stream, "@%s", reg_names[true_regnum (x)]);
619       break;
620
621     case PLUS:
622       {
623         rtx base = XEXP (x, 0);
624         rtx index = XEXP (x, 1);
625
626         switch (GET_CODE (index))
627           {
628           case CONST_INT:
629             fprintf (stream, "@(%d,%s)", (int) INTVAL (index),
630                      reg_names[true_regnum (base)]);
631             break;
632
633           case REG:
634           case SUBREG:
635             {
636               int base_num = true_regnum (base);
637               int index_num = true_regnum (index);
638
639               fprintf (stream, "@(r0,%s)",
640                        reg_names[MAX (base_num, index_num)]);
641               break;
642             }
643
644           default:
645             gcc_unreachable ();
646           }
647       }
648       break;
649
650     case PRE_DEC:
651       fprintf (stream, "@-%s", reg_names[true_regnum (XEXP (x, 0))]);
652       break;
653
654     case POST_INC:
655       fprintf (stream, "@%s+", reg_names[true_regnum (XEXP (x, 0))]);
656       break;
657
658     default:
659       x = mark_constant_pool_use (x);
660       output_addr_const (stream, x);
661       break;
662     }
663 }
664
665 /* Print operand x (an rtx) in assembler syntax to file stream
666    according to modifier code.
667
668    '.'  print a .s if insn needs delay slot
669    ','  print LOCAL_LABEL_PREFIX
670    '@'  print trap, rte or rts depending upon pragma interruptness
671    '#'  output a nop if there is nothing to put in the delay slot
672    '''  print likelihood suffix (/u for unlikely).
673    '>'  print branch target if -fverbose-asm
674    'O'  print a constant without the #
675    'R'  print the LSW of a dp value - changes if in little endian
676    'S'  print the MSW of a dp value - changes if in little endian
677    'T'  print the next word of a dp value - same as 'R' in big endian mode.
678    'M'  SHMEDIA: print an `x' if `m' will print `base,index'.
679         otherwise: print .b / .w / .l / .s / .d suffix if operand is a MEM.
680    'N'  print 'r63' if the operand is (const_int 0).
681    'd'  print a V2SF reg as dN instead of fpN.
682    'm'  print a pair `base,offset' or `base,index', for LD and ST.
683    'U'  Likewise for {LD,ST}{HI,LO}.
684    'V'  print the position of a single bit set.
685    'W'  print the position of a single bit cleared.
686    't'  print a memory address which is a register.
687    'u'  prints the lowest 16 bits of CONST_INT, as an unsigned value.
688    'o'  output an operator.  */
689
690 void
691 print_operand (FILE *stream, rtx x, int code)
692 {
693   int regno;
694   enum machine_mode mode;
695
696   switch (code)
697     {
698       tree trapa_attr;
699
700     case '.':
701       if (final_sequence
702           && ! INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0))
703           && get_attr_length (XVECEXP (final_sequence, 0, 1)))
704         fprintf (stream, ASSEMBLER_DIALECT ? "/s" : ".s");
705       break;
706     case ',':
707       fprintf (stream, "%s", LOCAL_LABEL_PREFIX);
708       break;
709     case '@':
710       trapa_attr = lookup_attribute ("trap_exit",
711                                       DECL_ATTRIBUTES (current_function_decl));
712       if (trapa_attr)
713         fprintf (stream, "trapa #%ld",
714                  (long) TREE_INT_CST_LOW (TREE_VALUE (TREE_VALUE (trapa_attr))));
715       else if (sh_cfun_interrupt_handler_p ())
716         {
717           if (sh_cfun_resbank_handler_p ())
718             fprintf (stream, "resbank\n");
719           fprintf (stream, "rte");
720         }
721       else
722         fprintf (stream, "rts");
723       break;
724     case '#':
725       /* Output a nop if there's nothing in the delay slot.  */
726       if (dbr_sequence_length () == 0)
727         fprintf (stream, "\n\tnop");
728       break;
729     case '\'':
730       {
731         rtx note = find_reg_note (current_output_insn, REG_BR_PROB, 0);
732
733         if (note && INTVAL (XEXP (note, 0)) * 2 < REG_BR_PROB_BASE)
734           fputs ("/u", stream);
735         break;
736       }
737     case '>':
738       if (flag_verbose_asm && JUMP_LABEL (current_output_insn))
739         {
740           fputs ("\t! target: ", stream);
741           output_addr_const (stream, JUMP_LABEL (current_output_insn));
742         }
743       break;
744     case 'O':
745       x = mark_constant_pool_use (x);
746       output_addr_const (stream, x);
747       break;
748     /* N.B.: %R / %S / %T adjust memory addresses by four.
749        For SHMEDIA, that means they can be used to access the first and
750        second 32 bit part of a 64 bit (or larger) value that
751        might be held in floating point registers or memory.
752        While they can be used to access 64 bit parts of a larger value
753        held in general purpose registers, that won't work with memory -
754        neither for fp registers, since the frxx names are used.  */
755     case 'R':
756       if (REG_P (x) || GET_CODE (x) == SUBREG)
757         {
758           regno = true_regnum (x);
759           regno += FP_REGISTER_P (regno) ? 1 : LSW;
760           fputs (reg_names[regno], (stream));
761         }
762       else if (MEM_P (x))
763         {
764           x = adjust_address (x, SImode, 4 * LSW);
765           print_operand_address (stream, XEXP (x, 0));
766         }
767       else
768         {
769           rtx sub = NULL_RTX;
770
771           mode = GET_MODE (x);
772           if (mode == VOIDmode)
773             mode = DImode;
774           if (GET_MODE_SIZE (mode) >= 8)
775             sub = simplify_subreg (SImode, x, mode, 4 * LSW);
776           if (sub)
777             print_operand (stream, sub, 0);
778           else
779             output_operand_lossage ("invalid operand to %%R");
780         }
781       break;
782     case 'S':
783       if (REG_P (x) || GET_CODE (x) == SUBREG)
784         {
785           regno = true_regnum (x);
786           regno += FP_REGISTER_P (regno) ? 0 : MSW;
787           fputs (reg_names[regno], (stream));
788         }
789       else if (MEM_P (x))
790         {
791           x = adjust_address (x, SImode, 4 * MSW);
792           print_operand_address (stream, XEXP (x, 0));
793         }
794       else
795         {
796           rtx sub = NULL_RTX;
797
798           mode = GET_MODE (x);
799           if (mode == VOIDmode)
800             mode = DImode;
801           if (GET_MODE_SIZE (mode) >= 8)
802             sub = simplify_subreg (SImode, x, mode, 4 * MSW);
803           if (sub)
804             print_operand (stream, sub, 0);
805           else
806             output_operand_lossage ("invalid operand to %%S");
807         }
808       break;
809     case 'T':
810       /* Next word of a double.  */
811       switch (GET_CODE (x))
812         {
813         case REG:
814           fputs (reg_names[REGNO (x) + 1], (stream));
815           break;
816         case MEM:
817           if (GET_CODE (XEXP (x, 0)) != PRE_DEC
818               && GET_CODE (XEXP (x, 0)) != POST_INC)
819             x = adjust_address (x, SImode, 4);
820           print_operand_address (stream, XEXP (x, 0));
821           break;
822         default:
823           break;
824         }
825       break;
826
827     case 't':
828       gcc_assert (GET_CODE (x) == MEM);
829       x = XEXP (x, 0);
830       switch (GET_CODE (x))
831         {
832         case REG:
833         case SUBREG:
834           print_operand (stream, x, 0);
835           break;
836         default:
837           break;
838         }
839       break;
840
841     case 'o':
842       switch (GET_CODE (x))
843         {
844         case PLUS:  fputs ("add", stream); break;
845         case MINUS: fputs ("sub", stream); break;
846         case MULT:  fputs ("mul", stream); break;
847         case DIV:   fputs ("div", stream); break;
848         case EQ:    fputs ("eq",  stream); break;
849         case NE:    fputs ("ne",  stream); break;
850         case GT:  case LT:  fputs ("gt",  stream); break;
851         case GE:  case LE:  fputs ("ge",  stream); break;
852         case GTU: case LTU: fputs ("gtu", stream); break;
853         case GEU: case LEU: fputs ("geu", stream); break;
854         default:
855           break;
856         }
857       break;
858     case 'M':
859       if (TARGET_SHMEDIA)
860         {
861           if (GET_CODE (x) == MEM
862               && GET_CODE (XEXP (x, 0)) == PLUS
863               && (GET_CODE (XEXP (XEXP (x, 0), 1)) == REG
864                   || GET_CODE (XEXP (XEXP (x, 0), 1)) == SUBREG))
865             fputc ('x', stream);
866         }
867       else
868         {
869           if (GET_CODE (x) == MEM)
870             {
871               switch (GET_MODE (x))
872                 {
873                 case QImode: fputs (".b", stream); break;
874                 case HImode: fputs (".w", stream); break;
875                 case SImode: fputs (".l", stream); break;
876                 case SFmode: fputs (".s", stream); break;
877                 case DFmode: fputs (".d", stream); break;
878                 default: gcc_unreachable ();
879                 }
880             }
881         }
882       break;
883
884     case 'm':
885       gcc_assert (GET_CODE (x) == MEM);
886       x = XEXP (x, 0);
887       /* Fall through.  */
888     case 'U':
889       switch (GET_CODE (x))
890         {
891         case REG:
892         case SUBREG:
893           print_operand (stream, x, 0);
894           fputs (", 0", stream);
895           break;
896
897         case PLUS:
898           print_operand (stream, XEXP (x, 0), 0);
899           fputs (", ", stream);
900           print_operand (stream, XEXP (x, 1), 0);
901           break;
902
903         default:
904           gcc_unreachable ();
905         }
906       break;
907
908     case 'V':
909       {
910         int num = exact_log2 (INTVAL (x));
911         gcc_assert (num >= 0);
912         fprintf (stream, "#%d", num);
913       }
914       break;
915
916     case 'W':
917       {
918         int num = exact_log2 (~INTVAL (x));
919         gcc_assert (num >= 0);
920         fprintf (stream, "#%d", num);
921       }
922       break;
923
924     case 'd':
925       gcc_assert (GET_CODE (x) == REG && GET_MODE (x) == V2SFmode);
926
927       fprintf ((stream), "d%s", reg_names[REGNO (x)] + 1);
928       break;
929
930     case 'N':
931       if (x == CONST0_RTX (GET_MODE (x)))
932         {
933           fprintf ((stream), "r63");
934           break;
935         }
936       goto default_output;
937     case 'u':
938       if (GET_CODE (x) == CONST_INT)
939         {
940           fprintf ((stream), "%u", (unsigned) INTVAL (x) & (0x10000 - 1));
941           break;
942         }
943       /* Fall through.  */
944
945     default_output:
946     default:
947       regno = 0;
948       mode = GET_MODE (x);
949
950       switch (GET_CODE (x))
951         {
952         case TRUNCATE:
953           {
954             rtx inner = XEXP (x, 0);
955             int offset = 0;
956             enum machine_mode inner_mode;
957
958             /* We might see SUBREGs with vector mode registers inside.  */
959             if (GET_CODE (inner) == SUBREG
960                 && (GET_MODE_SIZE (GET_MODE (inner))
961                     == GET_MODE_SIZE (GET_MODE (SUBREG_REG (inner))))
962                 && subreg_lowpart_p (inner))
963               inner = SUBREG_REG (inner);
964             if (GET_CODE (inner) == CONST_INT)
965               {
966                 x = GEN_INT (trunc_int_for_mode (INTVAL (inner), GET_MODE (x)));
967                 goto default_output;
968               }
969             inner_mode = GET_MODE (inner);
970             if (GET_CODE (inner) == SUBREG
971                 && (GET_MODE_SIZE (GET_MODE (inner))
972                     < GET_MODE_SIZE (GET_MODE (SUBREG_REG (inner))))
973                 && GET_CODE (SUBREG_REG (inner)) == REG)
974               {
975                 offset = subreg_regno_offset (REGNO (SUBREG_REG (inner)),
976                                               GET_MODE (SUBREG_REG (inner)),
977                                               SUBREG_BYTE (inner),
978                                               GET_MODE (inner));
979                 inner = SUBREG_REG (inner);
980               }
981             if (GET_CODE (inner) != REG || GET_MODE_SIZE (inner_mode) > 8)
982               abort ();
983             /* Floating point register pairs are always big endian;
984                general purpose registers are 64 bit wide.  */
985             regno = REGNO (inner);
986             regno = (HARD_REGNO_NREGS (regno, inner_mode)
987                      - HARD_REGNO_NREGS (regno, mode))
988                      + offset;
989             x = inner;
990             goto reg;
991           }
992         case SIGN_EXTEND:
993           x = XEXP (x, 0);
994           goto reg;
995           /* FIXME: We need this on SHmedia32 because reload generates
996              some sign-extended HI or QI loads into DImode registers
997              but, because Pmode is SImode, the address ends up with a
998              subreg:SI of the DImode register.  Maybe reload should be
999              fixed so as to apply alter_subreg to such loads?  */
1000         case IF_THEN_ELSE:
1001           gcc_assert (trapping_target_operand (x, VOIDmode));
1002           x = XEXP (XEXP (x, 2), 0);
1003           goto default_output;
1004         case SUBREG:
1005           gcc_assert (SUBREG_BYTE (x) == 0
1006                       && GET_CODE (SUBREG_REG (x)) == REG);
1007
1008           x = SUBREG_REG (x);
1009           /* Fall through.  */
1010
1011         reg:
1012         case REG:
1013           regno += REGNO (x);
1014           if (FP_REGISTER_P (regno)
1015               && mode == V16SFmode)
1016             fprintf ((stream), "mtrx%s", reg_names[regno] + 2);
1017           else if (FP_REGISTER_P (REGNO (x))
1018                    && mode == V4SFmode)
1019             fprintf ((stream), "fv%s", reg_names[regno] + 2);
1020           else if (GET_CODE (x) == REG
1021                    && mode == V2SFmode)
1022             fprintf ((stream), "fp%s", reg_names[regno] + 2);
1023           else if (FP_REGISTER_P (REGNO (x))
1024                    && GET_MODE_SIZE (mode) > 4)
1025             fprintf ((stream), "d%s", reg_names[regno] + 1);
1026           else
1027             fputs (reg_names[regno], (stream));
1028           break;
1029
1030         case MEM:
1031           output_address (XEXP (x, 0));
1032           break;
1033
1034         default:
1035           if (TARGET_SH1)
1036             fputc ('#', stream);
1037           output_addr_const (stream, x);
1038           break;
1039         }
1040       break;
1041     }
1042 }
1043 \f
1044
1045 /* Encode symbol attributes of a SYMBOL_REF into its
1046    SYMBOL_REF_FLAGS.  */
1047 static void
1048 sh_encode_section_info (tree decl, rtx rtl, int first)
1049 {
1050   default_encode_section_info (decl, rtl, first);
1051
1052   if (TREE_CODE (decl) == FUNCTION_DECL
1053       && sh2a_function_vector_p (decl) && TARGET_SH2A)
1054     SYMBOL_REF_FLAGS (XEXP (rtl, 0)) |= SYMBOL_FLAG_FUNCVEC_FUNCTION;
1055 }
1056
1057 /* Like force_operand, but guarantees that VALUE ends up in TARGET.  */
1058 static void
1059 force_into (rtx value, rtx target)
1060 {
1061   value = force_operand (value, target);
1062   if (! rtx_equal_p (value, target))
1063     emit_insn (gen_move_insn (target, value));
1064 }
1065
1066 /* Emit code to perform a block move.  Choose the best method.
1067
1068    OPERANDS[0] is the destination.
1069    OPERANDS[1] is the source.
1070    OPERANDS[2] is the size.
1071    OPERANDS[3] is the alignment safe to use.  */
1072
1073 int
1074 expand_block_move (rtx *operands)
1075 {
1076   int align = INTVAL (operands[3]);
1077   int constp = (GET_CODE (operands[2]) == CONST_INT);
1078   int bytes = (constp ? INTVAL (operands[2]) : 0);
1079
1080   if (! constp)
1081     return 0;
1082
1083   /* If we could use mov.l to move words and dest is word-aligned, we
1084      can use movua.l for loads and still generate a relatively short
1085      and efficient sequence.  */
1086   if (TARGET_SH4A_ARCH && align < 4
1087       && MEM_ALIGN (operands[0]) >= 32
1088       && can_move_by_pieces (bytes, 32))
1089     {
1090       rtx dest = copy_rtx (operands[0]);
1091       rtx src = copy_rtx (operands[1]);
1092       /* We could use different pseudos for each copied word, but
1093          since movua can only load into r0, it's kind of
1094          pointless.  */
1095       rtx temp = gen_reg_rtx (SImode);
1096       rtx src_addr = copy_addr_to_reg (XEXP (src, 0));
1097       int copied = 0;
1098
1099       while (copied + 4 <= bytes)
1100         {
1101           rtx to = adjust_address (dest, SImode, copied);
1102           rtx from = adjust_automodify_address (src, BLKmode,
1103                                                 src_addr, copied);
1104
1105           set_mem_size (from, GEN_INT (4));
1106           emit_insn (gen_movua (temp, from));
1107           emit_move_insn (src_addr, plus_constant (src_addr, 4));
1108           emit_move_insn (to, temp);
1109           copied += 4;
1110         }
1111
1112       if (copied < bytes)
1113         move_by_pieces (adjust_address (dest, BLKmode, copied),
1114                         adjust_automodify_address (src, BLKmode,
1115                                                    src_addr, copied),
1116                         bytes - copied, align, 0);
1117
1118       return 1;
1119     }
1120
1121   /* If it isn't a constant number of bytes, or if it doesn't have 4 byte
1122      alignment, or if it isn't a multiple of 4 bytes, then fail.  */
1123   if (align < 4 || (bytes % 4 != 0))
1124     return 0;
1125
1126   if (TARGET_HARD_SH4)
1127     {
1128       if (bytes < 12)
1129         return 0;
1130       else if (bytes == 12)
1131         {
1132           rtx func_addr_rtx = gen_reg_rtx (Pmode);
1133           rtx r4 = gen_rtx_REG (SImode, 4);
1134           rtx r5 = gen_rtx_REG (SImode, 5);
1135
1136           function_symbol (func_addr_rtx, "__movmemSI12_i4", SFUNC_STATIC);
1137           force_into (XEXP (operands[0], 0), r4);
1138           force_into (XEXP (operands[1], 0), r5);
1139           emit_insn (gen_block_move_real_i4 (func_addr_rtx));
1140           return 1;
1141         }
1142       else if (! TARGET_SMALLCODE)
1143         {
1144           const char *entry_name;
1145           rtx func_addr_rtx = gen_reg_rtx (Pmode);
1146           int dwords;
1147           rtx r4 = gen_rtx_REG (SImode, 4);
1148           rtx r5 = gen_rtx_REG (SImode, 5);
1149           rtx r6 = gen_rtx_REG (SImode, 6);
1150
1151           entry_name = (bytes & 4 ? "__movmem_i4_odd" : "__movmem_i4_even");
1152           function_symbol (func_addr_rtx, entry_name, SFUNC_STATIC);
1153           force_into (XEXP (operands[0], 0), r4);
1154           force_into (XEXP (operands[1], 0), r5);
1155
1156           dwords = bytes >> 3;
1157           emit_insn (gen_move_insn (r6, GEN_INT (dwords - 1)));
1158           emit_insn (gen_block_lump_real_i4 (func_addr_rtx));
1159           return 1;
1160         }
1161       else
1162         return 0;
1163     }
1164   if (bytes < 64)
1165     {
1166       char entry[30];
1167       rtx func_addr_rtx = gen_reg_rtx (Pmode);
1168       rtx r4 = gen_rtx_REG (SImode, 4);
1169       rtx r5 = gen_rtx_REG (SImode, 5);
1170
1171       sprintf (entry, "__movmemSI%d", bytes);
1172       function_symbol (func_addr_rtx, entry, SFUNC_STATIC);
1173       force_into (XEXP (operands[0], 0), r4);
1174       force_into (XEXP (operands[1], 0), r5);
1175       emit_insn (gen_block_move_real (func_addr_rtx));
1176       return 1;
1177     }
1178
1179   /* This is the same number of bytes as a memcpy call, but to a different
1180      less common function name, so this will occasionally use more space.  */
1181   if (! TARGET_SMALLCODE)
1182     {
1183       rtx func_addr_rtx = gen_reg_rtx (Pmode);
1184       int final_switch, while_loop;
1185       rtx r4 = gen_rtx_REG (SImode, 4);
1186       rtx r5 = gen_rtx_REG (SImode, 5);
1187       rtx r6 = gen_rtx_REG (SImode, 6);
1188
1189       function_symbol (func_addr_rtx, "__movmem", SFUNC_STATIC);
1190       force_into (XEXP (operands[0], 0), r4);
1191       force_into (XEXP (operands[1], 0), r5);
1192
1193       /* r6 controls the size of the move.  16 is decremented from it
1194          for each 64 bytes moved.  Then the negative bit left over is used
1195          as an index into a list of move instructions.  e.g., a 72 byte move
1196          would be set up with size(r6) = 14, for one iteration through the
1197          big while loop, and a switch of -2 for the last part.  */
1198
1199       final_switch = 16 - ((bytes / 4) % 16);
1200       while_loop = ((bytes / 4) / 16 - 1) * 16;
1201       emit_insn (gen_move_insn (r6, GEN_INT (while_loop + final_switch)));
1202       emit_insn (gen_block_lump_real (func_addr_rtx));
1203       return 1;
1204     }
1205
1206   return 0;
1207 }
1208
1209 /* Prepare operands for a move define_expand; specifically, one of the
1210    operands must be in a register.  */
1211
1212 int
1213 prepare_move_operands (rtx operands[], enum machine_mode mode)
1214 {
1215   if ((mode == SImode || mode == DImode)
1216       && flag_pic
1217       && ! ((mode == Pmode || mode == ptr_mode)
1218             && tls_symbolic_operand (operands[1], Pmode) != TLS_MODEL_NONE))
1219     {
1220       rtx temp;
1221       if (SYMBOLIC_CONST_P (operands[1]))
1222         {
1223           if (GET_CODE (operands[0]) == MEM)
1224             operands[1] = force_reg (Pmode, operands[1]);
1225           else if (TARGET_SHMEDIA
1226                    && GET_CODE (operands[1]) == LABEL_REF
1227                    && target_reg_operand (operands[0], mode))
1228             /* It's ok.  */;
1229           else
1230             {
1231               temp = (!can_create_pseudo_p ()
1232                       ? operands[0]
1233                       : gen_reg_rtx (Pmode));
1234               operands[1] = legitimize_pic_address (operands[1], mode, temp);
1235             }
1236         }
1237       else if (GET_CODE (operands[1]) == CONST
1238                && GET_CODE (XEXP (operands[1], 0)) == PLUS
1239                && SYMBOLIC_CONST_P (XEXP (XEXP (operands[1], 0), 0)))
1240         {
1241           temp = !can_create_pseudo_p () ? operands[0] : gen_reg_rtx (Pmode);
1242           temp = legitimize_pic_address (XEXP (XEXP (operands[1], 0), 0),
1243                                          mode, temp);
1244           operands[1] = expand_binop (mode, add_optab, temp,
1245                                       XEXP (XEXP (operands[1], 0), 1),
1246                                       (!can_create_pseudo_p ()
1247                                        ? temp
1248                                        : gen_reg_rtx (Pmode)),
1249                                       0, OPTAB_LIB_WIDEN);
1250         }
1251     }
1252
1253   if (! reload_in_progress && ! reload_completed)
1254     {
1255       /* Copy the source to a register if both operands aren't registers.  */
1256       if (! register_operand (operands[0], mode)
1257           && ! sh_register_operand (operands[1], mode))
1258         operands[1] = copy_to_mode_reg (mode, operands[1]);
1259
1260       if (GET_CODE (operands[0]) == MEM && ! memory_operand (operands[0], mode))
1261         {
1262           /* This is like change_address_1 (operands[0], mode, 0, 1) ,
1263              except that we can't use that function because it is static.  */
1264           rtx new_rtx = change_address (operands[0], mode, 0);
1265           MEM_COPY_ATTRIBUTES (new_rtx, operands[0]);
1266           operands[0] = new_rtx;
1267         }
1268
1269       /* This case can happen while generating code to move the result
1270          of a library call to the target.  Reject `st r0,@(rX,rY)' because
1271          reload will fail to find a spill register for rX, since r0 is already
1272          being used for the source.  */
1273       else if (TARGET_SH1
1274                && refers_to_regno_p (R0_REG, R0_REG + 1, operands[1], (rtx *)0)
1275                && GET_CODE (operands[0]) == MEM
1276                && GET_CODE (XEXP (operands[0], 0)) == PLUS
1277                && GET_CODE (XEXP (XEXP (operands[0], 0), 1)) == REG)
1278         operands[1] = copy_to_mode_reg (mode, operands[1]);
1279     }
1280
1281   if (mode == Pmode || mode == ptr_mode)
1282     {
1283       rtx op0, op1, opc;
1284       enum tls_model tls_kind;
1285
1286       op0 = operands[0];
1287       op1 = operands[1];
1288       if (GET_CODE (op1) == CONST
1289           && GET_CODE (XEXP (op1, 0)) == PLUS
1290           && (tls_symbolic_operand (XEXP (XEXP (op1, 0), 0), Pmode)
1291               != TLS_MODEL_NONE))
1292         {
1293           opc = XEXP (XEXP (op1, 0), 1);
1294           op1 = XEXP (XEXP (op1, 0), 0);
1295         }
1296       else
1297         opc = NULL_RTX;
1298
1299       if ((tls_kind = tls_symbolic_operand (op1, Pmode)) != TLS_MODEL_NONE)
1300         {
1301           rtx tga_op1, tga_ret, tmp, tmp2;
1302
1303           switch (tls_kind)
1304             {
1305             case TLS_MODEL_GLOBAL_DYNAMIC:
1306               tga_ret = gen_rtx_REG (Pmode, R0_REG);
1307               emit_call_insn (gen_tls_global_dynamic (tga_ret, op1));
1308               op1 = tga_ret;
1309               break;
1310
1311             case TLS_MODEL_LOCAL_DYNAMIC:
1312               tga_ret = gen_rtx_REG (Pmode, R0_REG);
1313               emit_call_insn (gen_tls_local_dynamic (tga_ret, op1));
1314
1315               tmp = gen_reg_rtx (Pmode);
1316               emit_move_insn (tmp, tga_ret);
1317
1318               if (register_operand (op0, Pmode))
1319                 tmp2 = op0;
1320               else
1321                 tmp2 = gen_reg_rtx (Pmode);
1322
1323               emit_insn (gen_symDTPOFF2reg (tmp2, op1, tmp));
1324               op1 = tmp2;
1325               break;
1326
1327             case TLS_MODEL_INITIAL_EXEC:
1328               if (! flag_pic)
1329                 {
1330                   /* Don't schedule insns for getting GOT address when
1331                      the first scheduling is enabled, to avoid spill
1332                      failures for R0.  */
1333                   if (flag_schedule_insns)
1334                     emit_insn (gen_blockage ());
1335                   emit_insn (gen_GOTaddr2picreg ());
1336                   emit_use (gen_rtx_REG (SImode, PIC_REG));
1337                   if (flag_schedule_insns)
1338                     emit_insn (gen_blockage ());
1339                 }
1340               tga_op1 = !can_create_pseudo_p () ? op0 : gen_reg_rtx (Pmode);
1341               tmp = gen_sym2GOTTPOFF (op1);
1342               emit_insn (gen_tls_initial_exec (tga_op1, tmp));
1343               op1 = tga_op1;
1344               break;
1345
1346             case TLS_MODEL_LOCAL_EXEC:
1347               tmp2 = gen_reg_rtx (Pmode);
1348               emit_insn (gen_load_gbr (tmp2));
1349               tmp = gen_reg_rtx (Pmode);
1350               emit_insn (gen_symTPOFF2reg (tmp, op1));
1351
1352               if (register_operand (op0, Pmode))
1353                 op1 = op0;
1354               else
1355                 op1 = gen_reg_rtx (Pmode);
1356
1357               emit_insn (gen_addsi3 (op1, tmp, tmp2));
1358               break;
1359
1360             default:
1361               gcc_unreachable ();
1362             }
1363           if (opc)
1364             emit_insn (gen_addsi3 (op1, op1, force_reg (SImode, opc)));
1365           operands[1] = op1;
1366         }
1367     }
1368
1369   return 0;
1370 }
1371
1372 enum rtx_code
1373 prepare_cbranch_operands (rtx *operands, enum machine_mode mode,
1374                           enum rtx_code comparison)
1375 {
1376   rtx op1;
1377   rtx scratch = NULL_RTX;
1378
1379   if (comparison == LAST_AND_UNUSED_RTX_CODE)
1380     comparison = GET_CODE (operands[0]);
1381   else
1382     scratch = operands[4];
1383   if (GET_CODE (operands[1]) == CONST_INT
1384       && GET_CODE (operands[2]) != CONST_INT)
1385     {
1386       rtx tmp = operands[1];
1387
1388       operands[1] = operands[2];
1389       operands[2] = tmp;
1390       comparison = swap_condition (comparison);
1391     }
1392   if (GET_CODE (operands[2]) == CONST_INT)
1393     {
1394       HOST_WIDE_INT val = INTVAL (operands[2]);
1395       if ((val == -1 || val == -0x81)
1396           && (comparison == GT || comparison == LE))
1397         {
1398           comparison = (comparison == GT) ? GE : LT;
1399           operands[2] = gen_int_mode (val + 1, mode);
1400         }
1401       else if ((val == 1 || val == 0x80)
1402                && (comparison == GE || comparison == LT))
1403         {
1404           comparison = (comparison == GE) ? GT : LE;
1405           operands[2] = gen_int_mode (val - 1, mode);
1406         }
1407       else if (val == 1 && (comparison == GEU || comparison == LTU))
1408         {
1409           comparison = (comparison == GEU) ? NE : EQ;
1410           operands[2] = CONST0_RTX (mode);
1411         }
1412       else if (val == 0x80 && (comparison == GEU || comparison == LTU))
1413         {
1414           comparison = (comparison == GEU) ? GTU : LEU;
1415           operands[2] = gen_int_mode (val - 1, mode);
1416         }
1417       else if (val == 0 && (comparison == GTU || comparison == LEU))
1418         comparison = (comparison == GTU) ? NE : EQ;
1419       else if (mode == SImode
1420                && ((val == 0x7fffffff
1421                     && (comparison == GTU || comparison == LEU))
1422                    || ((unsigned HOST_WIDE_INT) val
1423                         == (unsigned HOST_WIDE_INT) 0x7fffffff + 1
1424                        && (comparison == GEU || comparison == LTU))))
1425         {
1426           comparison = (comparison == GTU || comparison == GEU) ? LT : GE;
1427           operands[2] = CONST0_RTX (mode);
1428         }
1429     }
1430   op1 = operands[1];
1431   if (can_create_pseudo_p ())
1432     operands[1] = force_reg (mode, op1);
1433   /* When we are handling DImode comparisons, we want to keep constants so
1434      that we can optimize the component comparisons; however, memory loads
1435      are better issued as a whole so that they can be scheduled well.
1436      SImode equality comparisons allow I08 constants, but only when they
1437      compare r0.  Hence, if operands[1] has to be loaded from somewhere else
1438      into a register, that register might as well be r0, and we allow the
1439      constant.  If it is already in a register, this is likely to be
1440      allocated to a different hard register, thus we load the constant into
1441      a register unless it is zero.  */
1442   if (!REG_P (operands[2])
1443       && (GET_CODE (operands[2]) != CONST_INT
1444           || (mode == SImode && operands[2] != CONST0_RTX (SImode)
1445               && ((comparison != EQ && comparison != NE)
1446                   || (REG_P (op1) && REGNO (op1) != R0_REG)
1447                   || !satisfies_constraint_I08 (operands[2])))))
1448     {
1449       if (scratch && GET_MODE (scratch) == mode)
1450         {
1451           emit_move_insn (scratch, operands[2]);
1452           operands[2] = scratch;
1453         }
1454       else if (can_create_pseudo_p ())
1455         operands[2] = force_reg (mode, operands[2]);
1456     }
1457   return comparison;
1458 }
1459
1460 void
1461 expand_cbranchsi4 (rtx *operands, enum rtx_code comparison, int probability)
1462 {
1463   rtx (*branch_expander) (rtx) = gen_branch_true;
1464   rtx jump;
1465
1466   comparison = prepare_cbranch_operands (operands, SImode, comparison);
1467   switch (comparison)
1468     {
1469     case NE: case LT: case LE: case LTU: case LEU:
1470       comparison = reverse_condition (comparison);
1471       branch_expander = gen_branch_false;
1472     default: ;
1473     }
1474   emit_insn (gen_rtx_SET (VOIDmode, gen_rtx_REG (SImode, T_REG),
1475                           gen_rtx_fmt_ee (comparison, SImode,
1476                                           operands[1], operands[2])));
1477   jump = emit_jump_insn (branch_expander (operands[3]));
1478   if (probability >= 0)
1479     add_reg_note (jump, REG_BR_PROB, GEN_INT (probability));
1480
1481 }
1482
1483 /* ??? How should we distribute probabilities when more than one branch
1484    is generated.  So far we only have soem ad-hoc observations:
1485    - If the operands are random, they are likely to differ in both parts.
1486    - If comparing items in a hash chain, the operands are random or equal;
1487      operation should be EQ or NE.
1488    - If items are searched in an ordered tree from the root, we can expect
1489      the highpart to be unequal about half of the time; operation should be
1490      an inequality comparison, operands non-constant, and overall probability
1491      about 50%.  Likewise for quicksort.
1492    - Range checks will be often made against constants.  Even if we assume for
1493      simplicity an even distribution of the non-constant operand over a
1494      sub-range here, the same probability could be generated with differently
1495      wide sub-ranges - as long as the ratio of the part of the subrange that
1496      is before the threshold to the part that comes after the threshold stays
1497      the same.  Thus, we can't really tell anything here;
1498      assuming random distribution is at least simple.
1499  */
1500
1501 bool
1502 expand_cbranchdi4 (rtx *operands, enum rtx_code comparison)
1503 {
1504   enum rtx_code msw_taken, msw_skip, lsw_taken;
1505   rtx skip_label = NULL_RTX;
1506   rtx op1h, op1l, op2h, op2l;
1507   int num_branches;
1508   int prob, rev_prob;
1509   int msw_taken_prob = -1, msw_skip_prob = -1, lsw_taken_prob = -1;
1510   rtx scratch = operands[4];
1511
1512   comparison = prepare_cbranch_operands (operands, DImode, comparison);
1513   op1h = gen_highpart_mode (SImode, DImode, operands[1]);
1514   op2h = gen_highpart_mode (SImode, DImode, operands[2]);
1515   op1l = gen_lowpart (SImode, operands[1]);
1516   op2l = gen_lowpart (SImode, operands[2]);
1517   msw_taken = msw_skip = lsw_taken = LAST_AND_UNUSED_RTX_CODE;
1518   prob = split_branch_probability;
1519   rev_prob = REG_BR_PROB_BASE - prob;
1520   switch (comparison)
1521     {
1522     /* ??? Should we use the cmpeqdi_t pattern for equality comparisons?
1523        That costs 1 cycle more when the first branch can be predicted taken,
1524        but saves us mispredicts because only one branch needs prediction.
1525        It also enables generating the cmpeqdi_t-1 pattern.  */
1526     case EQ:
1527       if (TARGET_CMPEQDI_T)
1528         {
1529           emit_insn (gen_cmpeqdi_t (operands[1], operands[2]));
1530           emit_jump_insn (gen_branch_true (operands[3]));
1531           return true;
1532         }
1533       msw_skip = NE;
1534       lsw_taken = EQ;
1535       if (prob >= 0)
1536         {
1537           /* If we had more precision, we'd use rev_prob - (rev_prob >> 32) .
1538            */
1539           msw_skip_prob = rev_prob;
1540           if (REG_BR_PROB_BASE <= 65535)
1541             lsw_taken_prob = prob ? REG_BR_PROB_BASE : 0;
1542           else
1543             {
1544               gcc_assert (HOST_BITS_PER_WIDEST_INT >= 64);
1545               lsw_taken_prob
1546                 = (prob
1547                    ? (REG_BR_PROB_BASE
1548                       - ((HOST_WIDEST_INT) REG_BR_PROB_BASE * rev_prob
1549                          / ((HOST_WIDEST_INT) prob << 32)))
1550                    : 0);
1551             }
1552         }
1553       break;
1554     case NE:
1555       if (TARGET_CMPEQDI_T)
1556         {
1557           emit_insn (gen_cmpeqdi_t (operands[1], operands[2]));
1558           emit_jump_insn (gen_branch_false (operands[3]));
1559           return true;
1560         }
1561       msw_taken = NE;
1562       msw_taken_prob = prob;
1563       lsw_taken = NE;
1564       lsw_taken_prob = 0;
1565       break;
1566     case GTU: case GT:
1567       msw_taken = comparison;
1568       if (GET_CODE (op2l) == CONST_INT && INTVAL (op2l) == -1)
1569         break;
1570       if (comparison != GTU || op2h != CONST0_RTX (SImode))
1571         msw_skip = swap_condition (msw_taken);
1572       lsw_taken = GTU;
1573       break;
1574     case GEU: case GE:
1575       if (op2l == CONST0_RTX (SImode))
1576         msw_taken = comparison;
1577       else
1578         {
1579           msw_taken = comparison == GE ? GT : GTU;
1580           msw_skip = swap_condition (msw_taken);
1581           lsw_taken = GEU;
1582         }
1583       break;
1584     case LTU: case LT:
1585       msw_taken = comparison;
1586       if (op2l == CONST0_RTX (SImode))
1587         break;
1588       msw_skip = swap_condition (msw_taken);
1589       lsw_taken = LTU;
1590       break;
1591     case LEU: case LE:
1592       if (GET_CODE (op2l) == CONST_INT && INTVAL (op2l) == -1)
1593         msw_taken = comparison;
1594       else
1595         {
1596           lsw_taken = LEU;
1597           if (comparison == LE)
1598             msw_taken = LT;
1599           else if (op2h != CONST0_RTX (SImode))
1600             msw_taken = LTU;
1601           else
1602             break;
1603           msw_skip = swap_condition (msw_taken);
1604         }
1605       break;
1606     default: return false;
1607     }
1608   num_branches = ((msw_taken != LAST_AND_UNUSED_RTX_CODE)
1609                   + (msw_skip != LAST_AND_UNUSED_RTX_CODE)
1610                   + (lsw_taken != LAST_AND_UNUSED_RTX_CODE));
1611   if (comparison != EQ && comparison != NE && num_branches > 1)
1612     {
1613       if (!CONSTANT_P (operands[2])
1614           && prob >= (int) (REG_BR_PROB_BASE * 3 / 8U)
1615           && prob <= (int) (REG_BR_PROB_BASE * 5 / 8U))
1616         {
1617           msw_taken_prob = prob / 2U;
1618           msw_skip_prob
1619             = REG_BR_PROB_BASE * rev_prob / (REG_BR_PROB_BASE + rev_prob);
1620           lsw_taken_prob = prob;
1621         }
1622       else
1623         {
1624           msw_taken_prob = prob;
1625           msw_skip_prob = REG_BR_PROB_BASE;
1626           /* ??? If we have a constant op2h, should we use that when
1627              calculating lsw_taken_prob?  */
1628           lsw_taken_prob = prob;
1629         }
1630     }
1631   operands[1] = op1h;
1632   operands[2] = op2h;
1633   operands[4] = NULL_RTX;
1634   if (reload_completed
1635       && ! arith_reg_or_0_operand (op2h, SImode) && true_regnum (op1h)
1636       && (msw_taken != LAST_AND_UNUSED_RTX_CODE
1637           || msw_skip != LAST_AND_UNUSED_RTX_CODE))
1638     {
1639       emit_move_insn (scratch, operands[2]);
1640       operands[2] = scratch;
1641     }
1642   if (msw_taken != LAST_AND_UNUSED_RTX_CODE)
1643     expand_cbranchsi4 (operands, msw_taken, msw_taken_prob);
1644   if (msw_skip != LAST_AND_UNUSED_RTX_CODE)
1645     {
1646       rtx taken_label = operands[3];
1647
1648       /* Operands were possibly modified, but msw_skip doesn't expect this.
1649          Always use the original ones.  */
1650       if (msw_taken != LAST_AND_UNUSED_RTX_CODE)
1651         {
1652           operands[1] = op1h;
1653           operands[2] = op2h;
1654         }
1655
1656       operands[3] = skip_label = gen_label_rtx ();
1657       expand_cbranchsi4 (operands, msw_skip, msw_skip_prob);
1658       operands[3] = taken_label;
1659     }
1660   operands[1] = op1l;
1661   operands[2] = op2l;
1662   if (lsw_taken != LAST_AND_UNUSED_RTX_CODE)
1663     {
1664       if (reload_completed
1665           && ! arith_reg_or_0_operand (op2l, SImode) && true_regnum (op1l))
1666         operands[4] = scratch;
1667       expand_cbranchsi4 (operands, lsw_taken, lsw_taken_prob);
1668     }
1669   if (msw_skip != LAST_AND_UNUSED_RTX_CODE)
1670     emit_label (skip_label);
1671   return true;
1672 }
1673
1674 /* Emit INSN, possibly in a PARALLEL with an USE of fpscr for SH4.  */
1675
1676 static void
1677 sh_emit_set_t_insn (rtx insn, enum machine_mode mode)
1678 {
1679   if ((TARGET_SH4 || TARGET_SH2A) && GET_MODE_CLASS (mode) == MODE_FLOAT)
1680     {
1681       insn = gen_rtx_PARALLEL (VOIDmode,
1682                        gen_rtvec (2, insn,
1683                                   gen_rtx_USE (VOIDmode, get_fpscr_rtx ())));
1684       (mode == SFmode ? emit_sf_insn : emit_df_insn) (insn);
1685     }
1686   else
1687     emit_insn (insn);
1688 }
1689
1690 /* Prepare the operands for an scc instruction; make sure that the
1691    compare has been done and the result is in T_REG.  */
1692 void
1693 sh_emit_scc_to_t (enum rtx_code code, rtx op0, rtx op1)
1694 {
1695   rtx t_reg = gen_rtx_REG (SImode, T_REG);
1696   enum rtx_code oldcode = code;
1697   enum machine_mode mode;
1698
1699   /* First need a compare insn.  */
1700   switch (code)
1701     {
1702     case NE:
1703       /* It isn't possible to handle this case.  */
1704       gcc_unreachable ();
1705     case LT:
1706       code = GT;
1707       break;
1708     case LE:
1709       code = GE;
1710       break;
1711     case LTU:
1712       code = GTU;
1713       break;
1714     case LEU:
1715       code = GEU;
1716       break;
1717     default:
1718       break;
1719     }
1720   if (code != oldcode)
1721     {
1722       rtx tmp = op0;
1723       op0 = op1;
1724       op1 = tmp;
1725     }
1726
1727   mode = GET_MODE (op0);
1728   if (mode == VOIDmode)
1729     mode = GET_MODE (op1);
1730
1731   op0 = force_reg (mode, op0);
1732   if ((code != EQ && code != NE
1733        && (op1 != const0_rtx
1734            || code == GTU  || code == GEU || code == LTU || code == LEU))
1735       || (mode == DImode && op1 != const0_rtx)
1736       || (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT))
1737     op1 = force_reg (mode, op1);
1738
1739   sh_emit_set_t_insn (gen_rtx_SET (VOIDmode, t_reg,
1740                                    gen_rtx_fmt_ee (code, SImode, op0, op1)),
1741                       mode);
1742 }
1743
1744 rtx
1745 sh_emit_cheap_store_flag (enum machine_mode mode, enum rtx_code code,
1746                           rtx op0, rtx op1)
1747 {
1748   rtx target = gen_reg_rtx (SImode);
1749   rtx tmp;
1750
1751   gcc_assert (TARGET_SHMEDIA);
1752   switch (code)
1753     {
1754     case EQ:
1755     case GT:
1756     case LT:
1757     case UNORDERED:
1758     case GTU:
1759     case LTU:
1760       tmp = gen_rtx_fmt_ee (code, SImode, op0, op1);
1761       emit_insn (gen_cstore4_media (target, tmp, op0, op1));
1762       code = NE;
1763       break;
1764
1765     case NE:
1766     case GE:
1767     case LE:
1768     case ORDERED:
1769     case GEU:
1770     case LEU:
1771       tmp = gen_rtx_fmt_ee (reverse_condition (code), mode, op0, op1);
1772       emit_insn (gen_cstore4_media (target, tmp, op0, op1));
1773       code = EQ;
1774       break;
1775
1776     case UNEQ:
1777     case UNGE:
1778     case UNGT:
1779     case UNLE:
1780     case UNLT:
1781     case LTGT:
1782       return NULL_RTX;
1783
1784     default:
1785       gcc_unreachable ();
1786     }
1787
1788   if (mode == DImode)
1789     {
1790       rtx t2 = gen_reg_rtx (DImode);
1791       emit_insn (gen_extendsidi2 (t2, target));
1792       target = t2;
1793     }
1794
1795   return gen_rtx_fmt_ee (code, VOIDmode, target, const0_rtx);
1796 }
1797
1798 /* Called from the md file, set up the operands of a compare instruction.  */
1799
1800 void
1801 sh_emit_compare_and_branch (rtx *operands, enum machine_mode mode)
1802 {
1803   enum rtx_code code = GET_CODE (operands[0]);
1804   enum rtx_code branch_code;
1805   rtx op0 = operands[1];
1806   rtx op1 = operands[2];
1807   rtx insn, tem;
1808   bool need_ccmpeq = false;
1809
1810   if (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT)
1811     {
1812       op0 = force_reg (mode, op0);
1813       op1 = force_reg (mode, op1);
1814     }
1815   else
1816     {
1817       if (code != EQ || mode == DImode)
1818         {
1819           /* Force args into regs, since we can't use constants here.  */
1820           op0 = force_reg (mode, op0);
1821           if (op1 != const0_rtx || code == GTU  || code == GEU)
1822             op1 = force_reg (mode, op1);
1823         }
1824     }
1825
1826   if (GET_MODE_CLASS (mode) == MODE_FLOAT)
1827     {
1828       if (code == LT
1829           || (code == LE && TARGET_IEEE && TARGET_SH2E)
1830           || (code == GE && !(TARGET_IEEE && TARGET_SH2E)))
1831         {
1832           tem = op0, op0 = op1, op1 = tem;
1833           code = swap_condition (code);
1834         }
1835
1836       /* GE becomes fcmp/gt+fcmp/eq, for SH2E and TARGET_IEEE only.  */
1837       if (code == GE)
1838         {
1839           gcc_assert (TARGET_IEEE && TARGET_SH2E);
1840           need_ccmpeq = true;
1841           code = GT;
1842         }
1843
1844       /* Now we can have EQ, NE, GT, LE.  NE and LE are then transformed
1845          to EQ/GT respectively.  */
1846       gcc_assert (code == EQ || code == GT || code == NE || code == LE);
1847     }
1848
1849   switch (code)
1850     {
1851     case EQ:
1852     case GT:
1853     case GE:
1854     case GTU:
1855     case GEU:
1856       branch_code = code;
1857       break;
1858     case NE:
1859     case LT:
1860     case LE:
1861     case LTU:
1862     case LEU:
1863       branch_code = reverse_condition (code);
1864       break;
1865     default:
1866       gcc_unreachable ();
1867     }
1868
1869   insn = gen_rtx_SET (VOIDmode,
1870                       gen_rtx_REG (SImode, T_REG),
1871                       gen_rtx_fmt_ee (branch_code, SImode, op0, op1));
1872
1873   sh_emit_set_t_insn (insn, mode);
1874   if (need_ccmpeq)
1875     sh_emit_set_t_insn (gen_ieee_ccmpeqsf_t (op0, op1), mode);
1876
1877   if (branch_code == code)
1878     emit_jump_insn (gen_branch_true (operands[3]));
1879   else
1880     emit_jump_insn (gen_branch_false (operands[3]));
1881 }
1882
1883 void
1884 sh_emit_compare_and_set (rtx *operands, enum machine_mode mode)
1885 {
1886   enum rtx_code code = GET_CODE (operands[1]);
1887   rtx op0 = operands[2];
1888   rtx op1 = operands[3];
1889   rtx lab = NULL_RTX;
1890   bool invert = false;
1891   rtx tem;
1892
1893   op0 = force_reg (mode, op0);
1894   if ((code != EQ && code != NE
1895        && (op1 != const0_rtx
1896            || code == GTU  || code == GEU || code == LTU || code == LEU))
1897       || (mode == DImode && op1 != const0_rtx)
1898       || (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT))
1899     op1 = force_reg (mode, op1);
1900
1901   if (GET_MODE_CLASS (mode) == MODE_FLOAT)
1902     {
1903       if (code == LT || code == LE)
1904         {
1905           code = swap_condition (code);
1906           tem = op0, op0 = op1, op1 = tem;
1907         }
1908       if (code == GE)
1909         {
1910           if (TARGET_IEEE)
1911             {
1912               lab = gen_label_rtx ();
1913               sh_emit_scc_to_t (EQ, op0, op1);
1914               emit_jump_insn (gen_branch_true (lab));
1915               code = GT;
1916            }
1917           else
1918             {
1919               code = LT;
1920               invert = true;
1921             }
1922         }
1923     }
1924
1925   if (code == NE)
1926     {
1927       code = EQ;
1928       invert = true;
1929     }
1930
1931   sh_emit_scc_to_t (code, op0, op1);
1932   if (lab)
1933     emit_label (lab);
1934   if (invert)
1935     emit_insn (gen_movnegt (operands[0]));
1936   else
1937     emit_move_insn (operands[0], gen_rtx_REG (SImode, T_REG));
1938 }
1939 \f
1940 /* Functions to output assembly code.  */
1941
1942 /* Return a sequence of instructions to perform DI or DF move.
1943
1944    Since the SH cannot move a DI or DF in one instruction, we have
1945    to take care when we see overlapping source and dest registers.  */
1946
1947 const char *
1948 output_movedouble (rtx insn ATTRIBUTE_UNUSED, rtx operands[],
1949                    enum machine_mode mode)
1950 {
1951   rtx dst = operands[0];
1952   rtx src = operands[1];
1953
1954   if (GET_CODE (dst) == MEM
1955       && GET_CODE (XEXP (dst, 0)) == PRE_DEC)
1956     return "mov.l       %T1,%0\n\tmov.l %1,%0";
1957
1958   if (register_operand (dst, mode)
1959       && register_operand (src, mode))
1960     {
1961       if (REGNO (src) == MACH_REG)
1962         return "sts     mach,%S0\n\tsts macl,%R0";
1963
1964       /* When mov.d r1,r2 do r2->r3 then r1->r2;
1965          when mov.d r1,r0 do r1->r0 then r2->r1.  */
1966
1967       if (REGNO (src) + 1 == REGNO (dst))
1968         return "mov     %T1,%T0\n\tmov  %1,%0";
1969       else
1970         return "mov     %1,%0\n\tmov    %T1,%T0";
1971     }
1972   else if (GET_CODE (src) == CONST_INT)
1973     {
1974       if (INTVAL (src) < 0)
1975         output_asm_insn ("mov   #-1,%S0", operands);
1976       else
1977         output_asm_insn ("mov   #0,%S0", operands);
1978
1979       return "mov       %1,%R0";
1980     }
1981   else if (GET_CODE (src) == MEM)
1982     {
1983       int ptrreg = -1;
1984       int dreg = REGNO (dst);
1985       rtx inside = XEXP (src, 0);
1986
1987       switch (GET_CODE (inside))
1988         {
1989         case REG:
1990           ptrreg = REGNO (inside);
1991           break;
1992
1993         case SUBREG:
1994           ptrreg = subreg_regno (inside);
1995           break;
1996
1997         case PLUS:
1998           ptrreg = REGNO (XEXP (inside, 0));
1999           /* ??? A r0+REG address shouldn't be possible here, because it isn't
2000              an offsettable address.  Unfortunately, offsettable addresses use
2001              QImode to check the offset, and a QImode offsettable address
2002              requires r0 for the other operand, which is not currently
2003              supported, so we can't use the 'o' constraint.
2004              Thus we must check for and handle r0+REG addresses here.
2005              We punt for now, since this is likely very rare.  */
2006           gcc_assert (GET_CODE (XEXP (inside, 1)) != REG);
2007           break;
2008           
2009         case LABEL_REF:
2010           return "mov.l %1,%0\n\tmov.l  %1+4,%T0";
2011         case POST_INC:
2012           return "mov.l %1,%0\n\tmov.l  %1,%T0";
2013         default:
2014           gcc_unreachable ();
2015         }
2016
2017       /* Work out the safe way to copy.  Copy into the second half first.  */
2018       if (dreg == ptrreg)
2019         return "mov.l   %T1,%T0\n\tmov.l        %1,%0";
2020     }
2021
2022   return "mov.l %1,%0\n\tmov.l  %T1,%T0";
2023 }
2024
2025 /* Print an instruction which would have gone into a delay slot after
2026    another instruction, but couldn't because the other instruction expanded
2027    into a sequence where putting the slot insn at the end wouldn't work.  */
2028
2029 static void
2030 print_slot (rtx insn)
2031 {
2032   final_scan_insn (XVECEXP (insn, 0, 1), asm_out_file, optimize, 1, NULL);
2033
2034   INSN_DELETED_P (XVECEXP (insn, 0, 1)) = 1;
2035 }
2036
2037 const char *
2038 output_far_jump (rtx insn, rtx op)
2039 {
2040   struct { rtx lab, reg, op; } this_jmp;
2041   rtx braf_base_lab = NULL_RTX;
2042   const char *jump;
2043   int far;
2044   int offset = branch_dest (insn) - INSN_ADDRESSES (INSN_UID (insn));
2045   rtx prev;
2046
2047   this_jmp.lab = gen_label_rtx ();
2048
2049   if (TARGET_SH2
2050       && offset >= -32764
2051       && offset - get_attr_length (insn) <= 32766)
2052     {
2053       far = 0;
2054       jump = "mov.w     %O0,%1; braf    %1";
2055     }
2056   else
2057     {
2058       far = 1;
2059       if (flag_pic)
2060         {
2061           if (TARGET_SH2)
2062             jump = "mov.l       %O0,%1; braf    %1";
2063           else
2064             jump = "mov.l       r0,@-r15; mova  %O0,r0; mov.l   @r0,%1; add     r0,%1; mov.l    @r15+,r0; jmp   @%1";
2065         }
2066       else
2067         jump = "mov.l   %O0,%1; jmp     @%1";
2068     }
2069   /* If we have a scratch register available, use it.  */
2070   if (GET_CODE ((prev = prev_nonnote_insn (insn))) == INSN
2071       && INSN_CODE (prev) == CODE_FOR_indirect_jump_scratch)
2072     {
2073       this_jmp.reg = SET_DEST (XVECEXP (PATTERN (prev), 0, 0));
2074       if (REGNO (this_jmp.reg) == R0_REG && flag_pic && ! TARGET_SH2)
2075         jump = "mov.l   r1,@-r15; mova  %O0,r0; mov.l   @r0,r1; add     r1,r0; mov.l    @r15+,r1; jmp   @%1";
2076       output_asm_insn (jump, &this_jmp.lab);
2077       if (dbr_sequence_length ())
2078         print_slot (final_sequence);
2079       else
2080         output_asm_insn ("nop", 0);
2081     }
2082   else
2083     {
2084       /* Output the delay slot insn first if any.  */
2085       if (dbr_sequence_length ())
2086         print_slot (final_sequence);
2087
2088       this_jmp.reg = gen_rtx_REG (SImode, 13);
2089       /* We must keep the stack aligned to 8-byte boundaries on SH5.
2090          Fortunately, MACL is fixed and call-clobbered, and we never
2091          need its value across jumps, so save r13 in it instead of in
2092          the stack.  */
2093       if (TARGET_SH5)
2094         output_asm_insn ("lds   r13, macl", 0);
2095       else
2096         output_asm_insn ("mov.l r13,@-r15", 0);
2097       output_asm_insn (jump, &this_jmp.lab);
2098       if (TARGET_SH5)
2099         output_asm_insn ("sts   macl, r13", 0);
2100       else
2101         output_asm_insn ("mov.l @r15+,r13", 0);
2102     }
2103   if (far && flag_pic && TARGET_SH2)
2104     {
2105       braf_base_lab = gen_label_rtx ();
2106       (*targetm.asm_out.internal_label) (asm_out_file, "L",
2107                                  CODE_LABEL_NUMBER (braf_base_lab));
2108     }
2109   if (far)
2110     output_asm_insn (".align    2", 0);
2111   (*targetm.asm_out.internal_label) (asm_out_file, "L", CODE_LABEL_NUMBER (this_jmp.lab));
2112   this_jmp.op = op;
2113   if (far && flag_pic)
2114     {
2115       if (TARGET_SH2)
2116         this_jmp.lab = braf_base_lab;
2117       output_asm_insn (".long   %O2-%O0", &this_jmp.lab);
2118     }
2119   else
2120     output_asm_insn (far ? ".long       %O2" : ".word %O2-%O0", &this_jmp.lab);
2121   return "";
2122 }
2123
2124 /* Local label counter, used for constants in the pool and inside
2125    pattern branches.  */
2126
2127 static int lf = 100;
2128
2129 /* Output code for ordinary branches.  */
2130
2131 const char *
2132 output_branch (int logic, rtx insn, rtx *operands)
2133 {
2134   switch (get_attr_length (insn))
2135     {
2136     case 6:
2137       /* This can happen if filling the delay slot has caused a forward
2138          branch to exceed its range (we could reverse it, but only
2139          when we know we won't overextend other branches; this should
2140          best be handled by relaxation).
2141          It can also happen when other condbranches hoist delay slot insn
2142          from their destination, thus leading to code size increase.
2143          But the branch will still be in the range -4092..+4098 bytes.  */
2144
2145       if (! TARGET_RELAX)
2146         {
2147           int label = lf++;
2148           /* The call to print_slot will clobber the operands.  */
2149           rtx op0 = operands[0];
2150
2151           /* If the instruction in the delay slot is annulled (true), then
2152              there is no delay slot where we can put it now.  The only safe
2153              place for it is after the label.  final will do that by default.  */
2154
2155           if (final_sequence
2156               && ! INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0))
2157               && get_attr_length (XVECEXP (final_sequence, 0, 1)))
2158             {
2159               asm_fprintf (asm_out_file, "\tb%s%ss\t%LLF%d\n", logic ? "f" : "t",
2160                            ASSEMBLER_DIALECT ? "/" : ".", label);
2161               print_slot (final_sequence);
2162             }
2163           else
2164             asm_fprintf (asm_out_file, "\tb%s\t%LLF%d\n", logic ? "f" : "t", label);
2165
2166           output_asm_insn ("bra\t%l0", &op0);
2167           fprintf (asm_out_file, "\tnop\n");
2168           (*targetm.asm_out.internal_label) (asm_out_file, "LF", label);
2169
2170           return "";
2171         }
2172       /* When relaxing, handle this like a short branch.  The linker
2173          will fix it up if it still doesn't fit after relaxation.  */
2174     case 2:
2175       return logic ? "bt%.\t%l0" : "bf%.\t%l0";
2176
2177       /* These are for SH2e, in which we have to account for the
2178          extra nop because of the hardware bug in annulled branches.  */
2179     case 8:
2180       if (! TARGET_RELAX)
2181         {
2182           int label = lf++;
2183
2184           gcc_assert (!final_sequence
2185                       || !(INSN_ANNULLED_BRANCH_P
2186                            (XVECEXP (final_sequence, 0, 0))));
2187           asm_fprintf (asm_out_file, "b%s%ss\t%LLF%d\n",
2188                        logic ? "f" : "t",
2189                        ASSEMBLER_DIALECT ? "/" : ".", label);
2190           fprintf (asm_out_file, "\tnop\n");
2191           output_asm_insn ("bra\t%l0", operands);
2192           fprintf (asm_out_file, "\tnop\n");
2193           (*targetm.asm_out.internal_label) (asm_out_file, "LF", label);
2194
2195           return "";
2196         }
2197       /* When relaxing, fall through.  */
2198     case 4:
2199       {
2200         char buffer[10];
2201
2202         sprintf (buffer, "b%s%ss\t%%l0",
2203                  logic ? "t" : "f",
2204                  ASSEMBLER_DIALECT ? "/" : ".");
2205         output_asm_insn (buffer, &operands[0]);
2206         return "nop";
2207       }
2208
2209     default:
2210       /* There should be no longer branches now - that would
2211          indicate that something has destroyed the branches set
2212          up in machine_dependent_reorg.  */
2213       gcc_unreachable ();
2214     }
2215 }
2216
2217 /* Output a code sequence for INSN using TEMPL with OPERANDS; but before,
2218    fill in operands 9 as a label to the successor insn.
2219    We try to use jump threading where possible.
2220    IF CODE matches the comparison in the IF_THEN_ELSE of a following jump,
2221    we assume the jump is taken.  I.e. EQ means follow jmp and bf, NE means
2222    follow jmp and bt, if the address is in range.  */
2223 const char *
2224 output_branchy_insn (enum rtx_code code, const char *templ,
2225                      rtx insn, rtx *operands)
2226 {
2227   rtx next_insn = NEXT_INSN (insn);
2228
2229   if (next_insn && GET_CODE (next_insn) == JUMP_INSN && condjump_p (next_insn))
2230     {
2231       rtx src = SET_SRC (PATTERN (next_insn));
2232       if (GET_CODE (src) == IF_THEN_ELSE && GET_CODE (XEXP (src, 0)) != code)
2233         {
2234           /* Following branch not taken */
2235           operands[9] = gen_label_rtx ();
2236           emit_label_after (operands[9], next_insn);
2237           INSN_ADDRESSES_NEW (operands[9],
2238                               INSN_ADDRESSES (INSN_UID (next_insn))
2239                               + get_attr_length (next_insn));
2240           return templ;
2241         }
2242       else
2243         {
2244           int offset = (branch_dest (next_insn)
2245                         - INSN_ADDRESSES (INSN_UID (next_insn)) + 4);
2246           if (offset >= -252 && offset <= 258)
2247             {
2248               if (GET_CODE (src) == IF_THEN_ELSE)
2249                 /* branch_true */
2250                 src = XEXP (src, 1);
2251               operands[9] = src;
2252               return templ;
2253             }
2254         }
2255     }
2256   operands[9] = gen_label_rtx ();
2257   emit_label_after (operands[9], insn);
2258   INSN_ADDRESSES_NEW (operands[9],
2259                       INSN_ADDRESSES (INSN_UID (insn))
2260                       + get_attr_length (insn));
2261   return templ;
2262 }
2263
2264 const char *
2265 output_ieee_ccmpeq (rtx insn, rtx *operands)
2266 {
2267   return output_branchy_insn (NE, "bt\t%l9\n\tfcmp/eq\t%1,%0",
2268                               insn, operands);
2269 }
2270 \f
2271 /* Output the start of the assembler file.  */
2272
2273 static void
2274 sh_file_start (void)
2275 {
2276   default_file_start ();
2277
2278 #ifdef SYMBIAN
2279   /* Declare the .directive section before it is used.  */
2280   fputs ("\t.section .directive, \"SM\", @progbits, 1\n", asm_out_file);
2281   fputs ("\t.asciz \"#<SYMEDIT>#\\n\"\n", asm_out_file);
2282 #endif
2283
2284   if (TARGET_ELF)
2285     /* We need to show the text section with the proper
2286        attributes as in TEXT_SECTION_ASM_OP, before dwarf2out
2287        emits it without attributes in TEXT_SECTION_ASM_OP, else GAS
2288        will complain.  We can teach GAS specifically about the
2289        default attributes for our choice of text section, but
2290        then we would have to change GAS again if/when we change
2291        the text section name.  */
2292     fprintf (asm_out_file, "%s\n", TEXT_SECTION_ASM_OP);
2293   else
2294     /* Switch to the data section so that the coffsem symbol
2295        isn't in the text section.  */
2296     switch_to_section (data_section);
2297
2298   if (TARGET_LITTLE_ENDIAN)
2299     fputs ("\t.little\n", asm_out_file);
2300
2301   if (!TARGET_ELF)
2302     {
2303       if (TARGET_SHCOMPACT)
2304         fputs ("\t.mode\tSHcompact\n", asm_out_file);
2305       else if (TARGET_SHMEDIA)
2306         fprintf (asm_out_file, "\t.mode\tSHmedia\n\t.abi\t%i\n",
2307                  TARGET_SHMEDIA64 ? 64 : 32);
2308     }
2309 }
2310 \f
2311 /* Check if PAT includes UNSPEC_CALLER unspec pattern.  */
2312
2313 static bool
2314 unspec_caller_rtx_p (rtx pat)
2315 {
2316   rtx base, offset;
2317   int i;
2318
2319   split_const (pat, &base, &offset);
2320   if (GET_CODE (base) == UNSPEC)
2321     {
2322       if (XINT (base, 1) == UNSPEC_CALLER)
2323         return true;
2324       for (i = 0; i < XVECLEN (base, 0); i++)
2325         if (unspec_caller_rtx_p (XVECEXP (base, 0, i)))
2326           return true;
2327     }
2328   return false;
2329 }
2330
2331 /* Indicate that INSN cannot be duplicated.  This is true for insn
2332    that generates a unique label.  */
2333
2334 static bool
2335 sh_cannot_copy_insn_p (rtx insn)
2336 {
2337   rtx pat;
2338
2339   if (!reload_completed || !flag_pic)
2340     return false;
2341
2342   if (GET_CODE (insn) != INSN)
2343     return false;
2344   if (asm_noperands (insn) >= 0)
2345     return false;
2346
2347   pat = PATTERN (insn);
2348   if (GET_CODE (pat) != SET)
2349     return false;
2350   pat = SET_SRC (pat);
2351
2352   if (unspec_caller_rtx_p (pat))
2353     return true;
2354
2355   return false;
2356 }
2357 \f
2358 /* Actual number of instructions used to make a shift by N.  */
2359 static const char ashiftrt_insns[] =
2360   { 0,1,2,3,4,5,8,8,8,8,8,8,8,8,8,8,2,3,4,5,8,8,8,8,8,8,8,8,8,8,8,2};
2361
2362 /* Left shift and logical right shift are the same.  */
2363 static const char shift_insns[]    =
2364   { 0,1,1,2,2,3,3,4,1,2,2,3,3,4,3,3,1,2,2,3,3,4,3,3,2,3,3,4,4,4,3,3};
2365
2366 /* Individual shift amounts needed to get the above length sequences.
2367    One bit right shifts clobber the T bit, so when possible, put one bit
2368    shifts in the middle of the sequence, so the ends are eligible for
2369    branch delay slots.  */
2370 static const short shift_amounts[32][5] = {
2371   {0}, {1}, {2}, {2, 1},
2372   {2, 2}, {2, 1, 2}, {2, 2, 2}, {2, 2, 1, 2},
2373   {8}, {8, 1}, {8, 2}, {8, 1, 2},
2374   {8, 2, 2}, {8, 2, 1, 2}, {8, -2, 8}, {8, -1, 8},
2375   {16}, {16, 1}, {16, 2}, {16, 1, 2},
2376   {16, 2, 2}, {16, 2, 1, 2}, {16, -2, 8}, {16, -1, 8},
2377   {16, 8}, {16, 1, 8}, {16, 8, 2}, {16, 8, 1, 2},
2378   {16, 8, 2, 2}, {16, -1, -2, 16}, {16, -2, 16}, {16, -1, 16}};
2379
2380 /* Likewise, but for shift amounts < 16, up to three highmost bits
2381    might be clobbered.  This is typically used when combined with some
2382    kind of sign or zero extension.  */
2383
2384 static const char ext_shift_insns[]    =
2385   { 0,1,1,2,2,3,2,2,1,2,2,3,3,3,2,2,1,2,2,3,3,4,3,3,2,3,3,4,4,4,3,3};
2386
2387 static const short ext_shift_amounts[32][4] = {
2388   {0}, {1}, {2}, {2, 1},
2389   {2, 2}, {2, 1, 2}, {8, -2}, {8, -1},
2390   {8}, {8, 1}, {8, 2}, {8, 1, 2},
2391   {8, 2, 2}, {16, -2, -1}, {16, -2}, {16, -1},
2392   {16}, {16, 1}, {16, 2}, {16, 1, 2},
2393   {16, 2, 2}, {16, 2, 1, 2}, {16, -2, 8}, {16, -1, 8},
2394   {16, 8}, {16, 1, 8}, {16, 8, 2}, {16, 8, 1, 2},
2395   {16, 8, 2, 2}, {16, -1, -2, 16}, {16, -2, 16}, {16, -1, 16}};
2396
2397 /* Assuming we have a value that has been sign-extended by at least one bit,
2398    can we use the ext_shift_amounts with the last shift turned to an arithmetic shift
2399    to shift it by N without data loss, and quicker than by other means?  */
2400 #define EXT_SHIFT_SIGNED(n) (((n) | 8) == 15)
2401
2402 /* This is used in length attributes in sh.md to help compute the length
2403    of arbitrary constant shift instructions.  */
2404
2405 int
2406 shift_insns_rtx (rtx insn)
2407 {
2408   rtx set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
2409   int shift_count = INTVAL (XEXP (set_src, 1)) & 31;
2410   enum rtx_code shift_code = GET_CODE (set_src);
2411
2412   switch (shift_code)
2413     {
2414     case ASHIFTRT:
2415       return ashiftrt_insns[shift_count];
2416     case LSHIFTRT:
2417     case ASHIFT:
2418       return shift_insns[shift_count];
2419     default:
2420       gcc_unreachable ();
2421     }
2422 }
2423
2424 /* Return the cost of a shift.  */
2425
2426 static inline int
2427 shiftcosts (rtx x)
2428 {
2429   int value;
2430
2431   if (TARGET_SHMEDIA)
2432     return 1;
2433
2434   if (GET_MODE_SIZE (GET_MODE (x)) > UNITS_PER_WORD)
2435     {
2436       if (GET_MODE (x) == DImode
2437           && GET_CODE (XEXP (x, 1)) == CONST_INT
2438           && INTVAL (XEXP (x, 1)) == 1)
2439         return 2;
2440
2441       /* Everything else is invalid, because there is no pattern for it.  */
2442       return MAX_COST;
2443     }
2444   /* If shift by a non constant, then this will be expensive.  */
2445   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
2446     return SH_DYNAMIC_SHIFT_COST;
2447
2448   /* Otherwise, return the true cost in instructions.  Cope with out of range
2449      shift counts more or less arbitrarily.  */
2450   value = INTVAL (XEXP (x, 1)) & 31;
2451
2452   if (GET_CODE (x) == ASHIFTRT)
2453     {
2454       int cost = ashiftrt_insns[value];
2455       /* If SH3, then we put the constant in a reg and use shad.  */
2456       if (cost > 1 + SH_DYNAMIC_SHIFT_COST)
2457         cost = 1 + SH_DYNAMIC_SHIFT_COST;
2458       return cost;
2459     }
2460   else
2461     return shift_insns[value];
2462 }
2463
2464 /* Return the cost of an AND operation.  */
2465
2466 static inline int
2467 andcosts (rtx x)
2468 {
2469   int i;
2470
2471   /* Anding with a register is a single cycle and instruction.  */
2472   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
2473     return 1;
2474
2475   i = INTVAL (XEXP (x, 1));
2476
2477   if (TARGET_SHMEDIA)
2478     {
2479       if (satisfies_constraint_I10 (XEXP (x, 1))
2480           || satisfies_constraint_J16 (XEXP (x, 1)))
2481         return 1;
2482       else
2483         return 1 + rtx_cost (XEXP (x, 1), AND, !optimize_size);
2484     }
2485
2486   /* These constants are single cycle extu.[bw] instructions.  */
2487   if (i == 0xff || i == 0xffff)
2488     return 1;
2489   /* Constants that can be used in an and immediate instruction in a single
2490      cycle, but this requires r0, so make it a little more expensive.  */
2491   if (CONST_OK_FOR_K08 (i))
2492     return 2;
2493   /* Constants that can be loaded with a mov immediate and an and.
2494      This case is probably unnecessary.  */
2495   if (CONST_OK_FOR_I08 (i))
2496     return 2;
2497   /* Any other constants requires a 2 cycle pc-relative load plus an and.
2498      This case is probably unnecessary.  */
2499   return 3;
2500 }
2501
2502 /* Return the cost of an addition or a subtraction.  */
2503
2504 static inline int
2505 addsubcosts (rtx x)
2506 {
2507   /* Adding a register is a single cycle insn.  */
2508   if (GET_CODE (XEXP (x, 1)) == REG
2509       || GET_CODE (XEXP (x, 1)) == SUBREG)
2510     return 1;
2511
2512   /* Likewise for small constants.  */
2513   if (GET_CODE (XEXP (x, 1)) == CONST_INT
2514       && CONST_OK_FOR_ADD (INTVAL (XEXP (x, 1))))
2515     return 1;
2516
2517   if (TARGET_SHMEDIA)
2518     switch (GET_CODE (XEXP (x, 1)))
2519       {
2520       case CONST:
2521       case LABEL_REF:
2522       case SYMBOL_REF:
2523         return TARGET_SHMEDIA64 ? 5 : 3;
2524
2525       case CONST_INT:
2526         if (CONST_OK_FOR_I16 (INTVAL (XEXP (x, 1))))
2527           return 2;
2528         else if (CONST_OK_FOR_I16 (INTVAL (XEXP (x, 1)) >> 16))
2529           return 3;
2530         else if (CONST_OK_FOR_I16 ((INTVAL (XEXP (x, 1)) >> 16) >> 16))
2531           return 4;
2532
2533         /* Fall through.  */
2534       default:
2535         return 5;
2536       }
2537
2538   /* Any other constant requires a 2 cycle pc-relative load plus an
2539      addition.  */
2540   return 3;
2541 }
2542
2543 /* Return the cost of a multiply.  */
2544 static inline int
2545 multcosts (rtx x ATTRIBUTE_UNUSED)
2546 {
2547   if (sh_multcost >= 0)
2548     return sh_multcost;
2549   if (TARGET_SHMEDIA)
2550     /* ??? We have a mul insn, but it has a latency of three, and doesn't
2551        accept constants.  Ideally, we would use a cost of one or two and
2552        add the cost of the operand, but disregard the latter when inside loops
2553        and loop invariant code motion is still to follow.
2554        Using a multiply first and splitting it later if it's a loss
2555        doesn't work because of different sign / zero extension semantics
2556        of multiplies vs. shifts.  */
2557     return TARGET_SMALLCODE ? 2 : 3;
2558
2559   if (TARGET_SH2)
2560     {
2561       /* We have a mul insn, so we can never take more than the mul and the
2562          read of the mac reg, but count more because of the latency and extra
2563          reg usage.  */
2564       if (TARGET_SMALLCODE)
2565         return 2;
2566       return 3;
2567     }
2568
2569   /* If we're aiming at small code, then just count the number of
2570      insns in a multiply call sequence.  */
2571   if (TARGET_SMALLCODE)
2572     return 5;
2573
2574   /* Otherwise count all the insns in the routine we'd be calling too.  */
2575   return 20;
2576 }
2577
2578 /* Compute a (partial) cost for rtx X.  Return true if the complete
2579    cost has been computed, and false if subexpressions should be
2580    scanned.  In either case, *TOTAL contains the cost result.  */
2581
2582 static bool
2583 sh_rtx_costs (rtx x, int code, int outer_code, int *total,
2584               bool speed ATTRIBUTE_UNUSED)
2585 {
2586   switch (code)
2587     {
2588     case CONST_INT:
2589       if (TARGET_SHMEDIA)
2590         {
2591           if (INTVAL (x) == 0)
2592             *total = 0;
2593           else if (outer_code == AND && and_operand ((x), DImode))
2594             *total = 0;
2595           else if ((outer_code == IOR || outer_code == XOR
2596                     || outer_code == PLUS)
2597                    && CONST_OK_FOR_I10 (INTVAL (x)))
2598             *total = 0;
2599           else if (CONST_OK_FOR_I16 (INTVAL (x)))
2600             *total = COSTS_N_INSNS (outer_code != SET);
2601           else if (CONST_OK_FOR_I16 (INTVAL (x) >> 16))
2602             *total = COSTS_N_INSNS ((outer_code != SET) + 1);
2603           else if (CONST_OK_FOR_I16 ((INTVAL (x) >> 16) >> 16))
2604             *total = COSTS_N_INSNS ((outer_code != SET) + 2);
2605           else
2606             *total = COSTS_N_INSNS ((outer_code != SET) + 3);
2607           return true;
2608         }
2609       if (CONST_OK_FOR_I08 (INTVAL (x)))
2610         *total = 0;
2611       else if ((outer_code == AND || outer_code == IOR || outer_code == XOR)
2612                && CONST_OK_FOR_K08 (INTVAL (x)))
2613         *total = 1;
2614       /* prepare_cmp_insn will force costly constants int registers before
2615          the cbranch[sd]i4 patterns can see them, so preserve potentially
2616          interesting ones not covered by I08 above.  */
2617       else if (outer_code == COMPARE
2618                && ((unsigned HOST_WIDE_INT) INTVAL (x)
2619                     == (unsigned HOST_WIDE_INT) 0x7fffffff + 1
2620                     || INTVAL (x) == 0x7fffffff
2621                    || INTVAL (x) == 0x80 || INTVAL (x) == -0x81))
2622         *total = 1;
2623       else
2624         *total = 8;
2625       return true;
2626
2627     case CONST:
2628     case LABEL_REF:
2629     case SYMBOL_REF:
2630       if (TARGET_SHMEDIA64)
2631         *total = COSTS_N_INSNS (4);
2632       else if (TARGET_SHMEDIA32)
2633         *total = COSTS_N_INSNS (2);
2634       else
2635         *total = 5;
2636       return true;
2637
2638     case CONST_DOUBLE:
2639       if (TARGET_SHMEDIA)
2640         *total = COSTS_N_INSNS (4);
2641       /* prepare_cmp_insn will force costly constants int registers before
2642          the cbranchdi4 pattern can see them, so preserve potentially
2643          interesting ones.  */
2644       else if (outer_code == COMPARE && GET_MODE (x) == DImode)
2645         *total = 1;
2646       else
2647         *total = 10;
2648       return true;
2649     case CONST_VECTOR:
2650       if (x == CONST0_RTX (GET_MODE (x)))
2651         *total = 0;
2652       else if (sh_1el_vec (x, VOIDmode))
2653         *total = outer_code != SET;
2654       if (sh_rep_vec (x, VOIDmode))
2655         *total = ((GET_MODE_UNIT_SIZE (GET_MODE (x)) + 3) / 4
2656                   + (outer_code != SET));
2657       *total = COSTS_N_INSNS (3) + (outer_code != SET);
2658       return true;
2659
2660     case PLUS:
2661     case MINUS:
2662       *total = COSTS_N_INSNS (addsubcosts (x));
2663       return true;
2664
2665     case AND:
2666       *total = COSTS_N_INSNS (andcosts (x));
2667       return true;
2668
2669     case MULT:
2670       *total = COSTS_N_INSNS (multcosts (x));
2671       return true;
2672
2673     case ASHIFT:
2674     case ASHIFTRT:
2675     case LSHIFTRT:
2676       *total = COSTS_N_INSNS (shiftcosts (x));
2677       return true;
2678
2679     case DIV:
2680     case UDIV:
2681     case MOD:
2682     case UMOD:
2683       *total = COSTS_N_INSNS (20);
2684       return true;
2685
2686     case PARALLEL:
2687       if (sh_1el_vec (x, VOIDmode))
2688         *total = outer_code != SET;
2689       if (sh_rep_vec (x, VOIDmode))
2690         *total = ((GET_MODE_UNIT_SIZE (GET_MODE (x)) + 3) / 4
2691                   + (outer_code != SET));
2692       *total = COSTS_N_INSNS (3) + (outer_code != SET);
2693       return true;
2694
2695     case FLOAT:
2696     case FIX:
2697       *total = 100;
2698       return true;
2699
2700     default:
2701       return false;
2702     }
2703 }
2704
2705 /* Compute the cost of an address.  For the SH, all valid addresses are
2706    the same cost.  Use a slightly higher cost for reg + reg addressing,
2707    since it increases pressure on r0.  */
2708
2709 static int
2710 sh_address_cost (rtx X,
2711                  bool speed ATTRIBUTE_UNUSED)
2712 {
2713   return (GET_CODE (X) == PLUS
2714           && ! CONSTANT_P (XEXP (X, 1))
2715           && ! TARGET_SHMEDIA ? 1 : 0);
2716 }
2717
2718 /* Code to expand a shift.  */
2719
2720 void
2721 gen_ashift (int type, int n, rtx reg)
2722 {
2723   /* Negative values here come from the shift_amounts array.  */
2724   if (n < 0)
2725     {
2726       if (type == ASHIFT)
2727         type = LSHIFTRT;
2728       else
2729         type = ASHIFT;
2730       n = -n;
2731     }
2732
2733   switch (type)
2734     {
2735     case ASHIFTRT:
2736       emit_insn (gen_ashrsi3_k (reg, reg, GEN_INT (n)));
2737       break;
2738     case LSHIFTRT:
2739       if (n == 1)
2740         emit_insn (gen_lshrsi3_m (reg, reg, GEN_INT (n)));
2741       else
2742         emit_insn (gen_lshrsi3_k (reg, reg, GEN_INT (n)));
2743       break;
2744     case ASHIFT:
2745       emit_insn (gen_ashlsi3_std (reg, reg, GEN_INT (n)));
2746       break;
2747     }
2748 }
2749
2750 /* Same for HImode */
2751
2752 void
2753 gen_ashift_hi (int type, int n, rtx reg)
2754 {
2755   /* Negative values here come from the shift_amounts array.  */
2756   if (n < 0)
2757     {
2758       if (type == ASHIFT)
2759         type = LSHIFTRT;
2760       else
2761         type = ASHIFT;
2762       n = -n;
2763     }
2764
2765   switch (type)
2766     {
2767     case ASHIFTRT:
2768     case LSHIFTRT:
2769       /* We don't have HImode right shift operations because using the
2770          ordinary 32 bit shift instructions for that doesn't generate proper
2771          zero/sign extension.
2772          gen_ashift_hi is only called in contexts where we know that the
2773          sign extension works out correctly.  */
2774       {
2775         int offset = 0;
2776         if (GET_CODE (reg) == SUBREG)
2777           {
2778             offset = SUBREG_BYTE (reg);
2779             reg = SUBREG_REG (reg);
2780           }
2781         gen_ashift (type, n, gen_rtx_SUBREG (SImode, reg, offset));
2782         break;
2783       }
2784     case ASHIFT:
2785       emit_insn (gen_ashlhi3_k (reg, reg, GEN_INT (n)));
2786       break;
2787     }
2788 }
2789
2790 /* Output RTL to split a constant shift into its component SH constant
2791    shift instructions.  */
2792
2793 void
2794 gen_shifty_op (int code, rtx *operands)
2795 {
2796   int value = INTVAL (operands[2]);
2797   int max, i;
2798
2799   /* Truncate the shift count in case it is out of bounds.  */
2800   value = value & 31;
2801
2802   if (value == 31)
2803     {
2804       if (code == LSHIFTRT)
2805         {
2806           emit_insn (gen_rotlsi3_1 (operands[0], operands[0]));
2807           emit_insn (gen_movt (operands[0]));
2808           return;
2809         }
2810       else if (code == ASHIFT)
2811         {
2812           /* There is a two instruction sequence for 31 bit left shifts,
2813              but it requires r0.  */
2814           if (GET_CODE (operands[0]) == REG && REGNO (operands[0]) == 0)
2815             {
2816               emit_insn (gen_andsi3 (operands[0], operands[0], const1_rtx));
2817               emit_insn (gen_rotlsi3_31 (operands[0], operands[0]));
2818               return;
2819             }
2820         }
2821     }
2822   else if (value == 0)
2823     {
2824       /* This can happen even when optimizing, if there were subregs before
2825          reload.  Don't output a nop here, as this is never optimized away;
2826          use a no-op move instead.  */
2827       emit_insn (gen_rtx_SET (VOIDmode, operands[0], operands[0]));
2828       return;
2829     }
2830
2831   max = shift_insns[value];
2832   for (i = 0; i < max; i++)
2833     gen_ashift (code, shift_amounts[value][i], operands[0]);
2834 }
2835
2836 /* Same as above, but optimized for values where the topmost bits don't
2837    matter.  */
2838
2839 void
2840 gen_shifty_hi_op (int code, rtx *operands)
2841 {
2842   int value = INTVAL (operands[2]);
2843   int max, i;
2844   void (*gen_fun) (int, int, rtx);
2845
2846   /* This operation is used by and_shl for SImode values with a few
2847      high bits known to be cleared.  */
2848   value &= 31;
2849   if (value == 0)
2850     {
2851       emit_insn (gen_nop ());
2852       return;
2853     }
2854
2855   gen_fun = GET_MODE (operands[0]) == HImode ? gen_ashift_hi : gen_ashift;
2856   if (code == ASHIFT)
2857     {
2858       max = ext_shift_insns[value];
2859       for (i = 0; i < max; i++)
2860         gen_fun (code, ext_shift_amounts[value][i], operands[0]);
2861     }
2862   else
2863     /* When shifting right, emit the shifts in reverse order, so that
2864        solitary negative values come first.  */
2865     for (i = ext_shift_insns[value] - 1; i >= 0; i--)
2866       gen_fun (code, ext_shift_amounts[value][i], operands[0]);
2867 }
2868
2869 /* Output RTL for an arithmetic right shift.  */
2870
2871 /* ??? Rewrite to use super-optimizer sequences.  */
2872
2873 int
2874 expand_ashiftrt (rtx *operands)
2875 {
2876   rtx wrk;
2877   char func[18];
2878   int value;
2879
2880   if (TARGET_SH3)
2881     {
2882       if (GET_CODE (operands[2]) != CONST_INT)
2883         {
2884           rtx count = copy_to_mode_reg (SImode, operands[2]);
2885           emit_insn (gen_negsi2 (count, count));
2886           emit_insn (gen_ashrsi3_d (operands[0], operands[1], count));
2887           return 1;
2888         }
2889       else if (ashiftrt_insns[INTVAL (operands[2]) & 31]
2890                > 1 + SH_DYNAMIC_SHIFT_COST)
2891         {
2892           rtx count
2893             = force_reg (SImode, GEN_INT (- (INTVAL (operands[2]) & 31)));
2894           emit_insn (gen_ashrsi3_d (operands[0], operands[1], count));
2895           return 1;
2896         }
2897     }
2898   if (GET_CODE (operands[2]) != CONST_INT)
2899     return 0;
2900
2901   value = INTVAL (operands[2]) & 31;
2902
2903   if (value == 31)
2904     {
2905       /* If we are called from abs expansion, arrange things so that we
2906          we can use a single MT instruction that doesn't clobber the source,
2907          if LICM can hoist out the load of the constant zero.  */
2908       if (currently_expanding_to_rtl)
2909         {
2910           emit_insn (gen_cmpgtsi_t (force_reg (SImode, CONST0_RTX (SImode)),
2911                                     operands[1]));
2912           emit_insn (gen_mov_neg_si_t (operands[0]));
2913           return 1;
2914         }
2915       emit_insn (gen_ashrsi2_31 (operands[0], operands[1]));
2916       return 1;
2917     }
2918   else if (value >= 16 && value <= 19)
2919     {
2920       wrk = gen_reg_rtx (SImode);
2921       emit_insn (gen_ashrsi2_16 (wrk, operands[1]));
2922       value -= 16;
2923       while (value--)
2924         gen_ashift (ASHIFTRT, 1, wrk);
2925       emit_move_insn (operands[0], wrk);
2926       return 1;
2927     }
2928   /* Expand a short sequence inline, longer call a magic routine.  */
2929   else if (value <= 5)
2930     {
2931       wrk = gen_reg_rtx (SImode);
2932       emit_move_insn (wrk, operands[1]);
2933       while (value--)
2934         gen_ashift (ASHIFTRT, 1, wrk);
2935       emit_move_insn (operands[0], wrk);
2936       return 1;
2937     }
2938
2939   wrk = gen_reg_rtx (Pmode);
2940
2941   /* Load the value into an arg reg and call a helper.  */
2942   emit_move_insn (gen_rtx_REG (SImode, 4), operands[1]);
2943   sprintf (func, "__ashiftrt_r4_%d", value);
2944   function_symbol (wrk, func, SFUNC_STATIC);
2945   emit_insn (gen_ashrsi3_n (GEN_INT (value), wrk));
2946   emit_move_insn (operands[0], gen_rtx_REG (SImode, 4));
2947   return 1;
2948 }
2949
2950 int
2951 sh_dynamicalize_shift_p (rtx count)
2952 {
2953   return shift_insns[INTVAL (count) & 31] > 1 + SH_DYNAMIC_SHIFT_COST;
2954 }
2955
2956 /* Try to find a good way to implement the combiner pattern
2957   [(set (match_operand:SI 0 "register_operand" "r")
2958         (and:SI (ashift:SI (match_operand:SI 1 "register_operand" "r")
2959                            (match_operand:SI 2 "const_int_operand" "n"))
2960                 (match_operand:SI 3 "const_int_operand" "n"))) .
2961   LEFT_RTX is operand 2 in the above pattern, and MASK_RTX is operand 3.
2962   return 0 for simple right / left or left/right shift combination.
2963   return 1 for a combination of shifts with zero_extend.
2964   return 2 for a combination of shifts with an AND that needs r0.
2965   return 3 for a combination of shifts with an AND that needs an extra
2966     scratch register, when the three highmost bits of the AND mask are clear.
2967   return 4 for a combination of shifts with an AND that needs an extra
2968     scratch register, when any of the three highmost bits of the AND mask
2969     is set.
2970   If ATTRP is set, store an initial right shift width in ATTRP[0],
2971   and the instruction length in ATTRP[1] .  These values are not valid
2972   when returning 0.
2973   When ATTRP is set and returning 1, ATTRP[2] gets set to the index into
2974   shift_amounts for the last shift value that is to be used before the
2975   sign extend.  */
2976 int
2977 shl_and_kind (rtx left_rtx, rtx mask_rtx, int *attrp)
2978 {
2979   unsigned HOST_WIDE_INT mask, lsb, mask2, lsb2;
2980   int left = INTVAL (left_rtx), right;
2981   int best = 0;
2982   int cost, best_cost = 10000;
2983   int best_right = 0, best_len = 0;
2984   int i;
2985   int can_ext;
2986
2987   if (left < 0 || left > 31)
2988     return 0;
2989   if (GET_CODE (mask_rtx) == CONST_INT)
2990     mask = (unsigned HOST_WIDE_INT) INTVAL (mask_rtx) >> left;
2991   else
2992     mask = (unsigned HOST_WIDE_INT) GET_MODE_MASK (SImode) >> left;
2993   /* Can this be expressed as a right shift / left shift pair?  */
2994   lsb = ((mask ^ (mask - 1)) >> 1) + 1;
2995   right = exact_log2 (lsb);
2996   mask2 = ~(mask + lsb - 1);
2997   lsb2 = ((mask2 ^ (mask2 - 1)) >> 1) + 1;
2998   /* mask has no zeroes but trailing zeroes <==> ! mask2 */
2999   if (! mask2)
3000     best_cost = shift_insns[right] + shift_insns[right + left];
3001   /* mask has no trailing zeroes <==> ! right */
3002   else if (! right && mask2 == ~(lsb2 - 1))
3003     {
3004       int late_right = exact_log2 (lsb2);
3005       best_cost = shift_insns[left + late_right] + shift_insns[late_right];
3006     }
3007   /* Try to use zero extend.  */
3008   if (mask2 == ~(lsb2 - 1))
3009     {
3010       int width, first;
3011
3012       for (width = 8; width <= 16; width += 8)
3013         {
3014           /* Can we zero-extend right away?  */
3015           if (lsb2 == (unsigned HOST_WIDE_INT) 1 << width)
3016             {
3017               cost
3018                 = 1 + ext_shift_insns[right] + ext_shift_insns[left + right];
3019               if (cost < best_cost)
3020                 {
3021                   best = 1;
3022                   best_cost = cost;
3023                   best_right = right;
3024                   best_len = cost;
3025                   if (attrp)
3026                     attrp[2] = -1;
3027                 }
3028               continue;
3029             }
3030           /* ??? Could try to put zero extend into initial right shift,
3031              or even shift a bit left before the right shift.  */
3032           /* Determine value of first part of left shift, to get to the
3033              zero extend cut-off point.  */
3034           first = width - exact_log2 (lsb2) + right;
3035           if (first >= 0 && right + left - first >= 0)
3036             {
3037               cost = ext_shift_insns[right] + ext_shift_insns[first] + 1
3038                 + ext_shift_insns[right + left - first];
3039               if (cost < best_cost)
3040                 {
3041                   best = 1;
3042                   best_cost = cost;
3043                   best_right = right;
3044                   best_len = cost;
3045                   if (attrp)
3046                     attrp[2] = first;
3047                 }
3048             }
3049         }
3050     }
3051   /* Try to use r0 AND pattern */
3052   for (i = 0; i <= 2; i++)
3053     {
3054       if (i > right)
3055         break;
3056       if (! CONST_OK_FOR_K08 (mask >> i))
3057         continue;
3058       cost = (i != 0) + 2 + ext_shift_insns[left + i];
3059       if (cost < best_cost)
3060         {
3061           best = 2;
3062           best_cost = cost;
3063           best_right = i;
3064           best_len = cost - 1;
3065         }
3066     }
3067   /* Try to use a scratch register to hold the AND operand.  */
3068   can_ext = ((mask << left) & ((unsigned HOST_WIDE_INT) 3 << 30)) == 0;
3069   for (i = 0; i <= 2; i++)
3070     {
3071       if (i > right)
3072         break;
3073       cost = (i != 0) + (CONST_OK_FOR_I08 (mask >> i) ? 2 : 3)
3074         + (can_ext ? ext_shift_insns : shift_insns)[left + i];
3075       if (cost < best_cost)
3076         {
3077           best = 4 - can_ext;
3078           best_cost = cost;
3079           best_right = i;
3080           best_len = cost - 1 - ! CONST_OK_FOR_I08 (mask >> i);
3081         }
3082     }
3083
3084   if (attrp)
3085     {
3086       attrp[0] = best_right;
3087       attrp[1] = best_len;
3088     }
3089   return best;
3090 }
3091
3092 /* This is used in length attributes of the unnamed instructions
3093    corresponding to shl_and_kind return values of 1 and 2.  */
3094 int
3095 shl_and_length (rtx insn)
3096 {
3097   rtx set_src, left_rtx, mask_rtx;
3098   int attributes[3];
3099
3100   set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
3101   left_rtx = XEXP (XEXP (set_src, 0), 1);
3102   mask_rtx = XEXP (set_src, 1);
3103   shl_and_kind (left_rtx, mask_rtx, attributes);
3104   return attributes[1];
3105 }
3106
3107 /* This is used in length attribute of the and_shl_scratch instruction.  */
3108
3109 int
3110 shl_and_scr_length (rtx insn)
3111 {
3112   rtx set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
3113   int len = shift_insns[INTVAL (XEXP (set_src, 1)) & 31];
3114   rtx op = XEXP (set_src, 0);
3115   len += shift_insns[INTVAL (XEXP (op, 1)) & 31] + 1;
3116   op = XEXP (XEXP (op, 0), 0);
3117   return len + shift_insns[INTVAL (XEXP (op, 1)) & 31];
3118 }
3119
3120 /* Generate rtl for instructions for which shl_and_kind advised a particular
3121    method of generating them, i.e. returned zero.  */
3122
3123 int
3124 gen_shl_and (rtx dest, rtx left_rtx, rtx mask_rtx, rtx source)
3125 {
3126   int attributes[3];
3127   unsigned HOST_WIDE_INT mask;
3128   int kind = shl_and_kind (left_rtx, mask_rtx, attributes);
3129   int right, total_shift;
3130   void (*shift_gen_fun) (int, rtx *) = gen_shifty_hi_op;
3131
3132   right = attributes[0];
3133   total_shift = INTVAL (left_rtx) + right;
3134   mask = (unsigned HOST_WIDE_INT) INTVAL (mask_rtx) >> total_shift;
3135   switch (kind)
3136     {
3137     default:
3138       return -1;
3139     case 1:
3140       {
3141         int first = attributes[2];
3142         rtx operands[3];
3143
3144         if (first < 0)
3145           {
3146             emit_insn ((mask << right) <= 0xff
3147                        ? gen_zero_extendqisi2 (dest,
3148                                                gen_lowpart (QImode, source))
3149                        : gen_zero_extendhisi2 (dest,
3150                                                gen_lowpart (HImode, source)));
3151             source = dest;
3152           }
3153         if (source != dest)
3154           emit_insn (gen_movsi (dest, source));
3155         operands[0] = dest;
3156         if (right)
3157           {
3158             operands[2] = GEN_INT (right);
3159             gen_shifty_hi_op (LSHIFTRT, operands);
3160           }
3161         if (first > 0)
3162           {
3163             operands[2] = GEN_INT (first);
3164             gen_shifty_hi_op (ASHIFT, operands);
3165             total_shift -= first;
3166             mask <<= first;
3167           }
3168         if (first >= 0)
3169           emit_insn (mask <= 0xff
3170                      ? gen_zero_extendqisi2 (dest, gen_lowpart (QImode, dest))
3171                      : gen_zero_extendhisi2 (dest, gen_lowpart (HImode, dest)));
3172         if (total_shift > 0)
3173           {
3174             operands[2] = GEN_INT (total_shift);
3175             gen_shifty_hi_op (ASHIFT, operands);
3176           }
3177         break;
3178       }
3179     case 4:
3180       shift_gen_fun = gen_shifty_op;
3181     case 3:
3182       /* If the topmost bit that matters is set, set the topmost bits
3183          that don't matter.  This way, we might be able to get a shorter
3184          signed constant.  */
3185       if (mask & ((HOST_WIDE_INT) 1 << (31 - total_shift)))
3186         mask |= (HOST_WIDE_INT) ~0 << (31 - total_shift);
3187     case 2:
3188       /* Don't expand fine-grained when combining, because that will
3189          make the pattern fail.  */
3190       if (currently_expanding_to_rtl
3191           || reload_in_progress || reload_completed)
3192         {
3193           rtx operands[3];
3194
3195           /* Cases 3 and 4 should be handled by this split
3196              only while combining  */
3197           gcc_assert (kind <= 2);
3198           if (right)
3199             {
3200               emit_insn (gen_lshrsi3 (dest, source, GEN_INT (right)));
3201               source = dest;
3202             }
3203           emit_insn (gen_andsi3 (dest, source, GEN_INT (mask)));
3204           if (total_shift)
3205             {
3206               operands[0] = dest;
3207               operands[1] = dest;
3208               operands[2] = GEN_INT (total_shift);
3209               shift_gen_fun (ASHIFT, operands);
3210             }
3211           break;
3212         }
3213       else
3214         {
3215           int neg = 0;
3216           if (kind != 4 && total_shift < 16)
3217             {
3218               neg = -ext_shift_amounts[total_shift][1];
3219               if (neg > 0)
3220                 neg -= ext_shift_amounts[total_shift][2];
3221               else
3222                 neg = 0;
3223             }
3224           emit_insn (gen_and_shl_scratch (dest, source,
3225                                           GEN_INT (right),
3226                                           GEN_INT (mask),
3227                                           GEN_INT (total_shift + neg),
3228                                           GEN_INT (neg)));
3229           emit_insn (gen_movsi (dest, dest));
3230           break;
3231         }
3232     }
3233   return 0;
3234 }
3235
3236 /* Try to find a good way to implement the combiner pattern
3237   [(set (match_operand:SI 0 "register_operand" "=r")
3238         (sign_extract:SI (ashift:SI (match_operand:SI 1 "register_operand" "r")
3239                                     (match_operand:SI 2 "const_int_operand" "n")
3240                          (match_operand:SI 3 "const_int_operand" "n")
3241                          (const_int 0)))
3242    (clobber (reg:SI T_REG))]
3243   LEFT_RTX is operand 2 in the above pattern, and SIZE_RTX is operand 3.
3244   return 0 for simple left / right shift combination.
3245   return 1 for left shift / 8 bit sign extend / left shift.
3246   return 2 for left shift / 16 bit sign extend / left shift.
3247   return 3 for left shift / 8 bit sign extend / shift / sign extend.
3248   return 4 for left shift / 16 bit sign extend / shift / sign extend.
3249   return 5 for left shift / 16 bit sign extend / right shift
3250   return 6 for < 8 bit sign extend / left shift.
3251   return 7 for < 8 bit sign extend / left shift / single right shift.
3252   If COSTP is nonzero, assign the calculated cost to *COSTP.  */
3253
3254 int
3255 shl_sext_kind (rtx left_rtx, rtx size_rtx, int *costp)
3256 {
3257   int left, size, insize, ext;
3258   int cost = 0, best_cost;
3259   int kind;
3260
3261   left = INTVAL (left_rtx);
3262   size = INTVAL (size_rtx);
3263   insize = size - left;
3264   gcc_assert (insize > 0);
3265   /* Default to left / right shift.  */
3266   kind = 0;
3267   best_cost = shift_insns[32 - insize] + ashiftrt_insns[32 - size];
3268   if (size <= 16)
3269     {
3270       /* 16 bit shift / sign extend / 16 bit shift */
3271       cost = shift_insns[16 - insize] + 1 + ashiftrt_insns[16 - size];
3272       /* If ashiftrt_insns[16 - size] is 8, this choice will be overridden
3273          below, by alternative 3 or something even better.  */
3274       if (cost < best_cost)
3275         {
3276           kind = 5;
3277           best_cost = cost;
3278         }
3279     }
3280   /* Try a plain sign extend between two shifts.  */
3281   for (ext = 16; ext >= insize; ext -= 8)
3282     {
3283       if (ext <= size)
3284         {
3285           cost = ext_shift_insns[ext - insize] + 1 + shift_insns[size - ext];
3286           if (cost < best_cost)
3287             {
3288               kind = ext / (unsigned) 8;
3289               best_cost = cost;
3290             }
3291         }
3292       /* Check if we can do a sloppy shift with a final signed shift
3293          restoring the sign.  */
3294       if (EXT_SHIFT_SIGNED (size - ext))
3295         cost = ext_shift_insns[ext - insize] + ext_shift_insns[size - ext] + 1;
3296       /* If not, maybe it's still cheaper to do the second shift sloppy,
3297          and do a final sign extend?  */
3298       else if (size <= 16)
3299         cost = ext_shift_insns[ext - insize] + 1
3300           + ext_shift_insns[size > ext ? size - ext : ext - size] + 1;
3301       else
3302         continue;
3303       if (cost < best_cost)
3304         {
3305           kind = ext / (unsigned) 8 + 2;
3306           best_cost = cost;
3307         }
3308     }
3309   /* Check if we can sign extend in r0 */
3310   if (insize < 8)
3311     {
3312       cost = 3 + shift_insns[left];
3313       if (cost < best_cost)
3314         {
3315           kind = 6;
3316           best_cost = cost;
3317         }
3318       /* Try the same with a final signed shift.  */
3319       if (left < 31)
3320         {
3321           cost = 3 + ext_shift_insns[left + 1] + 1;
3322           if (cost < best_cost)
3323             {
3324               kind = 7;
3325               best_cost = cost;
3326             }
3327         }
3328     }
3329   if (TARGET_SH3)
3330     {
3331       /* Try to use a dynamic shift.  */
3332       cost = shift_insns[32 - insize] + 1 + SH_DYNAMIC_SHIFT_COST;
3333       if (cost < best_cost)
3334         {
3335           kind = 0;
3336           best_cost = cost;
3337         }
3338     }
3339   if (costp)
3340     *costp = cost;
3341   return kind;
3342 }
3343
3344 /* Function to be used in the length attribute of the instructions
3345    implementing this pattern.  */
3346
3347 int
3348 shl_sext_length (rtx insn)
3349 {
3350   rtx set_src, left_rtx, size_rtx;
3351   int cost;
3352
3353   set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
3354   left_rtx = XEXP (XEXP (set_src, 0), 1);
3355   size_rtx = XEXP (set_src, 1);
3356   shl_sext_kind (left_rtx, size_rtx, &cost);
3357   return cost;
3358 }
3359
3360 /* Generate rtl for this pattern */
3361
3362 int
3363 gen_shl_sext (rtx dest, rtx left_rtx, rtx size_rtx, rtx source)
3364 {
3365   int kind;
3366   int left, size, insize, cost;
3367   rtx operands[3];
3368
3369   kind = shl_sext_kind (left_rtx, size_rtx, &cost);
3370   left = INTVAL (left_rtx);
3371   size = INTVAL (size_rtx);
3372   insize = size - left;
3373   switch (kind)
3374     {
3375     case 1:
3376     case 2:
3377     case 3:
3378     case 4:
3379       {
3380         int ext = kind & 1 ? 8 : 16;
3381         int shift2 = size - ext;
3382
3383         /* Don't expand fine-grained when combining, because that will
3384            make the pattern fail.  */
3385         if (! currently_expanding_to_rtl
3386             && ! reload_in_progress && ! reload_completed)
3387           {
3388             emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
3389             emit_insn (gen_movsi (dest, source));
3390             break;
3391           }
3392         if (dest != source)
3393           emit_insn (gen_movsi (dest, source));
3394         operands[0] = dest;
3395         if (ext - insize)
3396           {
3397             operands[2] = GEN_INT (ext - insize);
3398             gen_shifty_hi_op (ASHIFT, operands);
3399           }
3400         emit_insn (kind & 1
3401                    ? gen_extendqisi2 (dest, gen_lowpart (QImode, dest))
3402                    : gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
3403         if (kind <= 2)
3404           {
3405             if (shift2)
3406               {
3407                 operands[2] = GEN_INT (shift2);
3408                 gen_shifty_op (ASHIFT, operands);
3409               }
3410           }
3411         else
3412           {
3413             if (shift2 > 0)
3414               {
3415                 if (EXT_SHIFT_SIGNED (shift2))
3416                   {
3417                     operands[2] = GEN_INT (shift2 + 1);
3418                     gen_shifty_op (ASHIFT, operands);
3419                     operands[2] = const1_rtx;
3420                     gen_shifty_op (ASHIFTRT, operands);
3421                     break;
3422                   }
3423                 operands[2] = GEN_INT (shift2);
3424                 gen_shifty_hi_op (ASHIFT, operands);
3425               }
3426             else if (shift2)
3427               {
3428                 operands[2] = GEN_INT (-shift2);
3429                 gen_shifty_hi_op (LSHIFTRT, operands);
3430               }
3431             emit_insn (size <= 8
3432                        ? gen_extendqisi2 (dest, gen_lowpart (QImode, dest))
3433                        : gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
3434           }
3435         break;
3436       }
3437     case 5:
3438       {
3439         int i = 16 - size;
3440         if (! currently_expanding_to_rtl
3441             && ! reload_in_progress && ! reload_completed)
3442           emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
3443         else
3444           {
3445             operands[0] = dest;
3446             operands[2] = GEN_INT (16 - insize);
3447             gen_shifty_hi_op (ASHIFT, operands);
3448             emit_insn (gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
3449           }
3450         /* Don't use gen_ashrsi3 because it generates new pseudos.  */
3451         while (--i >= 0)
3452           gen_ashift (ASHIFTRT, 1, dest);
3453         break;
3454       }
3455     case 6:
3456     case 7:
3457       /* Don't expand fine-grained when combining, because that will
3458          make the pattern fail.  */
3459       if (! currently_expanding_to_rtl
3460           && ! reload_in_progress && ! reload_completed)
3461         {
3462           emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
3463           emit_insn (gen_movsi (dest, source));
3464           break;
3465         }
3466       emit_insn (gen_andsi3 (dest, source, GEN_INT ((1 << insize) - 1)));
3467       emit_insn (gen_xorsi3 (dest, dest, GEN_INT (1 << (insize - 1))));
3468       emit_insn (gen_addsi3 (dest, dest, GEN_INT (-1 << (insize - 1))));
3469       operands[0] = dest;
3470       operands[2] = kind == 7 ? GEN_INT (left + 1) : left_rtx;
3471       gen_shifty_op (ASHIFT, operands);
3472       if (kind == 7)
3473         emit_insn (gen_ashrsi3_k (dest, dest, const1_rtx));
3474       break;
3475     default:
3476       return -1;
3477     }
3478   return 0;
3479 }
3480
3481 /* Prefix a symbol_ref name with "datalabel".  */
3482
3483 rtx
3484 gen_datalabel_ref (rtx sym)
3485 {
3486   const char *str;
3487
3488   if (GET_CODE (sym) == LABEL_REF)
3489     return gen_rtx_CONST (GET_MODE (sym),
3490                           gen_rtx_UNSPEC (GET_MODE (sym),
3491                                           gen_rtvec (1, sym),
3492                                           UNSPEC_DATALABEL));
3493
3494   gcc_assert (GET_CODE (sym) == SYMBOL_REF);
3495
3496   str = XSTR (sym, 0);
3497   /* Share all SYMBOL_REF strings with the same value - that is important
3498      for cse.  */
3499   str = IDENTIFIER_POINTER (get_identifier (str));
3500   XSTR (sym, 0) = str;
3501
3502   return sym;
3503 }
3504
3505 \f
3506 static alloc_pool label_ref_list_pool;
3507
3508 typedef struct label_ref_list_d
3509 {
3510   rtx label;
3511   struct label_ref_list_d *next;
3512 } *label_ref_list_t;
3513
3514 /* The SH cannot load a large constant into a register, constants have to
3515    come from a pc relative load.  The reference of a pc relative load
3516    instruction must be less than 1k in front of the instruction.  This
3517    means that we often have to dump a constant inside a function, and
3518    generate code to branch around it.
3519
3520    It is important to minimize this, since the branches will slow things
3521    down and make things bigger.
3522
3523    Worst case code looks like:
3524
3525    mov.l L1,rn
3526    bra   L2
3527    nop
3528    align
3529    L1:   .long value
3530    L2:
3531    ..
3532
3533    mov.l L3,rn
3534    bra   L4
3535    nop
3536    align
3537    L3:   .long value
3538    L4:
3539    ..
3540
3541    We fix this by performing a scan before scheduling, which notices which
3542    instructions need to have their operands fetched from the constant table
3543    and builds the table.
3544
3545    The algorithm is:
3546
3547    scan, find an instruction which needs a pcrel move.  Look forward, find the
3548    last barrier which is within MAX_COUNT bytes of the requirement.
3549    If there isn't one, make one.  Process all the instructions between
3550    the find and the barrier.
3551
3552    In the above example, we can tell that L3 is within 1k of L1, so
3553    the first move can be shrunk from the 3 insn+constant sequence into
3554    just 1 insn, and the constant moved to L3 to make:
3555
3556    mov.l        L1,rn
3557    ..
3558    mov.l        L3,rn
3559    bra          L4
3560    nop
3561    align
3562    L3:.long value
3563    L4:.long value
3564
3565    Then the second move becomes the target for the shortening process.  */
3566
3567 typedef struct
3568 {
3569   rtx value;                    /* Value in table.  */
3570   rtx label;                    /* Label of value.  */
3571   label_ref_list_t wend;        /* End of window.  */
3572   enum machine_mode mode;       /* Mode of value.  */
3573
3574   /* True if this constant is accessed as part of a post-increment
3575      sequence.  Note that HImode constants are never accessed in this way.  */
3576   bool part_of_sequence_p;
3577 } pool_node;
3578
3579 /* The maximum number of constants that can fit into one pool, since
3580    constants in the range 0..510 are at least 2 bytes long, and in the
3581    range from there to 1018 at least 4 bytes.  */
3582
3583 #define MAX_POOL_SIZE 372
3584 static pool_node pool_vector[MAX_POOL_SIZE];
3585 static int pool_size;
3586 static rtx pool_window_label;
3587 static int pool_window_last;
3588
3589 static int max_labelno_before_reorg;
3590
3591 /* ??? If we need a constant in HImode which is the truncated value of a
3592    constant we need in SImode, we could combine the two entries thus saving
3593    two bytes.  Is this common enough to be worth the effort of implementing
3594    it?  */
3595
3596 /* ??? This stuff should be done at the same time that we shorten branches.
3597    As it is now, we must assume that all branches are the maximum size, and
3598    this causes us to almost always output constant pools sooner than
3599    necessary.  */
3600
3601 /* Add a constant to the pool and return its label.  */
3602
3603 static rtx
3604 add_constant (rtx x, enum machine_mode mode, rtx last_value)
3605 {
3606   int i;
3607   rtx lab, new_rtx;
3608   label_ref_list_t ref, newref;
3609
3610   /* First see if we've already got it.  */
3611   for (i = 0; i < pool_size; i++)
3612     {
3613       if (x->code == pool_vector[i].value->code
3614           && mode == pool_vector[i].mode)
3615         {
3616           if (x->code == CODE_LABEL)
3617             {
3618               if (XINT (x, 3) != XINT (pool_vector[i].value, 3))
3619                 continue;
3620             }
3621           if (rtx_equal_p (x, pool_vector[i].value))
3622             {
3623               lab = new_rtx = 0;
3624               if (! last_value
3625                   || ! i
3626                   || ! rtx_equal_p (last_value, pool_vector[i-1].value))
3627                 {
3628                   new_rtx = gen_label_rtx ();
3629                   LABEL_REFS (new_rtx) = pool_vector[i].label;
3630                   pool_vector[i].label = lab = new_rtx;
3631                 }
3632               if (lab && pool_window_label)
3633                 {
3634                   newref = (label_ref_list_t) pool_alloc (label_ref_list_pool);
3635                   newref->label = pool_window_label;
3636                   ref = pool_vector[pool_window_last].wend;
3637                   newref->next = ref;
3638                   pool_vector[pool_window_last].wend = newref;
3639                 }
3640               if (new_rtx)
3641                 pool_window_label = new_rtx;
3642               pool_window_last = i;
3643               return lab;
3644             }
3645         }
3646     }
3647
3648   /* Need a new one.  */
3649   pool_vector[pool_size].value = x;
3650   if (last_value && rtx_equal_p (last_value, pool_vector[pool_size - 1].value))
3651     {
3652       lab = 0;
3653       pool_vector[pool_size - 1].part_of_sequence_p = true;
3654     }
3655   else
3656     lab = gen_label_rtx ();
3657   pool_vector[pool_size].mode = mode;
3658   pool_vector[pool_size].label = lab;
3659   pool_vector[pool_size].wend = NULL;
3660   pool_vector[pool_size].part_of_sequence_p = (lab == 0);
3661   if (lab && pool_window_label)
3662     {
3663       newref = (label_ref_list_t) pool_alloc (label_ref_list_pool);
3664       newref->label = pool_window_label;
3665       ref = pool_vector[pool_window_last].wend;
3666       newref->next = ref;
3667       pool_vector[pool_window_last].wend = newref;
3668     }
3669   if (lab)
3670     pool_window_label = lab;
3671   pool_window_last = pool_size;
3672   pool_size++;
3673   return lab;
3674 }
3675
3676 /* Output the literal table.  START, if nonzero, is the first instruction
3677    this table is needed for, and also indicates that there is at least one
3678    casesi_worker_2 instruction; We have to emit the operand3 labels from
3679    these insns at a 4-byte  aligned position.  BARRIER is the barrier
3680    after which we are to place the table.  */
3681
3682 static void
3683 dump_table (rtx start, rtx barrier)
3684 {
3685   rtx scan = barrier;
3686   int i;
3687   int need_align = 1;
3688   rtx lab;
3689   label_ref_list_t ref;
3690   int have_df = 0;
3691
3692   /* Do two passes, first time dump out the HI sized constants.  */
3693
3694   for (i = 0; i < pool_size; i++)
3695     {
3696       pool_node *p = &pool_vector[i];
3697
3698       if (p->mode == HImode)
3699         {
3700           if (need_align)
3701             {
3702               scan = emit_insn_after (gen_align_2 (), scan);
3703               need_align = 0;
3704             }
3705           for (lab = p->label; lab; lab = LABEL_REFS (lab))
3706             scan = emit_label_after (lab, scan);
3707           scan = emit_insn_after (gen_consttable_2 (p->value, const0_rtx),
3708                                   scan);
3709           for (ref = p->wend; ref; ref = ref->next)
3710             {
3711               lab = ref->label;
3712               scan = emit_insn_after (gen_consttable_window_end (lab), scan);
3713             }
3714         }
3715       else if (p->mode == DFmode)
3716         have_df = 1;
3717     }
3718
3719   need_align = 1;
3720
3721   if (start)
3722     {
3723       scan = emit_insn_after (gen_align_4 (), scan);
3724       need_align = 0;
3725       for (; start != barrier; start = NEXT_INSN (start))
3726         if (GET_CODE (start) == INSN
3727             && recog_memoized (start) == CODE_FOR_casesi_worker_2)
3728           {
3729             rtx src = SET_SRC (XVECEXP (PATTERN (start), 0, 0));
3730             rtx lab = XEXP (XVECEXP (src, 0, 3), 0);
3731
3732             scan = emit_label_after (lab, scan);
3733           }
3734     }
3735   if (TARGET_FMOVD && TARGET_ALIGN_DOUBLE && have_df)
3736     {
3737       rtx align_insn = NULL_RTX;
3738
3739       scan = emit_label_after (gen_label_rtx (), scan);
3740       scan = emit_insn_after (gen_align_log (GEN_INT (3)), scan);
3741       need_align = 0;
3742
3743       for (i = 0; i < pool_size; i++)
3744         {
3745           pool_node *p = &pool_vector[i];
3746
3747           switch (p->mode)
3748             {
3749             case HImode:
3750               break;
3751             case SImode:
3752             case SFmode:
3753               if (align_insn && !p->part_of_sequence_p)
3754                 {
3755                   for (lab = p->label; lab; lab = LABEL_REFS (lab))
3756                     emit_label_before (lab, align_insn);
3757                   emit_insn_before (gen_consttable_4 (p->value, const0_rtx),
3758                                     align_insn);
3759                   for (ref = p->wend; ref; ref = ref->next)
3760                     {
3761                       lab = ref->label;
3762                       emit_insn_before (gen_consttable_window_end (lab),
3763                                         align_insn);
3764                     }
3765                   delete_insn (align_insn);
3766                   align_insn = NULL_RTX;
3767                   continue;
3768                 }
3769               else
3770                 {
3771                   for (lab = p->label; lab; lab = LABEL_REFS (lab))
3772                     scan = emit_label_after (lab, scan);
3773                   scan = emit_insn_after (gen_consttable_4 (p->value,
3774                                                             const0_rtx), scan);
3775                   need_align = ! need_align;
3776                 }
3777               break;
3778             case DFmode:
3779               if (need_align)
3780                 {
3781                   scan = emit_insn_after (gen_align_log (GEN_INT (3)), scan);
3782                   align_insn = scan;
3783                   need_align = 0;
3784                 }
3785             case DImode:
3786               for (lab = p->label; lab; lab = LABEL_REFS (lab))
3787                 scan = emit_label_after (lab, scan);
3788               scan = emit_insn_after (gen_consttable_8 (p->value, const0_rtx),
3789                                       scan);
3790               break;
3791             default:
3792               gcc_unreachable ();
3793             }
3794
3795           if (p->mode != HImode)
3796             {
3797               for (ref = p->wend; ref; ref = ref->next)
3798                 {
3799                   lab = ref->label;
3800                   scan = emit_insn_after (gen_consttable_window_end (lab),
3801                                           scan);
3802                 }
3803             }
3804         }
3805
3806       pool_size = 0;
3807     }
3808
3809   for (i = 0; i < pool_size; i++)
3810     {
3811       pool_node *p = &pool_vector[i];
3812
3813       switch (p->mode)
3814         {
3815         case HImode:
3816           break;
3817         case SImode:
3818         case SFmode:
3819           if (need_align)
3820             {
3821               need_align = 0;
3822               scan = emit_label_after (gen_label_rtx (), scan);
3823               scan = emit_insn_after (gen_align_4 (), scan);
3824             }
3825           for (lab = p->label; lab; lab = LABEL_REFS (lab))
3826             scan = emit_label_after (lab, scan);
3827           scan = emit_insn_after (gen_consttable_4 (p->value, const0_rtx),
3828                                   scan);
3829           break;
3830         case DFmode:
3831         case DImode:
3832           if (need_align)
3833             {
3834               need_align = 0;
3835               scan = emit_label_after (gen_label_rtx (), scan);
3836               scan = emit_insn_after (gen_align_4 (), scan);
3837             }
3838           for (lab = p->label; lab; lab = LABEL_REFS (lab))
3839             scan = emit_label_after (lab, scan);
3840           scan = emit_insn_after (gen_consttable_8 (p->value, const0_rtx),
3841                                   scan);
3842           break;
3843         default:
3844           gcc_unreachable ();
3845         }
3846
3847       if (p->mode != HImode)
3848         {
3849           for (ref = p->wend; ref; ref = ref->next)
3850             {
3851               lab = ref->label;
3852               scan = emit_insn_after (gen_consttable_window_end (lab), scan);
3853             }
3854         }
3855     }
3856
3857   scan = emit_insn_after (gen_consttable_end (), scan);
3858   scan = emit_barrier_after (scan);
3859   pool_size = 0;
3860   pool_window_label = NULL_RTX;
3861   pool_window_last = 0;
3862 }
3863
3864 /* Return nonzero if constant would be an ok source for a
3865    mov.w instead of a mov.l.  */
3866
3867 static int
3868 hi_const (rtx src)
3869 {
3870   return (GET_CODE (src) == CONST_INT
3871           && INTVAL (src) >= -32768
3872           && INTVAL (src) <= 32767);
3873 }
3874
3875 #define MOVA_LABELREF(mova) XVECEXP (SET_SRC (PATTERN (mova)), 0, 0)
3876
3877 /* Nonzero if the insn is a move instruction which needs to be fixed.  */
3878
3879 /* ??? For a DImode/DFmode moves, we don't need to fix it if each half of the
3880    CONST_DOUBLE input value is CONST_OK_FOR_I08.  For a SFmode move, we don't
3881    need to fix it if the input value is CONST_OK_FOR_I08.  */
3882
3883 static int
3884 broken_move (rtx insn)
3885 {
3886   if (GET_CODE (insn) == INSN)
3887     {
3888       rtx pat = PATTERN (insn);
3889       if (GET_CODE (pat) == PARALLEL)
3890         pat = XVECEXP (pat, 0, 0);
3891       if (GET_CODE (pat) == SET
3892           /* We can load any 8-bit value if we don't care what the high
3893              order bits end up as.  */
3894           && GET_MODE (SET_DEST (pat)) != QImode
3895           && (CONSTANT_P (SET_SRC (pat))
3896               /* Match mova_const.  */
3897               || (GET_CODE (SET_SRC (pat)) == UNSPEC
3898                   && XINT (SET_SRC (pat), 1) == UNSPEC_MOVA
3899                   && GET_CODE (XVECEXP (SET_SRC (pat), 0, 0)) == CONST))
3900           && ! (TARGET_SH2E
3901                 && GET_CODE (SET_SRC (pat)) == CONST_DOUBLE
3902                 && (fp_zero_operand (SET_SRC (pat))
3903                     || fp_one_operand (SET_SRC (pat)))
3904                 /* ??? If this is a -m4 or -m4-single compilation, in general
3905                    we don't know the current setting of fpscr, so disable fldi.
3906                    There is an exception if this was a register-register move
3907                    before reload - and hence it was ascertained that we have
3908                    single precision setting - and in a post-reload optimization
3909                    we changed this to do a constant load.  In that case
3910                    we don't have an r0 clobber, hence we must use fldi.  */
3911                 && (! TARGET_SH4 || TARGET_FMOVD
3912                     || (GET_CODE (XEXP (XVECEXP (PATTERN (insn), 0, 2), 0))
3913                         == SCRATCH))
3914                 && GET_CODE (SET_DEST (pat)) == REG
3915                 && FP_REGISTER_P (REGNO (SET_DEST (pat))))
3916           && ! (TARGET_SH2A
3917                 && GET_MODE (SET_DEST (pat)) == SImode
3918                 && (satisfies_constraint_I20 (SET_SRC (pat))
3919                    || satisfies_constraint_I28 (SET_SRC (pat))))
3920           && ! satisfies_constraint_I08 (SET_SRC (pat)))
3921         return 1;
3922     }
3923
3924   return 0;
3925 }
3926
3927 static int
3928 mova_p (rtx insn)
3929 {
3930   return (GET_CODE (insn) == INSN
3931           && GET_CODE (PATTERN (insn)) == SET
3932           && GET_CODE (SET_SRC (PATTERN (insn))) == UNSPEC
3933           && XINT (SET_SRC (PATTERN (insn)), 1) == UNSPEC_MOVA
3934           /* Don't match mova_const.  */
3935           && GET_CODE (MOVA_LABELREF (insn)) == LABEL_REF);
3936 }
3937
3938 /* Fix up a mova from a switch that went out of range.  */
3939 static void
3940 fixup_mova (rtx mova)
3941 {
3942   PUT_MODE (XEXP (MOVA_LABELREF (mova), 0), QImode);
3943   if (! flag_pic)
3944     {
3945       SET_SRC (PATTERN (mova)) = MOVA_LABELREF (mova);
3946       INSN_CODE (mova) = -1;
3947     }
3948   else
3949     {
3950       rtx worker = mova;
3951       rtx lab = gen_label_rtx ();
3952       rtx wpat, wpat0, wpat1, wsrc, target, base, diff;
3953
3954       do
3955         {
3956           worker = NEXT_INSN (worker);
3957           gcc_assert (worker
3958                       && GET_CODE (worker) != CODE_LABEL
3959                       && GET_CODE (worker) != JUMP_INSN);
3960         } while (GET_CODE (worker) == NOTE
3961                  || recog_memoized (worker) != CODE_FOR_casesi_worker_1);
3962       wpat = PATTERN (worker);
3963       wpat0 = XVECEXP (wpat, 0, 0);
3964       wpat1 = XVECEXP (wpat, 0, 1);
3965       wsrc = SET_SRC (wpat0);
3966       PATTERN (worker) = (gen_casesi_worker_2
3967                           (SET_DEST (wpat0), XVECEXP (wsrc, 0, 1),
3968                            XEXP (XVECEXP (wsrc, 0, 2), 0), lab,
3969                            XEXP (wpat1, 0)));
3970       INSN_CODE (worker) = -1;
3971       target = XVECEXP (SET_SRC (PATTERN (mova)), 0, 0);
3972       base = gen_rtx_LABEL_REF (Pmode, lab);
3973       diff = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, target, base), UNSPEC_SYMOFF);
3974       SET_SRC (PATTERN (mova)) = gen_rtx_CONST (Pmode, diff);
3975       INSN_CODE (mova) = -1;
3976     }
3977 }
3978
3979 /* NEW_MOVA is a mova we've just encountered while scanning forward.  Update
3980    *num_mova, and check if the new mova is not nested within the first one.
3981    return 0 if *first_mova was replaced, 1 if new_mova was replaced,
3982    2 if new_mova has been assigned to *first_mova, -1 otherwise..  */
3983 static int
3984 untangle_mova (int *num_mova, rtx *first_mova, rtx new_mova)
3985 {
3986   int n_addr = 0; /* Initialization to shut up spurious warning.  */
3987   int f_target, n_target = 0; /* Likewise.  */
3988
3989   if (optimize)
3990     {
3991       /* If NEW_MOVA has no address yet, it will be handled later.  */
3992       if (INSN_ADDRESSES_SIZE() <= (unsigned) INSN_UID (new_mova))
3993         return -1;
3994
3995       n_addr = INSN_ADDRESSES (INSN_UID (new_mova));
3996       n_target = INSN_ADDRESSES (INSN_UID (XEXP (MOVA_LABELREF (new_mova), 0)));
3997       if (n_addr > n_target || n_addr + 1022 < n_target)
3998         {
3999           /* Change the mova into a load.
4000              broken_move will then return true for it.  */
4001           fixup_mova (new_mova);
4002           return 1;
4003         }
4004     }
4005   if (!(*num_mova)++)
4006     {
4007       *first_mova = new_mova;
4008       return 2;
4009     }
4010   if (!optimize
4011       || ((f_target
4012            = INSN_ADDRESSES (INSN_UID (XEXP (MOVA_LABELREF (*first_mova), 0))))
4013           >= n_target))
4014     return -1;
4015
4016   (*num_mova)--;
4017   if (f_target - INSN_ADDRESSES (INSN_UID (*first_mova))
4018       > n_target - n_addr)
4019     {
4020       fixup_mova (*first_mova);
4021       return 0;
4022     }
4023   else
4024     {
4025       fixup_mova (new_mova);
4026       return 1;
4027     }
4028 }
4029
4030 /* Find the last barrier from insn FROM which is close enough to hold the
4031    constant pool.  If we can't find one, then create one near the end of
4032    the range.  */
4033
4034 static rtx
4035 find_barrier (int num_mova, rtx mova, rtx from)
4036 {
4037   int count_si = 0;
4038   int count_hi = 0;
4039   int found_hi = 0;
4040   int found_si = 0;
4041   int found_di = 0;
4042   int hi_align = 2;
4043   int si_align = 2;
4044   int leading_mova = num_mova;
4045   rtx barrier_before_mova = 0, found_barrier = 0, good_barrier = 0;
4046   int si_limit;
4047   int hi_limit;
4048   rtx orig = from;
4049
4050   /* For HImode: range is 510, add 4 because pc counts from address of
4051      second instruction after this one, subtract 2 for the jump instruction
4052      that we may need to emit before the table, subtract 2 for the instruction
4053      that fills the jump delay slot (in very rare cases, reorg will take an
4054      instruction from after the constant pool or will leave the delay slot
4055      empty).  This gives 510.
4056      For SImode: range is 1020, add 4 because pc counts from address of
4057      second instruction after this one, subtract 2 in case pc is 2 byte
4058      aligned, subtract 2 for the jump instruction that we may need to emit
4059      before the table, subtract 2 for the instruction that fills the jump
4060      delay slot.  This gives 1018.  */
4061
4062   /* The branch will always be shortened now that the reference address for
4063      forward branches is the successor address, thus we need no longer make
4064      adjustments to the [sh]i_limit for -O0.  */
4065
4066   si_limit = 1018;
4067   hi_limit = 510;
4068
4069   while (from && count_si < si_limit && count_hi < hi_limit)
4070     {
4071       int inc = get_attr_length (from);
4072       int new_align = 1;
4073
4074       /* If this is a label that existed at the time of the compute_alignments
4075          call, determine the alignment.  N.B.  When find_barrier recurses for
4076          an out-of-reach mova, we might see labels at the start of previously
4077          inserted constant tables.  */
4078       if (GET_CODE (from) == CODE_LABEL
4079           && CODE_LABEL_NUMBER (from) <= max_labelno_before_reorg)
4080         {
4081           if (optimize)
4082             new_align = 1 << label_to_alignment (from);
4083           else if (GET_CODE (prev_nonnote_insn (from)) == BARRIER)
4084             new_align = 1 << barrier_align (from);
4085           else
4086             new_align = 1;
4087           inc = 0;
4088         }
4089       /* In case we are scanning a constant table because of recursion, check
4090          for explicit alignments.  If the table is long, we might be forced
4091          to emit the new table in front of it; the length of the alignment
4092          might be the last straw.  */
4093       else if (GET_CODE (from) == INSN
4094                && GET_CODE (PATTERN (from)) == UNSPEC_VOLATILE
4095                && XINT (PATTERN (from), 1) == UNSPECV_ALIGN)
4096         new_align = INTVAL (XVECEXP (PATTERN (from), 0, 0));
4097       /* When we find the end of a constant table, paste the new constant
4098          at the end.  That is better than putting it in front because
4099          this way, we don't need extra alignment for adding a 4-byte-aligned
4100          mov(a) label to a 2/4 or 8/4 byte aligned table.  */
4101       else if (GET_CODE (from) == INSN
4102                && GET_CODE (PATTERN (from)) == UNSPEC_VOLATILE
4103                && XINT (PATTERN (from), 1) == UNSPECV_CONST_END)
4104         return from;
4105
4106       if (GET_CODE (from) == BARRIER)
4107         {
4108           rtx next;
4109
4110           found_barrier = from;
4111
4112           /* If we are at the end of the function, or in front of an alignment
4113              instruction, we need not insert an extra alignment.  We prefer
4114              this kind of barrier.  */
4115           if (barrier_align (from) > 2)
4116             good_barrier = from;
4117
4118           /* If we are at the end of a hot/cold block, dump the constants
4119              here.  */
4120           next = NEXT_INSN (from);
4121           if (next
4122               && NOTE_P (next)
4123               && NOTE_KIND (next) == NOTE_INSN_SWITCH_TEXT_SECTIONS)
4124             break;
4125         }
4126
4127       if (broken_move (from))
4128         {
4129           rtx pat, src, dst;
4130           enum machine_mode mode;
4131
4132           pat = PATTERN (from);
4133           if (GET_CODE (pat) == PARALLEL)
4134             pat = XVECEXP (pat, 0, 0);
4135           src = SET_SRC (pat);
4136           dst = SET_DEST (pat);
4137           mode = GET_MODE (dst);
4138
4139           /* We must explicitly check the mode, because sometimes the
4140              front end will generate code to load unsigned constants into
4141              HImode targets without properly sign extending them.  */
4142           if (mode == HImode
4143               || (mode == SImode && hi_const (src) && REGNO (dst) != FPUL_REG))
4144             {
4145               found_hi += 2;
4146               /* We put the short constants before the long constants, so
4147                  we must count the length of short constants in the range
4148                  for the long constants.  */
4149               /* ??? This isn't optimal, but is easy to do.  */
4150               si_limit -= 2;
4151             }
4152           else
4153             {
4154               /* We dump DF/DI constants before SF/SI ones, because
4155                  the limit is the same, but the alignment requirements
4156                  are higher.  We may waste up to 4 additional bytes
4157                  for alignment, and the DF/DI constant may have
4158                  another SF/SI constant placed before it.  */
4159               if (TARGET_SHCOMPACT
4160                   && ! found_di
4161                   && (mode == DFmode || mode == DImode))
4162                 {
4163                   found_di = 1;
4164                   si_limit -= 8;
4165                 }
4166               while (si_align > 2 && found_si + si_align - 2 > count_si)
4167                 si_align >>= 1;
4168               if (found_si > count_si)
4169                 count_si = found_si;
4170               found_si += GET_MODE_SIZE (mode);
4171               if (num_mova)
4172                 si_limit -= GET_MODE_SIZE (mode);
4173             }
4174         }
4175
4176       if (mova_p (from))
4177         {
4178           switch (untangle_mova (&num_mova, &mova, from))
4179             {
4180               case 0:   return find_barrier (0, 0, mova);
4181               case 2:
4182                 {
4183                   leading_mova = 0;
4184                   barrier_before_mova
4185                     = good_barrier ? good_barrier : found_barrier;
4186                 }
4187               default:  break;
4188             }
4189           if (found_si > count_si)
4190             count_si = found_si;
4191         }
4192       else if (GET_CODE (from) == JUMP_INSN
4193                && (GET_CODE (PATTERN (from)) == ADDR_VEC
4194                    || GET_CODE (PATTERN (from)) == ADDR_DIFF_VEC))
4195         {
4196           if ((num_mova > 1 && GET_MODE (prev_nonnote_insn (from)) == VOIDmode)
4197               || (num_mova
4198                   && (prev_nonnote_insn (from)
4199                       == XEXP (MOVA_LABELREF (mova), 0))))
4200             num_mova--;
4201           if (barrier_align (next_real_insn (from)) == align_jumps_log)
4202             {
4203               /* We have just passed the barrier in front of the
4204                  ADDR_DIFF_VEC, which is stored in found_barrier.  Since
4205                  the ADDR_DIFF_VEC is accessed as data, just like our pool
4206                  constants, this is a good opportunity to accommodate what
4207                  we have gathered so far.
4208                  If we waited any longer, we could end up at a barrier in
4209                  front of code, which gives worse cache usage for separated
4210                  instruction / data caches.  */
4211               good_barrier = found_barrier;
4212               break;
4213             }
4214           else
4215             {
4216               rtx body = PATTERN (from);
4217               inc = XVECLEN (body, 1) * GET_MODE_SIZE (GET_MODE (body));
4218             }
4219         }
4220       /* For the SH1, we generate alignments even after jumps-around-jumps.  */
4221       else if (GET_CODE (from) == JUMP_INSN
4222                && ! TARGET_SH2
4223                && ! TARGET_SMALLCODE)
4224         new_align = 4;
4225
4226       if (found_si)
4227         {
4228           count_si += inc;
4229           if (new_align > si_align)
4230             {
4231               si_limit -= (count_si - 1) & (new_align - si_align);
4232               si_align = new_align;
4233             }
4234           count_si = (count_si + new_align - 1) & -new_align;
4235         }
4236       if (found_hi)
4237         {
4238           count_hi += inc;
4239           if (new_align > hi_align)
4240             {
4241               hi_limit -= (count_hi - 1) & (new_align - hi_align);
4242               hi_align = new_align;
4243             }
4244           count_hi = (count_hi + new_align - 1) & -new_align;
4245         }
4246       from = NEXT_INSN (from);
4247     }
4248
4249   if (num_mova)
4250     {
4251       if (leading_mova)
4252         {
4253           /* Try as we might, the leading mova is out of range.  Change
4254              it into a load (which will become a pcload) and retry.  */
4255           fixup_mova (mova);
4256           return find_barrier (0, 0, mova);
4257         }
4258       else
4259         {
4260           /* Insert the constant pool table before the mova instruction,
4261              to prevent the mova label reference from going out of range.  */
4262           from = mova;
4263           good_barrier = found_barrier = barrier_before_mova;
4264         }
4265     }
4266
4267   if (found_barrier)
4268     {
4269       if (good_barrier && next_real_insn (found_barrier))
4270         found_barrier = good_barrier;
4271     }
4272   else
4273     {
4274       /* We didn't find a barrier in time to dump our stuff,
4275          so we'll make one.  */
4276       rtx label = gen_label_rtx ();
4277
4278       /* If we exceeded the range, then we must back up over the last
4279          instruction we looked at.  Otherwise, we just need to undo the
4280          NEXT_INSN at the end of the loop.  */
4281       if (PREV_INSN (from) != orig
4282           && (count_hi > hi_limit || count_si > si_limit))
4283         from = PREV_INSN (PREV_INSN (from));
4284       else
4285         from = PREV_INSN (from);
4286
4287       /* Walk back to be just before any jump or label.
4288          Putting it before a label reduces the number of times the branch
4289          around the constant pool table will be hit.  Putting it before
4290          a jump makes it more likely that the bra delay slot will be
4291          filled.  */
4292       while (GET_CODE (from) == JUMP_INSN || GET_CODE (from) == NOTE
4293              || GET_CODE (from) == CODE_LABEL)
4294         from = PREV_INSN (from);
4295
4296       from = emit_jump_insn_after (gen_jump (label), from);
4297       JUMP_LABEL (from) = label;
4298       LABEL_NUSES (label) = 1;
4299       found_barrier = emit_barrier_after (from);
4300       emit_label_after (label, found_barrier);
4301     }
4302
4303   return found_barrier;
4304 }
4305
4306 /* If the instruction INSN is implemented by a special function, and we can
4307    positively find the register that is used to call the sfunc, and this
4308    register is not used anywhere else in this instruction - except as the
4309    destination of a set, return this register; else, return 0.  */
4310 rtx
4311 sfunc_uses_reg (rtx insn)
4312 {
4313   int i;
4314   rtx pattern, part, reg_part, reg;
4315
4316   if (GET_CODE (insn) != INSN)
4317     return 0;
4318   pattern = PATTERN (insn);
4319   if (GET_CODE (pattern) != PARALLEL || get_attr_type (insn) != TYPE_SFUNC)
4320     return 0;
4321
4322   for (reg_part = 0, i = XVECLEN (pattern, 0) - 1; i >= 1; i--)
4323     {
4324       part = XVECEXP (pattern, 0, i);
4325       if (GET_CODE (part) == USE && GET_MODE (XEXP (part, 0)) == SImode)
4326         reg_part = part;
4327     }
4328   if (! reg_part)
4329     return 0;
4330   reg = XEXP (reg_part, 0);
4331   for (i = XVECLEN (pattern, 0) - 1; i >= 0; i--)
4332     {
4333       part = XVECEXP (pattern, 0, i);
4334       if (part == reg_part || GET_CODE (part) == CLOBBER)
4335         continue;
4336       if (reg_mentioned_p (reg, ((GET_CODE (part) == SET
4337                                   && GET_CODE (SET_DEST (part)) == REG)
4338                                  ? SET_SRC (part) : part)))
4339         return 0;
4340     }
4341   return reg;
4342 }
4343
4344 /* See if the only way in which INSN uses REG is by calling it, or by
4345    setting it while calling it.  Set *SET to a SET rtx if the register
4346    is set by INSN.  */
4347
4348 static int
4349 noncall_uses_reg (rtx reg, rtx insn, rtx *set)
4350 {
4351   rtx pattern, reg2;
4352
4353   *set = NULL_RTX;
4354
4355   reg2 = sfunc_uses_reg (insn);
4356   if (reg2 && REGNO (reg2) == REGNO (reg))
4357     {
4358       pattern = single_set (insn);
4359       if (pattern
4360           && GET_CODE (SET_DEST (pattern)) == REG
4361           && REGNO (reg) == REGNO (SET_DEST (pattern)))
4362         *set = pattern;
4363       return 0;
4364     }
4365   if (GET_CODE (insn) != CALL_INSN)
4366     {
4367       /* We don't use rtx_equal_p because we don't care if the mode is
4368          different.  */
4369       pattern = single_set (insn);
4370       if (pattern
4371           && GET_CODE (SET_DEST (pattern)) == REG
4372           && REGNO (reg) == REGNO (SET_DEST (pattern)))
4373         {
4374           rtx par, part;
4375           int i;
4376
4377           *set = pattern;
4378           par = PATTERN (insn);
4379           if (GET_CODE (par) == PARALLEL)
4380             for (i = XVECLEN (par, 0) - 1; i >= 0; i--)
4381               {
4382                 part = XVECEXP (par, 0, i);
4383                 if (GET_CODE (part) != SET && reg_mentioned_p (reg, part))
4384                   return 1;
4385               }
4386           return reg_mentioned_p (reg, SET_SRC (pattern));
4387         }
4388
4389       return 1;
4390     }
4391
4392   pattern = PATTERN (insn);
4393
4394   if (GET_CODE (pattern) == PARALLEL)
4395     {
4396       int i;
4397
4398       for (i = XVECLEN (pattern, 0) - 1; i >= 1; i--)
4399         if (reg_mentioned_p (reg, XVECEXP (pattern, 0, i)))
4400           return 1;
4401       pattern = XVECEXP (pattern, 0, 0);
4402     }
4403
4404   if (GET_CODE (pattern) == SET)
4405     {
4406       if (reg_mentioned_p (reg, SET_DEST (pattern)))
4407         {
4408           /* We don't use rtx_equal_p, because we don't care if the
4409              mode is different.  */
4410           if (GET_CODE (SET_DEST (pattern)) != REG
4411               || REGNO (reg) != REGNO (SET_DEST (pattern)))
4412             return 1;
4413
4414           *set = pattern;
4415         }
4416
4417       pattern = SET_SRC (pattern);
4418     }
4419
4420   if (GET_CODE (pattern) != CALL
4421       || GET_CODE (XEXP (pattern, 0)) != MEM
4422       || ! rtx_equal_p (reg, XEXP (XEXP (pattern, 0), 0)))
4423     return 1;
4424
4425   return 0;
4426 }
4427
4428 /* Given a X, a pattern of an insn or a part of it, return a mask of used
4429    general registers.  Bits 0..15 mean that the respective registers
4430    are used as inputs in the instruction.  Bits 16..31 mean that the
4431    registers 0..15, respectively, are used as outputs, or are clobbered.
4432    IS_DEST should be set to 16 if X is the destination of a SET, else to 0.  */
4433 int
4434 regs_used (rtx x, int is_dest)
4435 {
4436   enum rtx_code code;
4437   const char *fmt;
4438   int i, used = 0;
4439
4440   if (! x)
4441     return used;
4442   code = GET_CODE (x);
4443   switch (code)
4444     {
4445     case REG:
4446       if (REGNO (x) < 16)
4447         return (((1 << HARD_REGNO_NREGS (0, GET_MODE (x))) - 1)
4448                 << (REGNO (x) + is_dest));
4449       return 0;
4450     case SUBREG:
4451       {
4452         rtx y = SUBREG_REG (x);
4453
4454         if (GET_CODE (y) != REG)
4455           break;
4456         if (REGNO (y) < 16)
4457           return (((1 << HARD_REGNO_NREGS (0, GET_MODE (x))) - 1)
4458                   << (REGNO (y) +
4459                       subreg_regno_offset (REGNO (y),
4460                                            GET_MODE (y),
4461                                            SUBREG_BYTE (x),
4462                                            GET_MODE (x)) + is_dest));
4463         return 0;
4464       }
4465     case SET:
4466       return regs_used (SET_SRC (x), 0) | regs_used (SET_DEST (x), 16);
4467     case RETURN:
4468       /* If there was a return value, it must have been indicated with USE.  */
4469       return 0x00ffff00;
4470     case CLOBBER:
4471       is_dest = 1;
4472       break;
4473     case MEM:
4474       is_dest = 0;
4475       break;
4476     case CALL:
4477       used |= 0x00ff00f0;
4478       break;
4479     default:
4480       break;
4481     }
4482
4483   fmt = GET_RTX_FORMAT (code);
4484
4485   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
4486     {
4487       if (fmt[i] == 'E')
4488         {
4489           register int j;
4490           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
4491             used |= regs_used (XVECEXP (x, i, j), is_dest);
4492         }
4493       else if (fmt[i] == 'e')
4494         used |= regs_used (XEXP (x, i), is_dest);
4495     }
4496   return used;
4497 }
4498
4499 /* Create an instruction that prevents redirection of a conditional branch
4500    to the destination of the JUMP with address ADDR.
4501    If the branch needs to be implemented as an indirect jump, try to find
4502    a scratch register for it.
4503    If NEED_BLOCK is 0, don't do anything unless we need a scratch register.
4504    If any preceding insn that doesn't fit into a delay slot is good enough,
4505    pass 1.  Pass 2 if a definite blocking insn is needed.
4506    -1 is used internally to avoid deep recursion.
4507    If a blocking instruction is made or recognized, return it.  */
4508
4509 static rtx
4510 gen_block_redirect (rtx jump, int addr, int need_block)
4511 {
4512   int dead = 0;
4513   rtx prev = prev_nonnote_insn (jump);
4514   rtx dest;
4515
4516   /* First, check if we already have an instruction that satisfies our need.  */
4517   if (prev && GET_CODE (prev) == INSN && ! INSN_DELETED_P (prev))
4518     {
4519       if (INSN_CODE (prev) == CODE_FOR_indirect_jump_scratch)
4520         return prev;
4521       if (GET_CODE (PATTERN (prev)) == USE
4522           || GET_CODE (PATTERN (prev)) == CLOBBER
4523           || get_attr_in_delay_slot (prev) == IN_DELAY_SLOT_YES)
4524         prev = jump;
4525       else if ((need_block &= ~1) < 0)
4526         return prev;
4527       else if (recog_memoized (prev) == CODE_FOR_block_branch_redirect)
4528         need_block = 0;
4529     }
4530   if (GET_CODE (PATTERN (jump)) == RETURN)
4531     {
4532       if (! need_block)
4533         return prev;
4534       /* Reorg even does nasty things with return insns that cause branches
4535          to go out of range - see find_end_label and callers.  */
4536       return emit_insn_before (gen_block_branch_redirect (const0_rtx) , jump);
4537     }
4538   /* We can't use JUMP_LABEL here because it might be undefined
4539      when not optimizing.  */
4540   dest = XEXP (SET_SRC (PATTERN (jump)), 0);
4541   /* If the branch is out of range, try to find a scratch register for it.  */
4542   if (optimize
4543       && (INSN_ADDRESSES (INSN_UID (dest)) - addr + (unsigned) 4092
4544           > 4092 + 4098))
4545     {
4546       rtx scan;
4547       /* Don't look for the stack pointer as a scratch register,
4548          it would cause trouble if an interrupt occurred.  */
4549       unsigned attempt = 0x7fff, used;
4550       int jump_left = flag_expensive_optimizations + 1;
4551
4552       /* It is likely that the most recent eligible instruction is wanted for
4553          the delay slot.  Therefore, find out which registers it uses, and
4554          try to avoid using them.  */
4555
4556       for (scan = jump; (scan = PREV_INSN (scan)); )
4557         {
4558           enum rtx_code code;
4559
4560           if (INSN_DELETED_P (scan))
4561             continue;
4562           code = GET_CODE (scan);
4563           if (code == CODE_LABEL || code == JUMP_INSN)
4564             break;
4565           if (code == INSN
4566               && GET_CODE (PATTERN (scan)) != USE
4567               && GET_CODE (PATTERN (scan)) != CLOBBER
4568               && get_attr_in_delay_slot (scan) == IN_DELAY_SLOT_YES)
4569             {
4570               attempt &= ~regs_used (PATTERN (scan), 0);
4571               break;
4572             }
4573         }
4574       for (used = dead = 0, scan = JUMP_LABEL (jump);
4575            (scan = NEXT_INSN (scan)); )
4576         {
4577           enum rtx_code code;
4578
4579           if (INSN_DELETED_P (scan))
4580             continue;
4581           code = GET_CODE (scan);
4582           if (INSN_P (scan))
4583             {
4584               used |= regs_used (PATTERN (scan), 0);
4585               if (code == CALL_INSN)
4586                 used |= regs_used (CALL_INSN_FUNCTION_USAGE (scan), 0);
4587               dead |= (used >> 16) & ~used;
4588               if (dead & attempt)
4589                 {
4590                   dead &= attempt;
4591                   break;
4592                 }
4593               if (code == JUMP_INSN)
4594                 {
4595                   if (jump_left-- && simplejump_p (scan))
4596                     scan = JUMP_LABEL (scan);
4597                   else
4598                     break;
4599                 }
4600             }
4601         }
4602       /* Mask out the stack pointer again, in case it was
4603          the only 'free' register we have found.  */
4604       dead &= 0x7fff;
4605     }
4606   /* If the immediate destination is still in range, check for possible
4607      threading with a jump beyond the delay slot insn.
4608      Don't check if we are called recursively; the jump has been or will be
4609      checked in a different invocation then.  */
4610
4611   else if (optimize && need_block >= 0)
4612     {
4613       rtx next = next_active_insn (next_active_insn (dest));
4614       if (next && GET_CODE (next) == JUMP_INSN
4615           && GET_CODE (PATTERN (next)) == SET
4616           && recog_memoized (next) == CODE_FOR_jump_compact)
4617         {
4618           dest = JUMP_LABEL (next);
4619           if (dest
4620               && (INSN_ADDRESSES (INSN_UID (dest)) - addr + (unsigned) 4092
4621                   > 4092 + 4098))
4622             gen_block_redirect (next, INSN_ADDRESSES (INSN_UID (next)), -1);
4623         }
4624     }
4625
4626   if (dead)
4627     {
4628       rtx reg = gen_rtx_REG (SImode, exact_log2 (dead & -dead));
4629
4630       /* It would be nice if we could convert the jump into an indirect
4631          jump / far branch right now, and thus exposing all constituent
4632          instructions to further optimization.  However, reorg uses
4633          simplejump_p to determine if there is an unconditional jump where
4634          it should try to schedule instructions from the target of the
4635          branch; simplejump_p fails for indirect jumps even if they have
4636          a JUMP_LABEL.  */
4637       rtx insn = emit_insn_before (gen_indirect_jump_scratch
4638                                    (reg, GEN_INT (INSN_UID (JUMP_LABEL (jump))))
4639                                    , jump);
4640       /* ??? We would like this to have the scope of the jump, but that
4641          scope will change when a delay slot insn of an inner scope is added.
4642          Hence, after delay slot scheduling, we'll have to expect
4643          NOTE_INSN_BLOCK_END notes between the indirect_jump_scratch and
4644          the jump.  */
4645
4646       INSN_LOCATOR (insn) = INSN_LOCATOR (jump);
4647       INSN_CODE (insn) = CODE_FOR_indirect_jump_scratch;
4648       return insn;
4649     }
4650   else if (need_block)
4651     /* We can't use JUMP_LABEL here because it might be undefined
4652        when not optimizing.  */
4653     return emit_insn_before (gen_block_branch_redirect
4654                       (GEN_INT (INSN_UID (XEXP (SET_SRC (PATTERN (jump)), 0))))
4655                       , jump);
4656   return prev;
4657 }
4658
4659 #define CONDJUMP_MIN -252
4660 #define CONDJUMP_MAX 262
4661 struct far_branch
4662 {
4663   /* A label (to be placed) in front of the jump
4664      that jumps to our ultimate destination.  */
4665   rtx near_label;
4666   /* Where we are going to insert it if we cannot move the jump any farther,
4667      or the jump itself if we have picked up an existing jump.  */
4668   rtx insert_place;
4669   /* The ultimate destination.  */
4670   rtx far_label;
4671   struct far_branch *prev;
4672   /* If the branch has already been created, its address;
4673      else the address of its first prospective user.  */
4674   int address;
4675 };
4676
4677 static void gen_far_branch (struct far_branch *);
4678 enum mdep_reorg_phase_e mdep_reorg_phase;
4679 static void
4680 gen_far_branch (struct far_branch *bp)
4681 {
4682   rtx insn = bp->insert_place;
4683   rtx jump;
4684   rtx label = gen_label_rtx ();
4685   int ok;
4686
4687   emit_label_after (label, insn);
4688   if (bp->far_label)
4689     {
4690       jump = emit_jump_insn_after (gen_jump (bp->far_label), insn);
4691       LABEL_NUSES (bp->far_label)++;
4692     }
4693   else
4694     jump = emit_jump_insn_after (gen_return (), insn);
4695   /* Emit a barrier so that reorg knows that any following instructions
4696      are not reachable via a fall-through path.
4697      But don't do this when not optimizing, since we wouldn't suppress the
4698      alignment for the barrier then, and could end up with out-of-range
4699      pc-relative loads.  */
4700   if (optimize)
4701     emit_barrier_after (jump);
4702   emit_label_after (bp->near_label, insn);
4703   JUMP_LABEL (jump) = bp->far_label;
4704   ok = invert_jump (insn, label, 1);
4705   gcc_assert (ok);
4706   
4707   /* If we are branching around a jump (rather than a return), prevent
4708      reorg from using an insn from the jump target as the delay slot insn -
4709      when reorg did this, it pessimized code (we rather hide the delay slot)
4710      and it could cause branches to go out of range.  */
4711   if (bp->far_label)
4712     (emit_insn_after
4713      (gen_stuff_delay_slot
4714       (GEN_INT (INSN_UID (XEXP (SET_SRC (PATTERN (jump)), 0))),
4715        GEN_INT (recog_memoized (insn) == CODE_FOR_branch_false)),
4716       insn));
4717   /* Prevent reorg from undoing our splits.  */
4718   gen_block_redirect (jump, bp->address += 2, 2);
4719 }
4720
4721 /* Fix up ADDR_DIFF_VECs.  */
4722 void
4723 fixup_addr_diff_vecs (rtx first)
4724 {
4725   rtx insn;
4726
4727   for (insn = first; insn; insn = NEXT_INSN (insn))
4728     {
4729       rtx vec_lab, pat, prev, prevpat, x, braf_label;
4730
4731       if (GET_CODE (insn) != JUMP_INSN
4732           || GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC)
4733         continue;
4734       pat = PATTERN (insn);
4735       vec_lab = XEXP (XEXP (pat, 0), 0);
4736
4737       /* Search the matching casesi_jump_2.  */
4738       for (prev = vec_lab; ; prev = PREV_INSN (prev))
4739         {
4740           if (GET_CODE (prev) != JUMP_INSN)
4741             continue;
4742           prevpat = PATTERN (prev);
4743           if (GET_CODE (prevpat) != PARALLEL || XVECLEN (prevpat, 0) != 2)
4744             continue;
4745           x = XVECEXP (prevpat, 0, 1);
4746           if (GET_CODE (x) != USE)
4747             continue;
4748           x = XEXP (x, 0);
4749           if (GET_CODE (x) == LABEL_REF && XEXP (x, 0) == vec_lab)
4750             break;
4751         }
4752       /* FIXME: This is a bug in the optimizer, but it seems harmless
4753          to just avoid panicing.  */
4754       if (!prev)
4755         continue;
4756
4757       /* Emit the reference label of the braf where it belongs, right after
4758          the casesi_jump_2 (i.e. braf).  */
4759       braf_label = XEXP (XEXP (SET_SRC (XVECEXP (prevpat, 0, 0)), 1), 0);
4760       emit_label_after (braf_label, prev);
4761
4762       /* Fix up the ADDR_DIF_VEC to be relative
4763          to the reference address of the braf.  */
4764       XEXP (XEXP (pat, 0), 0) = braf_label;
4765     }
4766 }
4767
4768 /* BARRIER_OR_LABEL is either a BARRIER or a CODE_LABEL immediately following
4769    a barrier.  Return the base 2 logarithm of the desired alignment.  */
4770 int
4771 barrier_align (rtx barrier_or_label)
4772 {
4773   rtx next = next_real_insn (barrier_or_label), pat, prev;
4774   int slot, credit, jump_to_next = 0;
4775
4776   if (! next)
4777     return 0;
4778
4779   pat = PATTERN (next);
4780
4781   if (GET_CODE (pat) == ADDR_DIFF_VEC)
4782     return 2;
4783
4784   if (GET_CODE (pat) == UNSPEC_VOLATILE && XINT (pat, 1) == UNSPECV_ALIGN)
4785     /* This is a barrier in front of a constant table.  */
4786     return 0;
4787
4788   prev = prev_real_insn (barrier_or_label);
4789   if (GET_CODE (PATTERN (prev)) == ADDR_DIFF_VEC)
4790     {
4791       pat = PATTERN (prev);
4792       /* If this is a very small table, we want to keep the alignment after
4793          the table to the minimum for proper code alignment.  */
4794       return ((TARGET_SMALLCODE
4795                || ((unsigned) XVECLEN (pat, 1) * GET_MODE_SIZE (GET_MODE (pat))
4796                    <= (unsigned) 1 << (CACHE_LOG - 2)))
4797               ? 1 << TARGET_SHMEDIA : align_jumps_log);
4798     }
4799
4800   if (TARGET_SMALLCODE)
4801     return 0;
4802
4803   if (! TARGET_SH2 || ! optimize)
4804     return align_jumps_log;
4805
4806   /* When fixing up pcloads, a constant table might be inserted just before
4807      the basic block that ends with the barrier.  Thus, we can't trust the
4808      instruction lengths before that.  */
4809   if (mdep_reorg_phase > SH_FIXUP_PCLOAD)
4810     {
4811       /* Check if there is an immediately preceding branch to the insn beyond
4812          the barrier.  We must weight the cost of discarding useful information
4813          from the current cache line when executing this branch and there is
4814          an alignment, against that of fetching unneeded insn in front of the
4815          branch target when there is no alignment.  */
4816
4817       /* There are two delay_slot cases to consider.  One is the simple case
4818          where the preceding branch is to the insn beyond the barrier (simple
4819          delay slot filling), and the other is where the preceding branch has
4820          a delay slot that is a duplicate of the insn after the barrier
4821          (fill_eager_delay_slots) and the branch is to the insn after the insn
4822          after the barrier.  */
4823
4824       /* PREV is presumed to be the JUMP_INSN for the barrier under
4825          investigation.  Skip to the insn before it.  */
4826       prev = prev_real_insn (prev);
4827
4828       for (slot = 2, credit = (1 << (CACHE_LOG - 2)) + 2;
4829            credit >= 0 && prev && GET_CODE (prev) == INSN;
4830            prev = prev_real_insn (prev))
4831         {
4832           jump_to_next = 0;
4833           if (GET_CODE (PATTERN (prev)) == USE
4834               || GET_CODE (PATTERN (prev)) == CLOBBER)
4835             continue;
4836           if (GET_CODE (PATTERN (prev)) == SEQUENCE)
4837             {
4838               prev = XVECEXP (PATTERN (prev), 0, 1);
4839               if (INSN_UID (prev) == INSN_UID (next))
4840                 {
4841                   /* Delay slot was filled with insn at jump target.  */
4842                   jump_to_next = 1;
4843                   continue;
4844                 }
4845             }
4846
4847           if (slot &&
4848               get_attr_in_delay_slot (prev) == IN_DELAY_SLOT_YES)
4849             slot = 0;
4850           credit -= get_attr_length (prev);
4851         }
4852       if (prev
4853           && GET_CODE (prev) == JUMP_INSN
4854           && JUMP_LABEL (prev))
4855         {
4856           rtx x;
4857           if (jump_to_next
4858               || next_real_insn (JUMP_LABEL (prev)) == next
4859               /* If relax_delay_slots() decides NEXT was redundant
4860                  with some previous instruction, it will have
4861                  redirected PREV's jump to the following insn.  */
4862               || JUMP_LABEL (prev) == next_nonnote_insn (next)
4863               /* There is no upper bound on redundant instructions
4864                  that might have been skipped, but we must not put an
4865                  alignment where none had been before.  */
4866               || (x = (NEXT_INSN (NEXT_INSN (PREV_INSN (prev)))),
4867                   (INSN_P (x)
4868                    && (INSN_CODE (x) == CODE_FOR_block_branch_redirect
4869                        || INSN_CODE (x) == CODE_FOR_indirect_jump_scratch
4870                        || INSN_CODE (x) == CODE_FOR_stuff_delay_slot))))
4871             {
4872               rtx pat = PATTERN (prev);
4873               if (GET_CODE (pat) == PARALLEL)
4874                 pat = XVECEXP (pat, 0, 0);
4875               if (credit - slot >= (GET_CODE (SET_SRC (pat)) == PC ? 2 : 0))
4876                 return 0;
4877             }
4878         }
4879     }
4880
4881   return align_jumps_log;
4882 }
4883
4884 /* If we are inside a phony loop, almost any kind of label can turn up as the
4885    first one in the loop.  Aligning a braf label causes incorrect switch
4886    destination addresses; we can detect braf labels because they are
4887    followed by a BARRIER.
4888    Applying loop alignment to small constant or switch tables is a waste
4889    of space, so we suppress this too.  */
4890 int
4891 sh_loop_align (rtx label)
4892 {
4893   rtx next = label;
4894
4895   do
4896     next = next_nonnote_insn (next);
4897   while (next && GET_CODE (next) == CODE_LABEL);
4898
4899   if (! next
4900       || ! INSN_P (next)
4901       || GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC
4902       || recog_memoized (next) == CODE_FOR_consttable_2)
4903     return 0;
4904
4905   return align_loops_log;
4906 }
4907
4908 /* Do a final pass over the function, just before delayed branch
4909    scheduling.  */
4910
4911 static void
4912 sh_reorg (void)
4913 {
4914   rtx first, insn, mova = NULL_RTX;
4915   int num_mova;
4916   rtx r0_rtx = gen_rtx_REG (Pmode, 0);
4917   rtx r0_inc_rtx = gen_rtx_POST_INC (Pmode, r0_rtx);
4918
4919   first = get_insns ();
4920   max_labelno_before_reorg = max_label_num ();
4921
4922   /* We must split call insns before introducing `mova's.  If we're
4923      optimizing, they'll have already been split.  Otherwise, make
4924      sure we don't split them too late.  */
4925   if (! optimize)
4926     split_all_insns_noflow ();
4927
4928   if (TARGET_SHMEDIA)
4929     return;
4930
4931   /* If relaxing, generate pseudo-ops to associate function calls with
4932      the symbols they call.  It does no harm to not generate these
4933      pseudo-ops.  However, when we can generate them, it enables to
4934      linker to potentially relax the jsr to a bsr, and eliminate the
4935      register load and, possibly, the constant pool entry.  */
4936
4937   mdep_reorg_phase = SH_INSERT_USES_LABELS;
4938   if (TARGET_RELAX)
4939     {
4940       /* Remove all REG_LABEL_OPERAND notes.  We want to use them for our
4941          own purposes.  This works because none of the remaining passes
4942          need to look at them.
4943
4944          ??? But it may break in the future.  We should use a machine
4945          dependent REG_NOTE, or some other approach entirely.  */
4946       for (insn = first; insn; insn = NEXT_INSN (insn))
4947         {
4948           if (INSN_P (insn))
4949             {
4950               rtx note;
4951
4952               while ((note = find_reg_note (insn, REG_LABEL_OPERAND,
4953                                             NULL_RTX)) != 0)
4954                 remove_note (insn, note);
4955             }
4956         }
4957
4958       for (insn = first; insn; insn = NEXT_INSN (insn))
4959         {
4960           rtx pattern, reg, link, set, scan, dies, label;
4961           int rescan = 0, foundinsn = 0;
4962
4963           if (GET_CODE (insn) == CALL_INSN)
4964             {
4965               pattern = PATTERN (insn);
4966
4967               if (GET_CODE (pattern) == PARALLEL)
4968                 pattern = XVECEXP (pattern, 0, 0);
4969               if (GET_CODE (pattern) == SET)
4970                 pattern = SET_SRC (pattern);
4971
4972               if (GET_CODE (pattern) != CALL
4973                   || GET_CODE (XEXP (pattern, 0)) != MEM)
4974                 continue;
4975
4976               reg = XEXP (XEXP (pattern, 0), 0);
4977             }
4978           else
4979             {
4980               reg = sfunc_uses_reg (insn);
4981               if (! reg)
4982                 continue;
4983             }
4984
4985           if (GET_CODE (reg) != REG)
4986             continue;
4987
4988           /* Try scanning backward to find where the register is set.  */
4989           link = NULL;
4990           for (scan = PREV_INSN (insn);
4991                scan && GET_CODE (scan) != CODE_LABEL;
4992                scan = PREV_INSN (scan))
4993             {
4994               if (! INSN_P (scan))
4995                 continue;
4996
4997               if (! reg_mentioned_p (reg, scan))
4998                 continue;
4999
5000               if (noncall_uses_reg (reg, scan, &set))
5001                 break;
5002
5003               if (set)
5004                 {
5005                   link = scan;
5006                   break;
5007                 }
5008             }
5009
5010           if (! link)
5011             continue;
5012
5013           /* The register is set at LINK.  */
5014
5015           /* We can only optimize the function call if the register is
5016              being set to a symbol.  In theory, we could sometimes
5017              optimize calls to a constant location, but the assembler
5018              and linker do not support that at present.  */
5019           if (GET_CODE (SET_SRC (set)) != SYMBOL_REF
5020               && GET_CODE (SET_SRC (set)) != LABEL_REF)
5021             continue;
5022
5023           /* Scan forward from LINK to the place where REG dies, and
5024              make sure that the only insns which use REG are
5025              themselves function calls.  */
5026
5027           /* ??? This doesn't work for call targets that were allocated
5028              by reload, since there may not be a REG_DEAD note for the
5029              register.  */
5030
5031           dies = NULL_RTX;
5032           for (scan = NEXT_INSN (link); scan; scan = NEXT_INSN (scan))
5033             {
5034               rtx scanset;
5035
5036               /* Don't try to trace forward past a CODE_LABEL if we haven't
5037                  seen INSN yet.  Ordinarily, we will only find the setting insn
5038                  if it is in the same basic block.  However,
5039                  cross-jumping can insert code labels in between the load and
5040                  the call, and can result in situations where a single call
5041                  insn may have two targets depending on where we came from.  */
5042
5043               if (GET_CODE (scan) == CODE_LABEL && ! foundinsn)
5044                 break;
5045
5046               if (! INSN_P (scan))
5047                 continue;
5048
5049               /* Don't try to trace forward past a JUMP.  To optimize
5050                  safely, we would have to check that all the
5051                  instructions at the jump destination did not use REG.  */
5052
5053               if (GET_CODE (scan) == JUMP_INSN)
5054                 break;
5055
5056               if (! reg_mentioned_p (reg, scan))
5057                 continue;
5058
5059               if (noncall_uses_reg (reg, scan, &scanset))
5060                 break;
5061
5062               if (scan == insn)
5063                 foundinsn = 1;
5064
5065               if (scan != insn
5066                   && (GET_CODE (scan) == CALL_INSN || sfunc_uses_reg (scan)))
5067                 {
5068                   /* There is a function call to this register other
5069                      than the one we are checking.  If we optimize
5070                      this call, we need to rescan again below.  */
5071                   rescan = 1;
5072                 }
5073
5074               /* ??? We shouldn't have to worry about SCANSET here.
5075                  We should just be able to check for a REG_DEAD note
5076                  on a function call.  However, the REG_DEAD notes are
5077                  apparently not dependable around libcalls; c-torture
5078                  execute/920501-2 is a test case.  If SCANSET is set,
5079                  then this insn sets the register, so it must have
5080                  died earlier.  Unfortunately, this will only handle
5081                  the cases in which the register is, in fact, set in a
5082                  later insn.  */
5083
5084               /* ??? We shouldn't have to use FOUNDINSN here.
5085                  This dates back to when we used LOG_LINKS to find 
5086                  the most recent insn which sets the register.  */
5087
5088               if (foundinsn
5089                   && (scanset
5090                       || find_reg_note (scan, REG_DEAD, reg)))
5091                 {
5092                   dies = scan;
5093                   break;
5094                 }
5095             }
5096
5097           if (! dies)
5098             {
5099               /* Either there was a branch, or some insn used REG
5100                  other than as a function call address.  */
5101               continue;
5102             }
5103
5104           /* Create a code label, and put it in a REG_LABEL_OPERAND note
5105              on the insn which sets the register, and on each call insn
5106              which uses the register.  In final_prescan_insn we look for
5107              the REG_LABEL_OPERAND notes, and output the appropriate label
5108              or pseudo-op.  */
5109
5110           label = gen_label_rtx ();
5111           add_reg_note (link, REG_LABEL_OPERAND, label);
5112           add_reg_note (insn, REG_LABEL_OPERAND, label);
5113           if (rescan)
5114             {
5115               scan = link;
5116               do
5117                 {
5118                   rtx reg2;
5119
5120                   scan = NEXT_INSN (scan);
5121                   if (scan != insn
5122                       && ((GET_CODE (scan) == CALL_INSN
5123                            && reg_mentioned_p (reg, scan))
5124                           || ((reg2 = sfunc_uses_reg (scan))
5125                               && REGNO (reg2) == REGNO (reg))))
5126                     add_reg_note (scan, REG_LABEL_OPERAND, label);
5127                 }
5128               while (scan != dies);
5129             }
5130         }
5131     }
5132
5133   if (TARGET_SH2)
5134     fixup_addr_diff_vecs (first);
5135
5136   if (optimize)
5137     {
5138       mdep_reorg_phase = SH_SHORTEN_BRANCHES0;
5139       shorten_branches (first);
5140     }
5141
5142   /* Scan the function looking for move instructions which have to be
5143      changed to pc-relative loads and insert the literal tables.  */
5144   label_ref_list_pool = create_alloc_pool ("label references list",
5145                                            sizeof (struct label_ref_list_d),
5146                                            30);
5147   mdep_reorg_phase = SH_FIXUP_PCLOAD;
5148   for (insn = first, num_mova = 0; insn; insn = NEXT_INSN (insn))
5149     {
5150       if (mova_p (insn))
5151         {
5152           /* ??? basic block reordering can move a switch table dispatch
5153              below the switch table.  Check if that has happened.
5154              We only have the addresses available when optimizing; but then,
5155              this check shouldn't be needed when not optimizing.  */
5156           if (!untangle_mova (&num_mova, &mova, insn))
5157             {
5158               insn = mova;
5159               num_mova = 0;
5160             }
5161         }
5162       else if (GET_CODE (insn) == JUMP_INSN
5163                && GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
5164                && num_mova
5165                /* ??? loop invariant motion can also move a mova out of a
5166                   loop.  Since loop does this code motion anyway, maybe we
5167                   should wrap UNSPEC_MOVA into a CONST, so that reload can
5168                   move it back.  */
5169                && ((num_mova > 1
5170                     && GET_MODE (prev_nonnote_insn (insn)) == VOIDmode)
5171                    || (prev_nonnote_insn (insn)
5172                        == XEXP (MOVA_LABELREF (mova), 0))))
5173         {
5174           rtx scan;
5175           int total;
5176
5177           num_mova--;
5178
5179           /* Some code might have been inserted between the mova and
5180              its ADDR_DIFF_VEC.  Check if the mova is still in range.  */
5181           for (scan = mova, total = 0; scan != insn; scan = NEXT_INSN (scan))
5182             total += get_attr_length (scan);
5183
5184           /* range of mova is 1020, add 4 because pc counts from address of
5185              second instruction after this one, subtract 2 in case pc is 2
5186              byte aligned.  Possible alignment needed for the ADDR_DIFF_VEC
5187              cancels out with alignment effects of the mova itself.  */
5188           if (total > 1022)
5189             {
5190               /* Change the mova into a load, and restart scanning
5191                  there.  broken_move will then return true for mova.  */
5192               fixup_mova (mova);
5193               insn = mova;
5194             }
5195         }
5196       if (broken_move (insn)
5197           || (GET_CODE (insn) == INSN
5198               && recog_memoized (insn) == CODE_FOR_casesi_worker_2))
5199         {
5200           rtx scan;
5201           /* Scan ahead looking for a barrier to stick the constant table
5202              behind.  */
5203           rtx barrier = find_barrier (num_mova, mova, insn);
5204           rtx last_float_move = NULL_RTX, last_float = 0, *last_float_addr = NULL;
5205           int need_aligned_label = 0;
5206
5207           if (num_mova && ! mova_p (mova))
5208             {
5209               /* find_barrier had to change the first mova into a
5210                  pcload; thus, we have to start with this new pcload.  */
5211               insn = mova;
5212               num_mova = 0;
5213             }
5214           /* Now find all the moves between the points and modify them.  */
5215           for (scan = insn; scan != barrier; scan = NEXT_INSN (scan))
5216             {
5217               if (GET_CODE (scan) == CODE_LABEL)
5218                 last_float = 0;
5219               if (GET_CODE (scan) == INSN
5220                   && recog_memoized (scan) == CODE_FOR_casesi_worker_2)
5221                 need_aligned_label = 1;
5222               if (broken_move (scan))
5223                 {
5224                   rtx *patp = &PATTERN (scan), pat = *patp;
5225                   rtx src, dst;
5226                   rtx lab;
5227                   rtx newsrc;
5228                   enum machine_mode mode;
5229
5230                   if (GET_CODE (pat) == PARALLEL)
5231                     patp = &XVECEXP (pat, 0, 0), pat = *patp;
5232                   src = SET_SRC (pat);
5233                   dst = SET_DEST (pat);
5234                   mode = GET_MODE (dst);
5235
5236                   if (mode == SImode && hi_const (src)
5237                       && REGNO (dst) != FPUL_REG)
5238                     {
5239                       int offset = 0;
5240
5241                       mode = HImode;
5242                       while (GET_CODE (dst) == SUBREG)
5243                         {
5244                           offset += subreg_regno_offset (REGNO (SUBREG_REG (dst)),
5245                                                          GET_MODE (SUBREG_REG (dst)),
5246                                                          SUBREG_BYTE (dst),
5247                                                          GET_MODE (dst));
5248                           dst = SUBREG_REG (dst);
5249                         }
5250                       dst = gen_rtx_REG (HImode, REGNO (dst) + offset);
5251                     }
5252                   if (GET_CODE (dst) == REG && FP_ANY_REGISTER_P (REGNO (dst)))
5253                     {
5254                       /* This must be an insn that clobbers r0.  */
5255                       rtx *clobberp = &XVECEXP (PATTERN (scan), 0,
5256                                                 XVECLEN (PATTERN (scan), 0)
5257                                                 - 1);
5258                       rtx clobber = *clobberp;
5259
5260                       gcc_assert (GET_CODE (clobber) == CLOBBER
5261                                   && rtx_equal_p (XEXP (clobber, 0), r0_rtx));
5262
5263                       if (last_float
5264                           && reg_set_between_p (r0_rtx, last_float_move, scan))
5265                         last_float = 0;
5266                       if (last_float
5267                           && TARGET_SHCOMPACT
5268                           && GET_MODE_SIZE (mode) != 4
5269                           && GET_MODE_SIZE (GET_MODE (last_float)) == 4)
5270                         last_float = 0;
5271                       lab = add_constant (src, mode, last_float);
5272                       if (lab)
5273                         emit_insn_before (gen_mova (lab), scan);
5274                       else
5275                         {
5276                           /* There will be a REG_UNUSED note for r0 on
5277                              LAST_FLOAT_MOVE; we have to change it to REG_INC,
5278                              lest reorg:mark_target_live_regs will not
5279                              consider r0 to be used, and we end up with delay
5280                              slot insn in front of SCAN that clobbers r0.  */
5281                           rtx note
5282                             = find_regno_note (last_float_move, REG_UNUSED, 0);
5283
5284                           /* If we are not optimizing, then there may not be
5285                              a note.  */
5286                           if (note)
5287                             PUT_REG_NOTE_KIND (note, REG_INC);
5288
5289                           *last_float_addr = r0_inc_rtx;
5290                         }
5291                       last_float_move = scan;
5292                       last_float = src;
5293                       newsrc = gen_const_mem (mode,
5294                                         (((TARGET_SH4 && ! TARGET_FMOVD)
5295                                           || REGNO (dst) == FPUL_REG)
5296                                          ? r0_inc_rtx
5297                                          : r0_rtx));
5298                       last_float_addr = &XEXP (newsrc, 0);
5299
5300                       /* Remove the clobber of r0.  */
5301                       *clobberp = gen_rtx_CLOBBER (GET_MODE (clobber),
5302                                                    gen_rtx_SCRATCH (Pmode));
5303                     }
5304                   /* This is a mova needing a label.  Create it.  */
5305                   else if (GET_CODE (src) == UNSPEC
5306                            && XINT (src, 1) == UNSPEC_MOVA
5307                            && GET_CODE (XVECEXP (src, 0, 0)) == CONST)
5308                     {
5309                       lab = add_constant (XVECEXP (src, 0, 0), mode, 0);
5310                       newsrc = gen_rtx_LABEL_REF (VOIDmode, lab);
5311                       newsrc = gen_rtx_UNSPEC (SImode,
5312                                                gen_rtvec (1, newsrc),
5313                                                UNSPEC_MOVA);
5314                     }
5315                   else
5316                     {
5317                       lab = add_constant (src, mode, 0);
5318                       newsrc = gen_rtx_LABEL_REF (VOIDmode, lab);
5319                       newsrc = gen_const_mem (mode, newsrc);
5320                     }
5321                   *patp = gen_rtx_SET (VOIDmode, dst, newsrc);
5322                   INSN_CODE (scan) = -1;
5323                 }
5324             }
5325           dump_table (need_aligned_label ? insn : 0, barrier);
5326           insn = barrier;
5327         }
5328     }
5329   free_alloc_pool (label_ref_list_pool);
5330   for (insn = first; insn; insn = NEXT_INSN (insn))
5331     PUT_MODE (insn, VOIDmode);
5332
5333   mdep_reorg_phase = SH_SHORTEN_BRANCHES1;
5334   INSN_ADDRESSES_FREE ();
5335   split_branches (first);
5336
5337   /* The INSN_REFERENCES_ARE_DELAYED in sh.h is problematic because it
5338      also has an effect on the register that holds the address of the sfunc.
5339      Insert an extra dummy insn in front of each sfunc that pretends to
5340      use this register.  */
5341   if (flag_delayed_branch)
5342     {
5343       for (insn = first; insn; insn = NEXT_INSN (insn))
5344         {
5345           rtx reg = sfunc_uses_reg (insn);
5346
5347           if (! reg)
5348             continue;
5349           emit_insn_before (gen_use_sfunc_addr (reg), insn);
5350         }
5351     }
5352 #if 0
5353   /* fpscr is not actually a user variable, but we pretend it is for the
5354      sake of the previous optimization passes, since we want it handled like
5355      one.  However, we don't have any debugging information for it, so turn
5356      it into a non-user variable now.  */
5357   if (TARGET_SH4)
5358     REG_USERVAR_P (get_fpscr_rtx ()) = 0;
5359 #endif
5360   mdep_reorg_phase = SH_AFTER_MDEP_REORG;
5361 }
5362
5363 int
5364 get_dest_uid (rtx label, int max_uid)
5365 {
5366   rtx dest = next_real_insn (label);
5367   int dest_uid;
5368   if (! dest)
5369     /* This can happen for an undefined label.  */
5370     return 0;
5371   dest_uid = INSN_UID (dest);
5372   /* If this is a newly created branch redirection blocking instruction,
5373      we cannot index the branch_uid or insn_addresses arrays with its
5374      uid.  But then, we won't need to, because the actual destination is
5375      the following branch.  */
5376   while (dest_uid >= max_uid)
5377     {
5378       dest = NEXT_INSN (dest);
5379       dest_uid = INSN_UID (dest);
5380     }
5381   if (GET_CODE (dest) == JUMP_INSN && GET_CODE (PATTERN (dest)) == RETURN)
5382     return 0;
5383   return dest_uid;
5384 }
5385
5386 /* Split condbranches that are out of range.  Also add clobbers for
5387    scratch registers that are needed in far jumps.
5388    We do this before delay slot scheduling, so that it can take our
5389    newly created instructions into account.  It also allows us to
5390    find branches with common targets more easily.  */
5391
5392 static void
5393 split_branches (rtx first)
5394 {
5395   rtx insn;
5396   struct far_branch **uid_branch, *far_branch_list = 0;
5397   int max_uid = get_max_uid ();
5398   int ok;
5399
5400   /* Find out which branches are out of range.  */
5401   shorten_branches (first);
5402
5403   uid_branch = (struct far_branch **) alloca (max_uid * sizeof *uid_branch);
5404   memset ((char *) uid_branch, 0, max_uid * sizeof *uid_branch);
5405
5406   for (insn = first; insn; insn = NEXT_INSN (insn))
5407     if (! INSN_P (insn))
5408       continue;
5409     else if (INSN_DELETED_P (insn))
5410       {
5411         /* Shorten_branches would split this instruction again,
5412            so transform it into a note.  */
5413         SET_INSN_DELETED (insn);
5414       }
5415     else if (GET_CODE (insn) == JUMP_INSN
5416              /* Don't mess with ADDR_DIFF_VEC */
5417              && (GET_CODE (PATTERN (insn)) == SET
5418                  || GET_CODE (PATTERN (insn)) == RETURN))
5419       {
5420         enum attr_type type = get_attr_type (insn);
5421         if (type == TYPE_CBRANCH)
5422           {
5423             rtx next, beyond;
5424
5425             if (get_attr_length (insn) > 4)
5426               {
5427                 rtx src = SET_SRC (PATTERN (insn));
5428                 rtx olabel = XEXP (XEXP (src, 1), 0);
5429                 int addr = INSN_ADDRESSES (INSN_UID (insn));
5430                 rtx label = 0;
5431                 int dest_uid = get_dest_uid (olabel, max_uid);
5432                 struct far_branch *bp = uid_branch[dest_uid];
5433
5434                 /* redirect_jump needs a valid JUMP_LABEL, and it might delete
5435                    the label if the LABEL_NUSES count drops to zero.  There is
5436                    always a jump_optimize pass that sets these values, but it
5437                    proceeds to delete unreferenced code, and then if not
5438                    optimizing, to un-delete the deleted instructions, thus
5439                    leaving labels with too low uses counts.  */
5440                 if (! optimize)
5441                   {
5442                     JUMP_LABEL (insn) = olabel;
5443                     LABEL_NUSES (olabel)++;
5444                   }
5445                 if (! bp)
5446                   {
5447                     bp = (struct far_branch *) alloca (sizeof *bp);
5448                     uid_branch[dest_uid] = bp;
5449                     bp->prev = far_branch_list;
5450                     far_branch_list = bp;
5451                     bp->far_label
5452                       = XEXP (XEXP (SET_SRC (PATTERN (insn)), 1), 0);
5453                     LABEL_NUSES (bp->far_label)++;
5454                   }
5455                 else
5456                   {
5457                     label = bp->near_label;
5458                     if (! label && bp->address - addr >= CONDJUMP_MIN)
5459                       {
5460                         rtx block = bp->insert_place;
5461
5462                         if (GET_CODE (PATTERN (block)) == RETURN)
5463                           block = PREV_INSN (block);
5464                         else
5465                           block = gen_block_redirect (block,
5466                                                       bp->address, 2);
5467                         label = emit_label_after (gen_label_rtx (),
5468                                                   PREV_INSN (block));
5469                         bp->near_label = label;
5470                       }
5471                     else if (label && ! NEXT_INSN (label))
5472                       {
5473                         if (addr + 2 - bp->address <= CONDJUMP_MAX)
5474                           bp->insert_place = insn;
5475                         else
5476                           gen_far_branch (bp);
5477                       }
5478                   }
5479                 if (! label
5480                     || (NEXT_INSN (label) && bp->address - addr < CONDJUMP_MIN))
5481                   {
5482                     bp->near_label = label = gen_label_rtx ();
5483                     bp->insert_place = insn;
5484                     bp->address = addr;
5485                   }
5486                 ok = redirect_jump (insn, label, 0);
5487                 gcc_assert (ok);
5488               }
5489             else
5490               {
5491                 /* get_attr_length (insn) == 2 */
5492                 /* Check if we have a pattern where reorg wants to redirect
5493                    the branch to a label from an unconditional branch that
5494                    is too far away.  */
5495                 /* We can't use JUMP_LABEL here because it might be undefined
5496                    when not optimizing.  */
5497                 /* A syntax error might cause beyond to be NULL_RTX.  */
5498                 beyond
5499                   = next_active_insn (XEXP (XEXP (SET_SRC (PATTERN (insn)), 1),
5500                                             0));
5501
5502                 if (beyond
5503                     && (GET_CODE (beyond) == JUMP_INSN
5504                         || ((beyond = next_active_insn (beyond))
5505                             && GET_CODE (beyond) == JUMP_INSN))
5506                     && GET_CODE (PATTERN (beyond)) == SET
5507                     && recog_memoized (beyond) == CODE_FOR_jump_compact
5508                     && ((INSN_ADDRESSES
5509                          (INSN_UID (XEXP (SET_SRC (PATTERN (beyond)), 0)))
5510                          - INSN_ADDRESSES (INSN_UID (insn)) + (unsigned) 252)
5511                         > 252 + 258 + 2))
5512                   gen_block_redirect (beyond,
5513                                       INSN_ADDRESSES (INSN_UID (beyond)), 1);
5514               }
5515
5516             next = next_active_insn (insn);
5517
5518             if ((GET_CODE (next) == JUMP_INSN
5519                  || ((next = next_active_insn (next))
5520                      && GET_CODE (next) == JUMP_INSN))
5521                 && GET_CODE (PATTERN (next)) == SET
5522                 && recog_memoized (next) == CODE_FOR_jump_compact
5523                 && ((INSN_ADDRESSES
5524                      (INSN_UID (XEXP (SET_SRC (PATTERN (next)), 0)))
5525                      - INSN_ADDRESSES (INSN_UID (insn)) + (unsigned) 252)
5526                     > 252 + 258 + 2))
5527               gen_block_redirect (next, INSN_ADDRESSES (INSN_UID (next)), 1);
5528           }
5529         else if (type == TYPE_JUMP || type == TYPE_RETURN)
5530           {
5531             int addr = INSN_ADDRESSES (INSN_UID (insn));
5532             rtx far_label = 0;
5533             int dest_uid = 0;
5534             struct far_branch *bp;
5535
5536             if (type == TYPE_JUMP)
5537               {
5538                 far_label = XEXP (SET_SRC (PATTERN (insn)), 0);
5539                 dest_uid = get_dest_uid (far_label, max_uid);
5540                 if (! dest_uid)
5541                   {
5542                     /* Parse errors can lead to labels outside
5543                       the insn stream.  */
5544                     if (! NEXT_INSN (far_label))
5545                       continue;
5546
5547                     if (! optimize)
5548                       {
5549                         JUMP_LABEL (insn) = far_label;
5550                         LABEL_NUSES (far_label)++;
5551                       }
5552                     redirect_jump (insn, NULL_RTX, 1);
5553                     far_label = 0;
5554                   }
5555               }
5556             bp = uid_branch[dest_uid];
5557             if (! bp)
5558               {
5559                 bp = (struct far_branch *) alloca (sizeof *bp);
5560                 uid_branch[dest_uid] = bp;
5561                 bp->prev = far_branch_list;
5562                 far_branch_list = bp;
5563                 bp->near_label = 0;
5564                 bp->far_label = far_label;
5565                 if (far_label)
5566                   LABEL_NUSES (far_label)++;
5567               }
5568             else if (bp->near_label && ! NEXT_INSN (bp->near_label))
5569               if (addr - bp->address <= CONDJUMP_MAX)
5570                 emit_label_after (bp->near_label, PREV_INSN (insn));
5571               else
5572                 {
5573                   gen_far_branch (bp);
5574                   bp->near_label = 0;
5575                 }
5576             else
5577               bp->near_label = 0;
5578             bp->address = addr;
5579             bp->insert_place = insn;
5580             if (! far_label)
5581               emit_insn_before (gen_block_branch_redirect (const0_rtx), insn);
5582             else
5583               gen_block_redirect (insn, addr, bp->near_label ? 2 : 0);
5584           }
5585       }
5586   /* Generate all pending far branches,
5587      and free our references to the far labels.  */
5588   while (far_branch_list)
5589     {
5590       if (far_branch_list->near_label
5591           && ! NEXT_INSN (far_branch_list->near_label))
5592         gen_far_branch (far_branch_list);
5593       if (optimize
5594           && far_branch_list->far_label
5595           && ! --LABEL_NUSES (far_branch_list->far_label))
5596         delete_insn (far_branch_list->far_label);
5597       far_branch_list = far_branch_list->prev;
5598     }
5599
5600   /* Instruction length information is no longer valid due to the new
5601      instructions that have been generated.  */
5602   init_insn_lengths ();
5603 }
5604
5605 /* Dump out instruction addresses, which is useful for debugging the
5606    constant pool table stuff.
5607
5608    If relaxing, output the label and pseudo-ops used to link together
5609    calls and the instruction which set the registers.  */
5610
5611 /* ??? The addresses printed by this routine for insns are nonsense for
5612    insns which are inside of a sequence where none of the inner insns have
5613    variable length.  This is because the second pass of shorten_branches
5614    does not bother to update them.  */
5615
5616 void
5617 final_prescan_insn (rtx insn, rtx *opvec ATTRIBUTE_UNUSED,
5618                     int noperands ATTRIBUTE_UNUSED)
5619 {
5620   if (TARGET_DUMPISIZE)
5621     fprintf (asm_out_file, "\n! at %04x\n", INSN_ADDRESSES (INSN_UID (insn)));
5622
5623   if (TARGET_RELAX)
5624     {
5625       rtx note;
5626
5627       note = find_reg_note (insn, REG_LABEL_OPERAND, NULL_RTX);
5628       if (note)
5629         {
5630           rtx pattern;
5631
5632           pattern = PATTERN (insn);
5633           if (GET_CODE (pattern) == PARALLEL)
5634             pattern = XVECEXP (pattern, 0, 0);
5635           switch (GET_CODE (pattern))
5636             {
5637             case SET:
5638               if (GET_CODE (SET_SRC (pattern)) != CALL
5639                   && get_attr_type (insn) != TYPE_SFUNC)
5640                 {
5641                   targetm.asm_out.internal_label
5642                     (asm_out_file, "L", CODE_LABEL_NUMBER (XEXP (note, 0)));
5643                   break;
5644                 }
5645               /* else FALLTHROUGH */
5646             case CALL:
5647               asm_fprintf (asm_out_file, "\t.uses %LL%d\n",
5648                            CODE_LABEL_NUMBER (XEXP (note, 0)));
5649               break;
5650
5651             default:
5652               gcc_unreachable ();
5653             }
5654         }
5655     }
5656 }
5657
5658 /* Dump out any constants accumulated in the final pass.  These will
5659    only be labels.  */
5660
5661 const char *
5662 output_jump_label_table (void)
5663 {
5664   int i;
5665
5666   if (pool_size)
5667     {
5668       fprintf (asm_out_file, "\t.align 2\n");
5669       for (i = 0; i < pool_size; i++)
5670         {
5671           pool_node *p = &pool_vector[i];
5672
5673           (*targetm.asm_out.internal_label) (asm_out_file, "L",
5674                                      CODE_LABEL_NUMBER (p->label));
5675           output_asm_insn (".long       %O0", &p->value);
5676         }
5677       pool_size = 0;
5678     }
5679
5680   return "";
5681 }
5682 \f
5683 /* A full frame looks like:
5684
5685    arg-5
5686    arg-4
5687    [ if current_function_anonymous_args
5688    arg-3
5689    arg-2
5690    arg-1
5691    arg-0 ]
5692    saved-fp
5693    saved-r10
5694    saved-r11
5695    saved-r12
5696    saved-pr
5697    local-n
5698    ..
5699    local-1
5700    local-0        <- fp points here.  */
5701
5702 /* Number of bytes pushed for anonymous args, used to pass information
5703    between expand_prologue and expand_epilogue.  */
5704
5705 /* Adjust the stack by SIZE bytes.  REG holds the rtl of the register to be
5706    adjusted.  If epilogue_p is zero, this is for a prologue; otherwise, it's
5707    for an epilogue and a negative value means that it's for a sibcall
5708    epilogue.  If LIVE_REGS_MASK is nonzero, it points to a HARD_REG_SET of
5709    all the registers that are about to be restored, and hence dead.  */
5710
5711 static void
5712 output_stack_adjust (int size, rtx reg, int epilogue_p,
5713                      HARD_REG_SET *live_regs_mask)
5714 {
5715   rtx (*emit_fn) (rtx) = epilogue_p ? &emit_insn : &frame_insn;
5716   if (size)
5717     {
5718       HOST_WIDE_INT align = STACK_BOUNDARY / BITS_PER_UNIT;
5719
5720 /* This test is bogus, as output_stack_adjust is used to re-align the
5721    stack.  */
5722 #if 0
5723       gcc_assert (!(size % align));
5724 #endif
5725
5726       if (CONST_OK_FOR_ADD (size))
5727         emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size)));
5728       /* Try to do it with two partial adjustments; however, we must make
5729          sure that the stack is properly aligned at all times, in case
5730          an interrupt occurs between the two partial adjustments.  */
5731       else if (CONST_OK_FOR_ADD (size / 2 & -align)
5732                && CONST_OK_FOR_ADD (size - (size / 2 & -align)))
5733         {
5734           emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size / 2 & -align)));
5735           emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size - (size / 2 & -align))));
5736         }
5737       else
5738         {
5739           rtx const_reg;
5740           rtx insn;
5741           int temp = epilogue_p ? 7 : (TARGET_SH5 ? 0 : 1);
5742           int i;
5743
5744           /* If TEMP is invalid, we could temporarily save a general
5745              register to MACL.  However, there is currently no need
5746              to handle this case, so just die when we see it.  */
5747           if (epilogue_p < 0
5748               || current_function_interrupt
5749               || ! call_really_used_regs[temp] || fixed_regs[temp])
5750             temp = -1;
5751           if (temp < 0 && ! current_function_interrupt
5752               && (TARGET_SHMEDIA || epilogue_p >= 0))
5753             {
5754               HARD_REG_SET temps;
5755               COPY_HARD_REG_SET (temps, call_used_reg_set);
5756               AND_COMPL_HARD_REG_SET (temps, call_fixed_reg_set);
5757               if (epilogue_p > 0)
5758                 {
5759                   int nreg = 0;
5760                   if (crtl->return_rtx)
5761                     {
5762                       enum machine_mode mode;
5763                       mode = GET_MODE (crtl->return_rtx);
5764                       if (BASE_RETURN_VALUE_REG (mode) == FIRST_RET_REG)
5765                         nreg = HARD_REGNO_NREGS (FIRST_RET_REG, mode);
5766                     }
5767                   for (i = 0; i < nreg; i++)
5768                     CLEAR_HARD_REG_BIT (temps, FIRST_RET_REG + i);
5769                   if (crtl->calls_eh_return)
5770                     {
5771                       CLEAR_HARD_REG_BIT (temps, EH_RETURN_STACKADJ_REGNO);
5772                       for (i = 0; i <= 3; i++)
5773                         CLEAR_HARD_REG_BIT (temps, EH_RETURN_DATA_REGNO (i));
5774                     }
5775                 }
5776               if (TARGET_SHMEDIA && epilogue_p < 0)
5777                 for (i = FIRST_TARGET_REG; i <= LAST_TARGET_REG; i++)
5778                   CLEAR_HARD_REG_BIT (temps, i);
5779               if (epilogue_p <= 0)
5780                 {
5781                   for (i = FIRST_PARM_REG;
5782                        i < FIRST_PARM_REG + NPARM_REGS (SImode); i++)
5783                     CLEAR_HARD_REG_BIT (temps, i);
5784                   if (cfun->static_chain_decl != NULL)
5785                     CLEAR_HARD_REG_BIT (temps, STATIC_CHAIN_REGNUM);
5786                 }
5787               temp = scavenge_reg (&temps);
5788             }
5789           if (temp < 0 && live_regs_mask)
5790             {
5791               HARD_REG_SET temps;
5792
5793               COPY_HARD_REG_SET (temps, *live_regs_mask);
5794               CLEAR_HARD_REG_BIT (temps, REGNO (reg));
5795               temp = scavenge_reg (&temps);
5796             }
5797           if (temp < 0)
5798             {
5799               rtx adj_reg, tmp_reg, mem;
5800               
5801               /* If we reached here, the most likely case is the (sibcall)
5802                  epilogue for non SHmedia.  Put a special push/pop sequence
5803                  for such case as the last resort.  This looks lengthy but
5804                  would not be problem because it seems to be very
5805                  rare.  */
5806               
5807               gcc_assert (!TARGET_SHMEDIA && epilogue_p);
5808               
5809
5810                /* ??? There is still the slight possibility that r4 or
5811                   r5 have been reserved as fixed registers or assigned
5812                   as global registers, and they change during an
5813                   interrupt.  There are possible ways to handle this:
5814                      
5815                   - If we are adjusting the frame pointer (r14), we can do
5816                     with a single temp register and an ordinary push / pop
5817                     on the stack.
5818                   - Grab any call-used or call-saved registers (i.e. not
5819                     fixed or globals) for the temps we need.  We might
5820                     also grab r14 if we are adjusting the stack pointer.
5821                     If we can't find enough available registers, issue
5822                     a diagnostic and die - the user must have reserved
5823                     way too many registers.
5824                  But since all this is rather unlikely to happen and
5825                  would require extra testing, we just die if r4 / r5
5826                  are not available.  */
5827               gcc_assert (!fixed_regs[4] && !fixed_regs[5]
5828                           && !global_regs[4] && !global_regs[5]);
5829
5830               adj_reg = gen_rtx_REG (GET_MODE (reg), 4);
5831               tmp_reg = gen_rtx_REG (GET_MODE (reg), 5);
5832               emit_move_insn (gen_tmp_stack_mem (Pmode, reg), adj_reg);
5833               emit_insn (GEN_MOV (adj_reg, GEN_INT (size)));
5834               emit_insn (GEN_ADD3 (adj_reg, adj_reg, reg));
5835               mem = gen_tmp_stack_mem (Pmode, gen_rtx_PRE_DEC (Pmode, adj_reg));
5836               emit_move_insn (mem, tmp_reg);
5837               emit_move_insn (tmp_reg, gen_tmp_stack_mem (Pmode, reg));
5838               mem = gen_tmp_stack_mem (Pmode, gen_rtx_PRE_DEC (Pmode, adj_reg));
5839               emit_move_insn (mem, tmp_reg);
5840               emit_move_insn (reg, adj_reg);
5841               mem = gen_tmp_stack_mem (Pmode, gen_rtx_POST_INC (Pmode, reg));
5842               emit_move_insn (adj_reg, mem);
5843               mem = gen_tmp_stack_mem (Pmode, gen_rtx_POST_INC (Pmode, reg));
5844               emit_move_insn (tmp_reg, mem);
5845               /* Tell flow the insns that pop r4/r5 aren't dead.  */
5846               emit_use (tmp_reg);
5847               emit_use (adj_reg);
5848               return;
5849             }
5850           const_reg = gen_rtx_REG (GET_MODE (reg), temp);
5851
5852           /* If SIZE is negative, subtract the positive value.
5853              This sometimes allows a constant pool entry to be shared
5854              between prologue and epilogue code.  */
5855           if (size < 0)
5856             {
5857               emit_insn (GEN_MOV (const_reg, GEN_INT (-size)));
5858               insn = emit_fn (GEN_SUB3 (reg, reg, const_reg));
5859             }
5860           else
5861             {
5862               emit_insn (GEN_MOV (const_reg, GEN_INT (size)));
5863               insn = emit_fn (GEN_ADD3 (reg, reg, const_reg));
5864             }
5865           if (! epilogue_p)
5866             add_reg_note (insn, REG_FRAME_RELATED_EXPR,
5867                           gen_rtx_SET (VOIDmode, reg,
5868                                        gen_rtx_PLUS (SImode, reg,
5869                                                      GEN_INT (size))));
5870         }
5871     }
5872 }
5873
5874 static rtx
5875 frame_insn (rtx x)
5876 {
5877   x = emit_insn (x);
5878   RTX_FRAME_RELATED_P (x) = 1;
5879   return x;
5880 }
5881
5882 /* Output RTL to push register RN onto the stack.  */
5883
5884 static rtx
5885 push (int rn)
5886 {
5887   rtx x;
5888   if (rn == FPUL_REG)
5889     x = gen_push_fpul ();
5890   else if (rn == FPSCR_REG)
5891     x = gen_push_fpscr ();
5892   else if ((TARGET_SH4 || TARGET_SH2A_DOUBLE) && TARGET_FMOVD && ! TARGET_FPU_SINGLE
5893            && FP_OR_XD_REGISTER_P (rn))
5894     {
5895       if (FP_REGISTER_P (rn) && (rn - FIRST_FP_REG) & 1)
5896         return NULL_RTX;
5897       x = gen_push_4 (gen_rtx_REG (DFmode, rn));
5898     }
5899   else if (TARGET_SH2E && FP_REGISTER_P (rn))
5900     x = gen_push_e (gen_rtx_REG (SFmode, rn));
5901   else
5902     x = gen_push (gen_rtx_REG (SImode, rn));
5903
5904   x = frame_insn (x);
5905   add_reg_note (x, REG_INC, gen_rtx_REG (SImode, STACK_POINTER_REGNUM));
5906   return x;
5907 }
5908
5909 /* Output RTL to pop register RN from the stack.  */
5910
5911 static void
5912 pop (int rn)
5913 {
5914   rtx x;
5915   if (rn == FPUL_REG)
5916     x = gen_pop_fpul ();
5917   else if (rn == FPSCR_REG)
5918     x = gen_pop_fpscr ();
5919   else if ((TARGET_SH4 || TARGET_SH2A_DOUBLE) && TARGET_FMOVD && ! TARGET_FPU_SINGLE
5920            && FP_OR_XD_REGISTER_P (rn))
5921     {
5922       if (FP_REGISTER_P (rn) && (rn - FIRST_FP_REG) & 1)
5923         return;
5924       x = gen_pop_4 (gen_rtx_REG (DFmode, rn));
5925     }
5926   else if (TARGET_SH2E && FP_REGISTER_P (rn))
5927     x = gen_pop_e (gen_rtx_REG (SFmode, rn));
5928   else
5929     x = gen_pop (gen_rtx_REG (SImode, rn));
5930
5931   x = emit_insn (x);
5932   add_reg_note (x, REG_INC, gen_rtx_REG (SImode, STACK_POINTER_REGNUM));
5933 }
5934
5935 /* Generate code to push the regs specified in the mask.  */
5936
5937 static void
5938 push_regs (HARD_REG_SET *mask, int interrupt_handler)
5939 {
5940   int i = interrupt_handler ? LAST_BANKED_REG + 1 : 0;
5941   int skip_fpscr = 0;
5942
5943   /* Push PR last; this gives better latencies after the prologue, and
5944      candidates for the return delay slot when there are no general
5945      registers pushed.  */
5946   for (; i < FIRST_PSEUDO_REGISTER; i++)
5947     {
5948       /* If this is an interrupt handler, and the SZ bit varies,
5949          and we have to push any floating point register, we need
5950          to switch to the correct precision first.  */
5951       if (i == FIRST_FP_REG && interrupt_handler && TARGET_FMOVD
5952           && hard_reg_set_intersect_p (*mask, reg_class_contents[DF_REGS]))
5953         {
5954           HARD_REG_SET unsaved;
5955
5956           push (FPSCR_REG);
5957           COMPL_HARD_REG_SET (unsaved, *mask);
5958           fpscr_set_from_mem (NORMAL_MODE (FP_MODE), unsaved);
5959           skip_fpscr = 1;
5960         }
5961       if (i != PR_REG
5962           && (i != FPSCR_REG || ! skip_fpscr)
5963           && TEST_HARD_REG_BIT (*mask, i))
5964            {
5965         /* If the ISR has RESBANK attribute assigned, don't push any of
5966            the following registers - R0-R14, MACH, MACL and GBR.  */
5967       if (! (sh_cfun_resbank_handler_p ()
5968              && ((i >= FIRST_GENERAL_REG && i < LAST_GENERAL_REG)
5969                  || i == MACH_REG
5970                  || i == MACL_REG
5971                  || i == GBR_REG)))
5972           push (i);
5973         }
5974     }
5975
5976   /* Push banked registers last to improve delay slot opportunities.  */
5977   if (interrupt_handler)
5978     for (i = FIRST_BANKED_REG; i <= LAST_BANKED_REG; i++)
5979       if (TEST_HARD_REG_BIT (*mask, i))
5980         push (i);
5981
5982   /* Don't push PR register for an ISR with RESBANK attribute assigned.  */
5983   if (TEST_HARD_REG_BIT (*mask, PR_REG) && !sh_cfun_resbank_handler_p ())
5984     push (PR_REG);
5985 }
5986
5987 /* Calculate how much extra space is needed to save all callee-saved
5988    target registers.
5989    LIVE_REGS_MASK is the register mask calculated by calc_live_regs.  */
5990
5991 static int
5992 shmedia_target_regs_stack_space (HARD_REG_SET *live_regs_mask)
5993 {
5994   int reg;
5995   int stack_space = 0;
5996   int interrupt_handler = sh_cfun_interrupt_handler_p ();
5997
5998   for (reg = LAST_TARGET_REG; reg >= FIRST_TARGET_REG; reg--)
5999     if ((! call_really_used_regs[reg] || interrupt_handler)
6000         && ! TEST_HARD_REG_BIT (*live_regs_mask, reg))
6001       /* Leave space to save this target register on the stack,
6002          in case target register allocation wants to use it.  */
6003       stack_space += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
6004   return stack_space;
6005 }
6006
6007 /* Decide whether we should reserve space for callee-save target registers,
6008    in case target register allocation wants to use them.  REGS_SAVED is
6009    the space, in bytes, that is already required for register saves.
6010    LIVE_REGS_MASK is the register mask calculated by calc_live_regs.  */
6011
6012 static int
6013 shmedia_reserve_space_for_target_registers_p (int regs_saved,
6014                                               HARD_REG_SET *live_regs_mask)
6015 {
6016   if (optimize_size)
6017     return 0;
6018   return shmedia_target_regs_stack_space (live_regs_mask) <= regs_saved;
6019 }
6020
6021 /* Decide how much space to reserve for callee-save target registers
6022    in case target register allocation wants to use them.
6023    LIVE_REGS_MASK is the register mask calculated by calc_live_regs.  */
6024
6025 static int
6026 shmedia_target_regs_stack_adjust (HARD_REG_SET *live_regs_mask)
6027 {
6028   if (shmedia_space_reserved_for_target_registers)
6029     return shmedia_target_regs_stack_space (live_regs_mask);
6030   else
6031     return 0;
6032 }
6033
6034 /* Work out the registers which need to be saved, both as a mask and a
6035    count of saved words.  Return the count.
6036
6037    If doing a pragma interrupt function, then push all regs used by the
6038    function, and if we call another function (we can tell by looking at PR),
6039    make sure that all the regs it clobbers are safe too.  */
6040
6041 static int
6042 calc_live_regs (HARD_REG_SET *live_regs_mask)
6043 {
6044   unsigned int reg;
6045   int count;
6046   tree attrs;
6047   bool interrupt_or_trapa_handler, trapa_handler, interrupt_handler;
6048   bool nosave_low_regs;
6049   int pr_live, has_call;
6050
6051   attrs = DECL_ATTRIBUTES (current_function_decl);
6052   interrupt_or_trapa_handler = sh_cfun_interrupt_handler_p ();
6053   trapa_handler = lookup_attribute ("trapa_handler", attrs) != NULL_TREE;
6054   interrupt_handler = interrupt_or_trapa_handler && ! trapa_handler;
6055   nosave_low_regs = lookup_attribute ("nosave_low_regs", attrs) != NULL_TREE;
6056
6057   CLEAR_HARD_REG_SET (*live_regs_mask);
6058   if ((TARGET_SH4 || TARGET_SH2A_DOUBLE) && TARGET_FMOVD && interrupt_handler
6059       && df_regs_ever_live_p (FPSCR_REG))
6060     target_flags &= ~MASK_FPU_SINGLE;
6061   /* If we can save a lot of saves by switching to double mode, do that.  */
6062   else if ((TARGET_SH4 || TARGET_SH2A_DOUBLE) && TARGET_FMOVD && TARGET_FPU_SINGLE)
6063     for (count = 0, reg = FIRST_FP_REG; reg <= LAST_FP_REG; reg += 2)
6064       if (df_regs_ever_live_p (reg) && df_regs_ever_live_p (reg+1)
6065           && (! call_really_used_regs[reg]
6066               || interrupt_handler)
6067           && ++count > 2)
6068         {
6069           target_flags &= ~MASK_FPU_SINGLE;
6070           break;
6071         }
6072   /* PR_MEDIA_REG is a general purpose register, thus global_alloc already
6073      knows how to use it.  That means the pseudo originally allocated for
6074      the initial value can become the PR_MEDIA_REG hard register, as seen for
6075      execute/20010122-1.c:test9.  */
6076   if (TARGET_SHMEDIA)
6077     /* ??? this function is called from initial_elimination_offset, hence we
6078        can't use the result of sh_media_register_for_return here.  */
6079     pr_live = sh_pr_n_sets ();
6080   else
6081     {
6082       rtx pr_initial = has_hard_reg_initial_val (Pmode, PR_REG);
6083       pr_live = (pr_initial
6084                  ? (GET_CODE (pr_initial) != REG
6085                     || REGNO (pr_initial) != (PR_REG))
6086                  : df_regs_ever_live_p (PR_REG));
6087       /* For Shcompact, if not optimizing, we end up with a memory reference
6088          using the return address pointer for __builtin_return_address even
6089          though there is no actual need to put the PR register on the stack.  */
6090       pr_live |= df_regs_ever_live_p (RETURN_ADDRESS_POINTER_REGNUM);
6091     }
6092   /* Force PR to be live if the prologue has to call the SHmedia
6093      argument decoder or register saver.  */
6094   if (TARGET_SHCOMPACT
6095       && ((crtl->args.info.call_cookie
6096            & ~ CALL_COOKIE_RET_TRAMP (1))
6097           || crtl->saves_all_registers))
6098     pr_live = 1;
6099   has_call = TARGET_SHMEDIA ? ! leaf_function_p () : pr_live;
6100   for (count = 0, reg = FIRST_PSEUDO_REGISTER; reg-- != 0; )
6101     {
6102       if (reg == (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG)
6103           ? pr_live
6104           : interrupt_handler
6105           ? (/* Need to save all the regs ever live.  */
6106              (df_regs_ever_live_p (reg)
6107               || (call_really_used_regs[reg]
6108                   && (! fixed_regs[reg] || reg == MACH_REG || reg == MACL_REG
6109                       || reg == PIC_OFFSET_TABLE_REGNUM)
6110                   && has_call)
6111               || (TARGET_SHMEDIA && has_call
6112                   && REGISTER_NATURAL_MODE (reg) == SImode
6113                   && (GENERAL_REGISTER_P (reg) || TARGET_REGISTER_P (reg))))
6114              && reg != STACK_POINTER_REGNUM && reg != ARG_POINTER_REGNUM
6115              && reg != RETURN_ADDRESS_POINTER_REGNUM
6116              && reg != T_REG && reg != GBR_REG
6117              /* Push fpscr only on targets which have FPU */
6118              && (reg != FPSCR_REG || TARGET_FPU_ANY))
6119           : (/* Only push those regs which are used and need to be saved.  */
6120              (TARGET_SHCOMPACT
6121               && flag_pic
6122               && crtl->args.info.call_cookie
6123               && reg == PIC_OFFSET_TABLE_REGNUM)
6124              || (df_regs_ever_live_p (reg)
6125                  && ((!call_really_used_regs[reg]
6126                       && !(reg != PIC_OFFSET_TABLE_REGNUM
6127                            && fixed_regs[reg] && call_used_regs[reg]))
6128                      || (trapa_handler && reg == FPSCR_REG && TARGET_FPU_ANY)))
6129              || (crtl->calls_eh_return
6130                  && (reg == EH_RETURN_DATA_REGNO (0)
6131                      || reg == EH_RETURN_DATA_REGNO (1)
6132                      || reg == EH_RETURN_DATA_REGNO (2)
6133                      || reg == EH_RETURN_DATA_REGNO (3)))
6134              || ((reg == MACL_REG || reg == MACH_REG)
6135                  && df_regs_ever_live_p (reg)
6136                  && sh_cfun_attr_renesas_p ())
6137              ))
6138         {
6139           SET_HARD_REG_BIT (*live_regs_mask, reg);
6140           count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
6141
6142           if ((TARGET_SH4 || TARGET_SH2A_DOUBLE || TARGET_SH5) && TARGET_FMOVD
6143               && GET_MODE_CLASS (REGISTER_NATURAL_MODE (reg)) == MODE_FLOAT)
6144             {
6145               if (FP_REGISTER_P (reg))
6146                 {
6147                   if (! TARGET_FPU_SINGLE && ! df_regs_ever_live_p (reg ^ 1))
6148                     {
6149                       SET_HARD_REG_BIT (*live_regs_mask, (reg ^ 1));
6150                       count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg ^ 1));
6151                     }
6152                 }
6153               else if (XD_REGISTER_P (reg))
6154                 {
6155                   /* Must switch to double mode to access these registers.  */
6156                   target_flags &= ~MASK_FPU_SINGLE;
6157                 }
6158             }
6159         }
6160       if (nosave_low_regs && reg == R8_REG)
6161         break;
6162     }
6163   /* If we have a target register optimization pass after prologue / epilogue
6164      threading, we need to assume all target registers will be live even if
6165      they aren't now.  */
6166   if (flag_branch_target_load_optimize2
6167       && TARGET_SAVE_ALL_TARGET_REGS
6168       && shmedia_space_reserved_for_target_registers)
6169     for (reg = LAST_TARGET_REG; reg >= FIRST_TARGET_REG; reg--)
6170       if ((! call_really_used_regs[reg] || interrupt_handler)
6171           && ! TEST_HARD_REG_BIT (*live_regs_mask, reg))
6172         {
6173           SET_HARD_REG_BIT (*live_regs_mask, reg);
6174           count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
6175         }
6176   /* If this is an interrupt handler, we don't have any call-clobbered
6177      registers we can conveniently use for target register save/restore.
6178      Make sure we save at least one general purpose register when we need
6179      to save target registers.  */
6180   if (interrupt_handler
6181       && hard_reg_set_intersect_p (*live_regs_mask,
6182                                    reg_class_contents[TARGET_REGS])
6183       && ! hard_reg_set_intersect_p (*live_regs_mask,
6184                                      reg_class_contents[GENERAL_REGS]))
6185     {
6186       SET_HARD_REG_BIT (*live_regs_mask, R0_REG);
6187       count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (R0_REG));
6188     }
6189
6190   return count;
6191 }
6192
6193 /* Code to generate prologue and epilogue sequences */
6194
6195 /* PUSHED is the number of bytes that are being pushed on the
6196    stack for register saves.  Return the frame size, padded
6197    appropriately so that the stack stays properly aligned.  */
6198 static HOST_WIDE_INT
6199 rounded_frame_size (int pushed)
6200 {
6201   HOST_WIDE_INT size = get_frame_size ();
6202   HOST_WIDE_INT align = STACK_BOUNDARY / BITS_PER_UNIT;
6203
6204   return ((size + pushed + align - 1) & -align) - pushed;
6205 }
6206
6207 /* Choose a call-clobbered target-branch register that remains
6208    unchanged along the whole function.  We set it up as the return
6209    value in the prologue.  */
6210 int
6211 sh_media_register_for_return (void)
6212 {
6213   int regno;
6214   int tr0_used;
6215
6216   if (! current_function_is_leaf)
6217     return -1;
6218   if (lookup_attribute ("interrupt_handler",
6219                         DECL_ATTRIBUTES (current_function_decl)))
6220     return -1;
6221   if (sh_cfun_interrupt_handler_p ())
6222     return -1;
6223
6224   tr0_used = flag_pic && df_regs_ever_live_p (PIC_OFFSET_TABLE_REGNUM);
6225
6226   for (regno = FIRST_TARGET_REG + tr0_used; regno <= LAST_TARGET_REG; regno++)
6227     if (call_really_used_regs[regno] && ! df_regs_ever_live_p (regno))
6228       return regno;
6229
6230   return -1;
6231 }
6232
6233 /* The maximum registers we need to save are:
6234    - 62 general purpose registers (r15 is stack pointer, r63 is zero)
6235    - 32 floating point registers (for each pair, we save none,
6236          one single precision value, or a double precision value).
6237    -  8 target registers
6238    -  add 1 entry for a delimiter.  */
6239 #define MAX_SAVED_REGS (62+32+8)
6240
6241 typedef struct save_entry_s
6242 {
6243   unsigned char reg;
6244   unsigned char mode;
6245   short offset;
6246 } save_entry;
6247
6248 #define MAX_TEMPS 4
6249
6250 /* There will be a delimiter entry with VOIDmode both at the start and the
6251    end of a filled in schedule.  The end delimiter has the offset of the
6252    save with the smallest (i.e. most negative) offset.  */
6253 typedef struct save_schedule_s
6254 {
6255   save_entry entries[MAX_SAVED_REGS + 2];
6256   int temps[MAX_TEMPS+1];
6257 } save_schedule;
6258
6259 /* Fill in SCHEDULE according to LIVE_REGS_MASK.  If RESTORE is nonzero,
6260    use reverse order.  Returns the last entry written to (not counting
6261    the delimiter).  OFFSET_BASE is a number to be added to all offset
6262    entries.  */
6263
6264 static save_entry *
6265 sh5_schedule_saves (HARD_REG_SET *live_regs_mask, save_schedule *schedule,
6266                     int offset_base)
6267 {
6268   int align, i;
6269   save_entry *entry = schedule->entries;
6270   int tmpx = 0;
6271   int offset;
6272
6273   if (! current_function_interrupt)
6274     for (i = FIRST_GENERAL_REG; tmpx < MAX_TEMPS && i <= LAST_GENERAL_REG; i++)
6275       if (call_really_used_regs[i] && ! fixed_regs[i] && i != PR_MEDIA_REG
6276           && ! FUNCTION_ARG_REGNO_P (i)
6277           && i != FIRST_RET_REG
6278           && ! (cfun->static_chain_decl != NULL && i == STATIC_CHAIN_REGNUM)
6279           && ! (crtl->calls_eh_return
6280                 && (i == EH_RETURN_STACKADJ_REGNO
6281                     || ((unsigned) i >= EH_RETURN_DATA_REGNO (0)
6282                         && (unsigned) i <= EH_RETURN_DATA_REGNO (3)))))
6283         schedule->temps[tmpx++] = i;
6284   entry->reg = -1;
6285   entry->mode = VOIDmode;
6286   entry->offset = offset_base;
6287   entry++;
6288   /* We loop twice: first, we save 8-byte aligned registers in the
6289      higher addresses, that are known to be aligned.  Then, we
6290      proceed to saving 32-bit registers that don't need 8-byte
6291      alignment.
6292      If this is an interrupt function, all registers that need saving
6293      need to be saved in full.  moreover, we need to postpone saving
6294      target registers till we have saved some general purpose registers
6295      we can then use as scratch registers.  */
6296   offset = offset_base;
6297   for (align = 1; align >= 0; align--)
6298     {
6299       for (i = FIRST_PSEUDO_REGISTER - 1; i >= 0; i--)
6300         if (TEST_HARD_REG_BIT (*live_regs_mask, i))
6301           {
6302             enum machine_mode mode = REGISTER_NATURAL_MODE (i);
6303             int reg = i;
6304
6305             if (current_function_interrupt)
6306               {
6307                 if (TARGET_REGISTER_P (i))
6308                   continue;
6309                 if (GENERAL_REGISTER_P (i))
6310                   mode = DImode;
6311               }
6312             if (mode == SFmode && (i % 2) == 1
6313                 && ! TARGET_FPU_SINGLE && FP_REGISTER_P (i)
6314                 && (TEST_HARD_REG_BIT (*live_regs_mask, (i ^ 1))))
6315               {
6316                 mode = DFmode;
6317                 i--;
6318                 reg--;
6319               }
6320
6321             /* If we're doing the aligned pass and this is not aligned,
6322                or we're doing the unaligned pass and this is aligned,
6323                skip it.  */
6324             if ((GET_MODE_SIZE (mode) % (STACK_BOUNDARY / BITS_PER_UNIT) == 0)
6325                 != align)
6326               continue;
6327
6328             if (current_function_interrupt
6329                 && GENERAL_REGISTER_P (i)
6330                 && tmpx < MAX_TEMPS)
6331               schedule->temps[tmpx++] = i;
6332
6333             offset -= GET_MODE_SIZE (mode);
6334             entry->reg = i;
6335             entry->mode = mode;
6336             entry->offset = offset;
6337             entry++;
6338           }
6339       if (align && current_function_interrupt)
6340         for (i = LAST_TARGET_REG; i >= FIRST_TARGET_REG; i--)
6341           if (TEST_HARD_REG_BIT (*live_regs_mask, i))
6342             {
6343               offset -= GET_MODE_SIZE (DImode);
6344               entry->reg = i;
6345               entry->mode = DImode;
6346               entry->offset = offset;
6347               entry++;
6348             }
6349     }
6350   entry->reg = -1;
6351   entry->mode = VOIDmode;
6352   entry->offset = offset;
6353   schedule->temps[tmpx] = -1;
6354   return entry - 1;
6355 }
6356
6357 void
6358 sh_expand_prologue (void)
6359 {
6360   HARD_REG_SET live_regs_mask;
6361   int d, i;
6362   int d_rounding = 0;
6363   int save_flags = target_flags;
6364   int pretend_args;
6365   tree sp_switch_attr
6366     = lookup_attribute ("sp_switch", DECL_ATTRIBUTES (current_function_decl));
6367
6368   current_function_interrupt = sh_cfun_interrupt_handler_p ();
6369
6370   /* We have pretend args if we had an object sent partially in registers
6371      and partially on the stack, e.g. a large structure.  */
6372   pretend_args = crtl->args.pretend_args_size;
6373   if (TARGET_VARARGS_PRETEND_ARGS (current_function_decl)
6374       && (NPARM_REGS(SImode)
6375           > crtl->args.info.arg_count[(int) SH_ARG_INT]))
6376     pretend_args = 0;
6377   output_stack_adjust (-pretend_args
6378                        - crtl->args.info.stack_regs * 8,
6379                        stack_pointer_rtx, 0, NULL);
6380
6381   if (TARGET_SHCOMPACT && flag_pic && crtl->args.info.call_cookie)
6382     /* We're going to use the PIC register to load the address of the
6383        incoming-argument decoder and/or of the return trampoline from
6384        the GOT, so make sure the PIC register is preserved and
6385        initialized.  */
6386     df_set_regs_ever_live (PIC_OFFSET_TABLE_REGNUM, true);
6387
6388   if (TARGET_SHCOMPACT
6389       && (crtl->args.info.call_cookie & ~ CALL_COOKIE_RET_TRAMP(1)))
6390     {
6391       int reg;
6392
6393       /* First, make all registers with incoming arguments that will
6394          be pushed onto the stack live, so that register renaming
6395          doesn't overwrite them.  */
6396       for (reg = 0; reg < NPARM_REGS (SImode); reg++)
6397         if (CALL_COOKIE_STACKSEQ_GET (crtl->args.info.call_cookie)
6398             >= NPARM_REGS (SImode) - reg)
6399           for (; reg < NPARM_REGS (SImode); reg++)
6400             emit_insn (gen_shcompact_preserve_incoming_args
6401                        (gen_rtx_REG (SImode, FIRST_PARM_REG + reg)));
6402         else if (CALL_COOKIE_INT_REG_GET
6403                  (crtl->args.info.call_cookie, reg) == 1)
6404           emit_insn (gen_shcompact_preserve_incoming_args
6405                      (gen_rtx_REG (SImode, FIRST_PARM_REG + reg)));
6406
6407       emit_move_insn (gen_rtx_REG (Pmode, MACL_REG),
6408                       stack_pointer_rtx);
6409       emit_move_insn (gen_rtx_REG (SImode, R0_REG),
6410                       GEN_INT (crtl->args.info.call_cookie));
6411       emit_move_insn (gen_rtx_REG (SImode, MACH_REG),
6412                       gen_rtx_REG (SImode, R0_REG));
6413     }
6414   else if (TARGET_SHMEDIA)
6415     {
6416       int tr = sh_media_register_for_return ();
6417
6418       if (tr >= 0)
6419         emit_move_insn (gen_rtx_REG (DImode, tr),
6420                         gen_rtx_REG (DImode, PR_MEDIA_REG));
6421     }
6422
6423   /* Emit the code for SETUP_VARARGS.  */
6424   if (cfun->stdarg)
6425     {
6426       if (TARGET_VARARGS_PRETEND_ARGS (current_function_decl))
6427         {
6428           /* Push arg regs as if they'd been provided by caller in stack.  */
6429           for (i = 0; i < NPARM_REGS(SImode); i++)
6430             {
6431               int rn = NPARM_REGS(SImode) + FIRST_PARM_REG - i - 1;
6432               rtx insn;
6433
6434               if (i >= (NPARM_REGS(SImode)
6435                         - crtl->args.info.arg_count[(int) SH_ARG_INT]
6436                         ))
6437                 break;
6438               insn = push (rn);
6439             }
6440         }
6441     }
6442
6443   /* If we're supposed to switch stacks at function entry, do so now.  */
6444   if (sp_switch_attr)
6445     {
6446       /* The argument specifies a variable holding the address of the
6447          stack the interrupt function should switch to/from at entry/exit.  */
6448       const char *s
6449         = ggc_strdup (TREE_STRING_POINTER (TREE_VALUE (sp_switch_attr)));
6450       rtx sp_switch = gen_rtx_SYMBOL_REF (Pmode, s);
6451
6452       emit_insn (gen_sp_switch_1 (sp_switch));
6453     }
6454
6455   d = calc_live_regs (&live_regs_mask);
6456   /* ??? Maybe we could save some switching if we can move a mode switch
6457      that already happens to be at the function start into the prologue.  */
6458   if (target_flags != save_flags && ! current_function_interrupt)
6459     emit_insn (gen_toggle_sz ());
6460
6461   if (TARGET_SH5)
6462     {
6463       int offset_base, offset;
6464       rtx r0 = NULL_RTX;
6465       int offset_in_r0 = -1;
6466       int sp_in_r0 = 0;
6467       int tregs_space = shmedia_target_regs_stack_adjust (&live_regs_mask);
6468       int total_size, save_size;
6469       save_schedule schedule;
6470       save_entry *entry;
6471       int *tmp_pnt;
6472
6473       if (call_really_used_regs[R0_REG] && ! fixed_regs[R0_REG]
6474           && ! current_function_interrupt)
6475         r0 = gen_rtx_REG (Pmode, R0_REG);
6476
6477       /* D is the actual number of bytes that we need for saving registers,
6478          however, in initial_elimination_offset we have committed to using
6479          an additional TREGS_SPACE amount of bytes - in order to keep both
6480          addresses to arguments supplied by the caller and local variables
6481          valid, we must keep this gap.  Place it between the incoming
6482          arguments and the actually saved registers in a bid to optimize
6483          locality of reference.  */
6484       total_size = d + tregs_space;
6485       total_size += rounded_frame_size (total_size);
6486       save_size = total_size - rounded_frame_size (d);
6487       if (save_size % (STACK_BOUNDARY / BITS_PER_UNIT))
6488         d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
6489                         - save_size % (STACK_BOUNDARY / BITS_PER_UNIT));
6490
6491       /* If adjusting the stack in a single step costs nothing extra, do so.
6492          I.e. either if a single addi is enough, or we need a movi anyway,
6493          and we don't exceed the maximum offset range (the test for the
6494          latter is conservative for simplicity).  */
6495       if (TARGET_SHMEDIA
6496           && (CONST_OK_FOR_I10 (-total_size)
6497               || (! CONST_OK_FOR_I10 (-(save_size + d_rounding))
6498                   && total_size <= 2044)))
6499         d_rounding = total_size - save_size;
6500
6501       offset_base = d + d_rounding;
6502
6503       output_stack_adjust (-(save_size + d_rounding), stack_pointer_rtx,
6504                            0, NULL);
6505
6506       sh5_schedule_saves (&live_regs_mask, &schedule, offset_base);
6507       tmp_pnt = schedule.temps;
6508       for (entry = &schedule.entries[1]; entry->mode != VOIDmode; entry++)
6509         {
6510           enum machine_mode mode = (enum machine_mode) entry->mode;
6511           unsigned int reg = entry->reg;
6512           rtx reg_rtx, mem_rtx, pre_dec = NULL_RTX;
6513           rtx orig_reg_rtx;
6514
6515           offset = entry->offset;
6516
6517           reg_rtx = gen_rtx_REG (mode, reg);
6518
6519           mem_rtx = gen_frame_mem (mode,
6520                                    gen_rtx_PLUS (Pmode,
6521                                                  stack_pointer_rtx,
6522                                                  GEN_INT (offset)));
6523
6524           if (!memory_address_p (mode, XEXP (mem_rtx, 0)))
6525             {
6526               gcc_assert (r0);
6527               mem_rtx = NULL_RTX;
6528             }
6529
6530           if (HAVE_PRE_DECREMENT
6531               && (offset_in_r0 - offset == GET_MODE_SIZE (mode)
6532                   || mem_rtx == NULL_RTX
6533                   || reg == PR_REG || SPECIAL_REGISTER_P (reg)))
6534             {
6535               pre_dec = gen_frame_mem (mode, gen_rtx_PRE_DEC (Pmode, r0));
6536
6537               if (!memory_address_p (mode, XEXP (pre_dec, 0)))
6538                 pre_dec = NULL_RTX;
6539               else
6540                 {
6541                   mem_rtx = NULL_RTX;
6542                   offset += GET_MODE_SIZE (mode);
6543                 }
6544             }
6545
6546           if (mem_rtx != NULL_RTX)
6547             goto addr_ok;
6548
6549           if (offset_in_r0 == -1)
6550             {
6551               emit_move_insn (r0, GEN_INT (offset));
6552               offset_in_r0 = offset;
6553             }
6554           else if (offset != offset_in_r0)
6555             {
6556               emit_move_insn (r0,
6557                               gen_rtx_PLUS
6558                               (Pmode, r0,
6559                                GEN_INT (offset - offset_in_r0)));
6560               offset_in_r0 += offset - offset_in_r0;
6561             }
6562
6563           if (pre_dec != NULL_RTX)
6564             {
6565               if (! sp_in_r0)
6566                 {
6567                   emit_move_insn (r0,
6568                                   gen_rtx_PLUS
6569                                   (Pmode, r0, stack_pointer_rtx));
6570                   sp_in_r0 = 1;
6571                 }
6572
6573               offset -= GET_MODE_SIZE (mode);
6574               offset_in_r0 -= GET_MODE_SIZE (mode);
6575
6576               mem_rtx = pre_dec;
6577             }
6578           else if (sp_in_r0)
6579             mem_rtx = gen_frame_mem (mode, r0);
6580           else
6581             mem_rtx = gen_frame_mem (mode,
6582                                      gen_rtx_PLUS (Pmode,
6583                                                    stack_pointer_rtx,
6584                                                    r0));
6585
6586           /* We must not use an r0-based address for target-branch
6587              registers or for special registers without pre-dec
6588              memory addresses, since we store their values in r0
6589              first.  */
6590           gcc_assert (!TARGET_REGISTER_P (reg)
6591                       && ((reg != PR_REG && !SPECIAL_REGISTER_P (reg))
6592                           || mem_rtx == pre_dec));
6593           
6594         addr_ok:
6595           orig_reg_rtx = reg_rtx;
6596           if (TARGET_REGISTER_P (reg)
6597               || ((reg == PR_REG || SPECIAL_REGISTER_P (reg))
6598                   && mem_rtx != pre_dec))
6599             {
6600               rtx tmp_reg = gen_rtx_REG (GET_MODE (reg_rtx), *tmp_pnt);
6601
6602               emit_move_insn (tmp_reg, reg_rtx);
6603
6604               if (REGNO (tmp_reg) == R0_REG)
6605                 {
6606                   offset_in_r0 = -1;
6607                   sp_in_r0 = 0;
6608                   gcc_assert (!refers_to_regno_p
6609                               (R0_REG, R0_REG+1, mem_rtx, (rtx *) 0));
6610                 }
6611
6612               if (*++tmp_pnt <= 0)
6613                 tmp_pnt = schedule.temps;
6614
6615               reg_rtx = tmp_reg;
6616             }
6617           {
6618             rtx insn;
6619
6620             /* Mark as interesting for dwarf cfi generator */
6621             insn = emit_move_insn (mem_rtx, reg_rtx);
6622             RTX_FRAME_RELATED_P (insn) = 1;
6623             /* If we use an intermediate register for the save, we can't
6624                describe this exactly in cfi as a copy of the to-be-saved
6625                register into the temporary register and then the temporary
6626                register on the stack, because the temporary register can
6627                have a different natural size than the to-be-saved register.
6628                Thus, we gloss over the intermediate copy and pretend we do
6629                a direct save from the to-be-saved register.  */
6630             if (REGNO (reg_rtx) != reg)
6631               {
6632                 rtx set;
6633
6634                 set = gen_rtx_SET (VOIDmode, mem_rtx, orig_reg_rtx);
6635                 add_reg_note (insn, REG_FRAME_RELATED_EXPR, set);
6636               }
6637
6638             if (TARGET_SHCOMPACT && (offset_in_r0 != -1))
6639               {
6640                 rtx reg_rtx = gen_rtx_REG (mode, reg);
6641                 rtx set;
6642                 rtx mem_rtx = gen_frame_mem (mode,
6643                                              gen_rtx_PLUS (Pmode,
6644                                                            stack_pointer_rtx,
6645                                                            GEN_INT (offset)));
6646
6647                 set = gen_rtx_SET (VOIDmode, mem_rtx, reg_rtx);
6648                 add_reg_note (insn, REG_FRAME_RELATED_EXPR, set);
6649               }
6650           }
6651         }
6652
6653       gcc_assert (entry->offset == d_rounding);
6654     }
6655   else
6656     push_regs (&live_regs_mask, current_function_interrupt);
6657
6658   if (flag_pic && df_regs_ever_live_p (PIC_OFFSET_TABLE_REGNUM))
6659     emit_insn (gen_GOTaddr2picreg ());
6660
6661   if (SHMEDIA_REGS_STACK_ADJUST ())
6662     {
6663       /* This must NOT go through the PLT, otherwise mach and macl
6664          may be clobbered.  */
6665       function_symbol (gen_rtx_REG (Pmode, R0_REG),
6666                        (TARGET_FPU_ANY
6667                         ? "__GCC_push_shmedia_regs"
6668                         : "__GCC_push_shmedia_regs_nofpu"), SFUNC_GOT);
6669       emit_insn (gen_shmedia_save_restore_regs_compact
6670                  (GEN_INT (-SHMEDIA_REGS_STACK_ADJUST ())));
6671     }
6672
6673   if (target_flags != save_flags && ! current_function_interrupt)
6674     emit_insn (gen_toggle_sz ());
6675
6676   target_flags = save_flags;
6677
6678   output_stack_adjust (-rounded_frame_size (d) + d_rounding,
6679                        stack_pointer_rtx, 0, NULL);
6680
6681   if (frame_pointer_needed)
6682     frame_insn (GEN_MOV (hard_frame_pointer_rtx, stack_pointer_rtx));
6683
6684   if (TARGET_SHCOMPACT
6685       && (crtl->args.info.call_cookie & ~ CALL_COOKIE_RET_TRAMP(1)))
6686     {
6687       /* This must NOT go through the PLT, otherwise mach and macl
6688          may be clobbered.  */
6689       function_symbol (gen_rtx_REG (Pmode, R0_REG),
6690                       "__GCC_shcompact_incoming_args", SFUNC_GOT);
6691       emit_insn (gen_shcompact_incoming_args ());
6692     }
6693 }
6694
6695 void
6696 sh_expand_epilogue (bool sibcall_p)
6697 {
6698   HARD_REG_SET live_regs_mask;
6699   int d, i;
6700   int d_rounding = 0;
6701
6702   int save_flags = target_flags;
6703   int frame_size, save_size;
6704   int fpscr_deferred = 0;
6705   int e = sibcall_p ? -1 : 1;
6706
6707   d = calc_live_regs (&live_regs_mask);
6708
6709   save_size = d;
6710   frame_size = rounded_frame_size (d);
6711
6712   if (TARGET_SH5)
6713     {
6714       int tregs_space = shmedia_target_regs_stack_adjust (&live_regs_mask);
6715       int total_size;
6716       if (d % (STACK_BOUNDARY / BITS_PER_UNIT))
6717       d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
6718                     - d % (STACK_BOUNDARY / BITS_PER_UNIT));
6719
6720       total_size = d + tregs_space;
6721       total_size += rounded_frame_size (total_size);
6722       save_size = total_size - frame_size;
6723
6724       /* If adjusting the stack in a single step costs nothing extra, do so.
6725          I.e. either if a single addi is enough, or we need a movi anyway,
6726          and we don't exceed the maximum offset range (the test for the
6727          latter is conservative for simplicity).  */
6728       if (TARGET_SHMEDIA
6729           && ! frame_pointer_needed
6730           && (CONST_OK_FOR_I10 (total_size)
6731               || (! CONST_OK_FOR_I10 (save_size + d_rounding)
6732                   && total_size <= 2044)))
6733         d_rounding = frame_size;
6734
6735       frame_size -= d_rounding;
6736     }
6737
6738   if (frame_pointer_needed)
6739     {
6740       /* We must avoid scheduling the epilogue with previous basic blocks
6741          when exception handling is enabled.  See PR/18032.  */
6742       if (flag_exceptions)
6743         emit_insn (gen_blockage ());
6744       output_stack_adjust (frame_size, hard_frame_pointer_rtx, e,
6745                            &live_regs_mask);
6746
6747       /* We must avoid moving the stack pointer adjustment past code
6748          which reads from the local frame, else an interrupt could
6749          occur after the SP adjustment and clobber data in the local
6750          frame.  */
6751       emit_insn (gen_blockage ());
6752       emit_insn (GEN_MOV (stack_pointer_rtx, hard_frame_pointer_rtx));
6753     }
6754   else if (frame_size)
6755     {
6756       /* We must avoid moving the stack pointer adjustment past code
6757          which reads from the local frame, else an interrupt could
6758          occur after the SP adjustment and clobber data in the local
6759          frame.  */
6760       emit_insn (gen_blockage ());
6761       output_stack_adjust (frame_size, stack_pointer_rtx, e, &live_regs_mask);
6762     }
6763
6764   if (SHMEDIA_REGS_STACK_ADJUST ())
6765     {
6766       function_symbol (gen_rtx_REG (Pmode, R0_REG),
6767                        (TARGET_FPU_ANY
6768                         ? "__GCC_pop_shmedia_regs"
6769                         : "__GCC_pop_shmedia_regs_nofpu"), SFUNC_GOT);
6770       /* This must NOT go through the PLT, otherwise mach and macl
6771          may be clobbered.  */
6772       emit_insn (gen_shmedia_save_restore_regs_compact
6773                  (GEN_INT (SHMEDIA_REGS_STACK_ADJUST ())));
6774     }
6775
6776   /* Pop all the registers.  */
6777
6778   if (target_flags != save_flags && ! current_function_interrupt)
6779     emit_insn (gen_toggle_sz ());
6780   if (TARGET_SH5)
6781     {
6782       int offset_base, offset;
6783       int offset_in_r0 = -1;
6784       int sp_in_r0 = 0;
6785       rtx r0 = gen_rtx_REG (Pmode, R0_REG);
6786       save_schedule schedule;
6787       save_entry *entry;
6788       int *tmp_pnt;
6789
6790       entry = sh5_schedule_saves (&live_regs_mask, &schedule, d_rounding);
6791       offset_base = -entry[1].offset + d_rounding;
6792       tmp_pnt = schedule.temps;
6793       for (; entry->mode != VOIDmode; entry--)
6794         {
6795           enum machine_mode mode = (enum machine_mode) entry->mode;
6796           int reg = entry->reg;
6797           rtx reg_rtx, mem_rtx, post_inc = NULL_RTX, insn;
6798
6799           offset = offset_base + entry->offset;
6800           reg_rtx = gen_rtx_REG (mode, reg);
6801
6802           mem_rtx = gen_frame_mem (mode,
6803                                    gen_rtx_PLUS (Pmode,
6804                                                  stack_pointer_rtx,
6805                                                  GEN_INT (offset)));
6806
6807           if (!memory_address_p (mode, XEXP (mem_rtx, 0)))
6808             mem_rtx = NULL_RTX;
6809
6810           if (HAVE_POST_INCREMENT
6811               && (offset == offset_in_r0
6812                   || (offset + GET_MODE_SIZE (mode) != d + d_rounding
6813                       && mem_rtx == NULL_RTX)
6814                   || reg == PR_REG || SPECIAL_REGISTER_P (reg)))
6815             {
6816               post_inc = gen_frame_mem (mode, gen_rtx_POST_INC (Pmode, r0));
6817
6818               if (!memory_address_p (mode, XEXP (post_inc, 0)))
6819                 post_inc = NULL_RTX;
6820               else
6821                 mem_rtx = NULL_RTX;
6822             }
6823
6824           if (mem_rtx != NULL_RTX)
6825             goto addr_ok;
6826
6827           if (offset_in_r0 == -1)
6828             {
6829               emit_move_insn (r0, GEN_INT (offset));
6830               offset_in_r0 = offset;
6831             }
6832           else if (offset != offset_in_r0)
6833             {
6834               emit_move_insn (r0,
6835                               gen_rtx_PLUS
6836                               (Pmode, r0,
6837                                GEN_INT (offset - offset_in_r0)));
6838               offset_in_r0 += offset - offset_in_r0;
6839             }
6840
6841           if (post_inc != NULL_RTX)
6842             {
6843               if (! sp_in_r0)
6844                 {
6845                   emit_move_insn (r0,
6846                                   gen_rtx_PLUS
6847                                   (Pmode, r0, stack_pointer_rtx));
6848                   sp_in_r0 = 1;
6849                 }
6850
6851               mem_rtx = post_inc;
6852
6853               offset_in_r0 += GET_MODE_SIZE (mode);
6854             }
6855           else if (sp_in_r0)
6856             mem_rtx = gen_frame_mem (mode, r0);
6857           else
6858             mem_rtx = gen_frame_mem (mode,
6859                                      gen_rtx_PLUS (Pmode,
6860                                                    stack_pointer_rtx,
6861                                                    r0));
6862
6863           gcc_assert ((reg != PR_REG && !SPECIAL_REGISTER_P (reg))
6864                       || mem_rtx == post_inc);
6865
6866         addr_ok:
6867           if ((reg == PR_REG || SPECIAL_REGISTER_P (reg))
6868               && mem_rtx != post_inc)
6869             {
6870               insn = emit_move_insn (r0, mem_rtx);
6871               mem_rtx = r0;
6872             }
6873           else if (TARGET_REGISTER_P (reg))
6874             {
6875               rtx tmp_reg = gen_rtx_REG (mode, *tmp_pnt);
6876
6877               /* Give the scheduler a bit of freedom by using up to
6878                  MAX_TEMPS registers in a round-robin fashion.  */
6879               insn = emit_move_insn (tmp_reg, mem_rtx);
6880               mem_rtx = tmp_reg;
6881               if (*++tmp_pnt < 0)
6882                 tmp_pnt = schedule.temps;
6883             }
6884
6885           insn = emit_move_insn (reg_rtx, mem_rtx);
6886         }
6887
6888       gcc_assert (entry->offset + offset_base == d + d_rounding);
6889     }
6890   else /* ! TARGET_SH5 */
6891     {
6892       int last_reg;
6893
6894       save_size = 0;
6895         /* For an ISR with RESBANK attribute assigned, don't pop PR
6896            register.  */
6897       if (TEST_HARD_REG_BIT (live_regs_mask, PR_REG)
6898           && !sh_cfun_resbank_handler_p ())     
6899         {
6900           if (!frame_pointer_needed)
6901             emit_insn (gen_blockage ());
6902           pop (PR_REG);
6903         }
6904
6905       /* Banked registers are poped first to avoid being scheduled in the
6906          delay slot. RTE switches banks before the ds instruction.  */
6907       if (current_function_interrupt)
6908         {
6909           for (i = FIRST_BANKED_REG; i <= LAST_BANKED_REG; i++)
6910             if (TEST_HARD_REG_BIT (live_regs_mask, i)) 
6911               pop (LAST_BANKED_REG - i);
6912
6913           last_reg = FIRST_PSEUDO_REGISTER - LAST_BANKED_REG - 1;
6914         }
6915       else
6916         last_reg = FIRST_PSEUDO_REGISTER;
6917
6918       for (i = 0; i < last_reg; i++)
6919         {
6920           int j = (FIRST_PSEUDO_REGISTER - 1) - i;
6921
6922           if (j == FPSCR_REG && current_function_interrupt && TARGET_FMOVD
6923               && hard_reg_set_intersect_p (live_regs_mask,
6924                                           reg_class_contents[DF_REGS]))
6925             fpscr_deferred = 1;
6926           /* For an ISR with RESBANK attribute assigned, don't pop
6927              following registers, R0-R14, MACH, MACL and GBR.  */
6928           else if (j != PR_REG && TEST_HARD_REG_BIT (live_regs_mask, j) 
6929                    && ! (sh_cfun_resbank_handler_p ()
6930                          && ((j >= FIRST_GENERAL_REG
6931                               && j < LAST_GENERAL_REG)
6932                               || j == MACH_REG
6933                               || j == MACL_REG
6934                               || j == GBR_REG)))
6935             pop (j);
6936
6937           if (j == FIRST_FP_REG && fpscr_deferred)
6938             pop (FPSCR_REG);
6939         }
6940     }
6941   if (target_flags != save_flags && ! current_function_interrupt)
6942     emit_insn (gen_toggle_sz ());
6943   target_flags = save_flags;
6944
6945   output_stack_adjust (crtl->args.pretend_args_size
6946                        + save_size + d_rounding
6947                        + crtl->args.info.stack_regs * 8,
6948                        stack_pointer_rtx, e, NULL);
6949
6950   if (crtl->calls_eh_return)
6951     emit_insn (GEN_ADD3 (stack_pointer_rtx, stack_pointer_rtx,
6952                          EH_RETURN_STACKADJ_RTX));
6953
6954   /* Switch back to the normal stack if necessary.  */
6955   if (lookup_attribute ("sp_switch", DECL_ATTRIBUTES (current_function_decl)))
6956     emit_insn (gen_sp_switch_2 ());
6957
6958   /* Tell flow the insn that pops PR isn't dead.  */
6959   /* PR_REG will never be live in SHmedia mode, and we don't need to
6960      USE PR_MEDIA_REG, since it will be explicitly copied to TR0_REG
6961      by the return pattern.  */
6962   if (TEST_HARD_REG_BIT (live_regs_mask, PR_REG))
6963     emit_use (gen_rtx_REG (SImode, PR_REG));
6964 }
6965
6966 static int sh_need_epilogue_known = 0;
6967
6968 int
6969 sh_need_epilogue (void)
6970 {
6971   if (! sh_need_epilogue_known)
6972     {
6973       rtx epilogue;
6974
6975       start_sequence ();
6976       sh_expand_epilogue (0);
6977       epilogue = get_insns ();
6978       end_sequence ();
6979       sh_need_epilogue_known = (epilogue == NULL ? -1 : 1);
6980     }
6981   return sh_need_epilogue_known > 0;
6982 }
6983
6984 /* Emit code to change the current function's return address to RA.
6985    TEMP is available as a scratch register, if needed.  */
6986
6987 void
6988 sh_set_return_address (rtx ra, rtx tmp)
6989 {
6990   HARD_REG_SET live_regs_mask;
6991   int d;
6992   int pr_reg = TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG;
6993   int pr_offset;
6994
6995   d = calc_live_regs (&live_regs_mask);
6996
6997   /* If pr_reg isn't life, we can set it (or the register given in
6998      sh_media_register_for_return) directly.  */
6999   if (! TEST_HARD_REG_BIT (live_regs_mask, pr_reg))
7000     {
7001       rtx rr;
7002
7003       if (TARGET_SHMEDIA)
7004         {
7005           int rr_regno = sh_media_register_for_return ();
7006
7007           if (rr_regno < 0)
7008             rr_regno = pr_reg;
7009
7010           rr = gen_rtx_REG (DImode, rr_regno);
7011         }
7012       else
7013         rr = gen_rtx_REG (SImode, pr_reg);
7014
7015       emit_insn (GEN_MOV (rr, ra));
7016       /* Tell flow the register for return isn't dead.  */
7017       emit_use (rr);
7018       return;
7019     }
7020
7021   if (TARGET_SH5)
7022     {
7023       int offset;
7024       save_schedule schedule;
7025       save_entry *entry;
7026
7027       entry = sh5_schedule_saves (&live_regs_mask, &schedule, 0);
7028       offset = entry[1].offset;
7029       for (; entry->mode != VOIDmode; entry--)
7030         if (entry->reg == pr_reg)
7031           goto found;
7032
7033       /* We can't find pr register.  */
7034       gcc_unreachable ();
7035
7036     found:
7037       offset = entry->offset - offset;
7038       pr_offset = (rounded_frame_size (d) + offset
7039                    + SHMEDIA_REGS_STACK_ADJUST ());
7040     }
7041   else
7042     pr_offset = rounded_frame_size (d);
7043
7044   emit_insn (GEN_MOV (tmp, GEN_INT (pr_offset)));
7045   emit_insn (GEN_ADD3 (tmp, tmp, hard_frame_pointer_rtx));
7046
7047   tmp = gen_frame_mem (Pmode, tmp);
7048   emit_insn (GEN_MOV (tmp, ra));
7049 }
7050
7051 /* Clear variables at function end.  */
7052
7053 static void
7054 sh_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
7055                              HOST_WIDE_INT size ATTRIBUTE_UNUSED)
7056 {
7057   sh_need_epilogue_known = 0;
7058 }
7059
7060 static rtx
7061 sh_builtin_saveregs (void)
7062 {
7063   /* First unnamed integer register.  */
7064   int first_intreg = crtl->args.info.arg_count[(int) SH_ARG_INT];
7065   /* Number of integer registers we need to save.  */
7066   int n_intregs = MAX (0, NPARM_REGS (SImode) - first_intreg);
7067   /* First unnamed SFmode float reg */
7068   int first_floatreg = crtl->args.info.arg_count[(int) SH_ARG_FLOAT];
7069   /* Number of SFmode float regs to save.  */
7070   int n_floatregs = MAX (0, NPARM_REGS (SFmode) - first_floatreg);
7071   rtx regbuf, fpregs;
7072   int bufsize, regno;
7073   alias_set_type alias_set;
7074
7075   if (TARGET_SH5)
7076     {
7077       if (n_intregs)
7078         {
7079           int pushregs = n_intregs;
7080
7081           while (pushregs < NPARM_REGS (SImode) - 1
7082                  && (CALL_COOKIE_INT_REG_GET
7083                         (crtl->args.info.call_cookie,
7084                          NPARM_REGS (SImode) - pushregs)
7085                      == 1))
7086             {
7087               crtl->args.info.call_cookie
7088                 &= ~ CALL_COOKIE_INT_REG (NPARM_REGS (SImode)
7089                                           - pushregs, 1);
7090               pushregs++;
7091             }
7092
7093           if (pushregs == NPARM_REGS (SImode))
7094             crtl->args.info.call_cookie
7095               |= (CALL_COOKIE_INT_REG (0, 1)
7096                   | CALL_COOKIE_STACKSEQ (pushregs - 1));
7097           else
7098             crtl->args.info.call_cookie
7099               |= CALL_COOKIE_STACKSEQ (pushregs);
7100
7101           crtl->args.pretend_args_size += 8 * n_intregs;
7102         }
7103       if (TARGET_SHCOMPACT)
7104         return const0_rtx;
7105     }
7106
7107   if (! TARGET_SH2E && ! TARGET_SH4 && ! TARGET_SH5)
7108     {
7109       error ("__builtin_saveregs not supported by this subtarget");
7110       return const0_rtx;
7111     }
7112
7113   if (TARGET_SHMEDIA)
7114     n_floatregs = 0;
7115
7116   /* Allocate block of memory for the regs.  */
7117   /* ??? If n_intregs + n_floatregs == 0, should we allocate at least 1 byte?
7118      Or can assign_stack_local accept a 0 SIZE argument?  */
7119   bufsize = (n_intregs * UNITS_PER_WORD) + (n_floatregs * UNITS_PER_WORD);
7120
7121   if (TARGET_SHMEDIA)
7122     regbuf = gen_frame_mem (BLKmode, gen_rtx_REG (Pmode, ARG_POINTER_REGNUM));
7123   else if (n_floatregs & 1)
7124     {
7125       rtx addr;
7126
7127       regbuf = assign_stack_local (BLKmode, bufsize + UNITS_PER_WORD, 0);
7128       addr = copy_to_mode_reg (Pmode, XEXP (regbuf, 0));
7129       emit_insn (gen_iorsi3 (addr, addr, GEN_INT (UNITS_PER_WORD)));
7130       regbuf = change_address (regbuf, BLKmode, addr);
7131     }
7132   else if (STACK_BOUNDARY < 64 && TARGET_FPU_DOUBLE && n_floatregs)
7133     {
7134       rtx addr, mask;
7135
7136       regbuf = assign_stack_local (BLKmode, bufsize + UNITS_PER_WORD, 0);
7137       addr = copy_to_mode_reg (Pmode, plus_constant (XEXP (regbuf, 0), 4));
7138       mask = copy_to_mode_reg (Pmode, GEN_INT (-8));
7139       emit_insn (gen_andsi3 (addr, addr, mask));
7140       regbuf = change_address (regbuf, BLKmode, addr);
7141     }
7142   else
7143     regbuf = assign_stack_local (BLKmode, bufsize, TARGET_FPU_DOUBLE ? 64 : 0);
7144   alias_set = get_varargs_alias_set ();
7145   set_mem_alias_set (regbuf, alias_set);
7146
7147   /* Save int args.
7148      This is optimized to only save the regs that are necessary.  Explicitly
7149      named args need not be saved.  */
7150   if (n_intregs > 0)
7151     move_block_from_reg (BASE_ARG_REG (SImode) + first_intreg,
7152                          adjust_address (regbuf, BLKmode,
7153                                          n_floatregs * UNITS_PER_WORD),
7154                          n_intregs);
7155
7156   if (TARGET_SHMEDIA)
7157     /* Return the address of the regbuf.  */
7158     return XEXP (regbuf, 0);
7159
7160   /* Save float args.
7161      This is optimized to only save the regs that are necessary.  Explicitly
7162      named args need not be saved.
7163      We explicitly build a pointer to the buffer because it halves the insn
7164      count when not optimizing (otherwise the pointer is built for each reg
7165      saved).
7166      We emit the moves in reverse order so that we can use predecrement.  */
7167
7168   fpregs = copy_to_mode_reg (Pmode,
7169                              plus_constant (XEXP (regbuf, 0),
7170                                             n_floatregs * UNITS_PER_WORD));
7171   if (TARGET_SH4 || TARGET_SH2A_DOUBLE)
7172     {
7173       rtx mem;
7174       for (regno = NPARM_REGS (DFmode) - 2; regno >= first_floatreg; regno -= 2)
7175         {
7176           emit_insn (gen_addsi3 (fpregs, fpregs,
7177                                  GEN_INT (-2 * UNITS_PER_WORD)));
7178           mem = change_address (regbuf, DFmode, fpregs);
7179           emit_move_insn (mem,
7180                           gen_rtx_REG (DFmode, BASE_ARG_REG (DFmode) + regno));
7181         }
7182       regno = first_floatreg;
7183       if (regno & 1)
7184         {
7185           emit_insn (gen_addsi3 (fpregs, fpregs, GEN_INT (-UNITS_PER_WORD)));
7186           mem = change_address (regbuf, SFmode, fpregs);
7187           emit_move_insn (mem,
7188                           gen_rtx_REG (SFmode, BASE_ARG_REG (SFmode) + regno
7189                                                 - (TARGET_LITTLE_ENDIAN != 0)));
7190         }
7191     }
7192   else
7193     for (regno = NPARM_REGS (SFmode) - 1; regno >= first_floatreg; regno--)
7194       {
7195         rtx mem;
7196
7197         emit_insn (gen_addsi3 (fpregs, fpregs, GEN_INT (-UNITS_PER_WORD)));
7198         mem = change_address (regbuf, SFmode, fpregs);
7199         emit_move_insn (mem,
7200                         gen_rtx_REG (SFmode, BASE_ARG_REG (SFmode) + regno));
7201       }
7202
7203   /* Return the address of the regbuf.  */
7204   return XEXP (regbuf, 0);
7205 }
7206
7207 /* Define the `__builtin_va_list' type for the ABI.  */
7208
7209 static tree
7210 sh_build_builtin_va_list (void)
7211 {
7212   tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
7213   tree record;
7214
7215   if (TARGET_SH5 || (! TARGET_SH2E && ! TARGET_SH4)
7216       || TARGET_HITACHI || sh_cfun_attr_renesas_p ())
7217     return ptr_type_node;
7218
7219   record = (*lang_hooks.types.make_type) (RECORD_TYPE);
7220
7221   f_next_o = build_decl (FIELD_DECL, get_identifier ("__va_next_o"),
7222                          ptr_type_node);
7223   f_next_o_limit = build_decl (FIELD_DECL,
7224                                get_identifier ("__va_next_o_limit"),
7225                                ptr_type_node);
7226   f_next_fp = build_decl (FIELD_DECL, get_identifier ("__va_next_fp"),
7227                           ptr_type_node);
7228   f_next_fp_limit = build_decl (FIELD_DECL,
7229                                 get_identifier ("__va_next_fp_limit"),
7230                                 ptr_type_node);
7231   f_next_stack = build_decl (FIELD_DECL, get_identifier ("__va_next_stack"),
7232                              ptr_type_node);
7233
7234   DECL_FIELD_CONTEXT (f_next_o) = record;
7235   DECL_FIELD_CONTEXT (f_next_o_limit) = record;
7236   DECL_FIELD_CONTEXT (f_next_fp) = record;
7237   DECL_FIELD_CONTEXT (f_next_fp_limit) = record;
7238   DECL_FIELD_CONTEXT (f_next_stack) = record;
7239
7240   TYPE_FIELDS (record) = f_next_o;
7241   TREE_CHAIN (f_next_o) = f_next_o_limit;
7242   TREE_CHAIN (f_next_o_limit) = f_next_fp;
7243   TREE_CHAIN (f_next_fp) = f_next_fp_limit;
7244   TREE_CHAIN (f_next_fp_limit) = f_next_stack;
7245
7246   layout_type (record);
7247
7248   return record;
7249 }
7250
7251 /* Implement `va_start' for varargs and stdarg.  */
7252
7253 static void
7254 sh_va_start (tree valist, rtx nextarg)
7255 {
7256   tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
7257   tree next_o, next_o_limit, next_fp, next_fp_limit, next_stack;
7258   tree t, u;
7259   int nfp, nint;
7260
7261   if (TARGET_SH5)
7262     {
7263       expand_builtin_saveregs ();
7264       std_expand_builtin_va_start (valist, nextarg);
7265       return;
7266     }
7267
7268   if ((! TARGET_SH2E && ! TARGET_SH4)
7269       || TARGET_HITACHI || sh_cfun_attr_renesas_p ())
7270     {
7271       std_expand_builtin_va_start (valist, nextarg);
7272       return;
7273     }
7274
7275   f_next_o = TYPE_FIELDS (va_list_type_node);
7276   f_next_o_limit = TREE_CHAIN (f_next_o);
7277   f_next_fp = TREE_CHAIN (f_next_o_limit);
7278   f_next_fp_limit = TREE_CHAIN (f_next_fp);
7279   f_next_stack = TREE_CHAIN (f_next_fp_limit);
7280
7281   next_o = build3 (COMPONENT_REF, TREE_TYPE (f_next_o), valist, f_next_o,
7282                    NULL_TREE);
7283   next_o_limit = build3 (COMPONENT_REF, TREE_TYPE (f_next_o_limit),
7284                          valist, f_next_o_limit, NULL_TREE);
7285   next_fp = build3 (COMPONENT_REF, TREE_TYPE (f_next_fp), valist, f_next_fp,
7286                     NULL_TREE);
7287   next_fp_limit = build3 (COMPONENT_REF, TREE_TYPE (f_next_fp_limit),
7288                           valist, f_next_fp_limit, NULL_TREE);
7289   next_stack = build3 (COMPONENT_REF, TREE_TYPE (f_next_stack),
7290                        valist, f_next_stack, NULL_TREE);
7291
7292   /* Call __builtin_saveregs.  */
7293   u = make_tree (sizetype, expand_builtin_saveregs ());
7294   u = fold_convert (ptr_type_node, u);
7295   t = build2 (MODIFY_EXPR, ptr_type_node, next_fp, u);
7296   TREE_SIDE_EFFECTS (t) = 1;
7297   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
7298
7299   nfp = crtl->args.info.arg_count[SH_ARG_FLOAT];
7300   if (nfp < 8)
7301     nfp = 8 - nfp;
7302   else
7303     nfp = 0;
7304   u = fold_build2 (POINTER_PLUS_EXPR, ptr_type_node, u,
7305                    size_int (UNITS_PER_WORD * nfp));
7306   t = build2 (MODIFY_EXPR, ptr_type_node, next_fp_limit, u);
7307   TREE_SIDE_EFFECTS (t) = 1;
7308   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
7309
7310   t = build2 (MODIFY_EXPR, ptr_type_node, next_o, u);
7311   TREE_SIDE_EFFECTS (t) = 1;
7312   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
7313
7314   nint = crtl->args.info.arg_count[SH_ARG_INT];
7315   if (nint < 4)
7316     nint = 4 - nint;
7317   else
7318     nint = 0;
7319   u = fold_build2 (POINTER_PLUS_EXPR, ptr_type_node, u,
7320                    size_int (UNITS_PER_WORD * nint));
7321   t = build2 (MODIFY_EXPR, ptr_type_node, next_o_limit, u);
7322   TREE_SIDE_EFFECTS (t) = 1;
7323   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
7324
7325   u = make_tree (ptr_type_node, nextarg);
7326   t = build2 (MODIFY_EXPR, ptr_type_node, next_stack, u);
7327   TREE_SIDE_EFFECTS (t) = 1;
7328   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
7329 }
7330
7331 /* TYPE is a RECORD_TYPE.  If there is only a single nonzero-sized
7332    member, return it.  */
7333 static tree
7334 find_sole_member (tree type)
7335 {
7336   tree field, member = NULL_TREE;
7337
7338   for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
7339     {
7340       if (TREE_CODE (field) != FIELD_DECL)
7341         continue;
7342       if (!DECL_SIZE (field))
7343         return NULL_TREE;
7344       if (integer_zerop (DECL_SIZE (field)))
7345         continue;
7346       if (member)
7347         return NULL_TREE;
7348       member = field;
7349     }
7350   return member;
7351 }
7352 /* Implement `va_arg'.  */
7353
7354 static tree
7355 sh_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
7356                          gimple_seq *post_p ATTRIBUTE_UNUSED)
7357 {
7358   HOST_WIDE_INT size, rsize;
7359   tree tmp, pptr_type_node;
7360   tree addr, lab_over = NULL, result = NULL;
7361   int pass_by_ref = targetm.calls.must_pass_in_stack (TYPE_MODE (type), type);
7362   tree eff_type;
7363
7364   if (pass_by_ref)
7365     type = build_pointer_type (type);
7366
7367   size = int_size_in_bytes (type);
7368   rsize = (size + UNITS_PER_WORD - 1) & -UNITS_PER_WORD;
7369   pptr_type_node = build_pointer_type (ptr_type_node);
7370
7371   if (! TARGET_SH5 && (TARGET_SH2E || TARGET_SH4)
7372       && ! (TARGET_HITACHI || sh_cfun_attr_renesas_p ()))
7373     {
7374       tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
7375       tree next_o, next_o_limit, next_fp, next_fp_limit, next_stack;
7376       int pass_as_float;
7377       tree lab_false;
7378       tree member;
7379
7380       f_next_o = TYPE_FIELDS (va_list_type_node);
7381       f_next_o_limit = TREE_CHAIN (f_next_o);
7382       f_next_fp = TREE_CHAIN (f_next_o_limit);
7383       f_next_fp_limit = TREE_CHAIN (f_next_fp);
7384       f_next_stack = TREE_CHAIN (f_next_fp_limit);
7385
7386       next_o = build3 (COMPONENT_REF, TREE_TYPE (f_next_o), valist, f_next_o,
7387                        NULL_TREE);
7388       next_o_limit = build3 (COMPONENT_REF, TREE_TYPE (f_next_o_limit),
7389                              valist, f_next_o_limit, NULL_TREE);
7390       next_fp = build3 (COMPONENT_REF, TREE_TYPE (f_next_fp),
7391                         valist, f_next_fp, NULL_TREE);
7392       next_fp_limit = build3 (COMPONENT_REF, TREE_TYPE (f_next_fp_limit),
7393                               valist, f_next_fp_limit, NULL_TREE);
7394       next_stack = build3 (COMPONENT_REF, TREE_TYPE (f_next_stack),
7395                            valist, f_next_stack, NULL_TREE);
7396
7397       /* Structures with a single member with a distinct mode are passed
7398          like their member.  This is relevant if the latter has a REAL_TYPE
7399          or COMPLEX_TYPE type.  */
7400       eff_type = type;
7401       while (TREE_CODE (eff_type) == RECORD_TYPE
7402              && (member = find_sole_member (eff_type))
7403              && (TREE_CODE (TREE_TYPE (member)) == REAL_TYPE
7404                  || TREE_CODE (TREE_TYPE (member)) == COMPLEX_TYPE
7405                  || TREE_CODE (TREE_TYPE (member)) == RECORD_TYPE))
7406         {
7407           tree field_type = TREE_TYPE (member);
7408
7409           if (TYPE_MODE (eff_type) == TYPE_MODE (field_type))
7410             eff_type = field_type;
7411           else
7412             {
7413               gcc_assert ((TYPE_ALIGN (eff_type)
7414                            < GET_MODE_ALIGNMENT (TYPE_MODE (field_type)))
7415                           || (TYPE_ALIGN (eff_type)
7416                               > GET_MODE_BITSIZE (TYPE_MODE (field_type))));
7417               break;
7418             }
7419         }
7420
7421       if (TARGET_SH4 || TARGET_SH2A_DOUBLE)
7422         {
7423           pass_as_float = ((TREE_CODE (eff_type) == REAL_TYPE && size <= 8)
7424                            || (TREE_CODE (eff_type) == COMPLEX_TYPE
7425                                && TREE_CODE (TREE_TYPE (eff_type)) == REAL_TYPE
7426                                && size <= 16));
7427         }
7428       else
7429         {
7430           pass_as_float = (TREE_CODE (eff_type) == REAL_TYPE && size == 4);
7431         }
7432
7433       addr = create_tmp_var (pptr_type_node, NULL);
7434       lab_false = create_artificial_label ();
7435       lab_over = create_artificial_label ();
7436
7437       valist = build1 (INDIRECT_REF, ptr_type_node, addr);
7438
7439       if (pass_as_float)
7440         {
7441           tree next_fp_tmp = create_tmp_var (TREE_TYPE (f_next_fp), NULL);
7442           tree cmp;
7443           bool is_double = size == 8 && TREE_CODE (eff_type) == REAL_TYPE;
7444
7445           tmp = build1 (ADDR_EXPR, pptr_type_node, unshare_expr (next_fp));
7446           gimplify_assign (unshare_expr (addr), tmp, pre_p);
7447
7448           gimplify_assign (unshare_expr (next_fp_tmp), valist, pre_p);
7449           tmp = next_fp_limit;
7450           if (size > 4 && !is_double)
7451             tmp = build2 (POINTER_PLUS_EXPR, TREE_TYPE (tmp),
7452                           unshare_expr (tmp), size_int (4 - size));
7453           tmp = build2 (GE_EXPR, boolean_type_node,
7454                         unshare_expr (next_fp_tmp), unshare_expr (tmp));
7455           cmp = build3 (COND_EXPR, void_type_node, tmp,
7456                         build1 (GOTO_EXPR, void_type_node,
7457                                 unshare_expr (lab_false)), NULL_TREE);
7458           if (!is_double)
7459             gimplify_and_add (cmp, pre_p);
7460
7461           if (TYPE_ALIGN (eff_type) > BITS_PER_WORD
7462               || (is_double || size == 16))
7463             {
7464               tmp = fold_convert (sizetype, next_fp_tmp);
7465               tmp = build2 (BIT_AND_EXPR, sizetype, tmp,
7466                             size_int (UNITS_PER_WORD));
7467               tmp = build2 (POINTER_PLUS_EXPR, ptr_type_node,
7468                             unshare_expr (next_fp_tmp), tmp);
7469               gimplify_assign (unshare_expr (next_fp_tmp), tmp, pre_p);
7470             }
7471           if (is_double)
7472             gimplify_and_add (cmp, pre_p);
7473
7474 #ifdef FUNCTION_ARG_SCmode_WART
7475           if (TYPE_MODE (eff_type) == SCmode
7476               && TARGET_SH4 && TARGET_LITTLE_ENDIAN)
7477             {
7478               tree subtype = TREE_TYPE (eff_type);
7479               tree real, imag;
7480
7481               imag
7482                 = std_gimplify_va_arg_expr (next_fp_tmp, subtype, pre_p, NULL);
7483               imag = get_initialized_tmp_var (imag, pre_p, NULL);
7484
7485               real
7486                 = std_gimplify_va_arg_expr (next_fp_tmp, subtype, pre_p, NULL);
7487               real = get_initialized_tmp_var (real, pre_p, NULL);
7488
7489               result = build2 (COMPLEX_EXPR, eff_type, real, imag);
7490               if (type != eff_type)
7491                 result = build1 (VIEW_CONVERT_EXPR, type, result);
7492               result = get_initialized_tmp_var (result, pre_p, NULL);
7493             }
7494 #endif /* FUNCTION_ARG_SCmode_WART */
7495
7496           tmp = build1 (GOTO_EXPR, void_type_node, unshare_expr (lab_over));
7497           gimplify_and_add (tmp, pre_p);
7498
7499           tmp = build1 (LABEL_EXPR, void_type_node, unshare_expr (lab_false));
7500           gimplify_and_add (tmp, pre_p);
7501
7502           tmp = build1 (ADDR_EXPR, pptr_type_node, unshare_expr (next_stack));
7503           gimplify_assign (unshare_expr (addr), tmp, pre_p);
7504           gimplify_assign (unshare_expr (next_fp_tmp),
7505                            unshare_expr (valist), pre_p);
7506
7507           gimplify_assign (unshare_expr (valist),
7508                            unshare_expr (next_fp_tmp), post_p);
7509           valist = next_fp_tmp;
7510         }
7511       else
7512         {
7513           tmp = build2 (POINTER_PLUS_EXPR, ptr_type_node,
7514                         unshare_expr (next_o), size_int (rsize));
7515           tmp = build2 (GT_EXPR, boolean_type_node, tmp,
7516                         unshare_expr (next_o_limit));
7517           tmp = build3 (COND_EXPR, void_type_node, tmp,
7518                         build1 (GOTO_EXPR, void_type_node,
7519                                 unshare_expr (lab_false)),
7520                         NULL_TREE);
7521           gimplify_and_add (tmp, pre_p);
7522
7523           tmp = build1 (ADDR_EXPR, pptr_type_node, unshare_expr (next_o));
7524           gimplify_assign (unshare_expr (addr), tmp, pre_p);
7525
7526           tmp = build1 (GOTO_EXPR, void_type_node, unshare_expr (lab_over));
7527           gimplify_and_add (tmp, pre_p);
7528
7529           tmp = build1 (LABEL_EXPR, void_type_node, unshare_expr (lab_false));
7530           gimplify_and_add (tmp, pre_p);
7531
7532           if (size > 4 && ! (TARGET_SH4 || TARGET_SH2A))
7533             gimplify_assign (unshare_expr (next_o),
7534                              unshare_expr (next_o_limit), pre_p);
7535
7536           tmp = build1 (ADDR_EXPR, pptr_type_node, unshare_expr (next_stack));
7537           gimplify_assign (unshare_expr (addr), tmp, pre_p);
7538         }
7539
7540       if (!result)
7541         {
7542           tmp = build1 (LABEL_EXPR, void_type_node, unshare_expr (lab_over));
7543           gimplify_and_add (tmp, pre_p);
7544         }
7545     }
7546
7547   /* ??? In va-sh.h, there had been code to make values larger than
7548      size 8 indirect.  This does not match the FUNCTION_ARG macros.  */
7549
7550   tmp = std_gimplify_va_arg_expr (valist, type, pre_p, NULL);
7551   if (result)
7552     {
7553       gimplify_assign (result, tmp, pre_p);
7554
7555       tmp = build1 (LABEL_EXPR, void_type_node, unshare_expr (lab_over));
7556       gimplify_and_add (tmp, pre_p);
7557     }
7558   else
7559     result = tmp;
7560
7561   if (pass_by_ref)
7562     result = build_va_arg_indirect_ref (result);
7563
7564   return result;
7565 }
7566
7567 /* 64 bit floating points memory transfers are paired single precision loads
7568    or store. So DWARF information needs fixing in little endian (unless
7569    PR=SZ=1 in FPSCR).  */
7570 rtx
7571 sh_dwarf_register_span (rtx reg)
7572 {
7573   unsigned regno = REGNO (reg);
7574
7575   if (WORDS_BIG_ENDIAN || GET_MODE (reg) != DFmode)
7576     return NULL_RTX;
7577
7578   return
7579     gen_rtx_PARALLEL (VOIDmode,
7580                       gen_rtvec (2,
7581                                  gen_rtx_REG (SFmode,
7582                                               DBX_REGISTER_NUMBER (regno+1)),
7583                                  gen_rtx_REG (SFmode,
7584                                               DBX_REGISTER_NUMBER (regno))));
7585 }
7586
7587 bool
7588 sh_promote_prototypes (const_tree type)
7589 {
7590   if (TARGET_HITACHI)
7591     return 0;
7592   if (! type)
7593     return 1;
7594   return ! sh_attr_renesas_p (type);
7595 }
7596
7597 /* Whether an argument must be passed by reference.  On SHcompact, we
7598    pretend arguments wider than 32-bits that would have been passed in
7599    registers are passed by reference, so that an SHmedia trampoline
7600    loads them into the full 64-bits registers.  */
7601
7602 static int
7603 shcompact_byref (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
7604                  const_tree type, bool named)
7605 {
7606   unsigned HOST_WIDE_INT size;
7607
7608   if (type)
7609     size = int_size_in_bytes (type);
7610   else
7611     size = GET_MODE_SIZE (mode);
7612
7613   if (cum->arg_count[SH_ARG_INT] < NPARM_REGS (SImode)
7614       && (!named
7615           || GET_SH_ARG_CLASS (mode) == SH_ARG_INT
7616           || (GET_SH_ARG_CLASS (mode) == SH_ARG_FLOAT
7617               && cum->arg_count[SH_ARG_FLOAT] >= NPARM_REGS (SFmode)))
7618       && size > 4
7619       && !SHCOMPACT_FORCE_ON_STACK (mode, type)
7620       && !SH5_WOULD_BE_PARTIAL_NREGS (*cum, mode, type, named))
7621     return size;
7622   else
7623     return 0;
7624 }
7625
7626 static bool
7627 sh_pass_by_reference (CUMULATIVE_ARGS *cum, enum machine_mode mode,
7628                       const_tree type, bool named)
7629 {
7630   if (targetm.calls.must_pass_in_stack (mode, type))
7631     return true;
7632
7633   /* ??? std_gimplify_va_arg_expr passes NULL for cum.  That function
7634      wants to know about pass-by-reference semantics for incoming
7635      arguments.  */
7636   if (! cum)
7637     return false;
7638
7639   if (TARGET_SHCOMPACT)
7640     {
7641       cum->byref = shcompact_byref (cum, mode, type, named);
7642       return cum->byref != 0;
7643     }
7644
7645   return false;
7646 }
7647
7648 static bool
7649 sh_callee_copies (CUMULATIVE_ARGS *cum, enum machine_mode mode,
7650                   const_tree type, bool named ATTRIBUTE_UNUSED)
7651 {
7652   /* ??? How can it possibly be correct to return true only on the
7653      caller side of the equation?  Is there someplace else in the
7654      sh backend that's magically producing the copies?  */
7655   return (cum->outgoing
7656           && ((mode == BLKmode ? TYPE_ALIGN (type) : GET_MODE_ALIGNMENT (mode))
7657               % SH_MIN_ALIGN_FOR_CALLEE_COPY == 0));
7658 }
7659
7660 static int
7661 sh_arg_partial_bytes (CUMULATIVE_ARGS *cum, enum machine_mode mode,
7662                       tree type, bool named ATTRIBUTE_UNUSED)
7663 {
7664   int words = 0;
7665
7666   if (!TARGET_SH5
7667       && PASS_IN_REG_P (*cum, mode, type)
7668       && !(TARGET_SH4 || TARGET_SH2A_DOUBLE)
7669       && (ROUND_REG (*cum, mode)
7670           + (mode != BLKmode
7671              ? ROUND_ADVANCE (GET_MODE_SIZE (mode))
7672              : ROUND_ADVANCE (int_size_in_bytes (type)))
7673           > NPARM_REGS (mode)))
7674     words = NPARM_REGS (mode) - ROUND_REG (*cum, mode);
7675
7676   else if (!TARGET_SHCOMPACT
7677            && SH5_WOULD_BE_PARTIAL_NREGS (*cum, mode, type, named))
7678     words = NPARM_REGS (SImode) - cum->arg_count[SH_ARG_INT];
7679
7680   return words * UNITS_PER_WORD;
7681 }
7682
7683
7684 /* Define where to put the arguments to a function.
7685    Value is zero to push the argument on the stack,
7686    or a hard register in which to store the argument.
7687
7688    MODE is the argument's machine mode.
7689    TYPE is the data type of the argument (as a tree).
7690     This is null for libcalls where that information may
7691     not be available.
7692    CUM is a variable of type CUMULATIVE_ARGS which gives info about
7693     the preceding args and about the function being called.
7694    NAMED is nonzero if this argument is a named parameter
7695     (otherwise it is an extra parameter matching an ellipsis).
7696
7697    On SH the first args are normally in registers
7698    and the rest are pushed.  Any arg that starts within the first
7699    NPARM_REGS words is at least partially passed in a register unless
7700    its data type forbids.  */
7701
7702
7703 rtx
7704 sh_function_arg (CUMULATIVE_ARGS *ca, enum machine_mode mode,
7705                  tree type, int named)
7706 {
7707   if (! TARGET_SH5 && mode == VOIDmode)
7708     return GEN_INT (ca->renesas_abi ? 1 : 0);
7709
7710   if (! TARGET_SH5
7711       && PASS_IN_REG_P (*ca, mode, type)
7712       && (named || ! (TARGET_HITACHI || ca->renesas_abi)))
7713     {
7714       int regno;
7715
7716       if (mode == SCmode && TARGET_SH4 && TARGET_LITTLE_ENDIAN
7717           && (! FUNCTION_ARG_SCmode_WART || (ROUND_REG (*ca, mode) & 1)))
7718         {
7719           rtx r1 = gen_rtx_EXPR_LIST (VOIDmode,
7720                                       gen_rtx_REG (SFmode,
7721                                                    BASE_ARG_REG (mode)
7722                                                    + (ROUND_REG (*ca, mode) ^ 1)),
7723                                       const0_rtx);
7724           rtx r2 = gen_rtx_EXPR_LIST (VOIDmode,
7725                                       gen_rtx_REG (SFmode,
7726                                                    BASE_ARG_REG (mode)
7727                                                    + ((ROUND_REG (*ca, mode) + 1) ^ 1)),
7728                                       GEN_INT (4));
7729           return gen_rtx_PARALLEL(SCmode, gen_rtvec(2, r1, r2));
7730         }
7731
7732      /* If the alignment of a DF value causes an SF register to be
7733         skipped, we will use that skipped register for the next SF
7734         value.  */
7735       if ((TARGET_HITACHI || ca->renesas_abi)
7736           && ca->free_single_fp_reg
7737           && mode == SFmode)
7738         return gen_rtx_REG (mode, ca->free_single_fp_reg);
7739
7740       regno = (BASE_ARG_REG (mode) + ROUND_REG (*ca, mode))
7741                ^ (mode == SFmode && TARGET_SH4
7742                   && TARGET_LITTLE_ENDIAN != 0
7743                   && ! TARGET_HITACHI && ! ca->renesas_abi);
7744       return gen_rtx_REG (mode, regno);
7745
7746     }
7747
7748   if (TARGET_SH5)
7749     {
7750       if (mode == VOIDmode && TARGET_SHCOMPACT)
7751         return GEN_INT (ca->call_cookie);
7752
7753       /* The following test assumes unnamed arguments are promoted to
7754          DFmode.  */
7755       if (mode == SFmode && ca->free_single_fp_reg)
7756         return SH5_PROTOTYPED_FLOAT_ARG (*ca, mode, ca->free_single_fp_reg);
7757
7758       if ((GET_SH_ARG_CLASS (mode) == SH_ARG_FLOAT)
7759           && (named || ! ca->prototype_p)
7760           && ca->arg_count[(int) SH_ARG_FLOAT] < NPARM_REGS (SFmode))
7761         {
7762           if (! ca->prototype_p && TARGET_SHMEDIA)
7763             return SH5_PROTOTYPELESS_FLOAT_ARG (*ca, mode);
7764
7765           return SH5_PROTOTYPED_FLOAT_ARG (*ca, mode,
7766                                            FIRST_FP_PARM_REG
7767                                            + ca->arg_count[(int) SH_ARG_FLOAT]);
7768         }
7769
7770       if (ca->arg_count[(int) SH_ARG_INT] < NPARM_REGS (SImode)
7771           && (! TARGET_SHCOMPACT
7772               || (! SHCOMPACT_FORCE_ON_STACK (mode, type)
7773                   && ! SH5_WOULD_BE_PARTIAL_NREGS (*ca, mode,
7774                                                    type, named))))
7775         {
7776           return gen_rtx_REG (mode, (FIRST_PARM_REG
7777                                        + ca->arg_count[(int) SH_ARG_INT]));
7778         }
7779
7780       return 0;
7781     }
7782
7783   return 0;
7784 }
7785
7786 /* Update the data in CUM to advance over an argument
7787    of mode MODE and data type TYPE.
7788    (TYPE is null for libcalls where that information may not be
7789    available.)  */
7790
7791 void
7792 sh_function_arg_advance (CUMULATIVE_ARGS *ca, enum machine_mode mode,
7793                          tree type, int named)
7794 {
7795   if (ca->force_mem)
7796     ca->force_mem = 0;
7797   else if (TARGET_SH5)
7798     {
7799       tree type2 = (ca->byref && type
7800                     ? TREE_TYPE (type)
7801                     : type);
7802       enum machine_mode mode2 = (ca->byref && type
7803                                  ? TYPE_MODE (type2)
7804                                  : mode);
7805       int dwords = ((ca->byref
7806                      ? ca->byref
7807                      : mode2 == BLKmode
7808                      ? int_size_in_bytes (type2)
7809                      : GET_MODE_SIZE (mode2)) + 7) / 8;
7810       int numregs = MIN (dwords, NPARM_REGS (SImode)
7811                          - ca->arg_count[(int) SH_ARG_INT]);
7812
7813       if (numregs)
7814         {
7815           ca->arg_count[(int) SH_ARG_INT] += numregs;
7816           if (TARGET_SHCOMPACT
7817               && SHCOMPACT_FORCE_ON_STACK (mode2, type2))
7818             {
7819               ca->call_cookie
7820                 |= CALL_COOKIE_INT_REG (ca->arg_count[(int) SH_ARG_INT]
7821                                         - numregs, 1);
7822               /* N.B. We want this also for outgoing.  */
7823               ca->stack_regs += numregs;
7824             }
7825           else if (ca->byref)
7826             {
7827               if (! ca->outgoing)
7828                 ca->stack_regs += numregs;
7829               ca->byref_regs += numregs;
7830               ca->byref = 0;
7831               do
7832                 ca->call_cookie
7833                   |= CALL_COOKIE_INT_REG (ca->arg_count[(int) SH_ARG_INT]
7834                                           - numregs, 2);
7835               while (--numregs);
7836               ca->call_cookie
7837                 |= CALL_COOKIE_INT_REG (ca->arg_count[(int) SH_ARG_INT]
7838                                         - 1, 1);
7839             }
7840           else if (dwords > numregs)
7841             {
7842               int pushregs = numregs;
7843
7844               if (TARGET_SHCOMPACT)
7845                 ca->stack_regs += numregs;
7846               while (pushregs < NPARM_REGS (SImode) - 1
7847                      && (CALL_COOKIE_INT_REG_GET
7848                          (ca->call_cookie,
7849                           NPARM_REGS (SImode) - pushregs)
7850                          == 1))
7851                 {
7852                   ca->call_cookie
7853                     &= ~ CALL_COOKIE_INT_REG (NPARM_REGS (SImode)
7854                                               - pushregs, 1);
7855                   pushregs++;
7856                 }
7857               if (numregs == NPARM_REGS (SImode))
7858                 ca->call_cookie
7859                   |= CALL_COOKIE_INT_REG (0, 1)
7860                   | CALL_COOKIE_STACKSEQ (numregs - 1);
7861               else
7862                 ca->call_cookie
7863                   |= CALL_COOKIE_STACKSEQ (numregs);
7864             }
7865         }
7866       if (GET_SH_ARG_CLASS (mode2) == SH_ARG_FLOAT
7867           && (named || ! ca->prototype_p))
7868         {
7869           if (mode2 == SFmode && ca->free_single_fp_reg)
7870             ca->free_single_fp_reg = 0;
7871           else if (ca->arg_count[(int) SH_ARG_FLOAT]
7872                    < NPARM_REGS (SFmode))
7873             {
7874               int numfpregs
7875                 = MIN ((GET_MODE_SIZE (mode2) + 7) / 8 * 2,
7876                        NPARM_REGS (SFmode)
7877                        - ca->arg_count[(int) SH_ARG_FLOAT]);
7878
7879               ca->arg_count[(int) SH_ARG_FLOAT] += numfpregs;
7880
7881               if (TARGET_SHCOMPACT && ! ca->prototype_p)
7882                 {
7883                   if (ca->outgoing && numregs > 0)
7884                     do
7885                       {
7886                         ca->call_cookie
7887                           |= (CALL_COOKIE_INT_REG
7888                               (ca->arg_count[(int) SH_ARG_INT]
7889                                - numregs + ((numfpregs - 2) / 2),
7890                                4 + (ca->arg_count[(int) SH_ARG_FLOAT]
7891                                     - numfpregs) / 2));
7892                       }
7893                     while (numfpregs -= 2);
7894                 }
7895               else if (mode2 == SFmode && (named)
7896                        && (ca->arg_count[(int) SH_ARG_FLOAT]
7897                            < NPARM_REGS (SFmode)))
7898                 ca->free_single_fp_reg
7899                   = FIRST_FP_PARM_REG - numfpregs
7900                   + ca->arg_count[(int) SH_ARG_FLOAT] + 1;
7901             }
7902         }
7903       return;
7904     }
7905
7906   if ((TARGET_HITACHI || ca->renesas_abi) && TARGET_FPU_DOUBLE)
7907     {
7908       /* Note that we've used the skipped register.  */
7909       if (mode == SFmode && ca->free_single_fp_reg)
7910         {
7911           ca->free_single_fp_reg = 0;
7912           return;
7913         }
7914       /* When we have a DF after an SF, there's an SF register that get
7915          skipped in order to align the DF value.  We note this skipped
7916          register, because the next SF value will use it, and not the
7917          SF that follows the DF.  */
7918       if (mode == DFmode
7919           && ROUND_REG (*ca, DFmode) != ROUND_REG (*ca, SFmode))
7920         {
7921           ca->free_single_fp_reg = (ROUND_REG (*ca, SFmode)
7922                                     + BASE_ARG_REG (mode));
7923         }
7924     }
7925
7926   if (! ((TARGET_SH4 || TARGET_SH2A) || ca->renesas_abi)
7927       || PASS_IN_REG_P (*ca, mode, type))
7928     (ca->arg_count[(int) GET_SH_ARG_CLASS (mode)]
7929      = (ROUND_REG (*ca, mode)
7930         + (mode == BLKmode
7931            ? ROUND_ADVANCE (int_size_in_bytes (type))
7932            : ROUND_ADVANCE (GET_MODE_SIZE (mode)))));
7933 }
7934
7935 /* The Renesas calling convention doesn't quite fit into this scheme since
7936    the address is passed like an invisible argument, but one that is always
7937    passed in memory.  */
7938 static rtx
7939 sh_struct_value_rtx (tree fndecl, int incoming ATTRIBUTE_UNUSED)
7940 {
7941   if (TARGET_HITACHI || sh_attr_renesas_p (fndecl))
7942     return 0;
7943   return gen_rtx_REG (Pmode, 2);
7944 }
7945
7946 /* Worker function for TARGET_RETURN_IN_MEMORY.  */
7947
7948 static bool
7949 sh_return_in_memory (const_tree type, const_tree fndecl)
7950 {
7951   if (TARGET_SH5)
7952     {
7953       if (TYPE_MODE (type) == BLKmode)
7954         return ((unsigned HOST_WIDE_INT) int_size_in_bytes (type)) > 8;
7955       else
7956         return GET_MODE_SIZE (TYPE_MODE (type)) > 8;
7957     }
7958   else
7959     {
7960       return (TYPE_MODE (type) == BLKmode
7961               || ((TARGET_HITACHI || sh_attr_renesas_p (fndecl))
7962                   && TREE_CODE (type) == RECORD_TYPE));
7963     }
7964 }
7965
7966 /* We actually emit the code in sh_expand_prologue.  We used to use
7967    a static variable to flag that we need to emit this code, but that
7968    doesn't when inlining, when functions are deferred and then emitted
7969    later.  Fortunately, we already have two flags that are part of struct
7970    function that tell if a function uses varargs or stdarg.  */
7971 static void
7972 sh_setup_incoming_varargs (CUMULATIVE_ARGS *ca,
7973                            enum machine_mode mode,
7974                            tree type,
7975                            int *pretend_arg_size,
7976                            int second_time ATTRIBUTE_UNUSED)
7977 {
7978   gcc_assert (cfun->stdarg);
7979   if (TARGET_VARARGS_PRETEND_ARGS (current_function_decl))
7980     {
7981       int named_parm_regs, anon_parm_regs;
7982
7983       named_parm_regs = (ROUND_REG (*ca, mode)
7984                          + (mode == BLKmode
7985                             ? ROUND_ADVANCE (int_size_in_bytes (type))
7986                             : ROUND_ADVANCE (GET_MODE_SIZE (mode))));
7987       anon_parm_regs = NPARM_REGS (SImode) - named_parm_regs;
7988       if (anon_parm_regs > 0)
7989         *pretend_arg_size = anon_parm_regs * 4;
7990     }
7991 }
7992
7993 static bool
7994 sh_strict_argument_naming (CUMULATIVE_ARGS *ca ATTRIBUTE_UNUSED)
7995 {
7996   return TARGET_SH5;
7997 }
7998
7999 static bool
8000 sh_pretend_outgoing_varargs_named (CUMULATIVE_ARGS *ca)
8001 {
8002   return ! (TARGET_HITACHI || ca->renesas_abi) && ! TARGET_SH5;
8003 }
8004
8005
8006 /* Define the offset between two registers, one to be eliminated, and
8007    the other its replacement, at the start of a routine.  */
8008
8009 int
8010 initial_elimination_offset (int from, int to)
8011 {
8012   int regs_saved;
8013   int regs_saved_rounding = 0;
8014   int total_saved_regs_space;
8015   int total_auto_space;
8016   int save_flags = target_flags;
8017   int copy_flags;
8018   HARD_REG_SET live_regs_mask;
8019
8020   shmedia_space_reserved_for_target_registers = false;
8021   regs_saved = calc_live_regs (&live_regs_mask);
8022   regs_saved += SHMEDIA_REGS_STACK_ADJUST ();
8023
8024   if (shmedia_reserve_space_for_target_registers_p (regs_saved, &live_regs_mask))
8025     {
8026       shmedia_space_reserved_for_target_registers = true;
8027       regs_saved += shmedia_target_regs_stack_adjust (&live_regs_mask);
8028     }
8029
8030   if (TARGET_SH5 && regs_saved % (STACK_BOUNDARY / BITS_PER_UNIT))
8031     regs_saved_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
8032                            - regs_saved % (STACK_BOUNDARY / BITS_PER_UNIT));
8033
8034   total_auto_space = rounded_frame_size (regs_saved) - regs_saved_rounding;
8035   copy_flags = target_flags;
8036   target_flags = save_flags;
8037
8038   total_saved_regs_space = regs_saved + regs_saved_rounding;
8039
8040   if (from == ARG_POINTER_REGNUM && to == HARD_FRAME_POINTER_REGNUM)
8041     return total_saved_regs_space + total_auto_space
8042       + crtl->args.info.byref_regs * 8;
8043
8044   if (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
8045     return total_saved_regs_space + total_auto_space
8046       + crtl->args.info.byref_regs * 8;
8047
8048   /* Initial gap between fp and sp is 0.  */
8049   if (from == HARD_FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
8050     return 0;
8051
8052   if (from == FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
8053     return rounded_frame_size (0);
8054
8055   if (from == FRAME_POINTER_REGNUM && to == HARD_FRAME_POINTER_REGNUM)
8056     return rounded_frame_size (0);
8057
8058   gcc_assert (from == RETURN_ADDRESS_POINTER_REGNUM
8059               && (to == HARD_FRAME_POINTER_REGNUM
8060                   || to == STACK_POINTER_REGNUM));
8061   if (TARGET_SH5)
8062     {
8063       int n = total_saved_regs_space;
8064       int pr_reg = TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG;
8065       save_schedule schedule;
8066       save_entry *entry;
8067       
8068       n += total_auto_space;
8069       
8070       /* If it wasn't saved, there's not much we can do.  */
8071       if (! TEST_HARD_REG_BIT (live_regs_mask, pr_reg))
8072         return n;
8073       
8074       target_flags = copy_flags;
8075       
8076       sh5_schedule_saves (&live_regs_mask, &schedule, n);
8077       for (entry = &schedule.entries[1]; entry->mode != VOIDmode; entry++)
8078         if (entry->reg == pr_reg)
8079           {
8080             target_flags = save_flags;
8081             return entry->offset;
8082           }
8083       gcc_unreachable ();
8084     }
8085   else
8086     return total_auto_space;
8087 }
8088
8089 /* Parse the -mfixed-range= option string.  */
8090 void
8091 sh_fix_range (const char *const_str)
8092 {
8093   int i, first, last;
8094   char *str, *dash, *comma;
8095   
8096   /* str must be of the form REG1'-'REG2{,REG1'-'REG} where REG1 and
8097      REG2 are either register names or register numbers.  The effect
8098      of this option is to mark the registers in the range from REG1 to
8099      REG2 as ``fixed'' so they won't be used by the compiler.  */
8100   
8101   i = strlen (const_str);
8102   str = (char *) alloca (i + 1);
8103   memcpy (str, const_str, i + 1);
8104   
8105   while (1)
8106     {
8107       dash = strchr (str, '-');
8108       if (!dash)
8109         {
8110           warning (0, "value of -mfixed-range must have form REG1-REG2");
8111           return;
8112         }
8113       *dash = '\0';
8114       comma = strchr (dash + 1, ',');
8115       if (comma)
8116         *comma = '\0';
8117       
8118       first = decode_reg_name (str);
8119       if (first < 0)
8120         {
8121           warning (0, "unknown register name: %s", str);
8122           return;
8123         }
8124       
8125       last = decode_reg_name (dash + 1);
8126       if (last < 0)
8127         {
8128           warning (0, "unknown register name: %s", dash + 1);
8129           return;
8130         }
8131       
8132       *dash = '-';
8133       
8134       if (first > last)
8135         {
8136           warning (0, "%s-%s is an empty range", str, dash + 1);
8137           return;
8138         }
8139       
8140       for (i = first; i <= last; ++i)
8141         fixed_regs[i] = call_used_regs[i] = 1;
8142
8143       if (!comma)
8144         break;
8145
8146       *comma = ',';
8147       str = comma + 1;
8148     }
8149 }
8150 \f
8151 /* Insert any deferred function attributes from earlier pragmas.  */
8152 static void
8153 sh_insert_attributes (tree node, tree *attributes)
8154 {
8155   tree attrs;
8156
8157   if (TREE_CODE (node) != FUNCTION_DECL)
8158     return;
8159
8160   /* We are only interested in fields.  */
8161   if (!DECL_P (node))
8162     return;
8163
8164   /* Append the attributes to the deferred attributes.  */
8165   *sh_deferred_function_attributes_tail = *attributes;
8166   attrs = sh_deferred_function_attributes;
8167   if (!attrs)
8168     return;
8169
8170   /* Some attributes imply or require the interrupt attribute.  */
8171   if (!lookup_attribute ("interrupt_handler", attrs)
8172       && !lookup_attribute ("interrupt_handler", DECL_ATTRIBUTES (node)))
8173     {
8174       /* If we have a trapa_handler, but no interrupt_handler attribute,
8175          insert an interrupt_handler attribute.  */
8176       if (lookup_attribute ("trapa_handler", attrs) != NULL_TREE)
8177         /* We can't use sh_pr_interrupt here because that's not in the
8178            java frontend.  */
8179         attrs
8180           = tree_cons (get_identifier("interrupt_handler"), NULL_TREE, attrs);
8181       /* However, for sp_switch, trap_exit, nosave_low_regs and resbank,
8182          if the interrupt attribute is missing, we ignore the attribute
8183          and warn.  */
8184       else if (lookup_attribute ("sp_switch", attrs)
8185                || lookup_attribute ("trap_exit", attrs)
8186                || lookup_attribute ("nosave_low_regs", attrs)
8187                || lookup_attribute ("resbank", attrs))
8188         {
8189           tree *tail;
8190
8191           for (tail = attributes; attrs; attrs = TREE_CHAIN (attrs))
8192             {
8193               if (is_attribute_p ("sp_switch", TREE_PURPOSE (attrs))
8194                   || is_attribute_p ("trap_exit", TREE_PURPOSE (attrs))
8195                   || is_attribute_p ("nosave_low_regs", TREE_PURPOSE (attrs))
8196                   || is_attribute_p ("resbank", TREE_PURPOSE (attrs)))
8197                 warning (OPT_Wattributes,
8198                          "%qE attribute only applies to interrupt functions",
8199                          TREE_PURPOSE (attrs));
8200               else
8201                 {
8202                   *tail = tree_cons (TREE_PURPOSE (attrs), NULL_TREE,
8203                                      NULL_TREE);
8204                   tail = &TREE_CHAIN (*tail);
8205                 }
8206             }
8207           attrs = *attributes;
8208         }
8209     }
8210
8211   /* Install the processed list.  */
8212   *attributes = attrs;
8213
8214   /* Clear deferred attributes.  */
8215   sh_deferred_function_attributes = NULL_TREE;
8216   sh_deferred_function_attributes_tail = &sh_deferred_function_attributes;
8217
8218   return;
8219 }
8220
8221 /* Supported attributes:
8222
8223    interrupt_handler -- specifies this function is an interrupt handler.
8224
8225    trapa_handler - like above, but don't save all registers.
8226
8227    sp_switch -- specifies an alternate stack for an interrupt handler
8228    to run on.
8229
8230    trap_exit -- use a trapa to exit an interrupt function instead of
8231    an rte instruction.
8232
8233    nosave_low_regs - don't save r0..r7 in an interrupt handler.
8234      This is useful on the SH3 and upwards,
8235      which has a separate set of low regs for User and Supervisor modes.
8236      This should only be used for the lowest level of interrupts.  Higher levels
8237      of interrupts must save the registers in case they themselves are
8238      interrupted.
8239
8240    renesas -- use Renesas calling/layout conventions (functions and
8241    structures).
8242
8243    resbank -- In case of an ISR, use a register bank to save registers
8244    R0-R14, MACH, MACL, GBR and PR.  This is useful only on SH2A targets.
8245 */
8246
8247 const struct attribute_spec sh_attribute_table[] =
8248 {
8249   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
8250   { "interrupt_handler", 0, 0, true,  false, false, sh_handle_interrupt_handler_attribute },
8251   { "sp_switch",         1, 1, true,  false, false, sh_handle_sp_switch_attribute },
8252   { "trap_exit",         1, 1, true,  false, false, sh_handle_trap_exit_attribute },
8253   { "renesas",           0, 0, false, true, false, sh_handle_renesas_attribute },
8254   { "trapa_handler",     0, 0, true,  false, false, sh_handle_interrupt_handler_attribute },
8255   { "nosave_low_regs",   0, 0, true,  false, false, sh_handle_interrupt_handler_attribute },
8256   { "resbank",           0, 0, true,  false, false, sh_handle_resbank_handler_attribute },
8257   { "function_vector",   1, 1, true,  false, false, sh2a_handle_function_vector_handler_attribute },
8258 #ifdef SYMBIAN
8259   /* Symbian support adds three new attributes:
8260      dllexport - for exporting a function/variable that will live in a dll
8261      dllimport - for importing a function/variable from a dll
8262
8263      Microsoft allows multiple declspecs in one __declspec, separating
8264      them with spaces.  We do NOT support this.  Instead, use __declspec
8265      multiple times.  */
8266   { "dllimport",         0, 0, true,  false, false, sh_symbian_handle_dll_attribute },
8267   { "dllexport",         0, 0, true,  false, false, sh_symbian_handle_dll_attribute },
8268 #endif
8269   { NULL,                0, 0, false, false, false, NULL }
8270 };
8271
8272 /* Handle a 'resbank' attribute.  */
8273 static tree
8274 sh_handle_resbank_handler_attribute (tree * node, tree name,
8275                                      tree args ATTRIBUTE_UNUSED,
8276                                      int flags ATTRIBUTE_UNUSED,
8277                                      bool * no_add_attrs)
8278 {
8279   if (!TARGET_SH2A)
8280     {
8281       warning (OPT_Wattributes, "%qE attribute is supported only for SH2A",
8282                name);
8283       *no_add_attrs = true;
8284     }
8285   if (TREE_CODE (*node) != FUNCTION_DECL)
8286     {
8287       warning (OPT_Wattributes, "%qE attribute only applies to functions",
8288                name);
8289       *no_add_attrs = true;
8290     }
8291
8292   return NULL_TREE;
8293 }
8294
8295 /* Handle an "interrupt_handler" attribute; arguments as in
8296    struct attribute_spec.handler.  */
8297 static tree
8298 sh_handle_interrupt_handler_attribute (tree *node, tree name,
8299                                        tree args ATTRIBUTE_UNUSED,
8300                                        int flags ATTRIBUTE_UNUSED,
8301                                        bool *no_add_attrs)
8302 {
8303   if (TREE_CODE (*node) != FUNCTION_DECL)
8304     {
8305       warning (OPT_Wattributes, "%qE attribute only applies to functions",
8306                name);
8307       *no_add_attrs = true;
8308     }
8309   else if (TARGET_SHCOMPACT)
8310     {
8311       error ("attribute interrupt_handler is not compatible with -m5-compact");
8312       *no_add_attrs = true;
8313     }
8314
8315   return NULL_TREE;
8316 }
8317
8318 /* Handle an 'function_vector' attribute; arguments as in
8319    struct attribute_spec.handler.  */
8320 static tree
8321 sh2a_handle_function_vector_handler_attribute (tree * node, tree name,
8322                                                tree args ATTRIBUTE_UNUSED,
8323                                                int flags ATTRIBUTE_UNUSED,
8324                                                bool * no_add_attrs)
8325 {
8326   if (!TARGET_SH2A)
8327     {
8328       warning (OPT_Wattributes, "%qE attribute only applies to SH2A",
8329                name);
8330       *no_add_attrs = true;
8331     }
8332   else if (TREE_CODE (*node) != FUNCTION_DECL)
8333     {
8334       warning (OPT_Wattributes, "%qE attribute only applies to functions",
8335                name);
8336       *no_add_attrs = true;
8337     }
8338   else if (TREE_CODE (TREE_VALUE (args)) != INTEGER_CST)
8339     {
8340       /* The argument must be a constant integer.  */
8341       warning (OPT_Wattributes,
8342                "%qE attribute argument not an integer constant",
8343                name);
8344       *no_add_attrs = true;
8345     }
8346   else if (TREE_INT_CST_LOW (TREE_VALUE (args)) > 255)
8347     {
8348       /* The argument value must be between 0 to 255.  */
8349       warning (OPT_Wattributes,
8350                "%qE attribute argument should be between 0 to 255",
8351                name);
8352       *no_add_attrs = true;
8353     }
8354   return NULL_TREE;
8355 }
8356
8357 /* Returns 1 if current function has been assigned the attribute
8358    'function_vector'.  */
8359 int
8360 sh2a_is_function_vector_call (rtx x)
8361 {
8362   if (GET_CODE (x) == SYMBOL_REF
8363       && (SYMBOL_REF_FLAGS (x) & SYMBOL_FLAG_FUNCVEC_FUNCTION))
8364     {
8365       tree tr = SYMBOL_REF_DECL (x);
8366
8367       if (sh2a_function_vector_p (tr))
8368         return 1;
8369     }
8370
8371   return 0;
8372 }
8373
8374 /* Returns the function vector number, if the the attribute
8375    'function_vector' is assigned, otherwise returns zero.  */
8376 int
8377 sh2a_get_function_vector_number (rtx x)
8378 {
8379   int num;
8380   tree list, t;
8381
8382   if ((GET_CODE (x) == SYMBOL_REF)
8383       && (SYMBOL_REF_FLAGS (x) & SYMBOL_FLAG_FUNCVEC_FUNCTION))
8384     {
8385       t = SYMBOL_REF_DECL (x);
8386
8387       if (TREE_CODE (t) != FUNCTION_DECL)
8388         return 0;
8389
8390       list = SH_ATTRIBUTES (t);
8391       while (list)
8392         {
8393           if (is_attribute_p ("function_vector", TREE_PURPOSE (list)))
8394             {
8395               num = TREE_INT_CST_LOW (TREE_VALUE (TREE_VALUE (list)));
8396               return num;
8397             }
8398
8399           list = TREE_CHAIN (list);
8400         }
8401
8402       return 0;
8403     }
8404   else
8405     return 0;
8406 }
8407
8408 /* Handle an "sp_switch" attribute; arguments as in
8409    struct attribute_spec.handler.  */
8410 static tree
8411 sh_handle_sp_switch_attribute (tree *node, tree name, tree args,
8412                                int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
8413 {
8414   if (TREE_CODE (*node) != FUNCTION_DECL)
8415     {
8416       warning (OPT_Wattributes, "%qE attribute only applies to functions",
8417                name);
8418       *no_add_attrs = true;
8419     }
8420   else if (TREE_CODE (TREE_VALUE (args)) != STRING_CST)
8421     {
8422       /* The argument must be a constant string.  */
8423       warning (OPT_Wattributes, "%qE attribute argument not a string constant",
8424                name);
8425       *no_add_attrs = true;
8426     }
8427
8428   return NULL_TREE;
8429 }
8430
8431 /* Handle an "trap_exit" attribute; arguments as in
8432    struct attribute_spec.handler.  */
8433 static tree
8434 sh_handle_trap_exit_attribute (tree *node, tree name, tree args,
8435                                int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
8436 {
8437   if (TREE_CODE (*node) != FUNCTION_DECL)
8438     {
8439       warning (OPT_Wattributes, "%qE attribute only applies to functions",
8440                name);
8441       *no_add_attrs = true;
8442     }
8443   /* The argument specifies a trap number to be used in a trapa instruction
8444      at function exit (instead of an rte instruction).  */
8445   else if (TREE_CODE (TREE_VALUE (args)) != INTEGER_CST)
8446     {
8447       /* The argument must be a constant integer.  */
8448       warning (OPT_Wattributes, "%qE attribute argument not an "
8449                "integer constant", name);
8450       *no_add_attrs = true;
8451     }
8452
8453   return NULL_TREE;
8454 }
8455
8456 static tree
8457 sh_handle_renesas_attribute (tree *node ATTRIBUTE_UNUSED,
8458                              tree name ATTRIBUTE_UNUSED,
8459                              tree args ATTRIBUTE_UNUSED,
8460                              int flags ATTRIBUTE_UNUSED,
8461                              bool *no_add_attrs ATTRIBUTE_UNUSED)
8462 {
8463   return NULL_TREE;
8464 }
8465
8466 /* True if __attribute__((renesas)) or -mrenesas.  */
8467 int
8468 sh_attr_renesas_p (const_tree td)
8469 {
8470   if (TARGET_HITACHI)
8471     return 1;
8472   if (td == 0)
8473     return 0;
8474   if (DECL_P (td))
8475     td = TREE_TYPE (td);
8476   if (td == error_mark_node)
8477     return 0;
8478   return (lookup_attribute ("renesas", TYPE_ATTRIBUTES (td))
8479           != NULL_TREE);
8480 }
8481
8482 /* True if __attribute__((renesas)) or -mrenesas, for the current
8483    function.  */
8484 int
8485 sh_cfun_attr_renesas_p (void)
8486 {
8487   return sh_attr_renesas_p (current_function_decl);
8488 }
8489
8490 int
8491 sh_cfun_interrupt_handler_p (void)
8492 {
8493   return (lookup_attribute ("interrupt_handler",
8494                             DECL_ATTRIBUTES (current_function_decl))
8495           != NULL_TREE);
8496 }
8497
8498 /* Returns 1 if FUNC has been assigned the attribute
8499    "function_vector".  */
8500 int
8501 sh2a_function_vector_p (tree func)
8502 {
8503   tree list;
8504   if (TREE_CODE (func) != FUNCTION_DECL)
8505     return 0;
8506
8507   list = SH_ATTRIBUTES (func);
8508   while (list)
8509     {
8510       if (is_attribute_p ("function_vector", TREE_PURPOSE (list)))
8511         return 1;
8512
8513       list = TREE_CHAIN (list);
8514     }
8515   return 0;
8516 }
8517
8518 /* Returns TRUE if given tree has the "resbank" attribute.  */
8519
8520 int
8521 sh_cfun_resbank_handler_p (void)
8522 {
8523   return ((lookup_attribute ("resbank",
8524                              DECL_ATTRIBUTES (current_function_decl))
8525            != NULL_TREE)
8526           && (lookup_attribute ("interrupt_handler",
8527                                 DECL_ATTRIBUTES (current_function_decl))
8528               != NULL_TREE) && TARGET_SH2A);
8529 }
8530
8531 /* Implement TARGET_CHECK_PCH_TARGET_FLAGS.  */
8532
8533 static const char *
8534 sh_check_pch_target_flags (int old_flags)
8535 {
8536   if ((old_flags ^ target_flags) & (MASK_SH1 | MASK_SH2 | MASK_SH3
8537                                     | MASK_SH_E | MASK_HARD_SH4
8538                                     | MASK_FPU_SINGLE | MASK_SH4))
8539     return _("created and used with different architectures / ABIs");
8540   if ((old_flags ^ target_flags) & MASK_HITACHI)
8541     return _("created and used with different ABIs");
8542   if ((old_flags ^ target_flags) & MASK_LITTLE_ENDIAN)
8543     return _("created and used with different endianness");
8544   return NULL;
8545 }
8546 \f
8547 /* Predicates used by the templates.  */
8548
8549 /* Returns 1 if OP is MACL, MACH or PR.  The input must be a REG rtx.
8550    Used only in general_movsrc_operand.  */
8551
8552 int
8553 system_reg_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
8554 {
8555   switch (REGNO (op))
8556     {
8557     case PR_REG:
8558     case MACL_REG:
8559     case MACH_REG:
8560       return 1;
8561     }
8562   return 0;
8563 }
8564
8565 /* Nonzero if OP is a floating point value with value 0.0.  */
8566
8567 int
8568 fp_zero_operand (rtx op)
8569 {
8570   REAL_VALUE_TYPE r;
8571
8572   if (GET_MODE (op) != SFmode)
8573     return 0;
8574
8575   REAL_VALUE_FROM_CONST_DOUBLE (r, op);
8576   return REAL_VALUES_EQUAL (r, dconst0) && ! REAL_VALUE_MINUS_ZERO (r);
8577 }
8578
8579 /* Nonzero if OP is a floating point value with value 1.0.  */
8580
8581 int
8582 fp_one_operand (rtx op)
8583 {
8584   REAL_VALUE_TYPE r;
8585
8586   if (GET_MODE (op) != SFmode)
8587     return 0;
8588
8589   REAL_VALUE_FROM_CONST_DOUBLE (r, op);
8590   return REAL_VALUES_EQUAL (r, dconst1);
8591 }
8592
8593 /* For -m4 and -m4-single-only, mode switching is used.  If we are
8594    compiling without -mfmovd, movsf_ie isn't taken into account for
8595    mode switching.  We could check in machine_dependent_reorg for
8596    cases where we know we are in single precision mode, but there is
8597    interface to find that out during reload, so we must avoid
8598    choosing an fldi alternative during reload and thus failing to
8599    allocate a scratch register for the constant loading.  */
8600 int
8601 fldi_ok (void)
8602 {
8603   return ! TARGET_SH4 || TARGET_FMOVD || reload_completed;
8604 }
8605
8606 int
8607 tertiary_reload_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
8608 {
8609   enum rtx_code code = GET_CODE (op);
8610   return code == MEM || (TARGET_SH4 && code == CONST_DOUBLE);
8611 }
8612
8613 /* Return the TLS type for TLS symbols, 0 for otherwise.  */
8614 enum tls_model
8615 tls_symbolic_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
8616 {
8617   if (GET_CODE (op) != SYMBOL_REF)
8618     return TLS_MODEL_NONE;
8619   return SYMBOL_REF_TLS_MODEL (op);
8620 }
8621 \f
8622 /* Return the destination address of a branch.  */
8623
8624 static int
8625 branch_dest (rtx branch)
8626 {
8627   rtx dest = SET_SRC (PATTERN (branch));
8628   int dest_uid;
8629
8630   if (GET_CODE (dest) == IF_THEN_ELSE)
8631     dest = XEXP (dest, 1);
8632   dest = XEXP (dest, 0);
8633   dest_uid = INSN_UID (dest);
8634   return INSN_ADDRESSES (dest_uid);
8635 }
8636 \f
8637 /* Return nonzero if REG is not used after INSN.
8638    We assume REG is a reload reg, and therefore does
8639    not live past labels.  It may live past calls or jumps though.  */
8640 int
8641 reg_unused_after (rtx reg, rtx insn)
8642 {
8643   enum rtx_code code;
8644   rtx set;
8645
8646   /* If the reg is set by this instruction, then it is safe for our
8647      case.  Disregard the case where this is a store to memory, since
8648      we are checking a register used in the store address.  */
8649   set = single_set (insn);
8650   if (set && GET_CODE (SET_DEST (set)) != MEM
8651       && reg_overlap_mentioned_p (reg, SET_DEST (set)))
8652     return 1;
8653
8654   while ((insn = NEXT_INSN (insn)))
8655     {
8656       rtx set;
8657       if (!INSN_P (insn))
8658         continue;
8659
8660       code = GET_CODE (insn);
8661
8662 #if 0
8663       /* If this is a label that existed before reload, then the register
8664          if dead here.  However, if this is a label added by reorg, then
8665          the register may still be live here.  We can't tell the difference,
8666          so we just ignore labels completely.  */
8667       if (code == CODE_LABEL)
8668         return 1;
8669       /* else */
8670 #endif
8671
8672       if (code == JUMP_INSN)
8673         return 0;
8674
8675       /* If this is a sequence, we must handle them all at once.
8676          We could have for instance a call that sets the target register,
8677          and an insn in a delay slot that uses the register.  In this case,
8678          we must return 0.  */
8679       else if (code == INSN && GET_CODE (PATTERN (insn)) == SEQUENCE)
8680         {
8681           int i;
8682           int retval = 0;
8683
8684           for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
8685             {
8686               rtx this_insn = XVECEXP (PATTERN (insn), 0, i);
8687               rtx set = single_set (this_insn);
8688
8689               if (GET_CODE (this_insn) == CALL_INSN)
8690                 code = CALL_INSN;
8691               else if (GET_CODE (this_insn) == JUMP_INSN)
8692                 {
8693                   if (INSN_ANNULLED_BRANCH_P (this_insn))
8694                     return 0;
8695                   code = JUMP_INSN;
8696                 }
8697
8698               if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
8699                 return 0;
8700               if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
8701                 {
8702                   if (GET_CODE (SET_DEST (set)) != MEM)
8703                     retval = 1;
8704                   else
8705                     return 0;
8706                 }
8707               if (set == 0
8708                   && reg_overlap_mentioned_p (reg, PATTERN (this_insn)))
8709                 return 0;
8710             }
8711           if (retval == 1)
8712             return 1;
8713           else if (code == JUMP_INSN)
8714             return 0;
8715         }
8716
8717       set = single_set (insn);
8718       if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
8719         return 0;
8720       if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
8721         return GET_CODE (SET_DEST (set)) != MEM;
8722       if (set == 0 && reg_overlap_mentioned_p (reg, PATTERN (insn)))
8723         return 0;
8724
8725       if (code == CALL_INSN && call_really_used_regs[REGNO (reg)])
8726         return 1;
8727     }
8728   return 1;
8729 }
8730 \f
8731 #include "ggc.h"
8732
8733 static GTY(()) rtx fpscr_rtx;
8734 rtx
8735 get_fpscr_rtx (void)
8736 {
8737   if (! fpscr_rtx)
8738     {
8739       fpscr_rtx = gen_rtx_REG (PSImode, FPSCR_REG);
8740       REG_USERVAR_P (fpscr_rtx) = 1;
8741       mark_user_reg (fpscr_rtx);
8742     }
8743   if (! reload_completed || mdep_reorg_phase != SH_AFTER_MDEP_REORG)
8744     mark_user_reg (fpscr_rtx);
8745   return fpscr_rtx;
8746 }
8747
8748 static GTY(()) tree fpscr_values;
8749
8750 static void
8751 emit_fpu_switch (rtx scratch, int index)
8752 {
8753   rtx dst, src;
8754
8755   if (fpscr_values == NULL)
8756     {
8757       tree t;
8758
8759       t = build_index_type (integer_one_node);
8760       t = build_array_type (integer_type_node, t);
8761       t = build_decl (VAR_DECL, get_identifier ("__fpscr_values"), t);
8762       DECL_ARTIFICIAL (t) = 1;
8763       DECL_IGNORED_P (t) = 1;
8764       DECL_EXTERNAL (t) = 1;
8765       TREE_STATIC (t) = 1;
8766       TREE_PUBLIC (t) = 1;
8767       TREE_USED (t) = 1;
8768
8769       fpscr_values = t;
8770     }
8771
8772   src = DECL_RTL (fpscr_values);
8773   if (!can_create_pseudo_p ())
8774     {
8775       emit_move_insn (scratch, XEXP (src, 0));
8776       if (index != 0)
8777         emit_insn (gen_addsi3 (scratch, scratch, GEN_INT (index * 4)));
8778       src = adjust_automodify_address (src, PSImode, scratch, index * 4);
8779     }
8780   else
8781     src = adjust_address (src, PSImode, index * 4);
8782
8783   dst = get_fpscr_rtx ();
8784   emit_move_insn (dst, src);
8785 }
8786
8787 void
8788 emit_sf_insn (rtx pat)
8789 {
8790   emit_insn (pat);
8791 }
8792
8793 void
8794 emit_df_insn (rtx pat)
8795 {
8796   emit_insn (pat);
8797 }
8798
8799 void
8800 expand_sf_unop (rtx (*fun) (rtx, rtx, rtx), rtx *operands)
8801 {
8802   emit_sf_insn ((*fun) (operands[0], operands[1], get_fpscr_rtx ()));
8803 }
8804
8805 void
8806 expand_sf_binop (rtx (*fun) (rtx, rtx, rtx, rtx), rtx *operands)
8807 {
8808   emit_sf_insn ((*fun) (operands[0], operands[1], operands[2],
8809                          get_fpscr_rtx ()));
8810 }
8811
8812 void
8813 expand_df_unop (rtx (*fun) (rtx, rtx, rtx), rtx *operands)
8814 {
8815   emit_df_insn ((*fun) (operands[0], operands[1], get_fpscr_rtx ()));
8816 }
8817
8818 void
8819 expand_df_binop (rtx (*fun) (rtx, rtx, rtx, rtx), rtx *operands)
8820 {
8821   emit_df_insn ((*fun) (operands[0], operands[1], operands[2],
8822                         get_fpscr_rtx ()));
8823 }
8824 \f
8825 static rtx get_free_reg (HARD_REG_SET);
8826
8827 /* This function returns a register to use to load the address to load
8828    the fpscr from.  Currently it always returns r1 or r7, but when we are
8829    able to use pseudo registers after combine, or have a better mechanism
8830    for choosing a register, it should be done here.  */
8831 /* REGS_LIVE is the liveness information for the point for which we
8832    need this allocation.  In some bare-bones exit blocks, r1 is live at the
8833    start.  We can even have all of r0..r3 being live:
8834 __complex__ long long f (double d) { if (d == 0) return 2; else return 3; }
8835    INSN before which new insns are placed with will clobber the register
8836    we return.  If a basic block consists only of setting the return value
8837    register to a pseudo and using that register, the return value is not
8838    live before or after this block, yet we we'll insert our insns right in
8839    the middle.  */
8840
8841 static rtx
8842 get_free_reg (HARD_REG_SET regs_live)
8843 {
8844   if (! TEST_HARD_REG_BIT (regs_live, 1))
8845     return gen_rtx_REG (Pmode, 1);
8846
8847   /* Hard reg 1 is live; since this is a SMALL_REGISTER_CLASSES target,
8848      there shouldn't be anything but a jump before the function end.  */
8849   gcc_assert (!TEST_HARD_REG_BIT (regs_live, 7));
8850   return gen_rtx_REG (Pmode, 7);
8851 }
8852
8853 /* This function will set the fpscr from memory.
8854    MODE is the mode we are setting it to.  */
8855 void
8856 fpscr_set_from_mem (int mode, HARD_REG_SET regs_live)
8857 {
8858   enum attr_fp_mode fp_mode = (enum attr_fp_mode) mode;
8859   enum attr_fp_mode norm_mode = ACTUAL_NORMAL_MODE (FP_MODE);
8860   rtx addr_reg;
8861
8862   addr_reg = !can_create_pseudo_p () ? get_free_reg (regs_live) : NULL_RTX;
8863   emit_fpu_switch (addr_reg, fp_mode == norm_mode);
8864 }
8865
8866 /* Is the given character a logical line separator for the assembler?  */
8867 #ifndef IS_ASM_LOGICAL_LINE_SEPARATOR
8868 #define IS_ASM_LOGICAL_LINE_SEPARATOR(C, STR) ((C) == ';')
8869 #endif
8870
8871 int
8872 sh_insn_length_adjustment (rtx insn)
8873 {
8874   /* Instructions with unfilled delay slots take up an extra two bytes for
8875      the nop in the delay slot.  */
8876   if (((GET_CODE (insn) == INSN
8877         && GET_CODE (PATTERN (insn)) != USE
8878         && GET_CODE (PATTERN (insn)) != CLOBBER)
8879        || GET_CODE (insn) == CALL_INSN
8880        || (GET_CODE (insn) == JUMP_INSN
8881            && GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC
8882            && GET_CODE (PATTERN (insn)) != ADDR_VEC))
8883       && GET_CODE (PATTERN (NEXT_INSN (PREV_INSN (insn)))) != SEQUENCE
8884       && get_attr_needs_delay_slot (insn) == NEEDS_DELAY_SLOT_YES)
8885     return 2;
8886
8887   /* SH2e has a bug that prevents the use of annulled branches, so if
8888      the delay slot is not filled, we'll have to put a NOP in it.  */
8889   if (sh_cpu_attr == CPU_SH2E
8890       && GET_CODE (insn) == JUMP_INSN
8891       && GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC
8892       && GET_CODE (PATTERN (insn)) != ADDR_VEC
8893       && get_attr_type (insn) == TYPE_CBRANCH
8894       && GET_CODE (PATTERN (NEXT_INSN (PREV_INSN (insn)))) != SEQUENCE)
8895     return 2;
8896
8897   /* sh-dsp parallel processing insn take four bytes instead of two.  */
8898
8899   if (GET_CODE (insn) == INSN)
8900     {
8901       int sum = 0;
8902       rtx body = PATTERN (insn);
8903       const char *templ;
8904       char c;
8905       int maybe_label = 1;
8906
8907       if (GET_CODE (body) == ASM_INPUT)
8908         templ = XSTR (body, 0);
8909       else if (asm_noperands (body) >= 0)
8910         templ
8911           = decode_asm_operands (body, NULL, NULL, NULL, NULL, NULL);
8912       else
8913         return 0;
8914       do
8915         {
8916           int ppi_adjust = 0;
8917
8918           do
8919             c = *templ++;
8920           while (c == ' ' || c == '\t');
8921           /* all sh-dsp parallel-processing insns start with p.
8922              The only non-ppi sh insn starting with p is pref.
8923              The only ppi starting with pr is prnd.  */
8924           if ((c == 'p' || c == 'P') && strncasecmp ("re", templ, 2))
8925             ppi_adjust = 2;
8926           /* The repeat pseudo-insn expands two three insns, a total of
8927              six bytes in size.  */
8928           else if ((c == 'r' || c == 'R')
8929                    && ! strncasecmp ("epeat", templ, 5))
8930             ppi_adjust = 4;
8931           while (c && c != '\n'
8932                  && ! IS_ASM_LOGICAL_LINE_SEPARATOR (c, templ))
8933             {
8934               /* If this is a label, it is obviously not a ppi insn.  */
8935               if (c == ':' && maybe_label)
8936                 {
8937                   ppi_adjust = 0;
8938                   break;
8939                 }
8940               else if (c == '\'' || c == '"')
8941                 maybe_label = 0;
8942               c = *templ++;
8943             }
8944           sum += ppi_adjust;
8945           maybe_label = c != ':';
8946         }
8947       while (c);
8948       return sum;
8949     }
8950   return 0;
8951 }
8952 \f
8953 /* Return TRUE for a valid displacement for the REG+disp addressing
8954    with MODE.  */
8955
8956 /* ??? The SH2e does not have the REG+disp addressing mode when loading values
8957    into the FRx registers.  We implement this by setting the maximum offset
8958    to zero when the value is SFmode.  This also restricts loading of SFmode
8959    values into the integer registers, but that can't be helped.  */
8960
8961 /* The SH allows a displacement in a QI or HI amode, but only when the
8962    other operand is R0. GCC doesn't handle this very well, so we forgot
8963    all of that.
8964
8965    A legitimate index for a QI or HI is 0, SI can be any number 0..63,
8966    DI can be any number 0..60.  */
8967
8968 bool
8969 sh_legitimate_index_p (enum machine_mode mode, rtx op)
8970 {
8971   if (GET_CODE (op) == CONST_INT)
8972     {
8973       if (TARGET_SHMEDIA)
8974         {
8975           int size;
8976
8977           /* Check if this the address of an unaligned load / store.  */
8978           if (mode == VOIDmode)
8979             return CONST_OK_FOR_I06 (INTVAL (op));
8980
8981           size = GET_MODE_SIZE (mode);
8982           return (!(INTVAL (op) & (size - 1))
8983                   && INTVAL (op) >= -512 * size
8984                   && INTVAL (op) < 512 * size);
8985         }
8986
8987       if (TARGET_SH2A)
8988         {
8989           if (GET_MODE_SIZE (mode) == 1
8990                 && (unsigned) INTVAL (op) < 4096)
8991             return true;
8992         }
8993
8994       if ((GET_MODE_SIZE (mode) == 4
8995            && (unsigned) INTVAL (op) < 64
8996            && !(INTVAL (op) & 3)
8997            && !(TARGET_SH2E && mode == SFmode))
8998           || (GET_MODE_SIZE (mode) == 4
8999               && (unsigned) INTVAL (op) < 16383
9000               && !(INTVAL (op) & 3) && TARGET_SH2A))
9001         return true;
9002
9003       if ((GET_MODE_SIZE (mode) == 8
9004            && (unsigned) INTVAL (op) < 60
9005            && !(INTVAL (op) & 3)
9006            && !((TARGET_SH4 || TARGET_SH2A) && mode == DFmode))
9007           || ((GET_MODE_SIZE (mode)==8)
9008               && (unsigned) INTVAL (op) < 8192
9009               && !(INTVAL (op) & (TARGET_SH2A_DOUBLE ? 7 : 3))
9010               && (TARGET_SH2A && mode == DFmode)))
9011         return true;
9012     }
9013
9014   return false;
9015 }
9016
9017 /* Recognize an RTL expression that is a valid memory address for
9018    an instruction.
9019    The MODE argument is the machine mode for the MEM expression
9020    that wants to use this address.
9021    Allow  REG
9022           REG+disp
9023           REG+r0
9024           REG++
9025           --REG  */
9026
9027 bool
9028 sh_legitimate_address_p (enum machine_mode mode, rtx x, bool strict)
9029 {
9030   if (MAYBE_BASE_REGISTER_RTX_P (x, strict))
9031     return true;
9032   else if ((GET_CODE (x) == POST_INC || GET_CODE (x) == PRE_DEC)
9033            && ! TARGET_SHMEDIA
9034            && MAYBE_BASE_REGISTER_RTX_P (XEXP (x, 0), strict))
9035     return true;
9036   else if (GET_CODE (x) == PLUS
9037            && (mode != PSImode || reload_completed))
9038     {
9039       rtx xop0 = XEXP (x, 0);
9040       rtx xop1 = XEXP (x, 1);
9041
9042       if (GET_MODE_SIZE (mode) <= 8
9043           && MAYBE_BASE_REGISTER_RTX_P (xop0, strict)
9044           && sh_legitimate_index_p (mode, xop1))
9045         return true;
9046
9047       if ((ALLOW_INDEXED_ADDRESS || GET_MODE (x) == DImode
9048            || ((xop0 == stack_pointer_rtx
9049                 || xop0 == hard_frame_pointer_rtx)
9050                && REG_P (xop1) && REGNO (xop1) == R0_REG)
9051            || ((xop1 == stack_pointer_rtx
9052                 || xop1 == hard_frame_pointer_rtx)
9053                && REG_P (xop0) && REGNO (xop0) == R0_REG))
9054           && ((!TARGET_SHMEDIA && GET_MODE_SIZE (mode) <= 4)
9055               || (TARGET_SHMEDIA && GET_MODE_SIZE (mode) <= 8)
9056               || ((TARGET_SH4 || TARGET_SH2A_DOUBLE)
9057                   && TARGET_FMOVD && mode == DFmode)))
9058         {
9059           if (MAYBE_BASE_REGISTER_RTX_P (xop1, strict)
9060               && MAYBE_INDEX_REGISTER_RTX_P (xop0, strict))
9061             return true;
9062           if (MAYBE_INDEX_REGISTER_RTX_P (xop1, strict)
9063               && MAYBE_BASE_REGISTER_RTX_P (xop0, strict))
9064             return true;
9065         }
9066     }
9067
9068   return false;
9069 }
9070 \f
9071 /* Return TRUE if X references a SYMBOL_REF or LABEL_REF whose symbol
9072    isn't protected by a PIC unspec.  */
9073 int
9074 nonpic_symbol_mentioned_p (rtx x)
9075 {
9076   register const char *fmt;
9077   register int i;
9078
9079   if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF
9080       || GET_CODE (x) == PC)
9081     return 1;
9082
9083   /* We don't want to look into the possible MEM location of a
9084      CONST_DOUBLE, since we're not going to use it, in general.  */
9085   if (GET_CODE (x) == CONST_DOUBLE)
9086     return 0;
9087
9088   if (GET_CODE (x) == UNSPEC
9089       && (XINT (x, 1) == UNSPEC_PIC
9090           || XINT (x, 1) == UNSPEC_GOT
9091           || XINT (x, 1) == UNSPEC_GOTOFF
9092           || XINT (x, 1) == UNSPEC_GOTPLT
9093           || XINT (x, 1) == UNSPEC_GOTTPOFF
9094           || XINT (x, 1) == UNSPEC_DTPOFF
9095           || XINT (x, 1) == UNSPEC_PLT
9096           || XINT (x, 1) == UNSPEC_SYMOFF
9097           || XINT (x, 1) == UNSPEC_PCREL_SYMOFF))
9098     return 0;
9099
9100   fmt = GET_RTX_FORMAT (GET_CODE (x));
9101   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
9102     {
9103       if (fmt[i] == 'E')
9104         {
9105           register int j;
9106
9107           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
9108             if (nonpic_symbol_mentioned_p (XVECEXP (x, i, j)))
9109               return 1;
9110         }
9111       else if (fmt[i] == 'e' && nonpic_symbol_mentioned_p (XEXP (x, i)))
9112         return 1;
9113     }
9114
9115   return 0;
9116 }
9117
9118 /* Convert a non-PIC address in `orig' to a PIC address using @GOT or
9119    @GOTOFF in `reg'.  */
9120 rtx
9121 legitimize_pic_address (rtx orig, enum machine_mode mode ATTRIBUTE_UNUSED,
9122                         rtx reg)
9123 {
9124   if (tls_symbolic_operand (orig, Pmode) != TLS_MODEL_NONE)
9125     return orig;
9126
9127   if (GET_CODE (orig) == LABEL_REF
9128       || (GET_CODE (orig) == SYMBOL_REF && SYMBOL_REF_LOCAL_P (orig)))
9129     {
9130       if (reg == 0)
9131         reg = gen_reg_rtx (Pmode);
9132
9133       emit_insn (gen_symGOTOFF2reg (reg, orig));
9134       return reg;
9135     }
9136   else if (GET_CODE (orig) == SYMBOL_REF)
9137     {
9138       if (reg == 0)
9139         reg = gen_reg_rtx (Pmode);
9140
9141       emit_insn (gen_symGOT2reg (reg, orig));
9142       return reg;
9143     }
9144   return orig;
9145 }
9146
9147 /* Try machine-dependent ways of modifying an illegitimate address
9148    to be legitimate.  If we find one, return the new, valid address.
9149    Otherwise, return X.
9150
9151    For the SH, if X is almost suitable for indexing, but the offset is
9152    out of range, convert it into a normal form so that CSE has a chance
9153    of reducing the number of address registers used.  */
9154
9155 static rtx
9156 sh_legitimize_address (rtx x, rtx oldx, enum machine_mode mode)
9157 {
9158   if (flag_pic)
9159     x = legitimize_pic_address (oldx, mode, NULL_RTX);
9160
9161   if (GET_CODE (x) == PLUS
9162       && (GET_MODE_SIZE (mode) == 4
9163           || GET_MODE_SIZE (mode) == 8)
9164       && GET_CODE (XEXP (x, 1)) == CONST_INT
9165       && BASE_REGISTER_RTX_P (XEXP (x, 0))
9166       && ! TARGET_SHMEDIA
9167       && ! ((TARGET_SH4 || TARGET_SH2A_DOUBLE) && mode == DFmode)
9168       && ! (TARGET_SH2E && mode == SFmode))
9169     {
9170       rtx index_rtx = XEXP (x, 1);
9171       HOST_WIDE_INT offset = INTVAL (index_rtx), offset_base;
9172       rtx sum;
9173
9174       /* On rare occasions, we might get an unaligned pointer
9175          that is indexed in a way to give an aligned address.
9176          Therefore, keep the lower two bits in offset_base.  */
9177       /* Instead of offset_base 128..131 use 124..127, so that
9178          simple add suffices.  */
9179       if (offset > 127)
9180         offset_base = ((offset + 4) & ~60) - 4;
9181       else
9182         offset_base = offset & ~60;
9183
9184       /* Sometimes the normal form does not suit DImode.  We
9185          could avoid that by using smaller ranges, but that
9186          would give less optimized code when SImode is
9187          prevalent.  */
9188       if (GET_MODE_SIZE (mode) + offset - offset_base <= 64)
9189         {
9190           sum = expand_binop (Pmode, add_optab, XEXP (x, 0),
9191                               GEN_INT (offset_base), NULL_RTX, 0,
9192                               OPTAB_LIB_WIDEN);
9193
9194           return gen_rtx_PLUS (Pmode, sum, GEN_INT (offset - offset_base));
9195         }
9196     }
9197
9198   return x;
9199 }
9200
9201 /* Mark the use of a constant in the literal table. If the constant
9202    has multiple labels, make it unique.  */
9203 static rtx
9204 mark_constant_pool_use (rtx x)
9205 {
9206   rtx insn, lab, pattern;
9207
9208   if (x == NULL)
9209     return x;
9210
9211   switch (GET_CODE (x))
9212     {
9213     case LABEL_REF:
9214       x = XEXP (x, 0);
9215     case CODE_LABEL:
9216       break;
9217     default:
9218       return x;
9219     }
9220
9221   /* Get the first label in the list of labels for the same constant
9222      and delete another labels in the list.  */
9223   lab = x;
9224   for (insn = PREV_INSN (x); insn; insn = PREV_INSN (insn))
9225     {
9226       if (GET_CODE (insn) != CODE_LABEL
9227           || LABEL_REFS (insn) != NEXT_INSN (insn))
9228         break;
9229       lab = insn;
9230     }
9231
9232   for (insn = LABEL_REFS (lab); insn; insn = LABEL_REFS (insn))
9233     INSN_DELETED_P (insn) = 1;
9234
9235   /* Mark constants in a window.  */
9236   for (insn = NEXT_INSN (x); insn; insn = NEXT_INSN (insn))
9237     {
9238       if (GET_CODE (insn) != INSN)
9239         continue;
9240
9241       pattern = PATTERN (insn);
9242       if (GET_CODE (pattern) != UNSPEC_VOLATILE)
9243         continue;
9244
9245       switch (XINT (pattern, 1))
9246         {
9247         case UNSPECV_CONST2:
9248         case UNSPECV_CONST4:
9249         case UNSPECV_CONST8:
9250           XVECEXP (pattern, 0, 1) = const1_rtx;
9251           break;
9252         case UNSPECV_WINDOW_END:
9253           if (XVECEXP (pattern, 0, 0) == x)
9254             return lab;
9255           break;
9256         case UNSPECV_CONST_END:
9257           return lab;
9258         default:
9259           break;
9260         }
9261     }
9262
9263   return lab;
9264 }
9265 \f
9266 /* Return true if it's possible to redirect BRANCH1 to the destination
9267    of an unconditional jump BRANCH2.  We only want to do this if the
9268    resulting branch will have a short displacement.  */
9269 int
9270 sh_can_redirect_branch (rtx branch1, rtx branch2)
9271 {
9272   if (flag_expensive_optimizations && simplejump_p (branch2))
9273     {
9274       rtx dest = XEXP (SET_SRC (single_set (branch2)), 0);
9275       rtx insn;
9276       int distance;
9277
9278       for (distance = 0, insn = NEXT_INSN (branch1);
9279            insn && distance < 256;
9280            insn = PREV_INSN (insn))
9281         {
9282           if (insn == dest)
9283             return 1;
9284           else
9285             distance += get_attr_length (insn);
9286         }
9287       for (distance = 0, insn = NEXT_INSN (branch1);
9288            insn && distance < 256;
9289            insn = NEXT_INSN (insn))
9290         {
9291           if (insn == dest)
9292             return 1;
9293           else
9294             distance += get_attr_length (insn);
9295         }
9296     }
9297   return 0;
9298 }
9299
9300 /* Return nonzero if register old_reg can be renamed to register new_reg.  */
9301 int
9302 sh_hard_regno_rename_ok (unsigned int old_reg ATTRIBUTE_UNUSED,
9303                          unsigned int new_reg)
9304 {
9305   /* Interrupt functions can only use registers that have already been
9306      saved by the prologue, even if they would normally be
9307      call-clobbered.  */
9308
9309   if (sh_cfun_interrupt_handler_p () && !df_regs_ever_live_p (new_reg))
9310     return 0;
9311
9312   return 1;
9313 }
9314
9315 /* Function to update the integer COST
9316    based on the relationship between INSN that is dependent on
9317    DEP_INSN through the dependence LINK.  The default is to make no
9318    adjustment to COST.  This can be used for example to specify to
9319    the scheduler that an output- or anti-dependence does not incur
9320    the same cost as a data-dependence.  The return value should be
9321    the new value for COST.  */
9322 static int
9323 sh_adjust_cost (rtx insn, rtx link ATTRIBUTE_UNUSED, rtx dep_insn, int cost)
9324 {
9325   rtx reg, use_pat;
9326
9327   if (TARGET_SHMEDIA)
9328     {
9329       /* On SHmedia, if the dependence is an anti-dependence or
9330          output-dependence, there is no cost.  */
9331       if (REG_NOTE_KIND (link) != 0)
9332         {
9333           /* However, dependencies between target register loads and
9334              uses of the register in a subsequent block that are separated
9335              by a conditional branch are not modelled - we have to do with
9336              the anti-dependency between the target register load and the
9337              conditional branch that ends the current block.  */
9338           if (REG_NOTE_KIND (link) == REG_DEP_ANTI
9339               && GET_CODE (PATTERN (dep_insn)) == SET
9340               && (get_attr_type (dep_insn) == TYPE_PT_MEDIA
9341                   || get_attr_type (dep_insn) == TYPE_PTABS_MEDIA)
9342               && get_attr_type (insn) == TYPE_CBRANCH_MEDIA)
9343             {
9344               int orig_cost = cost;
9345               rtx note = find_reg_note (insn, REG_BR_PROB, 0);
9346               rtx target = ((! note
9347                              || INTVAL (XEXP (note, 0)) * 2 < REG_BR_PROB_BASE)
9348                             ? insn : JUMP_LABEL (insn));
9349               /* On the likely path, the branch costs 1, on the unlikely path,
9350                  it costs 3.  */
9351               cost--;
9352               do
9353                 target = next_active_insn (target);
9354               while (target && ! flow_dependent_p (target, dep_insn)
9355                      && --cost > 0);
9356               /* If two branches are executed in immediate succession, with the
9357                  first branch properly predicted, this causes a stall at the
9358                  second branch, hence we won't need the target for the
9359                  second branch for two cycles after the launch of the first
9360                  branch.  */
9361               if (cost > orig_cost - 2)
9362                 cost = orig_cost - 2;
9363             }
9364           else
9365             cost = 0;
9366         }
9367
9368       else if (get_attr_is_mac_media (insn)
9369                && get_attr_is_mac_media (dep_insn))
9370         cost = 1;
9371
9372       else if (! reload_completed
9373                && GET_CODE (PATTERN (insn)) == SET
9374                && GET_CODE (SET_SRC (PATTERN (insn))) == FLOAT
9375                && GET_CODE (PATTERN (dep_insn)) == SET
9376                && fp_arith_reg_operand (SET_SRC (PATTERN (dep_insn)), VOIDmode)
9377                && cost < 4)
9378         cost = 4;
9379       /* Schedule the ptabs for a casesi_jump_media in preference to stuff
9380          that is needed at the target.  */
9381       else if (get_attr_type (insn) == TYPE_JUMP_MEDIA
9382                && ! flow_dependent_p (insn, dep_insn))
9383         cost--;
9384     }
9385   else if (REG_NOTE_KIND (link) == 0)
9386     {
9387       enum attr_type type;
9388       rtx dep_set;
9389
9390       if (recog_memoized (insn) < 0
9391           || recog_memoized (dep_insn) < 0)
9392         return cost;
9393
9394       dep_set = single_set (dep_insn);
9395
9396       /* The latency that we specify in the scheduling description refers
9397          to the actual output, not to an auto-increment register; for that,
9398          the latency is one.  */
9399       if (dep_set && MEM_P (SET_SRC (dep_set)) && cost > 1)
9400         {
9401           rtx set = single_set (insn);
9402
9403           if (set
9404               && !reg_mentioned_p (SET_DEST (dep_set), SET_SRC (set))
9405               && (!MEM_P (SET_DEST (set))
9406                   || !reg_mentioned_p (SET_DEST (dep_set),
9407                                        XEXP (SET_DEST (set), 0))))
9408             cost = 1;
9409         }
9410       /* The only input for a call that is timing-critical is the
9411          function's address.  */
9412       if (GET_CODE (insn) == CALL_INSN)
9413         {
9414           rtx call = PATTERN (insn);
9415
9416           if (GET_CODE (call) == PARALLEL)
9417             call = XVECEXP (call, 0 ,0);
9418           if (GET_CODE (call) == SET)
9419             call = SET_SRC (call);
9420           if (GET_CODE (call) == CALL && GET_CODE (XEXP (call, 0)) == MEM
9421                   /* sibcalli_thunk uses a symbol_ref in an unspec.  */
9422               && (GET_CODE (XEXP (XEXP (call, 0), 0)) == UNSPEC
9423                   || ! reg_set_p (XEXP (XEXP (call, 0), 0), dep_insn)))
9424             cost -= TARGET_SH4_300 ? 3 : 6;
9425         }
9426       /* Likewise, the most timing critical input for an sfuncs call
9427          is the function address.  However, sfuncs typically start
9428          using their arguments pretty quickly.
9429          Assume a four cycle delay for SH4 before they are needed.
9430          Cached ST40-300 calls are quicker, so assume only a one
9431          cycle delay there.
9432          ??? Maybe we should encode the delays till input registers
9433          are needed by sfuncs into the sfunc call insn.  */
9434       /* All sfunc calls are parallels with at least four components.
9435          Exploit this to avoid unnecessary calls to sfunc_uses_reg.  */
9436       else if (GET_CODE (PATTERN (insn)) == PARALLEL
9437                && XVECLEN (PATTERN (insn), 0) >= 4
9438                && (reg = sfunc_uses_reg (insn)))
9439         {
9440           if (! reg_set_p (reg, dep_insn))
9441             cost -= TARGET_SH4_300 ? 1 : 4;
9442         }
9443       if (TARGET_HARD_SH4 && !TARGET_SH4_300)
9444         {
9445           enum attr_type dep_type = get_attr_type (dep_insn);
9446
9447           if (dep_type == TYPE_FLOAD || dep_type == TYPE_PCFLOAD)
9448             cost--;
9449           else if ((dep_type == TYPE_LOAD_SI || dep_type == TYPE_PCLOAD_SI)
9450                    && (type = get_attr_type (insn)) != TYPE_CALL
9451                    && type != TYPE_SFUNC)
9452             cost--;
9453           /* When the preceding instruction loads the shift amount of
9454              the following SHAD/SHLD, the latency of the load is increased
9455              by 1 cycle.  */
9456           if (get_attr_type (insn) == TYPE_DYN_SHIFT
9457               && get_attr_any_int_load (dep_insn) == ANY_INT_LOAD_YES
9458               && reg_overlap_mentioned_p (SET_DEST (dep_set),
9459                                           XEXP (SET_SRC (single_set (insn)),
9460                                                 1)))
9461             cost++;
9462           /* When an LS group instruction with a latency of less than
9463              3 cycles is followed by a double-precision floating-point
9464              instruction, FIPR, or FTRV, the latency of the first
9465              instruction is increased to 3 cycles.  */
9466           else if (cost < 3
9467                    && get_attr_insn_class (dep_insn) == INSN_CLASS_LS_GROUP
9468                    && get_attr_dfp_comp (insn) == DFP_COMP_YES)
9469             cost = 3;
9470           /* The lsw register of a double-precision computation is ready one
9471              cycle earlier.  */
9472           else if (reload_completed
9473                    && get_attr_dfp_comp (dep_insn) == DFP_COMP_YES
9474                    && (use_pat = single_set (insn))
9475                    && ! regno_use_in (REGNO (SET_DEST (single_set (dep_insn))),
9476                                       SET_SRC (use_pat)))
9477             cost -= 1;
9478
9479           if (get_attr_any_fp_comp (dep_insn) == ANY_FP_COMP_YES
9480               && get_attr_late_fp_use (insn) == LATE_FP_USE_YES)
9481             cost -= 1;
9482         }
9483       else if (TARGET_SH4_300)
9484         {
9485           /* Stores need their input register two cycles later.  */
9486           if (dep_set && cost >= 1
9487               && ((type = get_attr_type (insn)) == TYPE_STORE
9488                   || type == TYPE_PSTORE
9489                   || type == TYPE_FSTORE || type == TYPE_MAC_MEM))
9490             {
9491               rtx set = single_set (insn);
9492
9493               if (!reg_mentioned_p (SET_SRC (set), XEXP (SET_DEST (set), 0))
9494                   && rtx_equal_p (SET_SRC (set), SET_DEST (dep_set)))
9495                 {
9496                   cost -= 2;
9497                   /* But don't reduce the cost below 1 if the address depends
9498                      on a side effect of dep_insn.  */
9499                   if (cost < 1
9500                       && modified_in_p (XEXP (SET_DEST (set), 0), dep_insn))
9501                     cost = 1;
9502                 }
9503             }
9504         }
9505     }
9506   /* An anti-dependence penalty of two applies if the first insn is a double
9507      precision fadd / fsub / fmul.  */
9508   else if (!TARGET_SH4_300
9509            && REG_NOTE_KIND (link) == REG_DEP_ANTI
9510            && recog_memoized (dep_insn) >= 0
9511            && (get_attr_type (dep_insn) == TYPE_DFP_ARITH
9512                || get_attr_type (dep_insn) == TYPE_DFP_MUL)
9513            /* A lot of alleged anti-flow dependences are fake,
9514               so check this one is real.  */
9515            && flow_dependent_p (dep_insn, insn))
9516     cost = 2;
9517
9518   return cost;
9519 }
9520
9521 /* Check if INSN is flow-dependent on DEP_INSN.  Can also be used to check
9522    if DEP_INSN is anti-flow dependent on INSN.  */
9523 static int
9524 flow_dependent_p (rtx insn, rtx dep_insn)
9525 {
9526   rtx tmp = PATTERN (insn);
9527
9528   note_stores (PATTERN (dep_insn), flow_dependent_p_1, &tmp);
9529   return tmp == NULL_RTX;
9530 }
9531
9532 /* A helper function for flow_dependent_p called through note_stores.  */
9533 static void
9534 flow_dependent_p_1 (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
9535 {
9536   rtx * pinsn = (rtx *) data;
9537
9538   if (*pinsn && reg_referenced_p (x, *pinsn))
9539     *pinsn = NULL_RTX;
9540 }
9541
9542 /* For use by sh_allocate_initial_value.  Note that sh.md contains some
9543    'special function' patterns (type sfunc) that clobber pr, but that
9544    do not look like function calls to leaf_function_p.  Hence we must
9545    do this extra check.  */
9546 static int
9547 sh_pr_n_sets (void)
9548 {
9549   return DF_REG_DEF_COUNT (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG);
9550 }
9551
9552 /* Return where to allocate pseudo for a given hard register initial
9553    value.  */
9554 static rtx
9555 sh_allocate_initial_value (rtx hard_reg)
9556 {
9557   rtx x;
9558
9559   if (REGNO (hard_reg) == (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG))
9560     {
9561       if (current_function_is_leaf
9562           && ! sh_pr_n_sets ()
9563           && ! (TARGET_SHCOMPACT
9564                 && ((crtl->args.info.call_cookie
9565                      & ~ CALL_COOKIE_RET_TRAMP (1))
9566                     || crtl->saves_all_registers)))
9567         x = hard_reg;
9568       else
9569         x = gen_frame_mem (Pmode, return_address_pointer_rtx);
9570     }
9571   else
9572     x = NULL_RTX;
9573
9574   return x;
9575 }
9576
9577 /* This function returns "2" to indicate dual issue for the SH4
9578    processor.  To be used by the DFA pipeline description.  */
9579 static int
9580 sh_issue_rate (void)
9581 {
9582   if (TARGET_SUPERSCALAR)
9583     return 2;
9584   else
9585     return 1;
9586 }
9587
9588 /* Functions for ready queue reordering for sched1.  */
9589
9590 /* Get weight for mode for a set x.  */
9591 static short
9592 find_set_regmode_weight (rtx x, enum machine_mode mode)
9593 {
9594   if (GET_CODE (x) == CLOBBER && register_operand (SET_DEST (x), mode))
9595     return 1;
9596   if (GET_CODE (x) == SET && register_operand (SET_DEST (x), mode))
9597     {
9598       if (GET_CODE (SET_DEST (x)) == REG)
9599         {
9600           if (!reg_mentioned_p (SET_DEST (x), SET_SRC (x)))
9601             return 1;
9602           else
9603             return 0;
9604         }
9605       return 1;
9606     }
9607   return 0;
9608 }
9609
9610 /* Get regmode weight for insn.  */
9611 static short
9612 find_insn_regmode_weight (rtx insn, enum machine_mode mode)
9613 {
9614   short reg_weight = 0;
9615   rtx x;
9616
9617   /* Increment weight for each register born here.  */
9618   x = PATTERN (insn);
9619   reg_weight += find_set_regmode_weight (x, mode);
9620   if (GET_CODE (x) == PARALLEL)
9621     {
9622       int j;
9623       for (j = XVECLEN (x, 0) - 1; j >= 0; j--)
9624         {
9625           x = XVECEXP (PATTERN (insn), 0, j);
9626           reg_weight += find_set_regmode_weight (x, mode);
9627         }
9628     }
9629   /* Decrement weight for each register that dies here.  */
9630   for (x = REG_NOTES (insn); x; x = XEXP (x, 1))
9631     {
9632       if (REG_NOTE_KIND (x) == REG_DEAD || REG_NOTE_KIND (x) == REG_UNUSED)
9633         {
9634           rtx note = XEXP (x, 0);
9635           if (GET_CODE (note) == REG && GET_MODE (note) == mode)
9636             reg_weight--;
9637         }
9638     }
9639   return reg_weight;
9640 }
9641
9642 /* Calculate regmode weights for all insns of a basic block.  */
9643 static void
9644 find_regmode_weight (basic_block b, enum machine_mode mode)
9645 {
9646   rtx insn, next_tail, head, tail;
9647
9648   get_ebb_head_tail (b, b, &head, &tail);
9649   next_tail = NEXT_INSN (tail);
9650
9651   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
9652     {
9653       /* Handle register life information.  */
9654       if (!INSN_P (insn))
9655         continue;
9656
9657       if (mode == SFmode)
9658         INSN_REGMODE_WEIGHT (insn, mode) =
9659           find_insn_regmode_weight (insn, mode) + 2 * find_insn_regmode_weight (insn, DFmode);
9660       else if (mode == SImode)
9661         INSN_REGMODE_WEIGHT (insn, mode) =
9662           find_insn_regmode_weight (insn, mode) + 2 * find_insn_regmode_weight (insn, DImode);
9663     }
9664 }
9665
9666 /* Comparison function for ready queue sorting.  */
9667 static int
9668 rank_for_reorder (const void *x, const void *y)
9669 {
9670   rtx tmp = *(const rtx *) y;
9671   rtx tmp2 = *(const rtx *) x;
9672
9673   /* The insn in a schedule group should be issued the first.  */
9674   if (SCHED_GROUP_P (tmp) != SCHED_GROUP_P (tmp2))
9675     return SCHED_GROUP_P (tmp2) ? 1 : -1;
9676
9677   /* If insns are equally good, sort by INSN_LUID (original insn order), This
9678      minimizes instruction movement, thus minimizing sched's effect on
9679      register pressure.  */
9680   return INSN_LUID (tmp) - INSN_LUID (tmp2);
9681 }
9682
9683 /* Resort the array A in which only element at index N may be out of order.  */
9684 static void
9685 swap_reorder (rtx *a, int n)
9686 {
9687   rtx insn = a[n - 1];
9688   int i = n - 2;
9689
9690   while (i >= 0 && rank_for_reorder (a + i, &insn) >= 0)
9691     {
9692       a[i + 1] = a[i];
9693       i -= 1;
9694     }
9695   a[i + 1] = insn;
9696 }
9697
9698 #define SCHED_REORDER(READY, N_READY)                                   \
9699   do                                                                    \
9700     {                                                                   \
9701       if ((N_READY) == 2)                                               \
9702         swap_reorder (READY, N_READY);                                  \
9703       else if ((N_READY) > 2)                                           \
9704         qsort (READY, N_READY, sizeof (rtx), rank_for_reorder);         \
9705     }                                                                   \
9706   while (0)
9707
9708 /* Sort the ready list READY by ascending priority, using the SCHED_REORDER
9709    macro.  */
9710 static void
9711 ready_reorder (rtx *ready, int nready)
9712 {
9713   SCHED_REORDER (ready, nready);
9714 }
9715
9716 /* Count life regions of r0 for a block.  */
9717 static int
9718 find_r0_life_regions (basic_block b)
9719 {
9720   rtx end, insn;
9721   rtx pset;
9722   rtx r0_reg;
9723   int live;
9724   int set;
9725   int death = 0;
9726
9727   if (REGNO_REG_SET_P (df_get_live_in (b), R0_REG))
9728     {
9729       set = 1;
9730       live = 1;
9731     }
9732   else
9733     {
9734       set = 0;
9735       live = 0;
9736     }
9737
9738   insn = BB_HEAD (b);
9739   end = BB_END (b);
9740   r0_reg = gen_rtx_REG (SImode, R0_REG);
9741   while (1)
9742     {
9743       if (INSN_P (insn))
9744         {
9745           if (find_regno_note (insn, REG_DEAD, R0_REG))
9746             {
9747               death++;
9748               live = 0;
9749             }
9750           if (!live
9751               && (pset = single_set (insn))
9752               && reg_overlap_mentioned_p (r0_reg, SET_DEST (pset))
9753               && !find_regno_note (insn, REG_UNUSED, R0_REG))
9754             {
9755               set++;
9756               live = 1;
9757             }
9758         }
9759       if (insn == end)
9760         break;
9761       insn = NEXT_INSN (insn);
9762     }
9763   return set - death;
9764 }
9765
9766 /* Calculate regmode weights for all insns of all basic block.  */
9767 static void
9768 sh_md_init_global (FILE *dump ATTRIBUTE_UNUSED,
9769                    int verbose ATTRIBUTE_UNUSED,
9770                    int old_max_uid)
9771 {
9772   basic_block b;
9773
9774   regmode_weight[0] = (short *) xcalloc (old_max_uid, sizeof (short));
9775   regmode_weight[1] = (short *) xcalloc (old_max_uid, sizeof (short));
9776   r0_life_regions = 0;
9777
9778   FOR_EACH_BB_REVERSE (b)
9779   {
9780     find_regmode_weight (b, SImode);
9781     find_regmode_weight (b, SFmode);
9782     if (!reload_completed)
9783       r0_life_regions += find_r0_life_regions (b);
9784   }
9785
9786   CURR_REGMODE_PRESSURE (SImode) = 0;
9787   CURR_REGMODE_PRESSURE (SFmode) = 0;
9788
9789 }
9790
9791 /* Cleanup.  */
9792 static void
9793 sh_md_finish_global (FILE *dump ATTRIBUTE_UNUSED,
9794                      int verbose ATTRIBUTE_UNUSED)
9795 {
9796   if (regmode_weight[0])
9797     {
9798       free (regmode_weight[0]);
9799       regmode_weight[0] = NULL;
9800     }
9801   if (regmode_weight[1])
9802     {
9803       free (regmode_weight[1]);
9804       regmode_weight[1] = NULL;
9805     }
9806 }
9807
9808 /* The scalar modes supported differs from the default version in TImode
9809    for 32-bit SHMEDIA.  */
9810 static bool
9811 sh_scalar_mode_supported_p (enum machine_mode mode)
9812 {
9813   if (TARGET_SHMEDIA32 && mode == TImode)
9814     return false;
9815
9816   return default_scalar_mode_supported_p (mode);
9817 }
9818
9819 /* Cache the can_issue_more so that we can return it from reorder2. Also,
9820    keep count of register pressures on SImode and SFmode. */
9821 static int
9822 sh_variable_issue (FILE *dump ATTRIBUTE_UNUSED,
9823                    int sched_verbose ATTRIBUTE_UNUSED,
9824                    rtx insn,
9825                    int can_issue_more)
9826 {
9827   if (GET_CODE (PATTERN (insn)) != USE
9828       && GET_CODE (PATTERN (insn)) != CLOBBER)
9829     cached_can_issue_more = can_issue_more - 1;
9830   else
9831     cached_can_issue_more = can_issue_more;
9832
9833   if (reload_completed)
9834     return cached_can_issue_more;
9835
9836   CURR_REGMODE_PRESSURE (SImode) += INSN_REGMODE_WEIGHT (insn, SImode);
9837   CURR_REGMODE_PRESSURE (SFmode) += INSN_REGMODE_WEIGHT (insn, SFmode);
9838
9839   return cached_can_issue_more;
9840 }
9841
9842 static void
9843 sh_md_init (FILE *dump ATTRIBUTE_UNUSED,
9844             int verbose ATTRIBUTE_UNUSED,
9845             int veclen ATTRIBUTE_UNUSED)
9846 {
9847   CURR_REGMODE_PRESSURE (SImode) = 0;
9848   CURR_REGMODE_PRESSURE (SFmode) = 0;
9849 }
9850
9851 /* Some magic numbers.  */
9852 /* Pressure on register r0 can lead to spill failures. so avoid sched1 for
9853    functions that already have high pressure on r0. */
9854 #define R0_MAX_LIFE_REGIONS 2
9855 /* Register Pressure thresholds for SImode and SFmode registers.  */
9856 #define SIMODE_MAX_WEIGHT 5
9857 #define SFMODE_MAX_WEIGHT 10
9858
9859 /* Return true if the pressure is high for MODE.  */
9860 static short
9861 high_pressure (enum machine_mode mode)
9862 {
9863   /* Pressure on register r0 can lead to spill failures. so avoid sched1 for
9864      functions that already have high pressure on r0. */
9865    if (r0_life_regions >= R0_MAX_LIFE_REGIONS)
9866      return 1;
9867
9868   if (mode == SFmode)
9869     return (CURR_REGMODE_PRESSURE (SFmode) > SFMODE_MAX_WEIGHT);
9870   else
9871     return (CURR_REGMODE_PRESSURE (SImode) > SIMODE_MAX_WEIGHT);
9872 }
9873
9874 /* Reorder ready queue if register pressure is high.  */
9875 static int
9876 sh_reorder (FILE *dump ATTRIBUTE_UNUSED,
9877             int sched_verbose ATTRIBUTE_UNUSED,
9878             rtx *ready,
9879             int *n_readyp,
9880             int clock_var ATTRIBUTE_UNUSED)
9881 {
9882   if (reload_completed)
9883     return sh_issue_rate ();
9884
9885   if (high_pressure (SFmode) || high_pressure (SImode))
9886     {
9887       ready_reorder (ready, *n_readyp);
9888     }
9889
9890   return sh_issue_rate ();
9891 }
9892
9893 /* Skip cycles if the current register pressure is high.  */
9894 static int
9895 sh_reorder2 (FILE *dump ATTRIBUTE_UNUSED,
9896              int sched_verbose ATTRIBUTE_UNUSED,
9897              rtx *ready ATTRIBUTE_UNUSED,
9898              int *n_readyp ATTRIBUTE_UNUSED,
9899              int clock_var ATTRIBUTE_UNUSED)
9900 {
9901   if (reload_completed)
9902     return cached_can_issue_more;
9903
9904   if (high_pressure(SFmode) || high_pressure (SImode))
9905     skip_cycles = 1;
9906
9907   return cached_can_issue_more;
9908 }
9909
9910 /* Skip cycles without sorting the ready queue. This will move insn from
9911    Q->R. If this is the last cycle we are skipping; allow sorting of ready
9912    queue by sh_reorder.  */
9913
9914 /* Generally, skipping these many cycles are sufficient for all insns to move
9915    from Q -> R.  */
9916 #define MAX_SKIPS 8
9917
9918 static int
9919 sh_dfa_new_cycle (FILE *sched_dump ATTRIBUTE_UNUSED,
9920                   int sched_verbose ATTRIBUTE_UNUSED,
9921                   rtx insn ATTRIBUTE_UNUSED,
9922                   int last_clock_var,
9923                   int clock_var,
9924                   int *sort_p)
9925 {
9926   if (reload_completed)
9927     return 0;
9928
9929   if (skip_cycles)
9930     {
9931       if ((clock_var - last_clock_var) < MAX_SKIPS)
9932         {
9933           *sort_p = 0;
9934           return 1;
9935         }
9936       /* If this is the last cycle we are skipping, allow reordering of R.  */
9937       if ((clock_var - last_clock_var) == MAX_SKIPS)
9938         {
9939           *sort_p = 1;
9940           return 1;
9941         }
9942     }
9943
9944   skip_cycles = 0;
9945
9946   return 0;
9947 }
9948
9949 /* SHmedia requires registers for branches, so we can't generate new
9950    branches past reload.  */
9951 static bool
9952 sh_cannot_modify_jumps_p (void)
9953 {
9954   return (TARGET_SHMEDIA && (reload_in_progress || reload_completed));
9955 }
9956
9957 static enum reg_class
9958 sh_target_reg_class (void)
9959 {
9960   return TARGET_SHMEDIA ? TARGET_REGS : NO_REGS;
9961 }
9962
9963 static bool
9964 sh_optimize_target_register_callee_saved (bool after_prologue_epilogue_gen)
9965 {
9966   HARD_REG_SET dummy;
9967 #if 0
9968   rtx insn;
9969 #endif
9970
9971   if (! shmedia_space_reserved_for_target_registers)
9972     return 0;
9973   if (after_prologue_epilogue_gen && ! TARGET_SAVE_ALL_TARGET_REGS)
9974     return 0;
9975   if (calc_live_regs (&dummy) >= 6 * 8)
9976     return 1;
9977   return 0;
9978 }
9979
9980 static bool
9981 sh_ms_bitfield_layout_p (const_tree record_type ATTRIBUTE_UNUSED)
9982 {
9983   return (TARGET_SH5 || TARGET_HITACHI || sh_attr_renesas_p (record_type));
9984 }
9985 \f
9986 /*
9987    On the SH1..SH4, the trampoline looks like
9988    2 0002 D202                  mov.l   l2,r2
9989    1 0000 D301                  mov.l   l1,r3
9990    3 0004 422B                  jmp     @r2
9991    4 0006 0009                  nop
9992    5 0008 00000000      l1:     .long   area
9993    6 000c 00000000      l2:     .long   function
9994
9995    SH5 (compact) uses r1 instead of r3 for the static chain.  */
9996
9997
9998 /* Emit RTL insns to initialize the variable parts of a trampoline.
9999    FNADDR is an RTX for the address of the function's pure code.
10000    CXT is an RTX for the static chain value for the function.  */
10001
10002 void
10003 sh_initialize_trampoline (rtx tramp, rtx fnaddr, rtx cxt)
10004 {
10005   rtx tramp_mem = gen_frame_mem (BLKmode, tramp);
10006
10007   if (TARGET_SHMEDIA64)
10008     {
10009       rtx tramp_templ;
10010       int fixed_len;
10011
10012       rtx movi1 = GEN_INT (0xcc000010);
10013       rtx shori1 = GEN_INT (0xc8000010);
10014       rtx src, dst;
10015
10016       /* The following trampoline works within a +- 128 KB range for cxt:
10017          ptb/u cxt,tr1; movi fnaddr >> 48,r0; shori fnaddr >> 32,r0;
10018          shori fnaddr >> 16,r0; shori fnaddr,r0; ptabs/l r0,tr0
10019          gettr tr1,r1; blink tr0,r63  */
10020       /* Address rounding makes it hard to compute the exact bounds of the
10021          offset for this trampoline, but we have a rather generous offset
10022          range, so frame_offset should do fine as an upper bound.  */
10023       if (cxt == virtual_stack_vars_rtx && frame_offset < 0x20000)
10024         {
10025           /* ??? could optimize this trampoline initialization
10026              by writing DImode words with two insns each.  */
10027           rtx mask = force_reg (DImode, GEN_INT (0x3fffc00));
10028           rtx insn = gen_rtx_MINUS (DImode, cxt, tramp);
10029           insn = gen_rtx_ASHIFT (DImode, insn, GEN_INT (10-2));
10030           insn = gen_rtx_AND (DImode, insn, mask);
10031           /* Or in ptb/u .,tr1 pattern */
10032           insn = gen_rtx_IOR (DImode, insn, gen_int_mode (0xec000010, SImode));
10033           insn = force_operand (insn, NULL_RTX);
10034           insn = gen_lowpart (SImode, insn);
10035           emit_move_insn (change_address (tramp_mem, SImode, NULL_RTX), insn);
10036           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (38));
10037           insn = gen_rtx_AND (DImode, insn, mask);
10038           insn = force_operand (gen_rtx_IOR (DImode, movi1, insn), NULL_RTX);
10039           insn = gen_lowpart (SImode, insn);
10040           emit_move_insn (adjust_address (tramp_mem, SImode, 4), insn);
10041           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (22));
10042           insn = gen_rtx_AND (DImode, insn, mask);
10043           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
10044           insn = gen_lowpart (SImode, insn);
10045           emit_move_insn (adjust_address (tramp_mem, SImode, 8), insn);
10046           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (6));
10047           insn = gen_rtx_AND (DImode, insn, mask);
10048           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
10049           insn = gen_lowpart (SImode, insn);
10050           emit_move_insn (adjust_address (tramp_mem, SImode, 12), insn);
10051           insn = gen_rtx_ASHIFT (DImode, fnaddr, GEN_INT (10));
10052           insn = gen_rtx_AND (DImode, insn, mask);
10053           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
10054           insn = gen_lowpart (SImode, insn);
10055           emit_move_insn (adjust_address (tramp_mem, SImode, 16), insn);
10056           emit_move_insn (adjust_address (tramp_mem, SImode, 20),
10057                           GEN_INT (0x6bf10600));
10058           emit_move_insn (adjust_address (tramp_mem, SImode, 24),
10059                           GEN_INT (0x4415fc10));
10060           emit_move_insn (adjust_address (tramp_mem, SImode, 28),
10061                           GEN_INT (0x4401fff0));
10062           emit_insn (gen_ic_invalidate_line (tramp));
10063           return;
10064         }
10065       tramp_templ = gen_rtx_SYMBOL_REF (Pmode,"__GCC_nested_trampoline");
10066       fixed_len = TRAMPOLINE_SIZE - 2 * GET_MODE_SIZE (Pmode);
10067
10068       tramp_templ = gen_datalabel_ref (tramp_templ);
10069       dst = tramp_mem;
10070       src = gen_const_mem (BLKmode, tramp_templ);
10071       set_mem_align (dst, 256);
10072       set_mem_align (src, 64);
10073       emit_block_move (dst, src, GEN_INT (fixed_len), BLOCK_OP_NORMAL);
10074
10075       emit_move_insn (adjust_address (tramp_mem, Pmode, fixed_len), fnaddr);
10076       emit_move_insn (adjust_address (tramp_mem, Pmode,
10077                                       fixed_len + GET_MODE_SIZE (Pmode)),
10078                       cxt);
10079       emit_insn (gen_ic_invalidate_line (tramp));
10080       return;
10081     }
10082   else if (TARGET_SHMEDIA)
10083     {
10084       /* movi fnaddr >> 16,r1; shori fnaddr,r1; ptabs/l r1,tr0
10085          movi cxt >> 16,r1; shori cxt,r1; blink tr0,r63  */
10086       rtx quad0 = gen_reg_rtx (DImode), cxtload = gen_reg_rtx (DImode);
10087       rtx quad1 = gen_reg_rtx (DImode), quad2 = gen_reg_rtx (DImode);
10088       /* movi 0,r1: 0xcc000010 shori 0,r1: c8000010  concatenated,
10089          rotated 10 right, and higher 16 bit of every 32 selected.  */
10090       rtx movishori
10091         = force_reg (V2HImode, (simplify_gen_subreg
10092                                 (V2HImode, GEN_INT (0x4330432), SImode, 0)));
10093       rtx ptabs = force_reg (DImode, GEN_INT (0x6bf10600));
10094       rtx blink = force_reg (DImode, GEN_INT (0x4401fff0));
10095
10096       tramp = force_reg (Pmode, tramp);
10097       fnaddr = force_reg (SImode, fnaddr);
10098       cxt = force_reg (SImode, cxt);
10099       emit_insn (gen_mshflo_w_x (gen_rtx_SUBREG (V4HImode, quad0, 0),
10100                                  gen_rtx_SUBREG (V2HImode, fnaddr, 0),
10101                                  movishori));
10102       emit_insn (gen_rotrdi3_mextr (quad0, quad0,
10103                                     GEN_INT (TARGET_LITTLE_ENDIAN ? 24 : 56)));
10104       emit_insn (gen_ashldi3_media (quad0, quad0, const2_rtx));
10105       emit_move_insn (change_address (tramp_mem, DImode, NULL_RTX), quad0);
10106       emit_insn (gen_mshflo_w_x (gen_rtx_SUBREG (V4HImode, cxtload, 0),
10107                                  gen_rtx_SUBREG (V2HImode, cxt, 0),
10108                                  movishori));
10109       emit_insn (gen_rotrdi3_mextr (cxtload, cxtload,
10110                                     GEN_INT (TARGET_LITTLE_ENDIAN ? 24 : 56)));
10111       emit_insn (gen_ashldi3_media (cxtload, cxtload, const2_rtx));
10112       if (TARGET_LITTLE_ENDIAN)
10113         {
10114           emit_insn (gen_mshflo_l_di (quad1, ptabs, cxtload));
10115           emit_insn (gen_mextr4 (quad2, cxtload, blink));
10116         }
10117       else
10118         {
10119           emit_insn (gen_mextr4 (quad1, cxtload, ptabs));
10120           emit_insn (gen_mshflo_l_di (quad2, blink, cxtload));
10121         }
10122       emit_move_insn (adjust_address (tramp_mem, DImode, 8), quad1);
10123       emit_move_insn (adjust_address (tramp_mem, DImode, 16), quad2);
10124       emit_insn (gen_ic_invalidate_line (tramp));
10125       return;
10126     }
10127   else if (TARGET_SHCOMPACT)
10128     {
10129       emit_insn (gen_initialize_trampoline (tramp, cxt, fnaddr));
10130       return;
10131     }
10132   emit_move_insn (change_address (tramp_mem, SImode, NULL_RTX),
10133                   gen_int_mode (TARGET_LITTLE_ENDIAN ? 0xd301d202 : 0xd202d301,
10134                                 SImode));
10135   emit_move_insn (adjust_address (tramp_mem, SImode, 4),
10136                   gen_int_mode (TARGET_LITTLE_ENDIAN ? 0x0009422b : 0x422b0009,
10137                                 SImode));
10138   emit_move_insn (adjust_address (tramp_mem, SImode, 8), cxt);
10139   emit_move_insn (adjust_address (tramp_mem, SImode, 12), fnaddr);
10140   if (TARGET_HARVARD)
10141     {
10142       if (!TARGET_INLINE_IC_INVALIDATE
10143           || (!(TARGET_SH4A_ARCH || TARGET_SH4_300) && TARGET_USERMODE))
10144         emit_library_call (function_symbol (NULL, "__ic_invalidate",
10145                                             FUNCTION_ORDINARY),
10146                            LCT_NORMAL, VOIDmode, 1, tramp, SImode);
10147       else
10148         emit_insn (gen_ic_invalidate_line (tramp));
10149     }
10150 }
10151
10152 /* FIXME: This is overly conservative.  A SHcompact function that
10153    receives arguments ``by reference'' will have them stored in its
10154    own stack frame, so it must not pass pointers or references to
10155    these arguments to other functions by means of sibling calls.  */
10156 /* If PIC, we cannot make sibling calls to global functions
10157    because the PLT requires r12 to be live.  */
10158 static bool
10159 sh_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
10160 {
10161   return (1
10162           && (! TARGET_SHCOMPACT
10163               || crtl->args.info.stack_regs == 0)
10164           && ! sh_cfun_interrupt_handler_p ()
10165           && (! flag_pic
10166               || (decl && ! TREE_PUBLIC (decl))
10167               || (decl && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT)));
10168 }
10169 \f
10170 /* Machine specific built-in functions.  */
10171
10172 struct builtin_description
10173 {
10174   const enum insn_code icode;
10175   const char *const name;
10176   int signature;
10177 };
10178
10179 /* describe number and signedness of arguments; arg[0] == result
10180    (1: unsigned, 2: signed, 4: don't care, 8: pointer 0: no argument */
10181 /* 9: 64-bit pointer, 10: 32-bit pointer */
10182 static const char signature_args[][4] =
10183 {
10184 #define SH_BLTIN_V2SI2 0
10185   { 4, 4 },
10186 #define SH_BLTIN_V4HI2 1
10187   { 4, 4 },
10188 #define SH_BLTIN_V2SI3 2
10189   { 4, 4, 4 },
10190 #define SH_BLTIN_V4HI3 3
10191   { 4, 4, 4 },
10192 #define SH_BLTIN_V8QI3 4
10193   { 4, 4, 4 },
10194 #define SH_BLTIN_MAC_HISI 5
10195   { 1, 4, 4, 1 },
10196 #define SH_BLTIN_SH_HI 6
10197   { 4, 4, 1 },
10198 #define SH_BLTIN_SH_SI 7
10199   { 4, 4, 1 },
10200 #define SH_BLTIN_V4HI2V2SI 8
10201   { 4, 4, 4 },
10202 #define SH_BLTIN_V4HI2V8QI 9
10203   { 4, 4, 4 },
10204 #define SH_BLTIN_SISF 10
10205   { 4, 2 },
10206 #define SH_BLTIN_LDUA_L 11
10207   { 2, 10 },
10208 #define SH_BLTIN_LDUA_Q 12
10209   { 1, 10 },
10210 #define SH_BLTIN_STUA_L 13
10211   { 0, 10, 2 },
10212 #define SH_BLTIN_STUA_Q 14
10213   { 0, 10, 1 },
10214 #define SH_BLTIN_LDUA_L64 15
10215   { 2, 9 },
10216 #define SH_BLTIN_LDUA_Q64 16
10217   { 1, 9 },
10218 #define SH_BLTIN_STUA_L64 17
10219   { 0, 9, 2 },
10220 #define SH_BLTIN_STUA_Q64 18
10221   { 0, 9, 1 },
10222 #define SH_BLTIN_NUM_SHARED_SIGNATURES 19
10223 #define SH_BLTIN_2 19
10224 #define SH_BLTIN_SU 19
10225   { 1, 2 },
10226 #define SH_BLTIN_3 20
10227 #define SH_BLTIN_SUS 20
10228   { 2, 2, 1 },
10229 #define SH_BLTIN_PSSV 21
10230   { 0, 8, 2, 2 },
10231 #define SH_BLTIN_XXUU 22
10232 #define SH_BLTIN_UUUU 22
10233   { 1, 1, 1, 1 },
10234 #define SH_BLTIN_PV 23
10235   { 0, 8 },
10236 };
10237 /* mcmv: operands considered unsigned.  */
10238 /* mmulsum_wq, msad_ubq: result considered unsigned long long.  */
10239 /* mperm: control value considered unsigned int.  */
10240 /* mshalds, mshard, mshards, mshlld, mshlrd: shift count is unsigned int.  */
10241 /* mshards_q: returns signed short.  */
10242 /* nsb: takes long long arg, returns unsigned char.  */
10243 static const struct builtin_description bdesc[] =
10244 {
10245   { CODE_FOR_absv2si2,  "__builtin_absv2si2", SH_BLTIN_V2SI2 },
10246   { CODE_FOR_absv4hi2,  "__builtin_absv4hi2", SH_BLTIN_V4HI2 },
10247   { CODE_FOR_addv2si3,  "__builtin_addv2si3", SH_BLTIN_V2SI3 },
10248   { CODE_FOR_addv4hi3,  "__builtin_addv4hi3", SH_BLTIN_V4HI3 },
10249   { CODE_FOR_ssaddv2si3,"__builtin_ssaddv2si3", SH_BLTIN_V2SI3 },
10250   { CODE_FOR_usaddv8qi3,"__builtin_usaddv8qi3", SH_BLTIN_V8QI3 },
10251   { CODE_FOR_ssaddv4hi3,"__builtin_ssaddv4hi3", SH_BLTIN_V4HI3 },
10252   { CODE_FOR_alloco_i,  "__builtin_sh_media_ALLOCO", SH_BLTIN_PV },
10253   { CODE_FOR_negcmpeqv8qi,"__builtin_sh_media_MCMPEQ_B", SH_BLTIN_V8QI3 },
10254   { CODE_FOR_negcmpeqv2si,"__builtin_sh_media_MCMPEQ_L", SH_BLTIN_V2SI3 },
10255   { CODE_FOR_negcmpeqv4hi,"__builtin_sh_media_MCMPEQ_W", SH_BLTIN_V4HI3 },
10256   { CODE_FOR_negcmpgtuv8qi,"__builtin_sh_media_MCMPGT_UB", SH_BLTIN_V8QI3 },
10257   { CODE_FOR_negcmpgtv2si,"__builtin_sh_media_MCMPGT_L", SH_BLTIN_V2SI3 },
10258   { CODE_FOR_negcmpgtv4hi,"__builtin_sh_media_MCMPGT_W", SH_BLTIN_V4HI3 },
10259   { CODE_FOR_mcmv,      "__builtin_sh_media_MCMV", SH_BLTIN_UUUU },
10260   { CODE_FOR_mcnvs_lw,  "__builtin_sh_media_MCNVS_LW", SH_BLTIN_3 },
10261   { CODE_FOR_mcnvs_wb,  "__builtin_sh_media_MCNVS_WB", SH_BLTIN_V4HI2V8QI },
10262   { CODE_FOR_mcnvs_wub, "__builtin_sh_media_MCNVS_WUB", SH_BLTIN_V4HI2V8QI },
10263   { CODE_FOR_mextr1,    "__builtin_sh_media_MEXTR1", SH_BLTIN_V8QI3 },
10264   { CODE_FOR_mextr2,    "__builtin_sh_media_MEXTR2", SH_BLTIN_V8QI3 },
10265   { CODE_FOR_mextr3,    "__builtin_sh_media_MEXTR3", SH_BLTIN_V8QI3 },
10266   { CODE_FOR_mextr4,    "__builtin_sh_media_MEXTR4", SH_BLTIN_V8QI3 },
10267   { CODE_FOR_mextr5,    "__builtin_sh_media_MEXTR5", SH_BLTIN_V8QI3 },
10268   { CODE_FOR_mextr6,    "__builtin_sh_media_MEXTR6", SH_BLTIN_V8QI3 },
10269   { CODE_FOR_mextr7,    "__builtin_sh_media_MEXTR7", SH_BLTIN_V8QI3 },
10270   { CODE_FOR_mmacfx_wl, "__builtin_sh_media_MMACFX_WL", SH_BLTIN_MAC_HISI },
10271   { CODE_FOR_mmacnfx_wl,"__builtin_sh_media_MMACNFX_WL", SH_BLTIN_MAC_HISI },
10272   { CODE_FOR_mulv2si3,  "__builtin_mulv2si3", SH_BLTIN_V2SI3, },
10273   { CODE_FOR_mulv4hi3,  "__builtin_mulv4hi3", SH_BLTIN_V4HI3 },
10274   { CODE_FOR_mmulfx_l,  "__builtin_sh_media_MMULFX_L", SH_BLTIN_V2SI3 },
10275   { CODE_FOR_mmulfx_w,  "__builtin_sh_media_MMULFX_W", SH_BLTIN_V4HI3 },
10276   { CODE_FOR_mmulfxrp_w,"__builtin_sh_media_MMULFXRP_W", SH_BLTIN_V4HI3 },
10277   { CODE_FOR_mmulhi_wl, "__builtin_sh_media_MMULHI_WL", SH_BLTIN_V4HI2V2SI },
10278   { CODE_FOR_mmullo_wl, "__builtin_sh_media_MMULLO_WL", SH_BLTIN_V4HI2V2SI },
10279   { CODE_FOR_mmulsum_wq,"__builtin_sh_media_MMULSUM_WQ", SH_BLTIN_XXUU },
10280   { CODE_FOR_mperm_w,   "__builtin_sh_media_MPERM_W", SH_BLTIN_SH_HI },
10281   { CODE_FOR_msad_ubq,  "__builtin_sh_media_MSAD_UBQ", SH_BLTIN_XXUU },
10282   { CODE_FOR_mshalds_l, "__builtin_sh_media_MSHALDS_L", SH_BLTIN_SH_SI },
10283   { CODE_FOR_mshalds_w, "__builtin_sh_media_MSHALDS_W", SH_BLTIN_SH_HI },
10284   { CODE_FOR_ashrv2si3, "__builtin_ashrv2si3", SH_BLTIN_SH_SI },
10285   { CODE_FOR_ashrv4hi3, "__builtin_ashrv4hi3", SH_BLTIN_SH_HI },
10286   { CODE_FOR_mshards_q, "__builtin_sh_media_MSHARDS_Q", SH_BLTIN_SUS },
10287   { CODE_FOR_mshfhi_b,  "__builtin_sh_media_MSHFHI_B", SH_BLTIN_V8QI3 },
10288   { CODE_FOR_mshfhi_l,  "__builtin_sh_media_MSHFHI_L", SH_BLTIN_V2SI3 },
10289   { CODE_FOR_mshfhi_w,  "__builtin_sh_media_MSHFHI_W", SH_BLTIN_V4HI3 },
10290   { CODE_FOR_mshflo_b,  "__builtin_sh_media_MSHFLO_B", SH_BLTIN_V8QI3 },
10291   { CODE_FOR_mshflo_l,  "__builtin_sh_media_MSHFLO_L", SH_BLTIN_V2SI3 },
10292   { CODE_FOR_mshflo_w,  "__builtin_sh_media_MSHFLO_W", SH_BLTIN_V4HI3 },
10293   { CODE_FOR_ashlv2si3, "__builtin_ashlv2si3", SH_BLTIN_SH_SI },
10294   { CODE_FOR_ashlv4hi3, "__builtin_ashlv4hi3", SH_BLTIN_SH_HI },
10295   { CODE_FOR_lshrv2si3, "__builtin_lshrv2si3", SH_BLTIN_SH_SI },
10296   { CODE_FOR_lshrv4hi3, "__builtin_lshrv4hi3", SH_BLTIN_SH_HI },
10297   { CODE_FOR_subv2si3,  "__builtin_subv2si3", SH_BLTIN_V2SI3 },
10298   { CODE_FOR_subv4hi3,  "__builtin_subv4hi3", SH_BLTIN_V4HI3 },
10299   { CODE_FOR_sssubv2si3,"__builtin_sssubv2si3", SH_BLTIN_V2SI3 },
10300   { CODE_FOR_ussubv8qi3,"__builtin_ussubv8qi3", SH_BLTIN_V8QI3 },
10301   { CODE_FOR_sssubv4hi3,"__builtin_sssubv4hi3", SH_BLTIN_V4HI3 },
10302   { CODE_FOR_fcosa_s,   "__builtin_sh_media_FCOSA_S", SH_BLTIN_SISF },
10303   { CODE_FOR_fsina_s,   "__builtin_sh_media_FSINA_S", SH_BLTIN_SISF },
10304   { CODE_FOR_fipr,      "__builtin_sh_media_FIPR_S", SH_BLTIN_3 },
10305   { CODE_FOR_ftrv,      "__builtin_sh_media_FTRV_S", SH_BLTIN_3 },
10306   { CODE_FOR_mac_media, "__builtin_sh_media_FMAC_S", SH_BLTIN_3 },
10307   { CODE_FOR_sqrtdf2,   "__builtin_sh_media_FSQRT_D", SH_BLTIN_2 },
10308   { CODE_FOR_sqrtsf2,   "__builtin_sh_media_FSQRT_S", SH_BLTIN_2 },
10309   { CODE_FOR_fsrra_s,   "__builtin_sh_media_FSRRA_S", SH_BLTIN_2 },
10310   { CODE_FOR_ldhi_l,    "__builtin_sh_media_LDHI_L", SH_BLTIN_LDUA_L },
10311   { CODE_FOR_ldhi_q,    "__builtin_sh_media_LDHI_Q", SH_BLTIN_LDUA_Q },
10312   { CODE_FOR_ldlo_l,    "__builtin_sh_media_LDLO_L", SH_BLTIN_LDUA_L },
10313   { CODE_FOR_ldlo_q,    "__builtin_sh_media_LDLO_Q", SH_BLTIN_LDUA_Q },
10314   { CODE_FOR_sthi_l,    "__builtin_sh_media_STHI_L", SH_BLTIN_STUA_L },
10315   { CODE_FOR_sthi_q,    "__builtin_sh_media_STHI_Q", SH_BLTIN_STUA_Q },
10316   { CODE_FOR_stlo_l,    "__builtin_sh_media_STLO_L", SH_BLTIN_STUA_L },
10317   { CODE_FOR_stlo_q,    "__builtin_sh_media_STLO_Q", SH_BLTIN_STUA_Q },
10318   { CODE_FOR_ldhi_l64,  "__builtin_sh_media_LDHI_L", SH_BLTIN_LDUA_L64 },
10319   { CODE_FOR_ldhi_q64,  "__builtin_sh_media_LDHI_Q", SH_BLTIN_LDUA_Q64 },
10320   { CODE_FOR_ldlo_l64,  "__builtin_sh_media_LDLO_L", SH_BLTIN_LDUA_L64 },
10321   { CODE_FOR_ldlo_q64,  "__builtin_sh_media_LDLO_Q", SH_BLTIN_LDUA_Q64 },
10322   { CODE_FOR_sthi_l64,  "__builtin_sh_media_STHI_L", SH_BLTIN_STUA_L64 },
10323   { CODE_FOR_sthi_q64,  "__builtin_sh_media_STHI_Q", SH_BLTIN_STUA_Q64 },
10324   { CODE_FOR_stlo_l64,  "__builtin_sh_media_STLO_L", SH_BLTIN_STUA_L64 },
10325   { CODE_FOR_stlo_q64,  "__builtin_sh_media_STLO_Q", SH_BLTIN_STUA_Q64 },
10326   { CODE_FOR_nsb,       "__builtin_sh_media_NSB", SH_BLTIN_SU },
10327   { CODE_FOR_byterev,   "__builtin_sh_media_BYTEREV", SH_BLTIN_2 },
10328   { CODE_FOR_prefetch,  "__builtin_sh_media_PREFO", SH_BLTIN_PSSV },
10329 };
10330
10331 static void
10332 sh_media_init_builtins (void)
10333 {
10334   tree shared[SH_BLTIN_NUM_SHARED_SIGNATURES];
10335   const struct builtin_description *d;
10336
10337   memset (shared, 0, sizeof shared);
10338   for (d = bdesc; d - bdesc < (int) ARRAY_SIZE (bdesc); d++)
10339     {
10340       tree type, arg_type = 0;
10341       int signature = d->signature;
10342       int i;
10343
10344       if (signature < SH_BLTIN_NUM_SHARED_SIGNATURES && shared[signature])
10345         type = shared[signature];
10346       else
10347         {
10348           int has_result = signature_args[signature][0] != 0;
10349
10350           if ((signature_args[signature][1] & 8)
10351               && (((signature_args[signature][1] & 1) && TARGET_SHMEDIA32)
10352                   || ((signature_args[signature][1] & 2) && TARGET_SHMEDIA64)))
10353             continue;
10354           if (! TARGET_FPU_ANY
10355               && FLOAT_MODE_P (insn_data[d->icode].operand[0].mode))
10356             continue;
10357           type = void_list_node;
10358           for (i = 3; ; i--)
10359             {
10360               int arg = signature_args[signature][i];
10361               int opno = i - 1 + has_result;
10362
10363               if (arg & 8)
10364                 arg_type = ptr_type_node;
10365               else if (arg)
10366                 arg_type = (*lang_hooks.types.type_for_mode)
10367                   (insn_data[d->icode].operand[opno].mode,
10368                    (arg & 1));
10369               else if (i)
10370                 continue;
10371               else
10372                 arg_type = void_type_node;
10373               if (i == 0)
10374                 break;
10375               type = tree_cons (NULL_TREE, arg_type, type);
10376             }
10377           type = build_function_type (arg_type, type);
10378           if (signature < SH_BLTIN_NUM_SHARED_SIGNATURES)
10379             shared[signature] = type;
10380         }
10381       add_builtin_function (d->name, type, d - bdesc, BUILT_IN_MD,
10382                             NULL, NULL_TREE);
10383     }
10384 }
10385
10386 /* Implements target hook vector_mode_supported_p.  */
10387 bool
10388 sh_vector_mode_supported_p (enum machine_mode mode)
10389 {
10390   if (TARGET_FPU_ANY
10391       && ((mode == V2SFmode)
10392           || (mode == V4SFmode)
10393           || (mode == V16SFmode)))
10394     return true;
10395
10396   else if (TARGET_SHMEDIA
10397            && ((mode == V8QImode)
10398                || (mode == V2HImode)
10399                || (mode == V4HImode)
10400                || (mode == V2SImode)))
10401     return true;
10402
10403   return false;
10404 }
10405
10406 /* Implements target hook dwarf_calling_convention.  Return an enum
10407    of dwarf_calling_convention.  */
10408 int
10409 sh_dwarf_calling_convention (const_tree func)
10410 {
10411   if (sh_attr_renesas_p (func))
10412     return DW_CC_GNU_renesas_sh;
10413
10414   return DW_CC_normal;
10415 }
10416
10417 static void
10418 sh_init_builtins (void)
10419 {
10420   if (TARGET_SHMEDIA)
10421     sh_media_init_builtins ();
10422 }
10423
10424 /* Expand an expression EXP that calls a built-in function,
10425    with result going to TARGET if that's convenient
10426    (and in mode MODE if that's convenient).
10427    SUBTARGET may be used as the target for computing one of EXP's operands.
10428    IGNORE is nonzero if the value is to be ignored.  */
10429
10430 static rtx
10431 sh_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
10432                    enum machine_mode mode ATTRIBUTE_UNUSED, int ignore)
10433 {
10434   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
10435   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
10436   const struct builtin_description *d = &bdesc[fcode];
10437   enum insn_code icode = d->icode;
10438   int signature = d->signature;
10439   enum machine_mode tmode = VOIDmode;
10440   int nop = 0, i;
10441   rtx op[4];
10442   rtx pat = 0;
10443
10444   if (signature_args[signature][0])
10445     {
10446       if (ignore)
10447         return 0;
10448
10449       tmode = insn_data[icode].operand[0].mode;
10450       if (! target
10451           || GET_MODE (target) != tmode
10452           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
10453         target = gen_reg_rtx (tmode);
10454       op[nop++] = target;
10455     }
10456   else
10457     target = 0;
10458
10459   for (i = 1; i <= 3; i++, nop++)
10460     {
10461       tree arg;
10462       enum machine_mode opmode, argmode;
10463       tree optype;
10464
10465       if (! signature_args[signature][i])
10466         break;
10467       arg = CALL_EXPR_ARG (exp, i - 1);
10468       if (arg == error_mark_node)
10469         return const0_rtx;
10470       if (signature_args[signature][i] & 8)
10471         {
10472           opmode = ptr_mode;
10473           optype = ptr_type_node;
10474         }
10475       else
10476         {
10477           opmode = insn_data[icode].operand[nop].mode;
10478           optype = (*lang_hooks.types.type_for_mode) (opmode, 0);
10479         }
10480       argmode = TYPE_MODE (TREE_TYPE (arg));
10481       if (argmode != opmode)
10482         arg = build1 (NOP_EXPR, optype, arg);
10483       op[nop] = expand_expr (arg, NULL_RTX, opmode, EXPAND_NORMAL);
10484       if (! (*insn_data[icode].operand[nop].predicate) (op[nop], opmode))
10485         op[nop] = copy_to_mode_reg (opmode, op[nop]);
10486     }
10487
10488   switch (nop)
10489     {
10490     case 1:
10491       pat = (*insn_data[d->icode].genfun) (op[0]);
10492       break;
10493     case 2:
10494       pat = (*insn_data[d->icode].genfun) (op[0], op[1]);
10495       break;
10496     case 3:
10497       pat = (*insn_data[d->icode].genfun) (op[0], op[1], op[2]);
10498       break;
10499     case 4:
10500       pat = (*insn_data[d->icode].genfun) (op[0], op[1], op[2], op[3]);
10501       break;
10502     default:
10503       gcc_unreachable ();
10504     }
10505   if (! pat)
10506     return 0;
10507   emit_insn (pat);
10508   return target;
10509 }
10510
10511 void
10512 sh_expand_unop_v2sf (enum rtx_code code, rtx op0, rtx op1)
10513 {
10514   rtx sel0 = const0_rtx;
10515   rtx sel1 = const1_rtx;
10516   rtx (*fn) (rtx, rtx, rtx, rtx, rtx) = gen_unary_sf_op;
10517   rtx op = gen_rtx_fmt_e (code, SFmode, op1);
10518
10519   emit_insn ((*fn) (op0, op1, op, sel0, sel0));
10520   emit_insn ((*fn) (op0, op1, op, sel1, sel1));
10521 }
10522
10523 void
10524 sh_expand_binop_v2sf (enum rtx_code code, rtx op0, rtx op1, rtx op2)
10525 {
10526   rtx op = gen_rtx_fmt_ee (code, SFmode, op1, op2);
10527
10528   emit_insn (gen_binary_sf_op0 (op0, op1, op2, op));
10529   emit_insn (gen_binary_sf_op1 (op0, op1, op2, op));
10530 }
10531
10532 /* Return true if hard register REGNO can hold a value of machine-mode MODE.
10533    We can allow any mode in any general register.  The special registers
10534    only allow SImode.  Don't allow any mode in the PR.
10535
10536    We cannot hold DCmode values in the XD registers because alter_reg
10537    handles subregs of them incorrectly.  We could work around this by
10538    spacing the XD registers like the DR registers, but this would require
10539    additional memory in every compilation to hold larger register vectors.
10540    We could hold SFmode / SCmode values in XD registers, but that
10541    would require a tertiary reload when reloading from / to memory,
10542    and a secondary reload to reload from / to general regs; that
10543    seems to be a loosing proposition.
10544
10545    We want to allow TImode FP regs so that when V4SFmode is loaded as TImode,
10546    it won't be ferried through GP registers first.  */
10547
10548 bool
10549 sh_hard_regno_mode_ok (unsigned int regno, enum machine_mode mode)
10550 {
10551   if (SPECIAL_REGISTER_P (regno))
10552     return mode == SImode;
10553
10554   if (regno == FPUL_REG)
10555     return (mode == SImode || mode == SFmode);
10556
10557   if (FP_REGISTER_P (regno) && mode == SFmode)
10558     return true;
10559
10560   if (mode == V2SFmode)
10561     {
10562       if (((FP_REGISTER_P (regno) && (regno - FIRST_FP_REG) % 2 == 0)
10563            || GENERAL_REGISTER_P (regno)))
10564         return true;
10565       else
10566         return false;
10567     }
10568
10569   if (mode == V4SFmode)
10570     {
10571       if ((FP_REGISTER_P (regno) && (regno - FIRST_FP_REG) % 4 == 0)
10572           || GENERAL_REGISTER_P (regno))
10573         return true;
10574       else
10575         return false;
10576     }
10577
10578   if (mode == V16SFmode)
10579     {
10580       if (TARGET_SHMEDIA)
10581         {
10582           if (FP_REGISTER_P (regno) && (regno - FIRST_FP_REG) % 16 == 0)
10583             return true;
10584           else
10585             return false;
10586         }
10587       else
10588         return regno == FIRST_XD_REG;
10589     }
10590
10591   if (FP_REGISTER_P (regno))
10592     {
10593       if (mode == SFmode
10594           || mode == SImode
10595           || ((TARGET_SH2E || TARGET_SHMEDIA) && mode == SCmode)
10596           || ((((TARGET_SH4 || TARGET_SH2A_DOUBLE) && mode == DFmode)
10597                || mode == DCmode
10598                || (TARGET_SHMEDIA
10599                    && (mode == DFmode || mode == DImode
10600                        || mode == V2SFmode || mode == TImode)))
10601               && ((regno - FIRST_FP_REG) & 1) == 0)
10602           || ((TARGET_SH4 || TARGET_SHMEDIA) && mode == TImode
10603               && ((regno - FIRST_FP_REG) & 3) == 0))
10604         return true;
10605       else
10606         return false;
10607     }
10608
10609   if (XD_REGISTER_P (regno))
10610     return mode == DFmode;
10611
10612   if (TARGET_REGISTER_P (regno))
10613     return (mode == DImode || mode == SImode || mode == PDImode);
10614
10615   if (regno == PR_REG)
10616     return mode == SImode;
10617
10618   if (regno == FPSCR_REG)
10619     return mode == PSImode;
10620
10621   /* FIXME.  This works around PR target/37633 for -O0.  */
10622   if (!optimize && TARGET_SHMEDIA32 && GET_MODE_SIZE (mode) > 4)
10623     {
10624       unsigned int n = GET_MODE_SIZE (mode) / 8;
10625
10626       if (regno >= FIRST_GENERAL_REG + 10 - n + 1
10627           && regno <= FIRST_GENERAL_REG + 14)
10628         return false;
10629     }
10630
10631   return true;
10632 }
10633
10634 /* Return the class of registers for which a mode change from FROM to TO
10635    is invalid.  */
10636 bool
10637 sh_cannot_change_mode_class (enum machine_mode from, enum machine_mode to,
10638                              enum reg_class rclass)
10639 {
10640   /* We want to enable the use of SUBREGs as a means to
10641      VEC_SELECT a single element of a vector.  */
10642   if (to == SFmode && VECTOR_MODE_P (from) && GET_MODE_INNER (from) == SFmode)
10643     return (reg_classes_intersect_p (GENERAL_REGS, rclass));
10644
10645   if (GET_MODE_SIZE (from) != GET_MODE_SIZE (to))
10646     {
10647       if (TARGET_LITTLE_ENDIAN)
10648         {
10649           if (GET_MODE_SIZE (to) < 8 || GET_MODE_SIZE (from) < 8)
10650             return reg_classes_intersect_p (DF_REGS, rclass);
10651         }
10652       else
10653         {
10654           if (GET_MODE_SIZE (from) < 8)
10655             return reg_classes_intersect_p (DF_HI_REGS, rclass);
10656         }
10657     }
10658   return 0;
10659 }
10660
10661
10662 /* If ADDRESS refers to a CODE_LABEL, add NUSES to the number of times
10663    that label is used.  */
10664
10665 void
10666 sh_mark_label (rtx address, int nuses)
10667 {
10668   if (GOTOFF_P (address))
10669     {
10670       /* Extract the label or symbol.  */
10671       address = XEXP (address, 0);
10672       if (GET_CODE (address) == PLUS)
10673         address = XEXP (address, 0);
10674       address = XVECEXP (address, 0, 0);
10675     }
10676   if (GET_CODE (address) == LABEL_REF
10677       && GET_CODE (XEXP (address, 0)) == CODE_LABEL)
10678     LABEL_NUSES (XEXP (address, 0)) += nuses;
10679 }
10680
10681 /* Compute extra cost of moving data between one register class
10682    and another.  */
10683
10684 /* If SECONDARY*_RELOAD_CLASS says something about the src/dst pair, regclass
10685    uses this information.  Hence, the general register <-> floating point
10686    register information here is not used for SFmode.  */
10687
10688 int
10689 sh_register_move_cost (enum machine_mode mode,
10690                        enum reg_class srcclass, enum reg_class dstclass)
10691 {
10692   if (dstclass == T_REGS || dstclass == PR_REGS)
10693     return 10;
10694
10695   if (dstclass == MAC_REGS && srcclass == MAC_REGS)
10696     return 4;
10697
10698   if (mode == SImode && ! TARGET_SHMEDIA && TARGET_FMOVD
10699       && REGCLASS_HAS_FP_REG (srcclass)
10700       && REGCLASS_HAS_FP_REG (dstclass))
10701     return 4;
10702
10703   if (REGCLASS_HAS_FP_REG (dstclass) && srcclass == T_REGS)
10704     return ((TARGET_HARD_SH4 && !optimize_size) ? 10 : 7);
10705
10706   if ((REGCLASS_HAS_FP_REG (dstclass) && srcclass == MAC_REGS)
10707       || (dstclass == MAC_REGS && REGCLASS_HAS_FP_REG (srcclass)))
10708     return 9;
10709
10710   if ((REGCLASS_HAS_FP_REG (dstclass)
10711        && REGCLASS_HAS_GENERAL_REG (srcclass))
10712       || (REGCLASS_HAS_GENERAL_REG (dstclass)
10713           && REGCLASS_HAS_FP_REG (srcclass)))
10714     return ((TARGET_SHMEDIA ? 4 : TARGET_FMOVD ? 8 : 12)
10715             * ((GET_MODE_SIZE (mode) + 7) / 8U));
10716
10717   if ((dstclass == FPUL_REGS
10718        && REGCLASS_HAS_GENERAL_REG (srcclass))
10719       || (srcclass == FPUL_REGS
10720           && REGCLASS_HAS_GENERAL_REG (dstclass)))
10721     return 5;
10722
10723   if ((dstclass == FPUL_REGS
10724        && (srcclass == PR_REGS || srcclass == MAC_REGS || srcclass == T_REGS))
10725       || (srcclass == FPUL_REGS
10726           && (dstclass == PR_REGS || dstclass == MAC_REGS)))
10727     return 7;
10728
10729   if ((srcclass == TARGET_REGS && ! REGCLASS_HAS_GENERAL_REG (dstclass))
10730       || ((dstclass) == TARGET_REGS && ! REGCLASS_HAS_GENERAL_REG (srcclass)))
10731     return 20;
10732
10733   /* ??? ptabs faults on (value & 0x3) == 0x3  */
10734   if (TARGET_SHMEDIA
10735       && ((srcclass) == TARGET_REGS || (srcclass) == SIBCALL_REGS))
10736     {
10737       if (sh_gettrcost >= 0)
10738         return sh_gettrcost;
10739       else if (!TARGET_PT_FIXED)
10740         return 100;
10741     }
10742
10743   if ((srcclass == FPSCR_REGS && ! REGCLASS_HAS_GENERAL_REG (dstclass))
10744       || (dstclass == FPSCR_REGS && ! REGCLASS_HAS_GENERAL_REG (srcclass)))
10745   return 4;
10746
10747   if (TARGET_SHMEDIA
10748       || (TARGET_FMOVD
10749           && ! REGCLASS_HAS_GENERAL_REG (srcclass)
10750           && ! REGCLASS_HAS_GENERAL_REG (dstclass)))
10751     return 2 * ((GET_MODE_SIZE (mode) + 7) / 8U);
10752
10753   return 2 * ((GET_MODE_SIZE (mode) + 3) / 4U);
10754 }
10755
10756 static rtx emit_load_ptr (rtx, rtx);
10757
10758 static rtx
10759 emit_load_ptr (rtx reg, rtx addr)
10760 {
10761   rtx mem = gen_const_mem (ptr_mode, addr);
10762
10763   if (Pmode != ptr_mode)
10764     mem = gen_rtx_SIGN_EXTEND (Pmode, mem);
10765   return emit_move_insn (reg, mem);
10766 }
10767
10768 static void
10769 sh_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
10770                     HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
10771                     tree function)
10772 {
10773   CUMULATIVE_ARGS cum;
10774   int structure_value_byref = 0;
10775   rtx this_rtx, this_value, sibcall, insns, funexp;
10776   tree funtype = TREE_TYPE (function);
10777   int simple_add = CONST_OK_FOR_ADD (delta);
10778   int did_load = 0;
10779   rtx scratch0, scratch1, scratch2;
10780   unsigned i;
10781
10782   reload_completed = 1;
10783   epilogue_completed = 1;
10784   current_function_uses_only_leaf_regs = 1;
10785
10786   emit_note (NOTE_INSN_PROLOGUE_END);
10787
10788   /* Find the "this" pointer.  We have such a wide range of ABIs for the
10789      SH that it's best to do this completely machine independently.
10790      "this" is passed as first argument, unless a structure return pointer
10791      comes first, in which case "this" comes second.  */
10792   INIT_CUMULATIVE_ARGS (cum, funtype, NULL_RTX, 0, 1);
10793 #ifndef PCC_STATIC_STRUCT_RETURN
10794   if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
10795     structure_value_byref = 1;
10796 #endif /* not PCC_STATIC_STRUCT_RETURN */
10797   if (structure_value_byref && sh_struct_value_rtx (function, 0) == 0)
10798     {
10799       tree ptype = build_pointer_type (TREE_TYPE (funtype));
10800
10801       FUNCTION_ARG_ADVANCE (cum, Pmode, ptype, 1);
10802     }
10803   this_rtx = FUNCTION_ARG (cum, Pmode, ptr_type_node, 1);
10804
10805   /* For SHcompact, we only have r0 for a scratch register: r1 is the
10806      static chain pointer (even if you can't have nested virtual functions
10807      right now, someone might implement them sometime), and the rest of the
10808      registers are used for argument passing, are callee-saved, or reserved.  */
10809   /* We need to check call_used_regs / fixed_regs in case -fcall_saved-reg /
10810      -ffixed-reg has been used.  */
10811   if (! call_used_regs[0] || fixed_regs[0])
10812     error ("r0 needs to be available as a call-clobbered register");
10813   scratch0 = scratch1 = scratch2 = gen_rtx_REG (Pmode, 0);
10814   if (! TARGET_SH5)
10815     {
10816       if (call_used_regs[1] && ! fixed_regs[1])
10817         scratch1 = gen_rtx_REG (ptr_mode, 1);
10818       /* N.B., if not TARGET_HITACHI, register 2 is used to pass the pointer
10819          pointing where to return struct values.  */
10820       if (call_used_regs[3] && ! fixed_regs[3])
10821         scratch2 = gen_rtx_REG (Pmode, 3);
10822     }
10823   else if (TARGET_SHMEDIA)
10824     {
10825       for (i = FIRST_GENERAL_REG; i <= LAST_GENERAL_REG; i++)
10826         if (i != REGNO (scratch0) &&
10827             call_used_regs[i] && ! fixed_regs[i] && ! FUNCTION_ARG_REGNO_P (i))
10828           {
10829             scratch1 = gen_rtx_REG (ptr_mode, i);
10830             break;
10831           }
10832       if (scratch1 == scratch0)
10833         error ("Need a second call-clobbered general purpose register");
10834       for (i = FIRST_TARGET_REG; i <= LAST_TARGET_REG; i++)
10835         if (call_used_regs[i] && ! fixed_regs[i])
10836           {
10837             scratch2 = gen_rtx_REG (Pmode, i);
10838             break;
10839           }
10840       if (scratch2 == scratch0)
10841         error ("Need a call-clobbered target register");
10842     }
10843
10844   this_value = plus_constant (this_rtx, delta);
10845   if (vcall_offset
10846       && (simple_add || scratch0 != scratch1)
10847       && strict_memory_address_p (ptr_mode, this_value))
10848     {
10849       emit_load_ptr (scratch0, this_value);
10850       did_load = 1;
10851     }
10852
10853   if (!delta)
10854     ; /* Do nothing.  */
10855   else if (simple_add)
10856     emit_move_insn (this_rtx, this_value);
10857   else
10858     {
10859       emit_move_insn (scratch1, GEN_INT (delta));
10860       emit_insn (gen_add2_insn (this_rtx, scratch1));
10861     }
10862
10863   if (vcall_offset)
10864     {
10865       rtx offset_addr;
10866
10867       if (!did_load)
10868         emit_load_ptr (scratch0, this_rtx);
10869
10870       offset_addr = plus_constant (scratch0, vcall_offset);
10871       if (strict_memory_address_p (ptr_mode, offset_addr))
10872         ; /* Do nothing.  */
10873       else if (! TARGET_SH5 && scratch0 != scratch1)
10874         {
10875           /* scratch0 != scratch1, and we have indexed loads.  Get better
10876              schedule by loading the offset into r1 and using an indexed
10877              load - then the load of r1 can issue before the load from
10878              (this_rtx + delta) finishes.  */
10879           emit_move_insn (scratch1, GEN_INT (vcall_offset));
10880           offset_addr = gen_rtx_PLUS (Pmode, scratch0, scratch1);
10881         }
10882       else if (CONST_OK_FOR_ADD (vcall_offset))
10883         {
10884           emit_insn (gen_add2_insn (scratch0, GEN_INT (vcall_offset)));
10885           offset_addr = scratch0;
10886         }
10887       else if (scratch0 != scratch1)
10888         {
10889           emit_move_insn (scratch1, GEN_INT (vcall_offset));
10890           emit_insn (gen_add2_insn (scratch0, scratch1));
10891           offset_addr = scratch0;
10892         }
10893       else
10894         gcc_unreachable (); /* FIXME */
10895       emit_load_ptr (scratch0, offset_addr);
10896
10897       if (Pmode != ptr_mode)
10898         scratch0 = gen_rtx_TRUNCATE (ptr_mode, scratch0);
10899       emit_insn (gen_add2_insn (this_rtx, scratch0));
10900     }
10901
10902   /* Generate a tail call to the target function.  */
10903   if (! TREE_USED (function))
10904     {
10905       assemble_external (function);
10906       TREE_USED (function) = 1;
10907     }
10908   funexp = XEXP (DECL_RTL (function), 0);
10909   /* If the function is overridden, so is the thunk, hence we don't
10910      need GOT addressing even if this is a public symbol.  */
10911 #if 0
10912   if (TARGET_SH1 && ! flag_weak)
10913     sibcall = gen_sibcalli_thunk (funexp, const0_rtx);
10914   else
10915 #endif
10916   if (TARGET_SH2 && flag_pic)
10917     {
10918       sibcall = gen_sibcall_pcrel (funexp, const0_rtx);
10919       XEXP (XVECEXP (sibcall, 0, 2), 0) = scratch2;
10920     }
10921   else
10922     {
10923       if (TARGET_SHMEDIA && flag_pic)
10924         {
10925           funexp = gen_sym2PIC (funexp);
10926           PUT_MODE (funexp, Pmode);
10927         }
10928       emit_move_insn (scratch2, funexp);
10929       funexp = gen_rtx_MEM (FUNCTION_MODE, scratch2);
10930       sibcall = gen_sibcall (funexp, const0_rtx, NULL_RTX);
10931     }
10932   sibcall = emit_call_insn (sibcall);
10933   SIBLING_CALL_P (sibcall) = 1;
10934   use_reg (&CALL_INSN_FUNCTION_USAGE (sibcall), this_rtx);
10935   emit_barrier ();
10936
10937   /* Run just enough of rest_of_compilation to do scheduling and get
10938      the insns emitted.  Note that use_thunk calls
10939      assemble_start_function and assemble_end_function.  */
10940
10941   insn_locators_alloc ();
10942   insns = get_insns ();
10943
10944   if (optimize > 0)
10945     {
10946       if (! cfun->cfg)
10947         init_flow (cfun);
10948       split_all_insns_noflow ();
10949     }
10950
10951   sh_reorg ();
10952
10953   if (optimize > 0 && flag_delayed_branch)
10954     dbr_schedule (insns);
10955
10956   shorten_branches (insns);
10957   final_start_function (insns, file, 1);
10958   final (insns, file, 1);
10959   final_end_function ();
10960   free_after_compilation (cfun);
10961
10962   reload_completed = 0;
10963   epilogue_completed = 0;
10964 }
10965
10966 rtx
10967 function_symbol (rtx target, const char *name, enum sh_function_kind kind)
10968 {
10969   rtx sym;
10970
10971   /* If this is not an ordinary function, the name usually comes from a
10972      string literal or an sprintf buffer.  Make sure we use the same
10973      string consistently, so that cse will be able to unify address loads.  */
10974   if (kind != FUNCTION_ORDINARY)
10975     name = IDENTIFIER_POINTER (get_identifier (name));
10976   sym = gen_rtx_SYMBOL_REF (Pmode, name);
10977   SYMBOL_REF_FLAGS (sym) = SYMBOL_FLAG_FUNCTION;
10978   if (flag_pic)
10979     switch (kind)
10980       {
10981       case FUNCTION_ORDINARY:
10982         break;
10983       case SFUNC_GOT:
10984         {
10985           rtx reg = target ? target : gen_reg_rtx (Pmode);
10986
10987           emit_insn (gen_symGOT2reg (reg, sym));
10988           sym = reg;
10989           break;
10990         }
10991       case SFUNC_STATIC:
10992         {
10993           /* ??? To allow cse to work, we use GOTOFF relocations.
10994              we could add combiner patterns to transform this into
10995              straight pc-relative calls with sym2PIC / bsrf when
10996              label load and function call are still 1:1 and in the
10997              same basic block during combine.  */
10998           rtx reg = target ? target : gen_reg_rtx (Pmode);
10999
11000           emit_insn (gen_symGOTOFF2reg (reg, sym));
11001           sym = reg;
11002           break;
11003         }
11004       }
11005   if (target && sym != target)
11006     {
11007       emit_move_insn (target, sym);
11008       return target;
11009     }
11010   return sym;
11011 }
11012
11013 /* Find the number of a general purpose register in S.  */
11014 static int
11015 scavenge_reg (HARD_REG_SET *s)
11016 {
11017   int r;
11018   for (r = FIRST_GENERAL_REG; r <= LAST_GENERAL_REG; r++)
11019     if (TEST_HARD_REG_BIT (*s, r))
11020       return r;
11021   return -1;
11022 }
11023
11024 rtx
11025 sh_get_pr_initial_val (void)
11026 {
11027   rtx val;
11028
11029   /* ??? Unfortunately, get_hard_reg_initial_val doesn't always work for the
11030      PR register on SHcompact, because it might be clobbered by the prologue.
11031      We check first if that is known to be the case.  */
11032   if (TARGET_SHCOMPACT
11033       && ((crtl->args.info.call_cookie
11034            & ~ CALL_COOKIE_RET_TRAMP (1))
11035           || crtl->saves_all_registers))
11036     return gen_frame_mem (SImode, return_address_pointer_rtx);
11037
11038   /* If we haven't finished rtl generation, there might be a nonlocal label
11039      that we haven't seen yet.
11040      ??? get_hard_reg_initial_val fails if it is called after register
11041      allocation has started, unless it has been called before for the
11042      same register.  And even then, we end in trouble if we didn't use
11043      the register in the same basic block before.  So call
11044      get_hard_reg_initial_val now and wrap it in an unspec if we might
11045      need to replace it.  */
11046   /* ??? We also must do this for TARGET_SH1 in general, because otherwise
11047      combine can put the pseudo returned by get_hard_reg_initial_val into
11048      instructions that need a general purpose registers, which will fail to
11049      be recognized when the pseudo becomes allocated to PR.  */
11050   val
11051     = get_hard_reg_initial_val (Pmode, TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG);
11052   if (TARGET_SH1)
11053     return gen_rtx_UNSPEC (SImode, gen_rtvec (1, val), UNSPEC_RA);
11054   return val;
11055 }
11056
11057 int
11058 sh_expand_t_scc (rtx operands[])
11059 {
11060   enum rtx_code code = GET_CODE (operands[1]);
11061   rtx target = operands[0];
11062   rtx op0 = operands[2];
11063   rtx op1 = operands[3];
11064   rtx result = target;
11065   HOST_WIDE_INT val;
11066
11067   if (GET_CODE (op0) != REG || REGNO (op0) != T_REG
11068       || GET_CODE (op1) != CONST_INT)
11069     return 0;
11070   if (GET_CODE (result) != REG)
11071     result = gen_reg_rtx (SImode);
11072   val = INTVAL (op1);
11073   if ((code == EQ && val == 1) || (code == NE && val == 0))
11074     emit_insn (gen_movt (result));
11075   else if (TARGET_SH2A && ((code == EQ && val == 0)
11076                             || (code == NE && val == 1)))
11077     emit_insn (gen_movrt (result));
11078   else if ((code == EQ && val == 0) || (code == NE && val == 1))
11079     {
11080       emit_clobber (result);
11081       emit_insn (gen_subc (result, result, result));
11082       emit_insn (gen_addsi3 (result, result, const1_rtx));
11083     }
11084   else if (code == EQ || code == NE)
11085     emit_insn (gen_move_insn (result, GEN_INT (code == NE)));
11086   else
11087     return 0;
11088   if (result != target)
11089     emit_move_insn (target, result);
11090   return 1;
11091 }
11092
11093 /* INSN is an sfunc; return the rtx that describes the address used.  */
11094 static rtx
11095 extract_sfunc_addr (rtx insn)
11096 {
11097   rtx pattern, part = NULL_RTX;
11098   int len, i;
11099
11100   pattern = PATTERN (insn);
11101   len = XVECLEN (pattern, 0);
11102   for (i = 0; i < len; i++)
11103     {
11104       part = XVECEXP (pattern, 0, i);
11105       if (GET_CODE (part) == USE && GET_MODE (XEXP (part, 0)) == Pmode
11106           && GENERAL_REGISTER_P (true_regnum (XEXP (part, 0))))
11107         return XEXP (part, 0);
11108     }
11109   gcc_assert (GET_CODE (XVECEXP (pattern, 0, 0)) == UNSPEC_VOLATILE);
11110   return XVECEXP (XVECEXP (pattern, 0, 0), 0, 1);
11111 }
11112
11113 /* Verify that the register in use_sfunc_addr still agrees with the address
11114    used in the sfunc.  This prevents fill_slots_from_thread from changing
11115    use_sfunc_addr.
11116    INSN is the use_sfunc_addr instruction, and REG is the register it
11117    guards.  */
11118 int
11119 check_use_sfunc_addr (rtx insn, rtx reg)
11120 {
11121   /* Search for the sfunc.  It should really come right after INSN.  */
11122   while ((insn = NEXT_INSN (insn)))
11123     {
11124       if (GET_CODE (insn) == CODE_LABEL || GET_CODE (insn) == JUMP_INSN)
11125         break;
11126       if (! INSN_P (insn))
11127         continue;
11128
11129       if (GET_CODE (PATTERN (insn)) == SEQUENCE)
11130         insn = XVECEXP (PATTERN (insn), 0, 0);
11131       if (GET_CODE (PATTERN (insn)) != PARALLEL
11132           || get_attr_type (insn) != TYPE_SFUNC)
11133         continue;
11134       return rtx_equal_p (extract_sfunc_addr (insn), reg);
11135     }
11136   gcc_unreachable ();
11137 }
11138
11139 /* This function returns a constant rtx that represents pi / 2**15 in
11140    SFmode.  it's used to scale SFmode angles, in radians, to a
11141    fixed-point signed 16.16-bit fraction of a full circle, i.e., 2*pi
11142    maps to 0x10000).  */
11143
11144 static GTY(()) rtx sh_fsca_sf2int_rtx;
11145
11146 rtx
11147 sh_fsca_sf2int (void)
11148 {
11149   if (! sh_fsca_sf2int_rtx)
11150     {
11151       REAL_VALUE_TYPE rv;
11152
11153       real_from_string (&rv, "10430.378350470453");
11154       sh_fsca_sf2int_rtx = const_double_from_real_value (rv, SFmode);
11155     }
11156
11157   return sh_fsca_sf2int_rtx;
11158 }
11159
11160 /* This function returns a constant rtx that represents pi / 2**15 in
11161    DFmode.  it's used to scale DFmode angles, in radians, to a
11162    fixed-point signed 16.16-bit fraction of a full circle, i.e., 2*pi
11163    maps to 0x10000).  */
11164
11165 static GTY(()) rtx sh_fsca_df2int_rtx;
11166
11167 rtx
11168 sh_fsca_df2int (void)
11169 {
11170   if (! sh_fsca_df2int_rtx)
11171     {
11172       REAL_VALUE_TYPE rv;
11173
11174       real_from_string (&rv, "10430.378350470453");
11175       sh_fsca_df2int_rtx = const_double_from_real_value (rv, DFmode);
11176     }
11177
11178   return sh_fsca_df2int_rtx;
11179 }
11180
11181 /* This function returns a constant rtx that represents 2**15 / pi in
11182    SFmode.  it's used to scale a fixed-point signed 16.16-bit fraction
11183    of a full circle back to a SFmode value, i.e., 0x10000 maps to
11184    2*pi).  */
11185
11186 static GTY(()) rtx sh_fsca_int2sf_rtx;
11187
11188 rtx
11189 sh_fsca_int2sf (void)
11190 {
11191   if (! sh_fsca_int2sf_rtx)
11192     {
11193       REAL_VALUE_TYPE rv;
11194
11195       real_from_string (&rv, "9.587379924285257e-5");
11196       sh_fsca_int2sf_rtx = const_double_from_real_value (rv, SFmode);
11197     }
11198
11199   return sh_fsca_int2sf_rtx;
11200 }
11201
11202 /* Initialize the CUMULATIVE_ARGS structure.  */
11203
11204 void
11205 sh_init_cumulative_args (CUMULATIVE_ARGS *  pcum,
11206                          tree               fntype,
11207                          rtx                libname ATTRIBUTE_UNUSED,
11208                          tree               fndecl,
11209                          signed int         n_named_args,
11210                          enum machine_mode  mode)
11211 {
11212   pcum->arg_count [(int) SH_ARG_FLOAT] = 0;
11213   pcum->free_single_fp_reg = 0;
11214   pcum->stack_regs = 0;
11215   pcum->byref_regs = 0;
11216   pcum->byref = 0;
11217   pcum->outgoing = (n_named_args == -1) ? 0 : 1;
11218
11219   /* XXX - Should we check TARGET_HITACHI here ???  */
11220   pcum->renesas_abi = sh_attr_renesas_p (fntype) ? 1 : 0;
11221
11222   if (fntype)
11223     {
11224       pcum->force_mem = ((TARGET_HITACHI || pcum->renesas_abi)
11225                          && aggregate_value_p (TREE_TYPE (fntype), fndecl));
11226       pcum->prototype_p = TYPE_ARG_TYPES (fntype) ? TRUE : FALSE;
11227       pcum->arg_count [(int) SH_ARG_INT]
11228         = TARGET_SH5 && aggregate_value_p (TREE_TYPE (fntype), fndecl);
11229
11230       pcum->call_cookie
11231         = CALL_COOKIE_RET_TRAMP (TARGET_SHCOMPACT
11232                                  && pcum->arg_count [(int) SH_ARG_INT] == 0
11233                                  && (TYPE_MODE (TREE_TYPE (fntype)) == BLKmode
11234                                      ? int_size_in_bytes (TREE_TYPE (fntype))
11235                                      : GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (fntype)))) > 4
11236                                  && (BASE_RETURN_VALUE_REG (TYPE_MODE (TREE_TYPE (fntype)))
11237                                      == FIRST_RET_REG));
11238     }
11239   else
11240     {
11241       pcum->arg_count [(int) SH_ARG_INT] = 0;
11242       pcum->prototype_p = FALSE;
11243       if (mode != VOIDmode)
11244         {
11245           pcum->call_cookie =
11246             CALL_COOKIE_RET_TRAMP (TARGET_SHCOMPACT
11247                                    && GET_MODE_SIZE (mode) > 4
11248                                    && BASE_RETURN_VALUE_REG (mode) == FIRST_RET_REG);
11249
11250           /* If the default ABI is the Renesas ABI then all library
11251              calls must assume that the library will be using the
11252              Renesas ABI.  So if the function would return its result
11253              in memory then we must force the address of this memory
11254              block onto the stack.  Ideally we would like to call
11255              targetm.calls.return_in_memory() here but we do not have
11256              the TYPE or the FNDECL available so we synthesize the
11257              contents of that function as best we can.  */
11258           pcum->force_mem =
11259             (TARGET_DEFAULT & MASK_HITACHI)
11260             && (mode == BLKmode
11261                 || (GET_MODE_SIZE (mode) > 4
11262                     && !(mode == DFmode
11263                          && TARGET_FPU_DOUBLE)));
11264         }
11265       else
11266         {
11267           pcum->call_cookie = 0;
11268           pcum->force_mem = FALSE;
11269         }
11270     }
11271 }
11272
11273 /* Replace any occurrence of FROM(n) in X with TO(n).  The function does
11274    not enter into CONST_DOUBLE for the replace.
11275
11276    Note that copying is not done so X must not be shared unless all copies
11277    are to be modified.
11278
11279    This is like replace_rtx, except that we operate on N_REPLACEMENTS
11280    replacements simultaneously - FROM(n) is replacements[n*2] and to(n) is
11281    replacements[n*2+1] - and that we take mode changes into account.
11282
11283    If a replacement is ambiguous, return NULL_RTX.
11284
11285    If MODIFY is zero, don't modify any rtl in place,
11286    just return zero or nonzero for failure / success.  */
11287
11288 rtx
11289 replace_n_hard_rtx (rtx x, rtx *replacements, int n_replacements, int modify)
11290 {
11291   int i, j;
11292   const char *fmt;
11293
11294   /* The following prevents loops occurrence when we change MEM in
11295      CONST_DOUBLE onto the same CONST_DOUBLE.  */
11296   if (x != 0 && GET_CODE (x) == CONST_DOUBLE)
11297     return x;
11298
11299   for (i = n_replacements - 1; i >= 0 ; i--)
11300   if (x == replacements[i*2] && GET_MODE (x) == GET_MODE (replacements[i*2+1]))
11301     return replacements[i*2+1];
11302
11303   /* Allow this function to make replacements in EXPR_LISTs.  */
11304   if (x == 0)
11305     return 0;
11306
11307   if (GET_CODE (x) == SUBREG)
11308     {
11309       rtx new_rtx = replace_n_hard_rtx (SUBREG_REG (x), replacements,
11310                                     n_replacements, modify);
11311
11312       if (GET_CODE (new_rtx) == CONST_INT)
11313         {
11314           x = simplify_subreg (GET_MODE (x), new_rtx,
11315                                GET_MODE (SUBREG_REG (x)),
11316                                SUBREG_BYTE (x));
11317           if (! x)
11318             abort ();
11319         }
11320       else if (modify)
11321         SUBREG_REG (x) = new_rtx;
11322
11323       return x;
11324     }
11325   else if (GET_CODE (x) == REG)
11326     {
11327       unsigned regno = REGNO (x);
11328       unsigned nregs = (regno < FIRST_PSEUDO_REGISTER
11329                         ? HARD_REGNO_NREGS (regno, GET_MODE (x)) : 1);
11330       rtx result = NULL_RTX;
11331
11332       for (i = n_replacements - 1; i >= 0; i--)
11333         {
11334           rtx from = replacements[i*2];
11335           rtx to = replacements[i*2+1];
11336           unsigned from_regno, from_nregs, to_regno, new_regno;
11337
11338           if (GET_CODE (from) != REG)
11339             continue;
11340           from_regno = REGNO (from);
11341           from_nregs = (from_regno < FIRST_PSEUDO_REGISTER
11342                         ? HARD_REGNO_NREGS (from_regno, GET_MODE (from)) : 1);
11343           if (regno < from_regno + from_nregs && regno + nregs > from_regno)
11344             {
11345               if (regno < from_regno
11346                   || regno + nregs > from_regno + nregs
11347                   || GET_CODE (to) != REG
11348                   || result)
11349                 return NULL_RTX;
11350               to_regno = REGNO (to);
11351               if (to_regno < FIRST_PSEUDO_REGISTER)
11352                 {
11353                   new_regno = regno + to_regno - from_regno;
11354                   if ((unsigned) HARD_REGNO_NREGS (new_regno, GET_MODE (x))
11355                       != nregs)
11356                     return NULL_RTX;
11357                   result = gen_rtx_REG (GET_MODE (x), new_regno);
11358                 }
11359               else if (GET_MODE (x) <= GET_MODE (to))
11360                 result = gen_lowpart_common (GET_MODE (x), to);
11361               else
11362                 result = gen_lowpart_SUBREG (GET_MODE (x), to);
11363             }
11364         }
11365       return result ? result : x;
11366     }
11367   else if (GET_CODE (x) == ZERO_EXTEND)
11368     {
11369       rtx new_rtx = replace_n_hard_rtx (XEXP (x, 0), replacements,
11370                                     n_replacements, modify);
11371
11372       if (GET_CODE (new_rtx) == CONST_INT)
11373         {
11374           x = simplify_unary_operation (ZERO_EXTEND, GET_MODE (x),
11375                                         new_rtx, GET_MODE (XEXP (x, 0)));
11376           if (! x)
11377             abort ();
11378         }
11379       else if (modify)
11380         XEXP (x, 0) = new_rtx;
11381
11382       return x;
11383     }
11384
11385   fmt = GET_RTX_FORMAT (GET_CODE (x));
11386   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
11387     {
11388       rtx new_rtx;
11389
11390       if (fmt[i] == 'e')
11391         {
11392           new_rtx = replace_n_hard_rtx (XEXP (x, i), replacements,
11393                                     n_replacements, modify);
11394           if (!new_rtx)
11395             return NULL_RTX;
11396           if (modify)
11397             XEXP (x, i) = new_rtx;
11398         }
11399       else if (fmt[i] == 'E')
11400         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
11401           {
11402             new_rtx = replace_n_hard_rtx (XVECEXP (x, i, j), replacements,
11403                                       n_replacements, modify);
11404           if (!new_rtx)
11405             return NULL_RTX;
11406             if (modify)
11407               XVECEXP (x, i, j) = new_rtx;
11408           }
11409     }
11410
11411   return x;
11412 }
11413
11414 rtx
11415 sh_gen_truncate (enum machine_mode mode, rtx x, int need_sign_ext)
11416 {
11417   enum rtx_code code = TRUNCATE;
11418
11419   if (GET_CODE (x) == ZERO_EXTEND || GET_CODE (x) == SIGN_EXTEND)
11420     {
11421       rtx inner = XEXP (x, 0);
11422       enum machine_mode inner_mode = GET_MODE (inner);
11423
11424       if (inner_mode == mode)
11425         return inner;
11426       else if (GET_MODE_SIZE (inner_mode) >= GET_MODE_SIZE (mode))
11427         x = inner;
11428       else if (GET_MODE_SIZE (inner_mode) < GET_MODE_SIZE (mode)
11429                && (! need_sign_ext || GET_CODE (x) == SIGN_EXTEND))
11430         {
11431           code = GET_CODE (x);
11432           x = inner;
11433         }
11434     }
11435   return gen_rtx_fmt_e (code, mode, x);
11436 }
11437
11438 /* called via for_each_rtx after reload, to clean up truncates of
11439    registers that span multiple actual hard registers.  */
11440 int
11441 shmedia_cleanup_truncate (rtx *p, void *n_changes)
11442 {
11443   rtx x = *p, reg;
11444
11445   if (GET_CODE (x) != TRUNCATE)
11446     return 0;
11447   reg = XEXP (x, 0);
11448   if (GET_MODE_SIZE (GET_MODE (reg)) > 8 && GET_CODE (reg) == REG)
11449     {
11450       enum machine_mode reg_mode = GET_MODE (reg);
11451       XEXP (x, 0) = simplify_subreg (DImode, reg, reg_mode,
11452                                      subreg_lowpart_offset (DImode, reg_mode));
11453       *(int*) n_changes += 1;
11454       return -1;
11455     }
11456   return 0;
11457 }
11458
11459 /* Load and store depend on the highpart of the address.  However,
11460    set_attr_alternative does not give well-defined results before reload,
11461    so we must look at the rtl ourselves to see if any of the feeding
11462    registers is used in a memref.  */
11463
11464 /* Called by sh_contains_memref_p via for_each_rtx.  */
11465 static int
11466 sh_contains_memref_p_1 (rtx *loc, void *data ATTRIBUTE_UNUSED)
11467 {
11468   return (GET_CODE (*loc) == MEM);
11469 }
11470
11471 /* Return nonzero iff INSN contains a MEM.  */
11472 int
11473 sh_contains_memref_p (rtx insn)
11474 {
11475   return for_each_rtx (&PATTERN (insn), &sh_contains_memref_p_1, NULL);
11476 }
11477
11478 /* Return nonzero iff INSN loads a banked register.  */
11479 int
11480 sh_loads_bankedreg_p (rtx insn)
11481 {
11482   if (GET_CODE (PATTERN (insn)) == SET)
11483     {
11484       rtx op = SET_DEST (PATTERN(insn));
11485       if (REG_P (op) && BANKED_REGISTER_P (REGNO (op)))
11486         return 1;
11487     }
11488
11489   return 0;  
11490 }
11491
11492 /* FNADDR is the MEM expression from a call expander.  Return an address
11493    to use in an SHmedia insn pattern.  */
11494 rtx
11495 shmedia_prepare_call_address (rtx fnaddr, int is_sibcall)
11496 {
11497   int is_sym;
11498
11499   fnaddr = XEXP (fnaddr, 0);
11500   is_sym = GET_CODE (fnaddr) == SYMBOL_REF;
11501   if (flag_pic && is_sym)
11502     {
11503       if (! SYMBOL_REF_LOCAL_P (fnaddr))
11504         {
11505           rtx reg = gen_reg_rtx (Pmode);
11506
11507           /* We must not use GOTPLT for sibcalls, because PIC_REG
11508              must be restored before the PLT code gets to run.  */
11509           if (is_sibcall)
11510             emit_insn (gen_symGOT2reg (reg, fnaddr));
11511           else
11512             emit_insn (gen_symGOTPLT2reg (reg, fnaddr));
11513           fnaddr = reg;
11514         }
11515       else
11516         {
11517           fnaddr = gen_sym2PIC (fnaddr);
11518           PUT_MODE (fnaddr, Pmode);
11519         }
11520     }
11521   /* If ptabs might trap, make this visible to the rest of the compiler.
11522      We generally assume that symbols pertain to valid locations, but
11523      it is possible to generate invalid symbols with asm or linker tricks.
11524      In a list of functions where each returns its successor, an invalid
11525      symbol might denote an empty list.  */
11526   if (!TARGET_PT_FIXED
11527       && (!is_sym || TARGET_INVALID_SYMBOLS)
11528       && (!REG_P (fnaddr) || ! TARGET_REGISTER_P (REGNO (fnaddr))))
11529     {
11530       rtx tr = gen_reg_rtx (PDImode);
11531
11532       emit_insn (gen_ptabs (tr, fnaddr));
11533       fnaddr = tr;
11534     }
11535   else if (! target_reg_operand (fnaddr, Pmode))
11536     fnaddr = copy_to_mode_reg (Pmode, fnaddr);
11537   return fnaddr;
11538 }
11539
11540 enum reg_class
11541 sh_secondary_reload (bool in_p, rtx x, enum reg_class rclass,
11542                      enum machine_mode mode, secondary_reload_info *sri)
11543 {
11544   if (in_p)
11545     {
11546       if (REGCLASS_HAS_FP_REG (rclass)
11547           && ! TARGET_SHMEDIA
11548           && immediate_operand ((x), mode)
11549           && ! ((fp_zero_operand (x) || fp_one_operand (x))
11550                 && mode == SFmode && fldi_ok ()))
11551         switch (mode)
11552           {
11553           case SFmode:
11554             sri->icode = CODE_FOR_reload_insf__frn;
11555             return NO_REGS;
11556           case DFmode:
11557             sri->icode = CODE_FOR_reload_indf__frn;
11558             return NO_REGS;
11559           case SImode:
11560             /* ??? If we knew that we are in the appropriate mode -
11561                single precision - we could use a reload pattern directly.  */
11562             return FPUL_REGS;
11563           default:
11564             abort ();
11565           }
11566       if (rclass == FPUL_REGS
11567           && ((GET_CODE (x) == REG
11568                && (REGNO (x) == MACL_REG || REGNO (x) == MACH_REG
11569                    || REGNO (x) == T_REG))
11570               || GET_CODE (x) == PLUS))
11571         return GENERAL_REGS;
11572       if (rclass == FPUL_REGS && immediate_operand (x, mode))
11573         {
11574           if (satisfies_constraint_I08 (x) || fp_zero_operand (x))
11575             return GENERAL_REGS;
11576           else if (mode == SFmode)
11577             return FP_REGS;
11578           sri->icode = CODE_FOR_reload_insi__i_fpul;
11579           return NO_REGS;
11580         }
11581       if (rclass == FPSCR_REGS
11582           && ((GET_CODE (x) == REG && REGNO (x) >= FIRST_PSEUDO_REGISTER)
11583               || (GET_CODE (x) == MEM && GET_CODE (XEXP (x, 0)) == PLUS)))
11584         return GENERAL_REGS;
11585       if (REGCLASS_HAS_FP_REG (rclass)
11586           && TARGET_SHMEDIA
11587           && immediate_operand (x, mode)
11588           && x != CONST0_RTX (GET_MODE (x))
11589           && GET_MODE (x) != V4SFmode)
11590         return GENERAL_REGS;
11591       if ((mode == QImode || mode == HImode)
11592           && TARGET_SHMEDIA && inqhi_operand (x, mode))
11593         {
11594           sri->icode = ((mode == QImode)
11595                         ? CODE_FOR_reload_inqi : CODE_FOR_reload_inhi);
11596           return NO_REGS;
11597         }
11598       if (TARGET_SHMEDIA && rclass == GENERAL_REGS
11599           && (GET_CODE (x) == LABEL_REF || PIC_ADDR_P (x)))
11600         return TARGET_REGS;
11601     } /* end of input-only processing.  */
11602
11603   if (((REGCLASS_HAS_FP_REG (rclass)
11604         && (GET_CODE (x) == REG
11605             && (GENERAL_OR_AP_REGISTER_P (REGNO (x))
11606                 || (FP_REGISTER_P (REGNO (x)) && mode == SImode
11607                     && TARGET_FMOVD))))
11608        || (REGCLASS_HAS_GENERAL_REG (rclass)
11609            && GET_CODE (x) == REG
11610            && FP_REGISTER_P (REGNO (x))))
11611       && ! TARGET_SHMEDIA
11612       && (mode == SFmode || mode == SImode))
11613     return FPUL_REGS;
11614   if ((rclass == FPUL_REGS
11615        || (REGCLASS_HAS_FP_REG (rclass)
11616            && ! TARGET_SHMEDIA && mode == SImode))
11617       && (GET_CODE (x) == MEM
11618           || (GET_CODE (x) == REG
11619               && (REGNO (x) >= FIRST_PSEUDO_REGISTER
11620                   || REGNO (x) == T_REG
11621                   || system_reg_operand (x, VOIDmode)))))
11622     {
11623       if (rclass == FPUL_REGS)
11624         return GENERAL_REGS;
11625       return FPUL_REGS;
11626     }
11627   if ((rclass == TARGET_REGS
11628        || (TARGET_SHMEDIA && rclass == SIBCALL_REGS))
11629       && !satisfies_constraint_Csy (x)
11630       && (GET_CODE (x) != REG || ! GENERAL_REGISTER_P (REGNO (x))))
11631     return GENERAL_REGS;
11632   if ((rclass == MAC_REGS || rclass == PR_REGS)
11633       && GET_CODE (x) == REG && ! GENERAL_REGISTER_P (REGNO (x))
11634       && rclass != REGNO_REG_CLASS (REGNO (x)))
11635     return GENERAL_REGS;
11636   if (rclass != GENERAL_REGS && GET_CODE (x) == REG
11637       && TARGET_REGISTER_P (REGNO (x)))
11638     return GENERAL_REGS;
11639   return NO_REGS;
11640 }
11641
11642 enum sh_divide_strategy_e sh_div_strategy = SH_DIV_STRATEGY_DEFAULT;
11643
11644 #include "gt-sh.h"