OSDN Git Service

482350af621de85d90c0a112af2e6f9d47f30325
[pf3gnuchains/gcc-fork.git] / gcc / config / sh / sh.c
1 /* Output routines for GCC for Hitachi / SuperH SH.
2    Copyright (C) 1993, 1994, 1995, 1997, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003 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 GNU CC.
8
9 GNU CC 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 2, or (at your option)
12 any later version.
13
14 GNU CC 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 GNU CC; see the file COPYING.  If not, write to
21 the Free Software Foundation, 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "insn-config.h"
29 #include "rtl.h"
30 #include "tree.h"
31 #include "flags.h"
32 #include "expr.h"
33 #include "optabs.h"
34 #include "function.h"
35 #include "regs.h"
36 #include "hard-reg-set.h"
37 #include "output.h"
38 #include "insn-attr.h"
39 #include "toplev.h"
40 #include "recog.h"
41 #include "c-pragma.h"
42 #include "integrate.h"
43 #include "tm_p.h"
44 #include "target.h"
45 #include "target-def.h"
46 #include "real.h"
47 #include "langhooks.h"
48 #include "basic-block.h"
49 #include "ra.h"
50
51 int code_for_indirect_jump_scratch = CODE_FOR_indirect_jump_scratch;
52
53 #define MSW (TARGET_LITTLE_ENDIAN ? 1 : 0)
54 #define LSW (TARGET_LITTLE_ENDIAN ? 0 : 1)
55
56 /* These are some macros to abstract register modes.  */
57 #define CONST_OK_FOR_ADD(size) \
58   (TARGET_SHMEDIA ? CONST_OK_FOR_P (size) : CONST_OK_FOR_I (size))
59 #define GEN_MOV (*(TARGET_SHMEDIA64 ? gen_movdi : gen_movsi))
60 #define GEN_ADD3 (*(TARGET_SHMEDIA64 ? gen_adddi3 : gen_addsi3))
61 #define GEN_SUB3 (*(TARGET_SHMEDIA64 ? gen_subdi3 : gen_subsi3))
62
63 /* Set to 1 by expand_prologue() when the function is an interrupt handler.  */
64 int current_function_interrupt;
65
66 /* ??? The pragma interrupt support will not work for SH3.  */
67 /* This is set by #pragma interrupt and #pragma trapa, and causes gcc to
68    output code for the next function appropriate for an interrupt handler.  */
69 int pragma_interrupt;
70
71 /* This is set by the trap_exit attribute for functions.   It specifies
72    a trap number to be used in a trapa instruction at function exit
73    (instead of an rte instruction).  */
74 int trap_exit;
75
76 /* This is used by the sp_switch attribute for functions.  It specifies
77    a variable holding the address of the stack the interrupt function
78    should switch to/from at entry/exit.  */
79 rtx sp_switch;
80
81 /* This is set by #pragma trapa, and is similar to the above, except that
82    the compiler doesn't emit code to preserve all registers.  */
83 static int pragma_trapa;
84
85 /* This is set by #pragma nosave_low_regs.  This is useful on the SH3,
86    which has a separate set of low regs for User and Supervisor modes.
87    This should only be used for the lowest level of interrupts.  Higher levels
88    of interrupts must save the registers in case they themselves are
89    interrupted.  */
90 int pragma_nosave_low_regs;
91
92 /* This is used for communication between SETUP_INCOMING_VARARGS and
93    sh_expand_prologue.  */
94 int current_function_anonymous_args;
95
96 /* Global variables for machine-dependent things.  */
97
98 /* Which cpu are we scheduling for.  */
99 enum processor_type sh_cpu;
100
101 /* Saved operands from the last compare to use when we generate an scc
102    or bcc insn.  */
103
104 rtx sh_compare_op0;
105 rtx sh_compare_op1;
106
107 /* Provides the class number of the smallest class containing
108    reg number.  */
109
110 int regno_reg_class[FIRST_PSEUDO_REGISTER] =
111 {
112   R0_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
113   GENERAL_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   FP0_REGS,FP_REGS, FP_REGS, FP_REGS,
129   FP_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   TARGET_REGS, TARGET_REGS, TARGET_REGS, TARGET_REGS,
145   TARGET_REGS, TARGET_REGS, TARGET_REGS, TARGET_REGS,
146   DF_REGS, DF_REGS, DF_REGS, DF_REGS,
147   DF_REGS, DF_REGS, DF_REGS, DF_REGS,
148   NO_REGS, GENERAL_REGS, PR_REGS, T_REGS,
149   MAC_REGS, MAC_REGS, FPUL_REGS, FPSCR_REGS,
150   GENERAL_REGS,
151 };
152
153 char sh_register_names[FIRST_PSEUDO_REGISTER] \
154   [MAX_REGISTER_NAME_LENGTH + 1] = SH_REGISTER_NAMES_INITIALIZER;
155
156 char sh_additional_register_names[ADDREGNAMES_SIZE] \
157   [MAX_ADDITIONAL_REGISTER_NAME_LENGTH + 1]
158   = SH_ADDITIONAL_REGISTER_NAMES_INITIALIZER;
159
160 /* Provide reg_class from a letter such as appears in the machine
161    description.  *: target independently reserved letter.
162    reg_class_from_letter['e' - 'a'] is set to NO_REGS for TARGET_FMOVD.  */
163
164 enum reg_class reg_class_from_letter[] =
165 {
166   /* a */ ALL_REGS,  /* b */ TARGET_REGS, /* c */ FPSCR_REGS, /* d */ DF_REGS,
167   /* e */ FP_REGS,   /* f */ FP_REGS,  /* g **/ NO_REGS,     /* h */ NO_REGS,
168   /* i **/ NO_REGS,  /* j */ NO_REGS,  /* k */ SIBCALL_REGS, /* l */ PR_REGS,
169   /* m **/ NO_REGS,  /* n **/ NO_REGS, /* o **/ NO_REGS,     /* p **/ NO_REGS,
170   /* q */ NO_REGS,   /* r **/ NO_REGS, /* s **/ NO_REGS,     /* t */ T_REGS,
171   /* u */ NO_REGS,   /* v */ NO_REGS,  /* w */ FP0_REGS,     /* x */ MAC_REGS,
172   /* y */ FPUL_REGS, /* z */ R0_REGS
173 };
174
175 int assembler_dialect;
176
177 static void split_branches PARAMS ((rtx));
178 static int branch_dest PARAMS ((rtx));
179 static void force_into PARAMS ((rtx, rtx));
180 static void print_slot PARAMS ((rtx));
181 static rtx add_constant PARAMS ((rtx, enum machine_mode, rtx));
182 static void dump_table PARAMS ((rtx));
183 static int hi_const PARAMS ((rtx));
184 static int broken_move PARAMS ((rtx));
185 static int mova_p PARAMS ((rtx));
186 static rtx find_barrier PARAMS ((int, rtx, rtx));
187 static int noncall_uses_reg PARAMS ((rtx, rtx, rtx *));
188 static rtx gen_block_redirect PARAMS ((rtx, int, int));
189 static void sh_reorg PARAMS ((void));
190 static void output_stack_adjust PARAMS ((int, rtx, int, rtx (*) (rtx)));
191 static rtx frame_insn PARAMS ((rtx));
192 static rtx push PARAMS ((int));
193 static void pop PARAMS ((int));
194 static void push_regs PARAMS ((HARD_REG_SET *, int));
195 static int calc_live_regs PARAMS ((HARD_REG_SET *));
196 static void mark_use PARAMS ((rtx, rtx *));
197 static HOST_WIDE_INT rounded_frame_size PARAMS ((int));
198 static rtx mark_constant_pool_use PARAMS ((rtx));
199 const struct attribute_spec sh_attribute_table[];
200 static tree sh_handle_interrupt_handler_attribute PARAMS ((tree *, tree, tree, int, bool *));
201 static tree sh_handle_sp_switch_attribute PARAMS ((tree *, tree, tree, int, bool *));
202 static tree sh_handle_trap_exit_attribute PARAMS ((tree *, tree, tree, int, bool *));
203 static void sh_output_function_epilogue PARAMS ((FILE *, HOST_WIDE_INT));
204 static void sh_insert_attributes PARAMS ((tree, tree *));
205 static int sh_adjust_cost PARAMS ((rtx, rtx, rtx, int));
206 static int sh_use_dfa_interface PARAMS ((void));
207 static int sh_issue_rate PARAMS ((void));
208 static bool sh_function_ok_for_sibcall PARAMS ((tree, tree));
209
210 static bool sh_cannot_modify_jumps_p PARAMS ((void));
211 static bool sh_ms_bitfield_layout_p PARAMS ((tree));
212
213 static void sh_init_builtins PARAMS ((void));
214 static void sh_media_init_builtins PARAMS ((void));
215 static rtx sh_expand_builtin PARAMS ((tree, rtx, rtx, enum machine_mode, int));
216 static void sh_output_mi_thunk PARAMS ((FILE *, tree, HOST_WIDE_INT,
217                                         HOST_WIDE_INT, tree));
218 static int flow_dependent_p PARAMS ((rtx, rtx));
219 static void flow_dependent_p_1 PARAMS ((rtx, rtx, void *));
220 static int shiftcosts PARAMS ((rtx));
221 static int andcosts PARAMS ((rtx));
222 static int addsubcosts PARAMS ((rtx));
223 static int multcosts PARAMS ((rtx));
224 static bool unspec_caller_rtx_p PARAMS ((rtx));
225 static bool sh_cannot_copy_insn_p PARAMS ((rtx));
226 static bool sh_rtx_costs PARAMS ((rtx, int, int, int *));
227 static int sh_address_cost PARAMS ((rtx));
228 \f
229 /* Initialize the GCC target structure.  */
230 #undef TARGET_ATTRIBUTE_TABLE
231 #define TARGET_ATTRIBUTE_TABLE sh_attribute_table
232
233 /* The next two are used for debug info when compiling with -gdwarf.  */
234 #undef TARGET_ASM_UNALIGNED_HI_OP
235 #define TARGET_ASM_UNALIGNED_HI_OP "\t.uaword\t"
236 #undef TARGET_ASM_UNALIGNED_SI_OP
237 #define TARGET_ASM_UNALIGNED_SI_OP "\t.ualong\t"
238
239 /* These are NULLed out on non-SH5 in OVERRIDE_OPTIONS.  */
240 #undef TARGET_ASM_UNALIGNED_DI_OP
241 #define TARGET_ASM_UNALIGNED_DI_OP "\t.uaquad\t"
242 #undef TARGET_ASM_ALIGNED_DI_OP
243 #define TARGET_ASM_ALIGNED_DI_OP "\t.quad\t"
244
245 #undef TARGET_ASM_FUNCTION_EPILOGUE
246 #define TARGET_ASM_FUNCTION_EPILOGUE sh_output_function_epilogue
247
248 #undef TARGET_ASM_OUTPUT_MI_THUNK
249 #define TARGET_ASM_OUTPUT_MI_THUNK sh_output_mi_thunk
250
251 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
252 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_tree_hwi_hwi_tree_true
253
254 #undef TARGET_INSERT_ATTRIBUTES
255 #define TARGET_INSERT_ATTRIBUTES sh_insert_attributes
256
257 #undef TARGET_SCHED_ADJUST_COST
258 #define TARGET_SCHED_ADJUST_COST sh_adjust_cost
259
260 #undef TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE 
261 #define TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE \
262                                 sh_use_dfa_interface
263 #undef TARGET_SCHED_ISSUE_RATE
264 #define TARGET_SCHED_ISSUE_RATE sh_issue_rate
265
266 #undef TARGET_CANNOT_MODIFY_JUMPS_P
267 #define TARGET_CANNOT_MODIFY_JUMPS_P sh_cannot_modify_jumps_p
268
269 #undef TARGET_MS_BITFIELD_LAYOUT_P
270 #define TARGET_MS_BITFIELD_LAYOUT_P sh_ms_bitfield_layout_p
271
272 #undef TARGET_INIT_BUILTINS
273 #define TARGET_INIT_BUILTINS sh_init_builtins
274 #undef TARGET_EXPAND_BUILTIN
275 #define TARGET_EXPAND_BUILTIN sh_expand_builtin
276
277 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
278 #define TARGET_FUNCTION_OK_FOR_SIBCALL sh_function_ok_for_sibcall
279
280 #undef TARGET_CANNOT_COPY_INSN_P
281 #define TARGET_CANNOT_COPY_INSN_P sh_cannot_copy_insn_p
282 #undef TARGET_RTX_COSTS
283 #define TARGET_RTX_COSTS sh_rtx_costs
284 #undef TARGET_ADDRESS_COST
285 #define TARGET_ADDRESS_COST sh_address_cost
286
287 #undef TARGET_MACHINE_DEPENDENT_REORG
288 #define TARGET_MACHINE_DEPENDENT_REORG sh_reorg
289
290 #ifdef HAVE_AS_TLS
291 #undef TARGET_HAVE_TLS
292 #define TARGET_HAVE_TLS true
293 #endif
294
295 struct gcc_target targetm = TARGET_INITIALIZER;
296 \f
297 /* Print the operand address in x to the stream.  */
298
299 void
300 print_operand_address (stream, x)
301      FILE *stream;
302      rtx x;
303 {
304   switch (GET_CODE (x))
305     {
306     case REG:
307     case SUBREG:
308       fprintf (stream, "@%s", reg_names[true_regnum (x)]);
309       break;
310
311     case PLUS:
312       {
313         rtx base = XEXP (x, 0);
314         rtx index = XEXP (x, 1);
315
316         switch (GET_CODE (index))
317           {
318           case CONST_INT:
319             fprintf (stream, "@(%d,%s)", (int) INTVAL (index),
320                      reg_names[true_regnum (base)]);
321             break;
322
323           case REG:
324           case SUBREG:
325             {
326               int base_num = true_regnum (base);
327               int index_num = true_regnum (index);
328
329               fprintf (stream, "@(r0,%s)",
330                        reg_names[MAX (base_num, index_num)]);
331               break;
332             }
333
334           default:
335             debug_rtx (x);
336             abort ();
337           }
338       }
339       break;
340
341     case PRE_DEC:
342       fprintf (stream, "@-%s", reg_names[true_regnum (XEXP (x, 0))]);
343       break;
344
345     case POST_INC:
346       fprintf (stream, "@%s+", reg_names[true_regnum (XEXP (x, 0))]);
347       break;
348
349     default:
350       x = mark_constant_pool_use (x);
351       output_addr_const (stream, x);
352       break;
353     }
354 }
355
356 /* Print operand x (an rtx) in assembler syntax to file stream
357    according to modifier code.
358
359    '.'  print a .s if insn needs delay slot
360    ','  print LOCAL_LABEL_PREFIX
361    '@'  print trap, rte or rts depending upon pragma interruptness
362    '#'  output a nop if there is nothing to put in the delay slot
363    '''  print likelyhood suffix (/u for unlikely).
364    'O'  print a constant without the #
365    'R'  print the LSW of a dp value - changes if in little endian
366    'S'  print the MSW of a dp value - changes if in little endian
367    'T'  print the next word of a dp value - same as 'R' in big endian mode.
368    'M'  print an `x' if `m' will print `base,index'.
369    'N'  print 'r63' if the operand is (const_int 0).
370    'm'  print a pair `base,offset' or `base,index', for LD and ST.
371    'u'  prints the lowest 16 bits of CONST_INT, as an unsigned value.
372    'o'  output an operator.  */
373
374 void
375 print_operand (stream, x, code)
376      FILE *stream;
377      rtx x;
378      int code;
379 {
380   switch (code)
381     {
382     case '.':
383       if (final_sequence
384           && ! INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0))
385           && get_attr_length (XVECEXP (final_sequence, 0, 1)))
386         fprintf (stream, ASSEMBLER_DIALECT ? "/s" : ".s");
387       break;
388     case ',':
389       fprintf (stream, "%s", LOCAL_LABEL_PREFIX);
390       break;
391     case '@':
392       if (trap_exit)
393         fprintf (stream, "trapa #%d", trap_exit);
394       else if (sh_cfun_interrupt_handler_p ())
395         fprintf (stream, "rte");
396       else
397         fprintf (stream, "rts");
398       break;
399     case '#':
400       /* Output a nop if there's nothing in the delay slot.  */
401       if (dbr_sequence_length () == 0)
402         fprintf (stream, "\n\tnop");
403       break;
404     case '\'':
405       {
406         rtx note = find_reg_note (current_output_insn, REG_BR_PROB, 0);
407
408         if (note && INTVAL (XEXP (note, 0)) * 2 < REG_BR_PROB_BASE)
409           fputs ("/u", stream);
410         break;
411       }
412     case 'O':
413       x = mark_constant_pool_use (x);
414       output_addr_const (stream, x);
415       break;
416     case 'R':
417       fputs (reg_names[REGNO (x) + LSW], (stream));
418       break;
419     case 'S':
420       fputs (reg_names[REGNO (x) + MSW], (stream));
421       break;
422     case 'T':
423       /* Next word of a double.  */
424       switch (GET_CODE (x))
425         {
426         case REG:
427           fputs (reg_names[REGNO (x) + 1], (stream));
428           break;
429         case MEM:
430           if (GET_CODE (XEXP (x, 0)) != PRE_DEC
431               && GET_CODE (XEXP (x, 0)) != POST_INC)
432             x = adjust_address (x, SImode, 4);
433           print_operand_address (stream, XEXP (x, 0));
434           break;
435         default:
436           break;
437         }
438       break;
439     case 'o':
440       switch (GET_CODE (x))
441         {
442         case PLUS:  fputs ("add", stream); break;
443         case MINUS: fputs ("sub", stream); break;
444         case MULT:  fputs ("mul", stream); break;
445         case DIV:   fputs ("div", stream); break;
446         case EQ:    fputs ("eq",  stream); break;
447         case NE:    fputs ("ne",  stream); break;
448         case GT:  case LT:  fputs ("gt",  stream); break;
449         case GE:  case LE:  fputs ("ge",  stream); break;
450         case GTU: case LTU: fputs ("gtu", stream); break;
451         case GEU: case LEU: fputs ("geu", stream); break;
452         default:
453           break;
454         }
455       break;
456     case 'M':
457       if (GET_CODE (x) == MEM
458           && GET_CODE (XEXP (x, 0)) == PLUS
459           && (GET_CODE (XEXP (XEXP (x, 0), 1)) == REG
460               || GET_CODE (XEXP (XEXP (x, 0), 1)) == SUBREG))
461         fputc ('x', stream);
462       break;
463
464     case 'm':
465       if (GET_CODE (x) != MEM)
466         abort ();
467       x = XEXP (x, 0);
468       switch (GET_CODE (x))
469         {
470         case REG:
471         case SUBREG:
472           print_operand (stream, x, 0);
473           fputs (", 0", stream);
474           break;
475
476         case PLUS:
477           print_operand (stream, XEXP (x, 0), 0);
478           fputs (", ", stream);
479           print_operand (stream, XEXP (x, 1), 0);
480           break;
481
482         default:
483           abort ();
484         }
485       break;
486
487     case 'N':
488       if (x == CONST0_RTX (GET_MODE (x)))
489         {
490           fprintf ((stream), "r63");
491           break;
492         }
493       goto default_output;
494     case 'u':
495       if (GET_CODE (x) == CONST_INT)
496         {
497           fprintf ((stream), "%u", (unsigned) INTVAL (x) & (0x10000 - 1));
498           break;
499         }
500       /* Fall through.  */
501
502     default_output:
503     default:
504       switch (GET_CODE (x))
505         {
506           /* FIXME: We need this on SHmedia32 because reload generates
507              some sign-extended HI or QI loads into DImode registers
508              but, because Pmode is SImode, the address ends up with a
509              subreg:SI of the DImode register.  Maybe reload should be
510              fixed so as to apply alter_subreg to such loads?  */
511         case SUBREG:
512           if (SUBREG_BYTE (x) != 0
513               || GET_CODE (SUBREG_REG (x)) != REG)
514             abort ();
515
516           x = SUBREG_REG (x);
517           /* Fall through.  */
518
519         case REG:
520           if (FP_REGISTER_P (REGNO (x))
521               && GET_MODE (x) == V16SFmode)
522             fprintf ((stream), "mtrx%s", reg_names[REGNO (x)] + 2);
523           else if (FP_REGISTER_P (REGNO (x))
524                    && GET_MODE (x) == V4SFmode)
525             fprintf ((stream), "fv%s", reg_names[REGNO (x)] + 2);
526           else if (GET_CODE (x) == REG
527                    && GET_MODE (x) == V2SFmode)
528             fprintf ((stream), "fp%s", reg_names[REGNO (x)] + 2);
529           else if (FP_REGISTER_P (REGNO (x))
530                    && GET_MODE_SIZE (GET_MODE (x)) > 4)
531             fprintf ((stream), "d%s", reg_names[REGNO (x)] + 1);
532           else
533             fputs (reg_names[REGNO (x)], (stream));
534           break;
535
536         case MEM:
537           output_address (XEXP (x, 0));
538           break;
539           
540         case CONST:
541           if (TARGET_SHMEDIA
542               && GET_CODE (XEXP (x, 0)) == SIGN_EXTEND
543               && GET_MODE (XEXP (x, 0)) == DImode
544               && GET_CODE (XEXP (XEXP (x, 0), 0)) == TRUNCATE
545               && GET_MODE (XEXP (XEXP (x, 0), 0)) == HImode)
546             {
547               rtx val = XEXP (XEXP (XEXP (x, 0), 0), 0);
548
549               fputc ('(', stream);
550               if (GET_CODE (val) == ASHIFTRT)
551                 {
552                   fputc ('(', stream);
553                   if (GET_CODE (XEXP (val, 0)) == CONST)
554                     fputc ('(', stream);
555                   output_addr_const (stream, XEXP (val, 0));
556                   if (GET_CODE (XEXP (val, 0)) == CONST)
557                     fputc (')', stream);
558                   fputs (" >> ", stream);
559                   output_addr_const (stream, XEXP (val, 1));
560                   fputc (')', stream);
561                 }
562               else
563                 {
564                   if (GET_CODE (val) == CONST)
565                     fputc ('(', stream);
566                   output_addr_const (stream, val);
567                   if (GET_CODE (val) == CONST)
568                     fputc (')', stream);
569                 }
570               fputs (" & 65535)", stream);
571               break;
572             }
573
574           /* Fall through.  */
575         default:
576           if (TARGET_SH1)
577             fputc ('#', stream);
578           output_addr_const (stream, x);
579           break;
580         }
581       break;
582     }
583 }
584 \f
585 /* Like force_operand, but guarantees that VALUE ends up in TARGET.  */
586 static void
587 force_into (value, target)
588      rtx value, target;
589 {
590   value = force_operand (value, target);
591   if (! rtx_equal_p (value, target))
592     emit_insn (gen_move_insn (target, value));
593 }
594
595 /* Emit code to perform a block move.  Choose the best method.
596
597    OPERANDS[0] is the destination.
598    OPERANDS[1] is the source.
599    OPERANDS[2] is the size.
600    OPERANDS[3] is the alignment safe to use.  */
601
602 int
603 expand_block_move (operands)
604      rtx *operands;
605 {
606   int align = INTVAL (operands[3]);
607   int constp = (GET_CODE (operands[2]) == CONST_INT);
608   int bytes = (constp ? INTVAL (operands[2]) : 0);
609
610   /* If it isn't a constant number of bytes, or if it doesn't have 4 byte
611      alignment, or if it isn't a multiple of 4 bytes, then fail.  */
612   if (! constp || align < 4 || (bytes % 4 != 0))
613     return 0;
614
615   if (TARGET_HARD_SH4)
616     {
617       if (bytes < 12)
618         return 0;
619       else if (bytes == 12)
620         {
621           tree entry_name;
622           rtx sym;
623           rtx func_addr_rtx;
624           rtx r4 = gen_rtx (REG, SImode, 4);
625           rtx r5 = gen_rtx (REG, SImode, 5);
626
627           entry_name = get_identifier ("__movstrSI12_i4");
628
629           sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (entry_name));
630           func_addr_rtx = copy_to_mode_reg (Pmode, sym);
631           force_into (XEXP (operands[0], 0), r4);
632           force_into (XEXP (operands[1], 0), r5);
633           emit_insn (gen_block_move_real_i4 (func_addr_rtx));
634           return 1;
635         }
636       else if (! TARGET_SMALLCODE)
637         {
638           tree entry_name;
639           rtx sym;
640           rtx func_addr_rtx;
641           int dwords;
642           rtx r4 = gen_rtx (REG, SImode, 4);
643           rtx r5 = gen_rtx (REG, SImode, 5);
644           rtx r6 = gen_rtx (REG, SImode, 6);
645
646           entry_name = get_identifier (bytes & 4
647                                        ? "__movstr_i4_odd"
648                                        : "__movstr_i4_even");
649           sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (entry_name));
650           func_addr_rtx = copy_to_mode_reg (Pmode, sym);
651           force_into (XEXP (operands[0], 0), r4);
652           force_into (XEXP (operands[1], 0), r5);
653
654           dwords = bytes >> 3;
655           emit_insn (gen_move_insn (r6, GEN_INT (dwords - 1)));
656           emit_insn (gen_block_lump_real_i4 (func_addr_rtx));
657           return 1;
658         }
659       else
660         return 0;
661     }
662   if (bytes < 64)
663     {
664       char entry[30];
665       tree entry_name;
666       rtx sym;
667       rtx func_addr_rtx;
668       rtx r4 = gen_rtx_REG (SImode, 4);
669       rtx r5 = gen_rtx_REG (SImode, 5);
670
671       sprintf (entry, "__movstrSI%d", bytes);
672       entry_name = get_identifier (entry);
673       sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (entry_name));
674       func_addr_rtx = copy_to_mode_reg (Pmode, sym);
675       force_into (XEXP (operands[0], 0), r4);
676       force_into (XEXP (operands[1], 0), r5);
677       emit_insn (gen_block_move_real (func_addr_rtx));
678       return 1;
679     }
680
681   /* This is the same number of bytes as a memcpy call, but to a different
682      less common function name, so this will occasionally use more space.  */
683   if (! TARGET_SMALLCODE)
684     {
685       tree entry_name;
686       rtx sym;
687       rtx func_addr_rtx;
688       int final_switch, while_loop;
689       rtx r4 = gen_rtx_REG (SImode, 4);
690       rtx r5 = gen_rtx_REG (SImode, 5);
691       rtx r6 = gen_rtx_REG (SImode, 6);
692
693       entry_name = get_identifier ("__movstr");
694       sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (entry_name));
695       func_addr_rtx = copy_to_mode_reg (Pmode, sym);
696       force_into (XEXP (operands[0], 0), r4);
697       force_into (XEXP (operands[1], 0), r5);
698
699       /* r6 controls the size of the move.  16 is decremented from it
700          for each 64 bytes moved.  Then the negative bit left over is used
701          as an index into a list of move instructions.  e.g., a 72 byte move
702          would be set up with size(r6) = 14, for one iteration through the
703          big while loop, and a switch of -2 for the last part.  */
704
705       final_switch = 16 - ((bytes / 4) % 16);
706       while_loop = ((bytes / 4) / 16 - 1) * 16;
707       emit_insn (gen_move_insn (r6, GEN_INT (while_loop + final_switch)));
708       emit_insn (gen_block_lump_real (func_addr_rtx));
709       return 1;
710     }
711
712   return 0;
713 }
714
715 /* Prepare operands for a move define_expand; specifically, one of the
716    operands must be in a register.  */
717
718 int
719 prepare_move_operands (operands, mode)
720      rtx operands[];
721      enum machine_mode mode;
722 {
723   if ((mode == SImode || mode == DImode)
724       && flag_pic
725       && ! ((mode == Pmode || mode == ptr_mode)
726             && tls_symbolic_operand (operands[1], Pmode) != 0))
727     {
728       rtx temp;
729       if (SYMBOLIC_CONST_P (operands[1]))
730         {
731           if (GET_CODE (operands[0]) == MEM)
732             operands[1] = force_reg (Pmode, operands[1]);
733           else if (TARGET_SHMEDIA
734                    && GET_CODE (operands[1]) == LABEL_REF
735                    && target_reg_operand (operands[0], mode))
736             /* It's ok.  */;
737           else
738             {
739               temp = no_new_pseudos ? operands[0] : gen_reg_rtx (Pmode);
740               operands[1] = legitimize_pic_address (operands[1], mode, temp);
741             }
742         }
743       else if (GET_CODE (operands[1]) == CONST
744                && GET_CODE (XEXP (operands[1], 0)) == PLUS
745                && SYMBOLIC_CONST_P (XEXP (XEXP (operands[1], 0), 0)))
746         {
747           temp = no_new_pseudos ? operands[0] : gen_reg_rtx (Pmode);
748           temp = legitimize_pic_address (XEXP (XEXP (operands[1], 0), 0),
749                                          mode, temp);
750           operands[1] = expand_binop (mode, add_optab, temp,
751                                       XEXP (XEXP (operands[1], 0), 1),
752                                       no_new_pseudos ? temp
753                                       : gen_reg_rtx (Pmode),
754                                       0, OPTAB_LIB_WIDEN);
755         }
756     }
757
758   if (! reload_in_progress && ! reload_completed)
759     {
760       /* Copy the source to a register if both operands aren't registers.  */
761       if (! register_operand (operands[0], mode)
762           && ! sh_register_operand (operands[1], mode))
763         operands[1] = copy_to_mode_reg (mode, operands[1]);
764
765       /* This case can happen while generating code to move the result
766          of a library call to the target.  Reject `st r0,@(rX,rY)' because
767          reload will fail to find a spill register for rX, since r0 is already
768          being used for the source.  */
769       else if (GET_CODE (operands[1]) == REG && REGNO (operands[1]) == 0
770                && GET_CODE (operands[0]) == MEM
771                && GET_CODE (XEXP (operands[0], 0)) == PLUS
772                && GET_CODE (XEXP (XEXP (operands[0], 0), 1)) == REG)
773         operands[1] = copy_to_mode_reg (mode, operands[1]);
774     }
775
776   if (mode == Pmode || mode == ptr_mode)
777     {
778       rtx op0, op1;
779       enum tls_model tls_kind;
780
781       op0 = operands[0];
782       op1 = operands[1];
783       if ((tls_kind = tls_symbolic_operand (op1, Pmode)))
784         {
785           rtx tga_op1, tga_ret, tmp, tmp2;
786
787           
788           switch (tls_kind)
789             {
790             case TLS_MODEL_GLOBAL_DYNAMIC:
791               tga_ret = gen_rtx_REG (Pmode, R0_REG);
792               emit_insn (gen_tls_global_dynamic (tga_ret, op1));
793               op1 = tga_ret;
794               break;
795
796             case TLS_MODEL_LOCAL_DYNAMIC:
797               tga_ret = gen_rtx_REG (Pmode, R0_REG);
798               emit_insn (gen_tls_local_dynamic (tga_ret, op1));
799
800               tmp = gen_reg_rtx (Pmode);
801               emit_move_insn (tmp, tga_ret);
802
803               if (register_operand (op0, Pmode))
804                 tmp2 = op0;
805               else
806                 tmp2 = gen_reg_rtx (Pmode);
807
808               emit_insn (gen_symDTPOFF2reg (tmp2, op1, tmp));
809               op1 = tmp2;
810               break;
811
812             case TLS_MODEL_INITIAL_EXEC:
813               if (! flag_pic)
814                 emit_insn (gen_GOTaddr2picreg ());
815               tga_op1 = gen_reg_rtx (Pmode);
816               tmp = gen_sym2GOTTPOFF (op1);
817               emit_insn (gen_tls_initial_exec (tga_op1, tmp));
818               op1 = tga_op1;
819               break;
820
821             case TLS_MODEL_LOCAL_EXEC:
822               tmp2 = gen_reg_rtx (Pmode);
823               emit_insn (gen_load_gbr (tmp2));
824               tmp = gen_reg_rtx (Pmode);
825               emit_insn (gen_symTPOFF2reg (tmp, op1));
826               RTX_UNCHANGING_P (tmp) = 1;
827
828               if (register_operand (op0, Pmode))
829                 op1 = op0;
830               else
831                 op1 = gen_reg_rtx (Pmode);
832
833               emit_insn (gen_addsi3 (op1, tmp, tmp2));
834               break;
835
836             default:
837               abort ();
838             }
839           operands[1] = op1;
840         }
841     }
842
843   return 0;
844 }
845
846 /* Prepare the operands for an scc instruction; make sure that the
847    compare has been done.  */
848 rtx
849 prepare_scc_operands (code)
850      enum rtx_code code;
851 {
852   rtx t_reg = gen_rtx_REG (SImode, T_REG);
853   enum rtx_code oldcode = code;
854   enum machine_mode mode;
855
856   /* First need a compare insn.  */
857   switch (code)
858     {
859     case NE:
860       /* It isn't possible to handle this case.  */
861       abort ();
862     case LT:
863       code = GT;
864       break;
865     case LE:
866       code = GE;
867       break;
868     case LTU:
869       code = GTU;
870       break;
871     case LEU:
872       code = GEU;
873       break;
874     default:
875       break;
876     }
877   if (code != oldcode)
878     {
879       rtx tmp = sh_compare_op0;
880       sh_compare_op0 = sh_compare_op1;
881       sh_compare_op1 = tmp;
882     }
883
884   mode = GET_MODE (sh_compare_op0);
885   if (mode == VOIDmode)
886     mode = GET_MODE (sh_compare_op1);
887
888   sh_compare_op0 = force_reg (mode, sh_compare_op0);
889   if ((code != EQ && code != NE
890        && (sh_compare_op1 != const0_rtx
891            || code == GTU  || code == GEU || code == LTU || code == LEU))
892       || (mode == DImode && sh_compare_op1 != const0_rtx)
893       || (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT))
894     sh_compare_op1 = force_reg (mode, sh_compare_op1);
895
896   if (TARGET_SH4 && GET_MODE_CLASS (mode) == MODE_FLOAT)
897     (mode == SFmode ? emit_sf_insn : emit_df_insn)
898      (gen_rtx (PARALLEL, VOIDmode, gen_rtvec (2,
899                 gen_rtx (SET, VOIDmode, t_reg,
900                          gen_rtx (code, SImode,
901                                   sh_compare_op0, sh_compare_op1)),
902                 gen_rtx (USE, VOIDmode, get_fpscr_rtx ()))));
903   else
904     emit_insn (gen_rtx (SET, VOIDmode, t_reg,
905                         gen_rtx (code, SImode, sh_compare_op0,
906                                  sh_compare_op1)));
907
908   return t_reg;
909 }
910
911 /* Called from the md file, set up the operands of a compare instruction.  */
912
913 void
914 from_compare (operands, code)
915      rtx *operands;
916      int code;
917 {
918   enum machine_mode mode = GET_MODE (sh_compare_op0);
919   rtx insn;
920   if (mode == VOIDmode)
921     mode = GET_MODE (sh_compare_op1);
922   if (code != EQ
923       || mode == DImode
924       || (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT))
925     {
926       /* Force args into regs, since we can't use constants here.  */
927       sh_compare_op0 = force_reg (mode, sh_compare_op0);
928       if (sh_compare_op1 != const0_rtx
929           || code == GTU  || code == GEU
930           || (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT))
931         sh_compare_op1 = force_reg (mode, sh_compare_op1);
932     }
933   if (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT && code == GE)
934     {
935       from_compare (operands, GT);
936       insn = gen_ieee_ccmpeqsf_t (sh_compare_op0, sh_compare_op1);
937     }
938   else
939     insn = gen_rtx_SET (VOIDmode,
940                         gen_rtx_REG (SImode, T_REG),
941                         gen_rtx (code, SImode, sh_compare_op0,
942                                  sh_compare_op1));
943   if (TARGET_SH4 && GET_MODE_CLASS (mode) == MODE_FLOAT)
944     {
945       insn = gen_rtx (PARALLEL, VOIDmode,
946                       gen_rtvec (2, insn,
947                                  gen_rtx (USE, VOIDmode, get_fpscr_rtx ())));
948       (mode == SFmode ? emit_sf_insn : emit_df_insn) (insn);
949     }
950   else
951     emit_insn (insn);
952 }
953 \f
954 /* Functions to output assembly code.  */
955
956 /* Return a sequence of instructions to perform DI or DF move.
957
958    Since the SH cannot move a DI or DF in one instruction, we have
959    to take care when we see overlapping source and dest registers.  */
960
961 const char *
962 output_movedouble (insn, operands, mode)
963      rtx insn ATTRIBUTE_UNUSED;
964      rtx operands[];
965      enum machine_mode mode;
966 {
967   rtx dst = operands[0];
968   rtx src = operands[1];
969
970   if (GET_CODE (dst) == MEM
971       && GET_CODE (XEXP (dst, 0)) == PRE_DEC)
972     return "mov.l       %T1,%0\n\tmov.l %1,%0";
973
974   if (register_operand (dst, mode)
975       && register_operand (src, mode))
976     {
977       if (REGNO (src) == MACH_REG)
978         return "sts     mach,%S0\n\tsts macl,%R0";
979
980       /* When mov.d r1,r2 do r2->r3 then r1->r2;
981          when mov.d r1,r0 do r1->r0 then r2->r1.  */
982
983       if (REGNO (src) + 1 == REGNO (dst))
984         return "mov     %T1,%T0\n\tmov  %1,%0";
985       else
986         return "mov     %1,%0\n\tmov    %T1,%T0";
987     }
988   else if (GET_CODE (src) == CONST_INT)
989     {
990       if (INTVAL (src) < 0)
991         output_asm_insn ("mov   #-1,%S0", operands);
992       else
993         output_asm_insn ("mov   #0,%S0", operands);
994
995       return "mov       %1,%R0";
996     }
997   else if (GET_CODE (src) == MEM)
998     {
999       int ptrreg = -1;
1000       int dreg = REGNO (dst);
1001       rtx inside = XEXP (src, 0);
1002
1003       if (GET_CODE (inside) == REG)
1004         ptrreg = REGNO (inside);
1005       else if (GET_CODE (inside) == SUBREG)
1006         ptrreg = subreg_regno (inside);
1007       else if (GET_CODE (inside) == PLUS)
1008         {
1009           ptrreg = REGNO (XEXP (inside, 0));
1010           /* ??? A r0+REG address shouldn't be possible here, because it isn't
1011              an offsettable address.  Unfortunately, offsettable addresses use
1012              QImode to check the offset, and a QImode offsettable address
1013              requires r0 for the other operand, which is not currently
1014              supported, so we can't use the 'o' constraint.
1015              Thus we must check for and handle r0+REG addresses here.
1016              We punt for now, since this is likely very rare.  */
1017           if (GET_CODE (XEXP (inside, 1)) == REG)
1018             abort ();
1019         }
1020       else if (GET_CODE (inside) == LABEL_REF)
1021         return "mov.l   %1,%0\n\tmov.l  %1+4,%T0";
1022       else if (GET_CODE (inside) == POST_INC)
1023         return "mov.l   %1,%0\n\tmov.l  %1,%T0";
1024       else
1025         abort ();
1026
1027       /* Work out the safe way to copy.  Copy into the second half first.  */
1028       if (dreg == ptrreg)
1029         return "mov.l   %T1,%T0\n\tmov.l        %1,%0";
1030     }
1031
1032   return "mov.l %1,%0\n\tmov.l  %T1,%T0";
1033 }
1034
1035 /* Print an instruction which would have gone into a delay slot after
1036    another instruction, but couldn't because the other instruction expanded
1037    into a sequence where putting the slot insn at the end wouldn't work.  */
1038
1039 static void
1040 print_slot (insn)
1041      rtx insn;
1042 {
1043   final_scan_insn (XVECEXP (insn, 0, 1), asm_out_file, optimize, 0, 1);
1044
1045   INSN_DELETED_P (XVECEXP (insn, 0, 1)) = 1;
1046 }
1047
1048 const char *
1049 output_far_jump (insn, op)
1050      rtx insn;
1051      rtx op;
1052 {
1053   struct { rtx lab, reg, op; } this;
1054   rtx braf_base_lab = NULL_RTX;
1055   const char *jump;
1056   int far;
1057   int offset = branch_dest (insn) - INSN_ADDRESSES (INSN_UID (insn));
1058   rtx prev;
1059
1060   this.lab = gen_label_rtx ();
1061
1062   if (TARGET_SH2
1063       && offset >= -32764
1064       && offset - get_attr_length (insn) <= 32766)
1065     {
1066       far = 0;
1067       jump = "mov.w     %O0,%1; braf    %1";
1068     }
1069   else
1070     {
1071       far = 1;
1072       if (flag_pic)
1073         {
1074           if (TARGET_SH2)
1075             jump = "mov.l       %O0,%1; braf    %1";
1076           else
1077             jump = "mov.l       r0,@-r15; mova  %O0,r0; mov.l   @r0,%1; add     r0,%1; mov.l    @r15+,r0; jmp   @%1";
1078         }
1079       else
1080         jump = "mov.l   %O0,%1; jmp     @%1";
1081     }
1082   /* If we have a scratch register available, use it.  */
1083   if (GET_CODE ((prev = prev_nonnote_insn (insn))) == INSN
1084       && INSN_CODE (prev) == CODE_FOR_indirect_jump_scratch)
1085     {
1086       this.reg = SET_DEST (XVECEXP (PATTERN (prev), 0, 0));
1087       if (REGNO (this.reg) == R0_REG && flag_pic && ! TARGET_SH2)
1088         jump = "mov.l   r1,@-r15; mova  %O0,r0; mov.l   @r0,r1; add     r1,r0; mov.l    @r15+,r1; jmp   @%1";
1089       output_asm_insn (jump, &this.lab);
1090       if (dbr_sequence_length ())
1091         print_slot (final_sequence);
1092       else
1093         output_asm_insn ("nop", 0);
1094     }
1095   else
1096     {
1097       /* Output the delay slot insn first if any.  */
1098       if (dbr_sequence_length ())
1099         print_slot (final_sequence);
1100
1101       this.reg = gen_rtx_REG (SImode, 13);
1102       /* We must keep the stack aligned to 8-byte boundaries on SH5.
1103          Fortunately, MACL is fixed and call-clobbered, and we never
1104          need its value across jumps, so save r13 in it instead of in
1105          the stack.  */
1106       if (TARGET_SH5)
1107         output_asm_insn ("lds   r13, macl", 0);
1108       else
1109         output_asm_insn ("mov.l r13,@-r15", 0);
1110       output_asm_insn (jump, &this.lab);
1111       if (TARGET_SH5)
1112         output_asm_insn ("sts   macl, r13", 0);
1113       else
1114         output_asm_insn ("mov.l @r15+,r13", 0);
1115     }
1116   if (far && flag_pic && TARGET_SH2)
1117     {
1118       braf_base_lab = gen_label_rtx ();
1119       (*targetm.asm_out.internal_label) (asm_out_file, "L",
1120                                  CODE_LABEL_NUMBER (braf_base_lab));
1121     }
1122   if (far)
1123     output_asm_insn (".align    2", 0);
1124   (*targetm.asm_out.internal_label) (asm_out_file, "L", CODE_LABEL_NUMBER (this.lab));
1125   this.op = op;
1126   if (far && flag_pic)
1127     {
1128       if (TARGET_SH2)
1129         this.lab = braf_base_lab;
1130       output_asm_insn (".long   %O2-%O0", &this.lab);
1131     }
1132   else
1133     output_asm_insn (far ? ".long       %O2" : ".word %O2-%O0", &this.lab);
1134   return "";
1135 }
1136
1137 /* Local label counter, used for constants in the pool and inside
1138    pattern branches.  */
1139
1140 static int lf = 100;
1141
1142 /* Output code for ordinary branches.  */
1143
1144 const char *
1145 output_branch (logic, insn, operands)
1146      int logic;
1147      rtx insn;
1148      rtx *operands;
1149 {
1150   switch (get_attr_length (insn))
1151     {
1152     case 6:
1153       /* This can happen if filling the delay slot has caused a forward
1154          branch to exceed its range (we could reverse it, but only
1155          when we know we won't overextend other branches; this should
1156          best be handled by relaxation).
1157          It can also happen when other condbranches hoist delay slot insn
1158          from their destination, thus leading to code size increase.
1159          But the branch will still be in the range -4092..+4098 bytes.  */
1160
1161       if (! TARGET_RELAX)
1162         {
1163           int label = lf++;
1164           /* The call to print_slot will clobber the operands.  */
1165           rtx op0 = operands[0];
1166     
1167           /* If the instruction in the delay slot is annulled (true), then
1168              there is no delay slot where we can put it now.  The only safe
1169              place for it is after the label.  final will do that by default.  */
1170     
1171           if (final_sequence
1172               && ! INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0)))
1173             {
1174               asm_fprintf (asm_out_file, "\tb%s%ss\t%LLF%d\n", logic ? "f" : "t",
1175                            ASSEMBLER_DIALECT ? "/" : ".", label);
1176               print_slot (final_sequence);
1177             }
1178           else
1179             asm_fprintf (asm_out_file, "\tb%s\t%LLF%d\n", logic ? "f" : "t", label);
1180     
1181           output_asm_insn ("bra\t%l0", &op0);
1182           fprintf (asm_out_file, "\tnop\n");
1183           (*targetm.asm_out.internal_label)(asm_out_file, "LF", label);
1184     
1185           return "";
1186         }
1187       /* When relaxing, handle this like a short branch.  The linker
1188          will fix it up if it still doesn't fit after relaxation.  */
1189     case 2:
1190       return logic ? "bt%.\t%l0" : "bf%.\t%l0";
1191
1192       /* These are for SH2e, in which we have to account for the
1193          extra nop because of the hardware bug in annulled branches.  */
1194     case 8:
1195       if (! TARGET_RELAX)
1196         {
1197           int label = lf++;
1198
1199           if (final_sequence
1200               && INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0)))
1201             abort ();
1202           asm_fprintf (asm_out_file, "b%s%ss\t%LLF%d\n",
1203                        logic ? "f" : "t",
1204                        ASSEMBLER_DIALECT ? "/" : ".", label);
1205           fprintf (asm_out_file, "\tnop\n");
1206           output_asm_insn ("bra\t%l0", operands);
1207           fprintf (asm_out_file, "\tnop\n");
1208           (*targetm.asm_out.internal_label) (asm_out_file, "LF", label);
1209
1210           return "";
1211         }
1212       /* When relaxing, fall through.  */
1213     case 4:
1214       {
1215         char buffer[10];
1216         
1217         sprintf (buffer, "b%s%ss\t%%l0",
1218                  logic ? "t" : "f",
1219                  ASSEMBLER_DIALECT ? "/" : ".");
1220         output_asm_insn (buffer, &operands[0]);
1221         return "nop";
1222       }
1223
1224     default:
1225       /* There should be no longer branches now - that would
1226          indicate that something has destroyed the branches set
1227          up in machine_dependent_reorg.  */
1228       abort ();
1229     }
1230 }
1231
1232 const char *
1233 output_branchy_insn (code, template, insn, operands)
1234      enum rtx_code code;
1235      const char *template;
1236      rtx insn;
1237      rtx *operands;
1238 {
1239   rtx next_insn = NEXT_INSN (insn);
1240
1241   if (next_insn && GET_CODE (next_insn) == JUMP_INSN && condjump_p (next_insn))
1242     {
1243       rtx src = SET_SRC (PATTERN (next_insn));
1244       if (GET_CODE (src) == IF_THEN_ELSE && GET_CODE (XEXP (src, 0)) != code)
1245         {
1246           /* Following branch not taken */
1247           operands[9] = gen_label_rtx ();
1248           emit_label_after (operands[9], next_insn);
1249           INSN_ADDRESSES_NEW (operands[9],
1250                               INSN_ADDRESSES (INSN_UID (next_insn))
1251                               + get_attr_length (next_insn));
1252           return template;
1253         }
1254       else
1255         {
1256           int offset = (branch_dest (next_insn)
1257                         - INSN_ADDRESSES (INSN_UID (next_insn)) + 4);
1258           if (offset >= -252 && offset <= 258)
1259             {
1260               if (GET_CODE (src) == IF_THEN_ELSE)
1261                 /* branch_true */
1262                 src = XEXP (src, 1);
1263               operands[9] = src;
1264               return template;
1265             }
1266         }
1267     }
1268   operands[9] = gen_label_rtx ();
1269   emit_label_after (operands[9], insn);
1270   INSN_ADDRESSES_NEW (operands[9],
1271                       INSN_ADDRESSES (INSN_UID (insn))
1272                       + get_attr_length (insn));
1273   return template;
1274 }
1275
1276 const char *
1277 output_ieee_ccmpeq (insn, operands)
1278      rtx insn, *operands;
1279 {
1280   return output_branchy_insn (NE, "bt\t%l9\\;fcmp/eq\t%1,%0", insn, operands);
1281 }
1282 \f
1283 /* Output to FILE the start of the assembler file.  */
1284
1285 void
1286 output_file_start (file)
1287      FILE *file;
1288 {
1289   output_file_directive (file, main_input_filename);
1290
1291   /* Switch to the data section so that the coffsem symbol
1292      isn't in the text section.  */
1293   data_section ();
1294
1295   if (TARGET_LITTLE_ENDIAN)
1296     fprintf (file, "\t.little\n");
1297
1298   if (TARGET_SHCOMPACT)
1299     fprintf (file, "\t.mode\tSHcompact\n");
1300   else if (TARGET_SHMEDIA)
1301     fprintf (file, "\t.mode\tSHmedia\n\t.abi\t%i\n",
1302              TARGET_SHMEDIA64 ? 64 : 32);
1303 }
1304 \f
1305 /* Check if PAT includes UNSPEC_CALLER unspec pattern.  */
1306
1307 static bool
1308 unspec_caller_rtx_p (pat)
1309      rtx pat;
1310 {
1311   switch (GET_CODE (pat))
1312     {
1313     case CONST:
1314       return unspec_caller_rtx_p (XEXP (pat, 0));
1315     case PLUS:
1316     case MINUS:
1317       if (unspec_caller_rtx_p (XEXP (pat, 0)))
1318         return true;
1319       return unspec_caller_rtx_p (XEXP (pat, 1));
1320     case UNSPEC:
1321       if (XINT (pat, 1) == UNSPEC_CALLER)
1322         return true;
1323     default:
1324       break;
1325     }
1326
1327   return false;
1328 }
1329
1330 /* Indicate that INSN cannot be duplicated.  This is true for insn
1331    that generates an unique label.  */
1332
1333 static bool
1334 sh_cannot_copy_insn_p (insn)
1335      rtx insn;
1336 {
1337   rtx pat;
1338
1339   if (!reload_completed || !flag_pic)
1340     return false;
1341
1342   if (GET_CODE (insn) != INSN)
1343     return false;
1344   if (asm_noperands (insn) >= 0)
1345     return false;
1346
1347   pat = PATTERN (insn);
1348   if (GET_CODE (pat) != SET)
1349     return false;
1350   pat = SET_SRC (pat);
1351
1352   if (unspec_caller_rtx_p (pat))
1353     return true;
1354
1355   return false;
1356 }
1357 \f
1358 /* Actual number of instructions used to make a shift by N.  */
1359 static const char ashiftrt_insns[] =
1360   { 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};
1361
1362 /* Left shift and logical right shift are the same.  */
1363 static const char shift_insns[]    =
1364   { 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};
1365
1366 /* Individual shift amounts needed to get the above length sequences.
1367    One bit right shifts clobber the T bit, so when possible, put one bit
1368    shifts in the middle of the sequence, so the ends are eligible for
1369    branch delay slots.  */
1370 static const short shift_amounts[32][5] = {
1371   {0}, {1}, {2}, {2, 1},
1372   {2, 2}, {2, 1, 2}, {2, 2, 2}, {2, 2, 1, 2},
1373   {8}, {8, 1}, {8, 2}, {8, 1, 2},
1374   {8, 2, 2}, {8, 2, 1, 2}, {8, -2, 8}, {8, -1, 8},
1375   {16}, {16, 1}, {16, 2}, {16, 1, 2},
1376   {16, 2, 2}, {16, 2, 1, 2}, {16, -2, 8}, {16, -1, 8},
1377   {16, 8}, {16, 1, 8}, {16, 8, 2}, {16, 8, 1, 2},
1378   {16, 8, 2, 2}, {16, -1, -2, 16}, {16, -2, 16}, {16, -1, 16}};
1379
1380 /* Likewise, but for shift amounts < 16, up to three highmost bits
1381    might be clobbered.  This is typically used when combined with some
1382    kind of sign or zero extension.  */
1383    
1384 static const char ext_shift_insns[]    =
1385   { 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};
1386
1387 static const short ext_shift_amounts[32][4] = {
1388   {0}, {1}, {2}, {2, 1},
1389   {2, 2}, {2, 1, 2}, {8, -2}, {8, -1},
1390   {8}, {8, 1}, {8, 2}, {8, 1, 2},
1391   {8, 2, 2}, {16, -2, -1}, {16, -2}, {16, -1},
1392   {16}, {16, 1}, {16, 2}, {16, 1, 2},
1393   {16, 2, 2}, {16, 2, 1, 2}, {16, -2, 8}, {16, -1, 8},
1394   {16, 8}, {16, 1, 8}, {16, 8, 2}, {16, 8, 1, 2},
1395   {16, 8, 2, 2}, {16, -1, -2, 16}, {16, -2, 16}, {16, -1, 16}};
1396
1397 /* Assuming we have a value that has been sign-extended by at least one bit,
1398    can we use the ext_shift_amounts with the last shift turned to an arithmetic shift
1399    to shift it by N without data loss, and quicker than by other means?  */
1400 #define EXT_SHIFT_SIGNED(n) (((n) | 8) == 15)
1401
1402 /* This is used in length attributes in sh.md to help compute the length
1403    of arbitrary constant shift instructions.  */
1404
1405 int
1406 shift_insns_rtx (insn)
1407      rtx insn;
1408 {
1409   rtx set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
1410   int shift_count = INTVAL (XEXP (set_src, 1));
1411   enum rtx_code shift_code = GET_CODE (set_src);
1412
1413   switch (shift_code)
1414     {
1415     case ASHIFTRT:
1416       return ashiftrt_insns[shift_count];
1417     case LSHIFTRT:
1418     case ASHIFT:
1419       return shift_insns[shift_count];
1420     default:
1421       abort();
1422     }
1423 }
1424
1425 /* Return the cost of a shift.  */
1426
1427 static inline int
1428 shiftcosts (x)
1429      rtx x;
1430 {
1431   int value;
1432
1433   if (TARGET_SHMEDIA)
1434     return 1;
1435
1436   if (GET_MODE_SIZE (GET_MODE (x)) > UNITS_PER_WORD)
1437     {
1438       if (GET_MODE (x) == DImode
1439           && GET_CODE (XEXP (x, 1)) == CONST_INT
1440           && INTVAL (XEXP (x, 1)) == 1)
1441         return 2;
1442
1443       /* Everything else is invalid, because there is no pattern for it.  */
1444       return 10000;
1445     }
1446   /* If shift by a non constant, then this will be expensive.  */
1447   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
1448     return SH_DYNAMIC_SHIFT_COST;
1449
1450   value = INTVAL (XEXP (x, 1));
1451
1452   /* Otherwise, return the true cost in instructions.  */
1453   if (GET_CODE (x) == ASHIFTRT)
1454     {
1455       int cost = ashiftrt_insns[value];
1456       /* If SH3, then we put the constant in a reg and use shad.  */
1457       if (cost > 1 + SH_DYNAMIC_SHIFT_COST)
1458         cost = 1 + SH_DYNAMIC_SHIFT_COST;
1459       return cost;
1460     }
1461   else
1462     return shift_insns[value];
1463 }
1464
1465 /* Return the cost of an AND operation.  */
1466
1467 static inline int
1468 andcosts (x)
1469      rtx x;
1470 {
1471   int i;
1472
1473   /* Anding with a register is a single cycle and instruction.  */
1474   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
1475     return 1;
1476
1477   i = INTVAL (XEXP (x, 1));
1478
1479   if (TARGET_SHMEDIA)
1480     {
1481       if ((GET_CODE (XEXP (x, 1)) == CONST_INT
1482            && CONST_OK_FOR_J (INTVAL (XEXP (x, 1))))
1483           || EXTRA_CONSTRAINT_S (XEXP (x, 1)))
1484         return 1;
1485       else
1486         return 2;
1487     }
1488
1489   /* These constants are single cycle extu.[bw] instructions.  */
1490   if (i == 0xff || i == 0xffff)
1491     return 1;
1492   /* Constants that can be used in an and immediate instruction is a single
1493      cycle, but this requires r0, so make it a little more expensive.  */
1494   if (CONST_OK_FOR_L (i))
1495     return 2;
1496   /* Constants that can be loaded with a mov immediate and an and.
1497      This case is probably unnecessary.  */
1498   if (CONST_OK_FOR_I (i))
1499     return 2;
1500   /* Any other constants requires a 2 cycle pc-relative load plus an and.
1501      This case is probably unnecessary.  */
1502   return 3;
1503 }
1504
1505 /* Return the cost of an addition or a subtraction.  */
1506
1507 static inline int
1508 addsubcosts (x)
1509      rtx x;
1510 {
1511   /* Adding a register is a single cycle insn.  */
1512   if (GET_CODE (XEXP (x, 1)) == REG
1513       || GET_CODE (XEXP (x, 1)) == SUBREG)
1514     return 1;
1515
1516   /* Likewise for small constants.  */
1517   if (GET_CODE (XEXP (x, 1)) == CONST_INT
1518       && CONST_OK_FOR_ADD (INTVAL (XEXP (x, 1))))
1519     return 1;
1520
1521   if (TARGET_SHMEDIA)
1522     switch (GET_CODE (XEXP (x, 1)))
1523       {
1524       case CONST:
1525       case LABEL_REF:
1526       case SYMBOL_REF:
1527         return TARGET_SHMEDIA64 ? 5 : 3;
1528
1529       case CONST_INT:
1530         if (CONST_OK_FOR_J (INTVAL (XEXP (x, 1))))
1531           return 2;
1532         else if (CONST_OK_FOR_J (INTVAL (XEXP (x, 1)) >> 16))
1533           return 3;
1534         else if (CONST_OK_FOR_J ((INTVAL (XEXP (x, 1)) >> 16) >> 16))
1535           return 4;
1536
1537         /* Fall through.  */
1538       default:
1539           return 5;
1540       }
1541
1542   /* Any other constant requires a 2 cycle pc-relative load plus an
1543      addition.  */
1544   return 3;
1545 }
1546
1547 /* Return the cost of a multiply.  */
1548 static inline int
1549 multcosts (x)
1550      rtx x ATTRIBUTE_UNUSED;
1551 {
1552   if (TARGET_SHMEDIA)
1553     return 3;
1554
1555   if (TARGET_SH2)
1556     {
1557       /* We have a mul insn, so we can never take more than the mul and the
1558          read of the mac reg, but count more because of the latency and extra
1559          reg usage.  */
1560       if (TARGET_SMALLCODE)
1561         return 2;
1562       return 3;
1563     }
1564
1565   /* If we're aiming at small code, then just count the number of
1566      insns in a multiply call sequence.  */
1567   if (TARGET_SMALLCODE)
1568     return 5;
1569
1570   /* Otherwise count all the insns in the routine we'd be calling too.  */
1571   return 20;
1572 }
1573
1574 /* Compute a (partial) cost for rtx X.  Return true if the complete
1575    cost has been computed, and false if subexpressions should be
1576    scanned.  In either case, *TOTAL contains the cost result.  */
1577
1578 static bool
1579 sh_rtx_costs (x, code, outer_code, total)
1580      rtx x;
1581      int code, outer_code, *total;
1582 {
1583   switch (code)
1584     {
1585     case CONST_INT:
1586       if (TARGET_SHMEDIA)
1587         {
1588           if (INTVAL (x) == 0)
1589             *total = 0;
1590           else if (outer_code == AND && and_operand ((x), DImode))
1591             *total = 0;
1592           else if ((outer_code == IOR || outer_code == XOR
1593                     || outer_code == PLUS)
1594                    && CONST_OK_FOR_P (INTVAL (x)))
1595             *total = 0;
1596           else if (CONST_OK_FOR_J (INTVAL (x)))
1597             *total = COSTS_N_INSNS (outer_code != SET);
1598           else if (CONST_OK_FOR_J (INTVAL (x) >> 16))
1599             *total = COSTS_N_INSNS (2);
1600           else if (CONST_OK_FOR_J ((INTVAL (x) >> 16) >> 16))
1601             *total = COSTS_N_INSNS (3);
1602           else
1603             *total = COSTS_N_INSNS (4);
1604           return true;
1605         }
1606       if (CONST_OK_FOR_I (INTVAL (x)))
1607         *total = 0;
1608       else if ((outer_code == AND || outer_code == IOR || outer_code == XOR)
1609                && CONST_OK_FOR_L (INTVAL (x)))
1610         *total = 1;
1611       else
1612         *total = 8;
1613       return true;
1614
1615     case CONST:
1616     case LABEL_REF:
1617     case SYMBOL_REF:
1618       if (TARGET_SHMEDIA64)
1619         *total = COSTS_N_INSNS (4);
1620       else if (TARGET_SHMEDIA32)
1621         *total = COSTS_N_INSNS (2);
1622       else
1623         *total = 5;
1624       return true;
1625
1626     case CONST_DOUBLE:
1627       if (TARGET_SHMEDIA)
1628         *total = COSTS_N_INSNS (4);
1629       else
1630         *total = 10;
1631       return true;
1632
1633     case PLUS:
1634       *total = COSTS_N_INSNS (addsubcosts (x));
1635       return true;
1636
1637     case AND:
1638       *total = COSTS_N_INSNS (andcosts (x));
1639       return true;
1640
1641     case MULT:
1642       *total = COSTS_N_INSNS (multcosts (x));
1643       return true;
1644
1645     case ASHIFT:
1646     case ASHIFTRT:
1647     case LSHIFTRT:
1648       *total = COSTS_N_INSNS (shiftcosts (x));
1649       return true;
1650
1651     case DIV:
1652     case UDIV:
1653     case MOD:
1654     case UMOD:
1655       *total = COSTS_N_INSNS (20);
1656       return true;
1657
1658     case FLOAT:
1659     case FIX:
1660       *total = 100;
1661       return true;
1662
1663     default:
1664       return false;
1665     }
1666 }
1667
1668 /* Compute the cost of an address.  For the SH, all valid addresses are
1669    the same cost.  Use a slightly higher cost for reg + reg addressing,
1670    since it increases pressure on r0.  */
1671
1672 static int
1673 sh_address_cost (X)
1674      rtx X;
1675 {
1676   return (GET_CODE (X) == PLUS
1677           && ! CONSTANT_P (XEXP (X, 1))
1678           && ! TARGET_SHMEDIA ? 1 : 0);
1679 }
1680
1681 /* Code to expand a shift.  */
1682
1683 void
1684 gen_ashift (type, n, reg)
1685      int type;
1686      int n;
1687      rtx reg;
1688 {
1689   /* Negative values here come from the shift_amounts array.  */
1690   if (n < 0)
1691     {
1692       if (type == ASHIFT)
1693         type = LSHIFTRT;
1694       else
1695         type = ASHIFT;
1696       n = -n;
1697     }
1698
1699   switch (type)
1700     {
1701     case ASHIFTRT:
1702       emit_insn (gen_ashrsi3_k (reg, reg, GEN_INT (n)));
1703       break;
1704     case LSHIFTRT:
1705       if (n == 1)
1706         emit_insn (gen_lshrsi3_m (reg, reg, GEN_INT (n)));
1707       else
1708         emit_insn (gen_lshrsi3_k (reg, reg, GEN_INT (n)));
1709       break;
1710     case ASHIFT:
1711       emit_insn (gen_ashlsi3_std (reg, reg, GEN_INT (n)));
1712       break;
1713     }
1714 }
1715
1716 /* Same for HImode */
1717
1718 void
1719 gen_ashift_hi (type, n, reg)
1720      int type;
1721      int n;
1722      rtx reg;
1723 {
1724   /* Negative values here come from the shift_amounts array.  */
1725   if (n < 0)
1726     {
1727       if (type == ASHIFT)
1728         type = LSHIFTRT;
1729       else
1730         type = ASHIFT;
1731       n = -n;
1732     }
1733
1734   switch (type)
1735     {
1736     case ASHIFTRT:
1737     case LSHIFTRT:
1738       /* We don't have HImode right shift operations because using the
1739          ordinary 32 bit shift instructions for that doesn't generate proper
1740          zero/sign extension.
1741          gen_ashift_hi is only called in contexts where we know that the
1742          sign extension works out correctly.  */
1743       {
1744         int offset = 0;
1745         if (GET_CODE (reg) == SUBREG)
1746           {
1747             offset = SUBREG_BYTE (reg);
1748             reg = SUBREG_REG (reg);
1749           }
1750         gen_ashift (type, n, gen_rtx_SUBREG (SImode, reg, offset));
1751         break;
1752       }
1753     case ASHIFT:
1754       emit_insn (gen_ashlhi3_k (reg, reg, GEN_INT (n)));
1755       break;
1756     }
1757 }
1758
1759 /* Output RTL to split a constant shift into its component SH constant
1760    shift instructions.  */
1761    
1762 void
1763 gen_shifty_op (code, operands)
1764      int code;
1765      rtx *operands;
1766 {
1767   int value = INTVAL (operands[2]);
1768   int max, i;
1769
1770   /* Truncate the shift count in case it is out of bounds.  */
1771   value = value & 0x1f;
1772  
1773   if (value == 31)
1774     {
1775       if (code == LSHIFTRT)
1776         {
1777           emit_insn (gen_rotlsi3_1 (operands[0], operands[0]));
1778           emit_insn (gen_movt (operands[0]));
1779           return;
1780         }
1781       else if (code == ASHIFT)
1782         {
1783           /* There is a two instruction sequence for 31 bit left shifts,
1784              but it requires r0.  */
1785           if (GET_CODE (operands[0]) == REG && REGNO (operands[0]) == 0)
1786             {
1787               emit_insn (gen_andsi3 (operands[0], operands[0], const1_rtx));
1788               emit_insn (gen_rotlsi3_31 (operands[0], operands[0]));
1789               return;
1790             }
1791         }
1792     }
1793   else if (value == 0)
1794     {
1795       /* This can happen when not optimizing.  We must output something here
1796          to prevent the compiler from aborting in final.c after the try_split
1797          call.  */
1798       emit_insn (gen_nop ());
1799       return;
1800     }
1801
1802   max = shift_insns[value];
1803   for (i = 0; i < max; i++)
1804     gen_ashift (code, shift_amounts[value][i], operands[0]);
1805 }
1806    
1807 /* Same as above, but optimized for values where the topmost bits don't
1808    matter.  */
1809
1810 void
1811 gen_shifty_hi_op (code, operands)
1812      int code;
1813      rtx *operands;
1814 {
1815   int value = INTVAL (operands[2]);
1816   int max, i;
1817   void (*gen_fun) PARAMS ((int, int, rtx));
1818
1819   /* This operation is used by and_shl for SImode values with a few
1820      high bits known to be cleared.  */
1821   value &= 31;
1822   if (value == 0)
1823     {
1824       emit_insn (gen_nop ());
1825       return;
1826     }
1827
1828   gen_fun = GET_MODE (operands[0]) == HImode ? gen_ashift_hi : gen_ashift;
1829   if (code == ASHIFT)
1830     {
1831       max = ext_shift_insns[value];
1832       for (i = 0; i < max; i++)
1833         gen_fun (code, ext_shift_amounts[value][i], operands[0]);
1834     }
1835   else
1836     /* When shifting right, emit the shifts in reverse order, so that
1837        solitary negative values come first.  */
1838     for (i = ext_shift_insns[value] - 1; i >= 0; i--)
1839       gen_fun (code, ext_shift_amounts[value][i], operands[0]);
1840 }
1841
1842 /* Output RTL for an arithmetic right shift.  */
1843
1844 /* ??? Rewrite to use super-optimizer sequences.  */
1845
1846 int
1847 expand_ashiftrt (operands)
1848      rtx *operands;
1849 {
1850   rtx sym;
1851   rtx wrk;
1852   char func[18];
1853   tree func_name;
1854   int value;
1855
1856   if (TARGET_SH3)
1857     {
1858       if (GET_CODE (operands[2]) != CONST_INT)
1859         {
1860           rtx count = copy_to_mode_reg (SImode, operands[2]);
1861           emit_insn (gen_negsi2 (count, count));
1862           emit_insn (gen_ashrsi3_d (operands[0], operands[1], count));
1863           return 1;
1864         }
1865       else if (ashiftrt_insns[INTVAL (operands[2]) & 31]
1866                > 1 + SH_DYNAMIC_SHIFT_COST)
1867         {
1868           rtx count
1869             = force_reg (SImode, GEN_INT (- (INTVAL (operands[2]) & 31)));
1870           emit_insn (gen_ashrsi3_d (operands[0], operands[1], count));
1871           return 1;
1872         }
1873     }
1874   if (GET_CODE (operands[2]) != CONST_INT)
1875     return 0;
1876
1877   value = INTVAL (operands[2]) & 31;
1878
1879   if (value == 31)
1880     {
1881       emit_insn (gen_ashrsi2_31 (operands[0], operands[1]));
1882       return 1;
1883     }
1884   else if (value >= 16 && value <= 19)
1885     {
1886       wrk = gen_reg_rtx (SImode);
1887       emit_insn (gen_ashrsi2_16 (wrk, operands[1]));
1888       value -= 16;
1889       while (value--)
1890         gen_ashift (ASHIFTRT, 1, wrk);
1891       emit_move_insn (operands[0], wrk);
1892       return 1;
1893     }
1894   /* Expand a short sequence inline, longer call a magic routine.  */
1895   else if (value <= 5)
1896     {
1897       wrk = gen_reg_rtx (SImode);
1898       emit_move_insn (wrk, operands[1]);
1899       while (value--)
1900         gen_ashift (ASHIFTRT, 1, wrk);
1901       emit_move_insn (operands[0], wrk);
1902       return 1;
1903     }
1904
1905   wrk = gen_reg_rtx (Pmode);
1906
1907   /* Load the value into an arg reg and call a helper.  */
1908   emit_move_insn (gen_rtx_REG (SImode, 4), operands[1]);
1909   sprintf (func, "__ashiftrt_r4_%d", value);
1910   func_name = get_identifier (func);
1911   sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (func_name));
1912   emit_move_insn (wrk, sym);
1913   emit_insn (gen_ashrsi3_n (GEN_INT (value), wrk));
1914   emit_move_insn (operands[0], gen_rtx_REG (SImode, 4));
1915   return 1;
1916 }
1917
1918 int
1919 sh_dynamicalize_shift_p (count)
1920      rtx count;
1921 {
1922   return shift_insns[INTVAL (count)] > 1 + SH_DYNAMIC_SHIFT_COST;
1923 }
1924
1925 /* Try to find a good way to implement the combiner pattern
1926   [(set (match_operand:SI 0 "register_operand" "r")
1927         (and:SI (ashift:SI (match_operand:SI 1 "register_operand" "r")
1928                            (match_operand:SI 2 "const_int_operand" "n"))
1929                 (match_operand:SI 3 "const_int_operand" "n"))) .
1930   LEFT_RTX is operand 2 in the above pattern, and MASK_RTX is operand 3.
1931   return 0 for simple right / left or left/right shift combination.
1932   return 1 for a combination of shifts with zero_extend.
1933   return 2 for a combination of shifts with an AND that needs r0.
1934   return 3 for a combination of shifts with an AND that needs an extra
1935     scratch register, when the three highmost bits of the AND mask are clear.
1936   return 4 for a combination of shifts with an AND that needs an extra
1937     scratch register, when any of the three highmost bits of the AND mask
1938     is set.
1939   If ATTRP is set, store an initial right shift width in ATTRP[0],
1940   and the instruction length in ATTRP[1] .  These values are not valid
1941   when returning 0.
1942   When ATTRP is set and returning 1, ATTRP[2] gets set to the index into
1943   shift_amounts for the last shift value that is to be used before the
1944   sign extend.  */
1945 int
1946 shl_and_kind (left_rtx, mask_rtx, attrp)
1947      rtx left_rtx, mask_rtx;
1948      int *attrp;
1949 {
1950   unsigned HOST_WIDE_INT mask, lsb, mask2, lsb2;
1951   int left = INTVAL (left_rtx), right;
1952   int best = 0;
1953   int cost, best_cost = 10000;
1954   int best_right = 0, best_len = 0;
1955   int i;
1956   int can_ext;
1957
1958   if (left < 0 || left > 31)
1959     return 0;
1960   if (GET_CODE (mask_rtx) == CONST_INT)
1961     mask = (unsigned HOST_WIDE_INT) INTVAL (mask_rtx) >> left;
1962   else
1963     mask = (unsigned HOST_WIDE_INT) GET_MODE_MASK (SImode) >> left;
1964   /* Can this be expressed as a right shift / left shift pair ? */
1965   lsb = ((mask ^ (mask - 1)) >> 1) + 1;
1966   right = exact_log2 (lsb);
1967   mask2 = ~(mask + lsb - 1);
1968   lsb2 = ((mask2 ^ (mask2 - 1)) >> 1) + 1;
1969   /* mask has no zeroes but trailing zeroes <==> ! mask2 */
1970   if (! mask2)
1971     best_cost = shift_insns[right] + shift_insns[right + left];
1972   /* mask has no trailing zeroes <==> ! right */
1973   else if (! right && mask2 == ~(lsb2 - 1))
1974     {
1975       int late_right = exact_log2 (lsb2);
1976       best_cost = shift_insns[left + late_right] + shift_insns[late_right];
1977     }
1978   /* Try to use zero extend */
1979   if (mask2 == ~(lsb2 - 1))
1980     {
1981       int width, first;
1982
1983       for (width = 8; width <= 16; width += 8)
1984         {
1985           /* Can we zero-extend right away? */
1986           if (lsb2 == (unsigned HOST_WIDE_INT)1 << width)
1987             {
1988               cost
1989                 = 1 + ext_shift_insns[right] + ext_shift_insns[left + right];
1990               if (cost < best_cost)
1991                 {
1992                   best = 1;
1993                   best_cost = cost;
1994                   best_right = right;
1995                   best_len = cost;
1996                   if (attrp)
1997                     attrp[2] = -1;
1998                 }
1999               continue;
2000             }
2001           /* ??? Could try to put zero extend into initial right shift,
2002              or even shift a bit left before the right shift.  */
2003           /* Determine value of first part of left shift, to get to the
2004              zero extend cut-off point.  */
2005           first = width - exact_log2 (lsb2) + right;
2006           if (first >= 0 && right + left - first >= 0)
2007             {
2008               cost = ext_shift_insns[right] + ext_shift_insns[first] + 1
2009                 + ext_shift_insns[right + left - first];
2010               if (cost < best_cost)
2011                 {
2012                   best = 1;
2013                   best_cost = cost;
2014                   best_right = right;
2015                   best_len = cost;
2016                   if (attrp)
2017                     attrp[2] = first;
2018                   }
2019             }
2020         }
2021     }
2022   /* Try to use r0 AND pattern */
2023   for (i = 0; i <= 2; i++)
2024     {
2025       if (i > right)
2026         break;
2027       if (! CONST_OK_FOR_L (mask >> i))
2028         continue;
2029       cost = (i != 0) + 2 + ext_shift_insns[left + i];
2030       if (cost < best_cost)
2031         {
2032           best = 2;
2033           best_cost = cost;
2034           best_right = i;
2035           best_len = cost - 1;
2036         }
2037     }
2038   /* Try to use a scratch register to hold the AND operand.  */
2039   can_ext = ((mask << left) & ((unsigned HOST_WIDE_INT)3 << 30)) == 0;
2040   for (i = 0; i <= 2; i++)
2041     {
2042       if (i > right)
2043         break;
2044       cost = (i != 0) + (CONST_OK_FOR_I (mask >> i) ? 2 : 3)
2045         + (can_ext ? ext_shift_insns : shift_insns)[left + i];
2046       if (cost < best_cost)
2047         {
2048           best = 4 - can_ext;
2049           best_cost = cost;
2050           best_right = i;
2051           best_len = cost - 1 - ! CONST_OK_FOR_I (mask >> i);
2052         }
2053     }
2054
2055   if (attrp)
2056     {
2057       attrp[0] = best_right;
2058       attrp[1] = best_len;
2059     }
2060   return best;
2061 }
2062
2063 /* This is used in length attributes of the unnamed instructions
2064    corresponding to shl_and_kind return values of 1 and 2.  */
2065 int
2066 shl_and_length (insn)
2067      rtx insn;
2068 {
2069   rtx set_src, left_rtx, mask_rtx;
2070   int attributes[3];
2071
2072   set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
2073   left_rtx = XEXP (XEXP (set_src, 0), 1);
2074   mask_rtx = XEXP (set_src, 1);
2075   shl_and_kind (left_rtx, mask_rtx, attributes);
2076   return attributes[1];
2077 }
2078
2079 /* This is used in length attribute of the and_shl_scratch instruction.  */
2080
2081 int
2082 shl_and_scr_length (insn)
2083      rtx insn;
2084 {
2085   rtx set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
2086   int len = shift_insns[INTVAL (XEXP (set_src, 1))];
2087   rtx op = XEXP (set_src, 0);
2088   len += shift_insns[INTVAL (XEXP (op, 1))] + 1;
2089   op = XEXP (XEXP (op, 0), 0);
2090   return len + shift_insns[INTVAL (XEXP (op, 1))];
2091 }
2092
2093 /* Generating rtl? */
2094 extern int rtx_equal_function_value_matters;
2095
2096 /* Generate rtl for instructions for which shl_and_kind advised a particular
2097    method of generating them, i.e. returned zero.  */
2098
2099 int
2100 gen_shl_and (dest, left_rtx, mask_rtx, source)
2101      rtx dest, left_rtx, mask_rtx, source;
2102 {
2103   int attributes[3];
2104   unsigned HOST_WIDE_INT mask;
2105   int kind = shl_and_kind (left_rtx, mask_rtx, attributes);
2106   int right, total_shift;
2107   void (*shift_gen_fun) PARAMS ((int, rtx*)) = gen_shifty_hi_op;
2108
2109   right = attributes[0];
2110   total_shift = INTVAL (left_rtx) + right;
2111   mask = (unsigned HOST_WIDE_INT) INTVAL (mask_rtx) >> total_shift;
2112   switch (kind)
2113     {
2114     default:
2115       return -1;
2116     case 1:
2117       {
2118         int first = attributes[2];
2119         rtx operands[3];
2120
2121         if (first < 0)
2122           {
2123             emit_insn ((mask << right) <= 0xff
2124                        ? gen_zero_extendqisi2(dest,
2125                                               gen_lowpart (QImode, source))
2126                        : gen_zero_extendhisi2(dest,
2127                                               gen_lowpart (HImode, source)));
2128             source = dest;
2129           }
2130         if (source != dest)
2131           emit_insn (gen_movsi (dest, source));
2132         operands[0] = dest;
2133         if (right)
2134           {
2135             operands[2] = GEN_INT (right);
2136             gen_shifty_hi_op (LSHIFTRT, operands);
2137           }
2138         if (first > 0)
2139           {
2140             operands[2] = GEN_INT (first);
2141             gen_shifty_hi_op (ASHIFT, operands);
2142             total_shift -= first;
2143             mask <<= first;
2144           }
2145         if (first >= 0)
2146           emit_insn (mask <= 0xff
2147                      ? gen_zero_extendqisi2(dest, gen_lowpart (QImode, dest))
2148                      : gen_zero_extendhisi2(dest, gen_lowpart (HImode, dest)));
2149         if (total_shift > 0)
2150           {
2151             operands[2] = GEN_INT (total_shift);
2152             gen_shifty_hi_op (ASHIFT, operands);
2153           }
2154         break;
2155       }
2156     case 4:
2157       shift_gen_fun = gen_shifty_op;
2158     case 3:
2159       /* If the topmost bit that matters is set, set the topmost bits
2160          that don't matter.  This way, we might be able to get a shorter
2161          signed constant.  */
2162       if (mask & ((HOST_WIDE_INT)1 << (31 - total_shift)))
2163         mask |= (HOST_WIDE_INT)~0 << (31 - total_shift);
2164     case 2:
2165       /* Don't expand fine-grained when combining, because that will
2166          make the pattern fail.  */
2167       if (rtx_equal_function_value_matters
2168           || reload_in_progress || reload_completed)
2169         {
2170           rtx operands[3];
2171   
2172           /* Cases 3 and 4 should be handled by this split
2173              only while combining  */
2174           if (kind > 2)
2175             abort ();
2176           if (right)
2177             {
2178               emit_insn (gen_lshrsi3 (dest, source, GEN_INT (right)));
2179               source = dest;
2180             }
2181           emit_insn (gen_andsi3 (dest, source, GEN_INT (mask)));
2182           if (total_shift)
2183             {
2184               operands[0] = dest;
2185               operands[1] = dest;
2186               operands[2] = GEN_INT (total_shift);
2187               shift_gen_fun (ASHIFT, operands);
2188             }
2189           break;
2190         }
2191       else
2192         {
2193           int neg = 0;
2194           if (kind != 4 && total_shift < 16)
2195             {
2196               neg = -ext_shift_amounts[total_shift][1];
2197               if (neg > 0)
2198                 neg -= ext_shift_amounts[total_shift][2];
2199               else
2200                 neg = 0;
2201             }
2202           emit_insn (gen_and_shl_scratch (dest, source,
2203                                           GEN_INT (right),
2204                                           GEN_INT (mask),
2205                                           GEN_INT (total_shift + neg),
2206                                           GEN_INT (neg)));
2207           emit_insn (gen_movsi (dest, dest));
2208           break;
2209         }
2210     }
2211   return 0;
2212 }
2213
2214 /* Try to find a good way to implement the combiner pattern
2215   [(set (match_operand:SI 0 "register_operand" "=r")
2216         (sign_extract:SI (ashift:SI (match_operand:SI 1 "register_operand" "r")
2217                                     (match_operand:SI 2 "const_int_operand" "n")
2218                          (match_operand:SI 3 "const_int_operand" "n")
2219                          (const_int 0)))
2220    (clobber (reg:SI T_REG))]
2221   LEFT_RTX is operand 2 in the above pattern, and SIZE_RTX is operand 3.
2222   return 0 for simple left / right shift combination.
2223   return 1 for left shift / 8 bit sign extend / left shift.
2224   return 2 for left shift / 16 bit sign extend / left shift.
2225   return 3 for left shift / 8 bit sign extend / shift / sign extend.
2226   return 4 for left shift / 16 bit sign extend / shift / sign extend.
2227   return 5 for left shift / 16 bit sign extend / right shift
2228   return 6 for < 8 bit sign extend / left shift.
2229   return 7 for < 8 bit sign extend / left shift / single right shift.
2230   If COSTP is nonzero, assign the calculated cost to *COSTP.  */
2231
2232 int
2233 shl_sext_kind (left_rtx, size_rtx, costp)
2234      rtx left_rtx, size_rtx;
2235      int *costp;
2236 {
2237   int left, size, insize, ext;
2238   int cost = 0, best_cost;
2239   int kind;
2240
2241   left = INTVAL (left_rtx);
2242   size = INTVAL (size_rtx);
2243   insize = size - left;
2244   if (insize <= 0)
2245     abort ();
2246   /* Default to left / right shift.  */
2247   kind = 0;
2248   best_cost = shift_insns[32 - insize] + ashiftrt_insns[32 - size];
2249   if (size <= 16)
2250     {
2251       /* 16 bit shift / sign extend / 16 bit shift */
2252       cost = shift_insns[16 - insize] + 1 + ashiftrt_insns[16 - size];
2253       /* If ashiftrt_insns[16 - size] is 8, this choice will be overridden
2254          below, by alternative 3 or something even better.  */
2255       if (cost < best_cost)
2256         {
2257           kind = 5;
2258           best_cost = cost;
2259         }
2260     }
2261   /* Try a plain sign extend between two shifts.  */
2262   for (ext = 16; ext >= insize; ext -= 8)
2263     {
2264       if (ext <= size)
2265         {
2266           cost = ext_shift_insns[ext - insize] + 1 + shift_insns[size - ext];
2267           if (cost < best_cost)
2268             {
2269               kind = ext / (unsigned) 8;
2270               best_cost = cost;
2271             }
2272         }
2273       /* Check if we can do a sloppy shift with a final signed shift
2274          restoring the sign.  */
2275       if (EXT_SHIFT_SIGNED (size - ext))
2276         cost = ext_shift_insns[ext - insize] + ext_shift_insns[size - ext] + 1;
2277       /* If not, maybe it's still cheaper to do the second shift sloppy,
2278          and do a final sign extend?  */
2279       else if (size <= 16)
2280         cost = ext_shift_insns[ext - insize] + 1
2281           + ext_shift_insns[size > ext ? size - ext : ext - size] + 1;
2282       else
2283         continue;
2284       if (cost < best_cost)
2285         {
2286           kind = ext / (unsigned) 8 + 2;
2287           best_cost = cost;
2288         }
2289     }
2290   /* Check if we can sign extend in r0 */
2291   if (insize < 8)
2292     {
2293       cost = 3 + shift_insns[left];
2294       if (cost < best_cost)
2295         {
2296           kind = 6;
2297           best_cost = cost;
2298         }
2299       /* Try the same with a final signed shift.  */
2300       if (left < 31)
2301         {
2302           cost = 3 + ext_shift_insns[left + 1] + 1;
2303           if (cost < best_cost)
2304             {
2305               kind = 7;
2306               best_cost = cost;
2307             }
2308         }
2309     }
2310   if (TARGET_SH3)
2311     {
2312       /* Try to use a dynamic shift.  */
2313       cost = shift_insns[32 - insize] + 1 + SH_DYNAMIC_SHIFT_COST;
2314       if (cost < best_cost)
2315         {
2316           kind = 0;
2317           best_cost = cost;
2318         }
2319     }
2320   if (costp)
2321     *costp = cost;
2322   return kind;
2323 }
2324
2325 /* Function to be used in the length attribute of the instructions
2326    implementing this pattern.  */
2327
2328 int
2329 shl_sext_length (insn)
2330      rtx insn;
2331 {
2332   rtx set_src, left_rtx, size_rtx;
2333   int cost;
2334
2335   set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
2336   left_rtx = XEXP (XEXP (set_src, 0), 1);
2337   size_rtx = XEXP (set_src, 1);
2338   shl_sext_kind (left_rtx, size_rtx, &cost);
2339   return cost;
2340 }
2341
2342 /* Generate rtl for this pattern */
2343
2344 int
2345 gen_shl_sext (dest, left_rtx, size_rtx, source)
2346      rtx dest, left_rtx, size_rtx, source;
2347 {
2348   int kind;
2349   int left, size, insize, cost;
2350   rtx operands[3];
2351
2352   kind = shl_sext_kind (left_rtx, size_rtx, &cost);
2353   left = INTVAL (left_rtx);
2354   size = INTVAL (size_rtx);
2355   insize = size - left;
2356   switch (kind)
2357     {
2358     case 1:
2359     case 2:
2360     case 3:
2361     case 4:
2362       {
2363         int ext = kind & 1 ? 8 : 16;
2364         int shift2 = size - ext;
2365
2366         /* Don't expand fine-grained when combining, because that will
2367            make the pattern fail.  */
2368         if (! rtx_equal_function_value_matters
2369             && ! reload_in_progress && ! reload_completed)
2370           {
2371             emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
2372             emit_insn (gen_movsi (dest, source));
2373             break;
2374           }
2375         if (dest != source)
2376           emit_insn (gen_movsi (dest, source));
2377         operands[0] = dest;
2378         if (ext - insize)
2379           {
2380             operands[2] = GEN_INT (ext - insize);
2381             gen_shifty_hi_op (ASHIFT, operands);
2382           }
2383         emit_insn (kind & 1
2384                    ? gen_extendqisi2(dest, gen_lowpart (QImode, dest))
2385                    : gen_extendhisi2(dest, gen_lowpart (HImode, dest)));
2386         if (kind <= 2)
2387           {
2388             if (shift2)
2389               {
2390                 operands[2] = GEN_INT (shift2);
2391                 gen_shifty_op (ASHIFT, operands);
2392               }
2393           }
2394         else
2395           {
2396             if (shift2 > 0)
2397               {
2398                 if (EXT_SHIFT_SIGNED (shift2))
2399                   {
2400                     operands[2] = GEN_INT (shift2 + 1);
2401                     gen_shifty_op (ASHIFT, operands);
2402                     operands[2] = GEN_INT (1);
2403                     gen_shifty_op (ASHIFTRT, operands);
2404                     break;
2405                   }
2406                 operands[2] = GEN_INT (shift2);
2407                 gen_shifty_hi_op (ASHIFT, operands);
2408               }
2409             else if (shift2)
2410               {
2411                 operands[2] = GEN_INT (-shift2);
2412                 gen_shifty_hi_op (LSHIFTRT, operands);
2413               }
2414             emit_insn (size <= 8
2415                        ? gen_extendqisi2 (dest, gen_lowpart (QImode, dest))
2416                        : gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
2417           }
2418         break;
2419       }
2420     case 5:
2421       {
2422         int i = 16 - size;
2423         if (! rtx_equal_function_value_matters
2424             && ! reload_in_progress && ! reload_completed)
2425           emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
2426         else
2427           {
2428             operands[0] = dest;
2429             operands[2] = GEN_INT (16 - insize);
2430             gen_shifty_hi_op (ASHIFT, operands);
2431             emit_insn (gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
2432           }
2433         /* Don't use gen_ashrsi3 because it generates new pseudos.  */
2434         while (--i >= 0)
2435           gen_ashift (ASHIFTRT, 1, dest);
2436         break;
2437       }
2438     case 6:
2439     case 7:
2440       /* Don't expand fine-grained when combining, because that will
2441          make the pattern fail.  */
2442       if (! rtx_equal_function_value_matters
2443           && ! reload_in_progress && ! reload_completed)
2444         {
2445           emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
2446           emit_insn (gen_movsi (dest, source));
2447           break;
2448         }
2449       emit_insn (gen_andsi3 (dest, source, GEN_INT ((1 << insize) - 1)));
2450       emit_insn (gen_xorsi3 (dest, dest, GEN_INT (1 << (insize - 1))));
2451       emit_insn (gen_addsi3 (dest, dest, GEN_INT (-1 << (insize - 1))));
2452       operands[0] = dest;
2453       operands[2] = kind == 7 ? GEN_INT (left + 1) : left_rtx;
2454       gen_shifty_op (ASHIFT, operands);
2455       if (kind == 7)
2456         emit_insn (gen_ashrsi3_k (dest, dest, GEN_INT (1)));
2457       break;
2458     default:
2459       return -1;
2460     }
2461   return 0;
2462 }
2463
2464 /* Prefix a symbol_ref name with "datalabel".  */
2465
2466 rtx
2467 gen_datalabel_ref (sym)
2468      rtx sym;
2469 {
2470   if (GET_CODE (sym) == LABEL_REF)
2471     return gen_rtx_CONST (GET_MODE (sym),
2472                           gen_rtx_UNSPEC (GET_MODE (sym),
2473                                           gen_rtvec (1, sym),
2474                                           UNSPEC_DATALABEL));
2475     
2476   if (GET_CODE (sym) != SYMBOL_REF)
2477     abort ();
2478
2479   return sym;
2480 }
2481
2482 \f
2483 /* The SH cannot load a large constant into a register, constants have to
2484    come from a pc relative load.  The reference of a pc relative load
2485    instruction must be less than 1k infront of the instruction.  This
2486    means that we often have to dump a constant inside a function, and
2487    generate code to branch around it.
2488
2489    It is important to minimize this, since the branches will slow things
2490    down and make things bigger.
2491
2492    Worst case code looks like:
2493
2494    mov.l L1,rn
2495    bra   L2
2496    nop
2497    align
2498    L1:   .long value
2499    L2:
2500    ..
2501
2502    mov.l L3,rn
2503    bra   L4
2504    nop
2505    align
2506    L3:   .long value
2507    L4:
2508    ..
2509
2510    We fix this by performing a scan before scheduling, which notices which
2511    instructions need to have their operands fetched from the constant table
2512    and builds the table.
2513
2514    The algorithm is:
2515
2516    scan, find an instruction which needs a pcrel move.  Look forward, find the
2517    last barrier which is within MAX_COUNT bytes of the requirement.
2518    If there isn't one, make one.  Process all the instructions between
2519    the find and the barrier.
2520
2521    In the above example, we can tell that L3 is within 1k of L1, so
2522    the first move can be shrunk from the 3 insn+constant sequence into
2523    just 1 insn, and the constant moved to L3 to make:
2524
2525    mov.l        L1,rn
2526    ..
2527    mov.l        L3,rn
2528    bra          L4
2529    nop
2530    align
2531    L3:.long value
2532    L4:.long value
2533
2534    Then the second move becomes the target for the shortening process.  */
2535
2536 typedef struct
2537 {
2538   rtx value;                    /* Value in table.  */
2539   rtx label;                    /* Label of value.  */
2540   rtx wend;                     /* End of window.  */
2541   enum machine_mode mode;       /* Mode of value.  */
2542
2543   /* True if this constant is accessed as part of a post-increment
2544      sequence.  Note that HImode constants are never accessed in this way.  */
2545   bool part_of_sequence_p;
2546 } pool_node;
2547
2548 /* The maximum number of constants that can fit into one pool, since
2549    the pc relative range is 0...1020 bytes and constants are at least 4
2550    bytes long.  */
2551
2552 #define MAX_POOL_SIZE (1020/4)
2553 static pool_node pool_vector[MAX_POOL_SIZE];
2554 static int pool_size;
2555 static rtx pool_window_label;
2556 static int pool_window_last;
2557
2558 /* ??? If we need a constant in HImode which is the truncated value of a
2559    constant we need in SImode, we could combine the two entries thus saving
2560    two bytes.  Is this common enough to be worth the effort of implementing
2561    it?  */
2562
2563 /* ??? This stuff should be done at the same time that we shorten branches.
2564    As it is now, we must assume that all branches are the maximum size, and
2565    this causes us to almost always output constant pools sooner than
2566    necessary.  */
2567
2568 /* Add a constant to the pool and return its label.  */
2569
2570 static rtx
2571 add_constant (x, mode, last_value)
2572      rtx x;
2573      enum machine_mode mode;
2574      rtx last_value;
2575 {
2576   int i;
2577   rtx lab, new, ref, newref;
2578
2579   /* First see if we've already got it.  */
2580   for (i = 0; i < pool_size; i++)
2581     {
2582       if (x->code == pool_vector[i].value->code
2583           && mode == pool_vector[i].mode)
2584         {
2585           if (x->code == CODE_LABEL)
2586             {
2587               if (XINT (x, 3) != XINT (pool_vector[i].value, 3))
2588                 continue;
2589             }
2590           if (rtx_equal_p (x, pool_vector[i].value))
2591             {
2592               lab = new = 0;
2593               if (! last_value
2594                   || ! i
2595                   || ! rtx_equal_p (last_value, pool_vector[i-1].value))
2596                 {
2597                   new = gen_label_rtx ();
2598                   LABEL_REFS (new) = pool_vector[i].label;
2599                   pool_vector[i].label = lab = new;
2600                 }
2601               if (lab && pool_window_label)
2602                 {
2603                   newref = gen_rtx_LABEL_REF (VOIDmode, pool_window_label);
2604                   ref = pool_vector[pool_window_last].wend;
2605                   LABEL_NEXTREF (newref) = ref;
2606                   pool_vector[pool_window_last].wend = newref;
2607                 }
2608               if (new)
2609                 pool_window_label = new;
2610               pool_window_last = i;
2611               return lab;
2612             }
2613         }
2614     }
2615
2616   /* Need a new one.  */
2617   pool_vector[pool_size].value = x;
2618   if (last_value && rtx_equal_p (last_value, pool_vector[pool_size - 1].value))
2619     {
2620       lab = 0;
2621       pool_vector[pool_size - 1].part_of_sequence_p = true;
2622     }
2623   else
2624     lab = gen_label_rtx ();
2625   pool_vector[pool_size].mode = mode;
2626   pool_vector[pool_size].label = lab;
2627   pool_vector[pool_size].wend = NULL_RTX;
2628   pool_vector[pool_size].part_of_sequence_p = (lab == 0);
2629   if (lab && pool_window_label)
2630     {
2631       newref = gen_rtx_LABEL_REF (VOIDmode, pool_window_label);
2632       ref = pool_vector[pool_window_last].wend;
2633       LABEL_NEXTREF (newref) = ref;
2634       pool_vector[pool_window_last].wend = newref;
2635     }
2636   if (lab)
2637     pool_window_label = lab;
2638   pool_window_last = pool_size;
2639   pool_size++;
2640   return lab;
2641 }
2642
2643 /* Output the literal table.  */
2644
2645 static void
2646 dump_table (scan)
2647      rtx scan;
2648 {
2649   int i;
2650   int need_align = 1;
2651   rtx lab, ref;
2652   int have_df = 0;
2653
2654   /* Do two passes, first time dump out the HI sized constants.  */
2655
2656   for (i = 0; i < pool_size; i++)
2657     {
2658       pool_node *p = &pool_vector[i];
2659
2660       if (p->mode == HImode)
2661         {
2662           if (need_align)
2663             {
2664               scan = emit_insn_after (gen_align_2 (), scan);
2665               need_align = 0;
2666             }
2667           for (lab = p->label; lab; lab = LABEL_REFS (lab))
2668             scan = emit_label_after (lab, scan);
2669           scan = emit_insn_after (gen_consttable_2 (p->value, const0_rtx),
2670                                   scan);
2671           for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2672             {
2673               lab = XEXP (ref, 0);
2674               scan = emit_insn_after (gen_consttable_window_end (lab), scan);
2675             }
2676         }
2677       else if (p->mode == DFmode)
2678         have_df = 1;
2679     }
2680
2681   need_align = 1;
2682
2683   if (TARGET_FMOVD && TARGET_ALIGN_DOUBLE && have_df)
2684     {
2685       rtx align_insn = NULL_RTX;
2686
2687       scan = emit_label_after (gen_label_rtx (), scan);
2688       scan = emit_insn_after (gen_align_log (GEN_INT (3)), scan);
2689       need_align = 0;
2690
2691       for (i = 0; i < pool_size; i++)
2692         {
2693           pool_node *p = &pool_vector[i];
2694
2695           switch (p->mode)
2696             {
2697             case HImode:
2698               break;
2699             case SImode:
2700             case SFmode:
2701               if (align_insn && !p->part_of_sequence_p)
2702                 {
2703                   for (lab = p->label; lab; lab = LABEL_REFS (lab))
2704                     emit_label_before (lab, align_insn);
2705                   emit_insn_before (gen_consttable_4 (p->value, const0_rtx),
2706                                     align_insn);
2707                   for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2708                     {
2709                       lab = XEXP (ref, 0);
2710                       emit_insn_before (gen_consttable_window_end (lab),
2711                                        align_insn);
2712                     }
2713                   delete_insn (align_insn);
2714                   align_insn = NULL_RTX;
2715                   continue;
2716                 }
2717               else
2718                 {
2719                   for (lab = p->label; lab; lab = LABEL_REFS (lab))
2720                     scan = emit_label_after (lab, scan);
2721                   scan = emit_insn_after (gen_consttable_4 (p->value,
2722                                                             const0_rtx), scan);
2723                   need_align = ! need_align;
2724                 }
2725               break;
2726             case DFmode:
2727               if (need_align)
2728                 {
2729                   scan = emit_insn_after (gen_align_log (GEN_INT (3)), scan);
2730                   align_insn = scan;
2731                   need_align = 0;
2732                 }
2733             case DImode:
2734               for (lab = p->label; lab; lab = LABEL_REFS (lab))
2735                 scan = emit_label_after (lab, scan);
2736               scan = emit_insn_after (gen_consttable_8 (p->value, const0_rtx),
2737                                       scan);
2738               break;
2739             default:
2740               abort ();
2741               break;
2742             }
2743
2744           if (p->mode != HImode)
2745             {
2746               for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2747                 {
2748                   lab = XEXP (ref, 0);
2749                   scan = emit_insn_after (gen_consttable_window_end (lab),
2750                                           scan);
2751                 }
2752             }
2753         }
2754
2755       pool_size = 0;
2756     }
2757   
2758   for (i = 0; i < pool_size; i++)
2759     {
2760       pool_node *p = &pool_vector[i];
2761
2762       switch (p->mode)
2763         {
2764         case HImode:
2765           break;
2766         case SImode:
2767         case SFmode:
2768           if (need_align)
2769             {
2770               need_align = 0;
2771               scan = emit_label_after (gen_label_rtx (), scan);
2772               scan = emit_insn_after (gen_align_4 (), scan);
2773             }
2774           for (lab = p->label; lab; lab = LABEL_REFS (lab))
2775             scan = emit_label_after (lab, scan);
2776           scan = emit_insn_after (gen_consttable_4 (p->value, const0_rtx),
2777                                   scan);
2778           break;
2779         case DFmode:
2780         case DImode:
2781           if (need_align)
2782             {
2783               need_align = 0;
2784               scan = emit_label_after (gen_label_rtx (), scan);
2785               scan = emit_insn_after (gen_align_4 (), scan);
2786             }
2787           for (lab = p->label; lab; lab = LABEL_REFS (lab))
2788             scan = emit_label_after (lab, scan);
2789           scan = emit_insn_after (gen_consttable_8 (p->value, const0_rtx),
2790                                   scan);
2791           break;
2792         default:
2793           abort ();
2794           break;
2795         }
2796
2797       if (p->mode != HImode)
2798         {
2799           for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2800             {
2801               lab = XEXP (ref, 0);
2802               scan = emit_insn_after (gen_consttable_window_end (lab), scan);
2803             }
2804         }
2805     }
2806
2807   scan = emit_insn_after (gen_consttable_end (), scan);
2808   scan = emit_barrier_after (scan);
2809   pool_size = 0;
2810   pool_window_label = NULL_RTX;
2811   pool_window_last = 0;
2812 }
2813
2814 /* Return nonzero if constant would be an ok source for a
2815    mov.w instead of a mov.l.  */
2816
2817 static int
2818 hi_const (src)
2819      rtx src;
2820 {
2821   return (GET_CODE (src) == CONST_INT
2822           && INTVAL (src) >= -32768
2823           && INTVAL (src) <= 32767);
2824 }
2825
2826 /* Nonzero if the insn is a move instruction which needs to be fixed.  */
2827
2828 /* ??? For a DImode/DFmode moves, we don't need to fix it if each half of the
2829    CONST_DOUBLE input value is CONST_OK_FOR_I.  For a SFmode move, we don't
2830    need to fix it if the input value is CONST_OK_FOR_I.  */
2831
2832 static int
2833 broken_move (insn)
2834      rtx insn;
2835 {
2836   if (GET_CODE (insn) == INSN)
2837     {
2838       rtx pat = PATTERN (insn);
2839       if (GET_CODE (pat) == PARALLEL)
2840         pat = XVECEXP (pat, 0, 0);
2841       if (GET_CODE (pat) == SET
2842           /* We can load any 8 bit value if we don't care what the high
2843              order bits end up as.  */
2844           && GET_MODE (SET_DEST (pat)) != QImode
2845           && (CONSTANT_P (SET_SRC (pat))
2846               /* Match mova_const.  */
2847               || (GET_CODE (SET_SRC (pat)) == UNSPEC
2848                   && XINT (SET_SRC (pat), 1) == UNSPEC_MOVA
2849                   && GET_CODE (XVECEXP (SET_SRC (pat), 0, 0)) == CONST))
2850           && ! (TARGET_SH2E
2851                 && GET_CODE (SET_SRC (pat)) == CONST_DOUBLE
2852                 && (fp_zero_operand (SET_SRC (pat))
2853                     || fp_one_operand (SET_SRC (pat)))
2854                 /* ??? If this is a -m4 or -m4-single compilation, in general
2855                    we don't know the current setting of fpscr, so disable fldi.
2856                    There is an exception if this was a register-register move
2857                    before reload - and hence it was ascertained that we have
2858                    single precision setting - and in a post-reload optimization
2859                    we changed this to do a constant load.  In that case
2860                    we don't have an r0 clobber, hence we must use fldi.  */
2861                 && (! TARGET_SH4 || TARGET_FMOVD
2862                     || (GET_CODE (XEXP (XVECEXP (PATTERN (insn), 0, 2), 0))
2863                         == SCRATCH))
2864                 && GET_CODE (SET_DEST (pat)) == REG
2865                 && FP_REGISTER_P (REGNO (SET_DEST (pat))))
2866           && (GET_CODE (SET_SRC (pat)) != CONST_INT
2867               || ! CONST_OK_FOR_I (INTVAL (SET_SRC (pat)))))
2868         return 1;
2869     }
2870
2871   return 0;
2872 }
2873
2874 static int
2875 mova_p (insn)
2876      rtx insn;
2877 {
2878   return (GET_CODE (insn) == INSN
2879           && GET_CODE (PATTERN (insn)) == SET
2880           && GET_CODE (SET_SRC (PATTERN (insn))) == UNSPEC
2881           && XINT (SET_SRC (PATTERN (insn)), 1) == UNSPEC_MOVA
2882           /* Don't match mova_const.  */
2883           && GET_CODE (XVECEXP (SET_SRC (PATTERN (insn)), 0, 0)) == LABEL_REF);
2884 }
2885
2886 /* Find the last barrier from insn FROM which is close enough to hold the
2887    constant pool.  If we can't find one, then create one near the end of
2888    the range.  */
2889
2890 static rtx
2891 find_barrier (num_mova, mova, from)
2892      int num_mova;
2893      rtx mova, from;
2894 {
2895   int count_si = 0;
2896   int count_hi = 0;
2897   int found_hi = 0;
2898   int found_si = 0;
2899   int found_di = 0;
2900   int hi_align = 2;
2901   int si_align = 2;
2902   int leading_mova = num_mova;
2903   rtx barrier_before_mova = 0, found_barrier = 0, good_barrier = 0;
2904   int si_limit;
2905   int hi_limit;
2906
2907   /* For HImode: range is 510, add 4 because pc counts from address of
2908      second instruction after this one, subtract 2 for the jump instruction
2909      that we may need to emit before the table, subtract 2 for the instruction
2910      that fills the jump delay slot (in very rare cases, reorg will take an
2911      instruction from after the constant pool or will leave the delay slot
2912      empty).  This gives 510.
2913      For SImode: range is 1020, add 4 because pc counts from address of
2914      second instruction after this one, subtract 2 in case pc is 2 byte
2915      aligned, subtract 2 for the jump instruction that we may need to emit
2916      before the table, subtract 2 for the instruction that fills the jump
2917      delay slot.  This gives 1018.  */
2918
2919   /* The branch will always be shortened now that the reference address for
2920      forward branches is the successor address, thus we need no longer make
2921      adjustments to the [sh]i_limit for -O0.  */
2922
2923   si_limit = 1018;
2924   hi_limit = 510;
2925
2926   while (from && count_si < si_limit && count_hi < hi_limit)
2927     {
2928       int inc = get_attr_length (from);
2929       int new_align = 1;
2930
2931       if (GET_CODE (from) == CODE_LABEL)
2932         {
2933           if (optimize)
2934             new_align = 1 << label_to_alignment (from);
2935           else if (GET_CODE (prev_nonnote_insn (from)) == BARRIER)
2936             new_align = 1 << barrier_align (from);
2937           else
2938             new_align = 1;
2939           inc = 0;
2940         }
2941
2942       if (GET_CODE (from) == BARRIER)
2943         {
2944
2945           found_barrier = from;
2946
2947           /* If we are at the end of the function, or in front of an alignment
2948              instruction, we need not insert an extra alignment.  We prefer
2949              this kind of barrier.  */
2950           if (barrier_align (from) > 2)
2951             good_barrier = from;
2952         }
2953
2954       if (broken_move (from))
2955         {
2956           rtx pat, src, dst;
2957           enum machine_mode mode;
2958
2959           pat = PATTERN (from);
2960           if (GET_CODE (pat) == PARALLEL)
2961             pat = XVECEXP (pat, 0, 0);
2962           src = SET_SRC (pat);
2963           dst = SET_DEST (pat);
2964           mode = GET_MODE (dst);
2965
2966           /* We must explicitly check the mode, because sometimes the
2967              front end will generate code to load unsigned constants into
2968              HImode targets without properly sign extending them.  */
2969           if (mode == HImode
2970               || (mode == SImode && hi_const (src) && REGNO (dst) != FPUL_REG))
2971             {
2972               found_hi += 2;
2973               /* We put the short constants before the long constants, so
2974                  we must count the length of short constants in the range
2975                  for the long constants.  */
2976               /* ??? This isn't optimal, but is easy to do.  */
2977               si_limit -= 2;
2978             }
2979           else
2980             {
2981               /* We dump DF/DI constants before SF/SI ones, because
2982                  the limit is the same, but the alignment requirements
2983                  are higher.  We may waste up to 4 additional bytes
2984                  for alignment, and the DF/DI constant may have
2985                  another SF/SI constant placed before it. */
2986               if (TARGET_SHCOMPACT
2987                   && ! found_di
2988                   && (mode == DFmode || mode == DImode))
2989                 {
2990                   found_di = 1;
2991                   si_limit -= 8;
2992                 }
2993               while (si_align > 2 && found_si + si_align - 2 > count_si)
2994                 si_align >>= 1;
2995               if (found_si > count_si)
2996                 count_si = found_si;
2997               found_si += GET_MODE_SIZE (mode);
2998               if (num_mova)
2999                 si_limit -= GET_MODE_SIZE (mode);
3000             }
3001
3002           /* See the code in machine_dependent_reorg, which has a similar if
3003              statement that generates a new mova insn in many cases.  */
3004           if (GET_CODE (dst) == REG && FP_ANY_REGISTER_P (REGNO (dst)))
3005             inc += 2;
3006         }
3007
3008       if (mova_p (from))
3009         {
3010           if (! num_mova++)
3011             {
3012               leading_mova = 0;
3013               mova = from;
3014               barrier_before_mova = good_barrier ? good_barrier : found_barrier;
3015             }
3016           if (found_si > count_si)
3017             count_si = found_si;
3018         }
3019       else if (GET_CODE (from) == JUMP_INSN
3020                && (GET_CODE (PATTERN (from)) == ADDR_VEC
3021                    || GET_CODE (PATTERN (from)) == ADDR_DIFF_VEC))
3022         {
3023           if (num_mova)
3024             num_mova--;
3025           if (barrier_align (next_real_insn (from)) == align_jumps_log)
3026             {
3027               /* We have just passed the barrier in front of the
3028                  ADDR_DIFF_VEC, which is stored in found_barrier.  Since
3029                  the ADDR_DIFF_VEC is accessed as data, just like our pool
3030                  constants, this is a good opportunity to accommodate what
3031                  we have gathered so far.
3032                  If we waited any longer, we could end up at a barrier in
3033                  front of code, which gives worse cache usage for separated
3034                  instruction / data caches.  */
3035               good_barrier = found_barrier;
3036               break;
3037             }
3038           else
3039             {
3040               rtx body = PATTERN (from);
3041               inc = XVECLEN (body, 1) * GET_MODE_SIZE (GET_MODE (body));
3042             }
3043         }
3044       /* For the SH1, we generate alignments even after jumps-around-jumps.  */
3045       else if (GET_CODE (from) == JUMP_INSN
3046                && ! TARGET_SH2
3047                && ! TARGET_SMALLCODE)
3048         new_align = 4;
3049
3050       if (found_si)
3051         {
3052           count_si += inc;
3053           if (new_align > si_align)
3054             {
3055               si_limit -= (count_si - 1) & (new_align - si_align);
3056               si_align = new_align;
3057             }
3058           count_si = (count_si + new_align - 1) & -new_align;
3059         }
3060       if (found_hi)
3061         {
3062           count_hi += inc;
3063           if (new_align > hi_align)
3064             {
3065               hi_limit -= (count_hi - 1) & (new_align - hi_align);
3066               hi_align = new_align;
3067             }
3068           count_hi = (count_hi + new_align - 1) & -new_align;
3069         }
3070       from = NEXT_INSN (from);
3071     }
3072
3073   if (num_mova)
3074     {
3075       if (leading_mova)
3076         {
3077           /* Try as we might, the leading mova is out of range.  Change
3078              it into a load (which will become a pcload) and retry.  */
3079           SET_SRC (PATTERN (mova)) = XVECEXP (SET_SRC (PATTERN (mova)), 0, 0);
3080           INSN_CODE (mova) = -1;
3081           return find_barrier (0, 0, mova);
3082         }
3083       else
3084         {
3085           /* Insert the constant pool table before the mova instruction,
3086              to prevent the mova label reference from going out of range.  */
3087           from = mova;
3088           good_barrier = found_barrier = barrier_before_mova;
3089         }
3090     }
3091
3092   if (found_barrier)
3093     {
3094       if (good_barrier && next_real_insn (found_barrier))
3095         found_barrier = good_barrier;
3096     }
3097   else
3098     {
3099       /* We didn't find a barrier in time to dump our stuff,
3100          so we'll make one.  */
3101       rtx label = gen_label_rtx ();
3102
3103       /* If we exceeded the range, then we must back up over the last
3104          instruction we looked at.  Otherwise, we just need to undo the
3105          NEXT_INSN at the end of the loop.  */
3106       if (count_hi > hi_limit || count_si > si_limit)
3107         from = PREV_INSN (PREV_INSN (from));
3108       else
3109         from = PREV_INSN (from);
3110
3111       /* Walk back to be just before any jump or label.
3112          Putting it before a label reduces the number of times the branch
3113          around the constant pool table will be hit.  Putting it before
3114          a jump makes it more likely that the bra delay slot will be
3115          filled.  */
3116       while (GET_CODE (from) == JUMP_INSN || GET_CODE (from) == NOTE
3117              || GET_CODE (from) == CODE_LABEL)
3118         from = PREV_INSN (from);
3119
3120       from = emit_jump_insn_after (gen_jump (label), from);
3121       JUMP_LABEL (from) = label;
3122       LABEL_NUSES (label) = 1;
3123       found_barrier = emit_barrier_after (from);
3124       emit_label_after (label, found_barrier);
3125     }
3126
3127   return found_barrier;
3128 }
3129
3130 /* If the instruction INSN is implemented by a special function, and we can
3131    positively find the register that is used to call the sfunc, and this
3132    register is not used anywhere else in this instruction - except as the
3133    destination of a set, return this register; else, return 0.  */
3134 rtx
3135 sfunc_uses_reg (insn)
3136      rtx insn;
3137 {
3138   int i;
3139   rtx pattern, part, reg_part, reg;
3140
3141   if (GET_CODE (insn) != INSN)
3142     return 0;
3143   pattern = PATTERN (insn);
3144   if (GET_CODE (pattern) != PARALLEL || get_attr_type (insn) != TYPE_SFUNC)
3145     return 0;
3146
3147   for (reg_part = 0, i = XVECLEN (pattern, 0) - 1; i >= 1; i--)
3148     {
3149       part = XVECEXP (pattern, 0, i);
3150       if (GET_CODE (part) == USE && GET_MODE (XEXP (part, 0)) == SImode)
3151         reg_part = part;
3152     }
3153   if (! reg_part)
3154     return 0;
3155   reg = XEXP (reg_part, 0);
3156   for (i = XVECLEN (pattern, 0) - 1; i >= 0; i--)
3157     {
3158       part = XVECEXP (pattern, 0, i);
3159       if (part == reg_part || GET_CODE (part) == CLOBBER)
3160         continue;
3161       if (reg_mentioned_p (reg, ((GET_CODE (part) == SET
3162                                   && GET_CODE (SET_DEST (part)) == REG)
3163                                  ? SET_SRC (part) : part)))
3164         return 0;
3165     }
3166   return reg;
3167 }
3168
3169 /* See if the only way in which INSN uses REG is by calling it, or by
3170    setting it while calling it.  Set *SET to a SET rtx if the register
3171    is set by INSN.  */
3172
3173 static int
3174 noncall_uses_reg (reg, insn, set)
3175      rtx reg;
3176      rtx insn;
3177      rtx *set;
3178 {
3179   rtx pattern, reg2;
3180
3181   *set = NULL_RTX;
3182
3183   reg2 = sfunc_uses_reg (insn);
3184   if (reg2 && REGNO (reg2) == REGNO (reg))
3185     {
3186       pattern = single_set (insn);
3187       if (pattern
3188           && GET_CODE (SET_DEST (pattern)) == REG
3189           && REGNO (reg) == REGNO (SET_DEST (pattern)))
3190         *set = pattern;
3191       return 0;
3192     }
3193   if (GET_CODE (insn) != CALL_INSN)
3194     {
3195       /* We don't use rtx_equal_p because we don't care if the mode is
3196          different.  */
3197       pattern = single_set (insn);
3198       if (pattern
3199           && GET_CODE (SET_DEST (pattern)) == REG
3200           && REGNO (reg) == REGNO (SET_DEST (pattern)))
3201         {
3202           rtx par, part;
3203           int i;
3204
3205           *set = pattern;
3206           par = PATTERN (insn);
3207           if (GET_CODE (par) == PARALLEL)
3208             for (i = XVECLEN (par, 0) - 1; i >= 0; i--)
3209               {
3210                 part = XVECEXP (par, 0, i);
3211                 if (GET_CODE (part) != SET && reg_mentioned_p (reg, part))
3212                   return 1;
3213               }
3214           return reg_mentioned_p (reg, SET_SRC (pattern));
3215         }
3216
3217       return 1;
3218     }
3219
3220   pattern = PATTERN (insn);
3221
3222   if (GET_CODE (pattern) == PARALLEL)
3223     {
3224       int i;
3225
3226       for (i = XVECLEN (pattern, 0) - 1; i >= 1; i--)
3227         if (reg_mentioned_p (reg, XVECEXP (pattern, 0, i)))
3228           return 1;
3229       pattern = XVECEXP (pattern, 0, 0);
3230     }
3231
3232   if (GET_CODE (pattern) == SET)
3233     {
3234       if (reg_mentioned_p (reg, SET_DEST (pattern)))
3235         {
3236           /* We don't use rtx_equal_p, because we don't care if the
3237              mode is different.  */
3238           if (GET_CODE (SET_DEST (pattern)) != REG
3239               || REGNO (reg) != REGNO (SET_DEST (pattern)))
3240             return 1;
3241
3242           *set = pattern;
3243         }
3244
3245       pattern = SET_SRC (pattern);
3246     }
3247
3248   if (GET_CODE (pattern) != CALL
3249       || GET_CODE (XEXP (pattern, 0)) != MEM
3250       || ! rtx_equal_p (reg, XEXP (XEXP (pattern, 0), 0)))
3251     return 1;
3252
3253   return 0;
3254 }
3255
3256 /* Given a X, a pattern of an insn or a part of it, return a mask of used
3257    general registers.  Bits 0..15 mean that the respective registers
3258    are used as inputs in the instruction.  Bits 16..31 mean that the
3259    registers 0..15, respectively, are used as outputs, or are clobbered.
3260    IS_DEST should be set to 16 if X is the destination of a SET, else to 0.  */
3261 int
3262 regs_used (x, is_dest)
3263      rtx x; int is_dest;
3264 {
3265   enum rtx_code code;
3266   const char *fmt;
3267   int i, used = 0;
3268
3269   if (! x)
3270     return used;
3271   code = GET_CODE (x);
3272   switch (code)
3273     {
3274     case REG:
3275       if (REGNO (x) < 16)
3276         return (((1 << HARD_REGNO_NREGS (0, GET_MODE (x))) - 1)
3277                 << (REGNO (x) + is_dest));
3278       return 0;
3279     case SUBREG:
3280       {
3281         rtx y = SUBREG_REG (x);
3282      
3283         if (GET_CODE (y) != REG)
3284           break;
3285         if (REGNO (y) < 16)
3286           return (((1 << HARD_REGNO_NREGS (0, GET_MODE (x))) - 1)
3287                   << (REGNO (y) +
3288                       subreg_regno_offset (REGNO (y),
3289                                            GET_MODE (y),
3290                                            SUBREG_BYTE (x),
3291                                            GET_MODE (x)) + is_dest));
3292         return 0;
3293       }
3294     case SET:
3295       return regs_used (SET_SRC (x), 0) | regs_used (SET_DEST (x), 16);
3296     case RETURN:
3297       /* If there was a return value, it must have been indicated with USE.  */
3298       return 0x00ffff00;
3299     case CLOBBER:
3300       is_dest = 1;
3301       break;
3302     case MEM:
3303       is_dest = 0;
3304       break;
3305     case CALL:
3306       used |= 0x00ff00f0;
3307       break;
3308     default:
3309       break;
3310     }
3311
3312   fmt = GET_RTX_FORMAT (code);
3313
3314   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3315     {
3316       if (fmt[i] == 'E')
3317         {
3318           register int j;
3319           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
3320             used |= regs_used (XVECEXP (x, i, j), is_dest);
3321         }
3322       else if (fmt[i] == 'e')
3323         used |= regs_used (XEXP (x, i), is_dest);
3324     }
3325   return used;
3326 }
3327
3328 /* Create an instruction that prevents redirection of a conditional branch
3329    to the destination of the JUMP with address ADDR.
3330    If the branch needs to be implemented as an indirect jump, try to find
3331    a scratch register for it.
3332    If NEED_BLOCK is 0, don't do anything unless we need a scratch register.
3333    If any preceding insn that doesn't fit into a delay slot is good enough,
3334    pass 1.  Pass 2 if a definite blocking insn is needed.
3335    -1 is used internally to avoid deep recursion.
3336    If a blocking instruction is made or recognized, return it.  */
3337    
3338 static rtx
3339 gen_block_redirect (jump, addr, need_block)
3340      rtx jump;
3341      int addr, need_block;
3342 {
3343   int dead = 0;
3344   rtx prev = prev_nonnote_insn (jump);
3345   rtx dest;
3346
3347   /* First, check if we already have an instruction that satisfies our need.  */
3348   if (prev && GET_CODE (prev) == INSN && ! INSN_DELETED_P (prev))
3349     {
3350       if (INSN_CODE (prev) == CODE_FOR_indirect_jump_scratch)
3351         return prev;
3352       if (GET_CODE (PATTERN (prev)) == USE
3353           || GET_CODE (PATTERN (prev)) == CLOBBER
3354           || get_attr_in_delay_slot (prev) == IN_DELAY_SLOT_YES)
3355         prev = jump;
3356       else if ((need_block &= ~1) < 0)
3357         return prev;
3358       else if (recog_memoized (prev) == CODE_FOR_block_branch_redirect)
3359         need_block = 0;
3360     }
3361   /* We can't use JUMP_LABEL here because it might be undefined
3362      when not optimizing.  */
3363   dest = XEXP (SET_SRC (PATTERN (jump)), 0);
3364   /* If the branch is out of range, try to find a scratch register for it.  */
3365   if (optimize
3366       && (INSN_ADDRESSES (INSN_UID (dest)) - addr + (unsigned) 4092
3367           > 4092 + 4098))
3368     {
3369       rtx scan;
3370       /* Don't look for the stack pointer as a scratch register,
3371          it would cause trouble if an interrupt occurred.  */
3372       unsigned try = 0x7fff, used;
3373       int jump_left = flag_expensive_optimizations + 1;
3374     
3375       /* It is likely that the most recent eligible instruction is wanted for
3376          the delay slot.  Therefore, find out which registers it uses, and
3377          try to avoid using them.  */
3378          
3379       for (scan = jump; (scan = PREV_INSN (scan)); )
3380         {
3381           enum rtx_code code;
3382
3383           if (INSN_DELETED_P (scan))
3384             continue;
3385           code = GET_CODE (scan);
3386           if (code == CODE_LABEL || code == JUMP_INSN)
3387             break;
3388           if (code == INSN
3389               && GET_CODE (PATTERN (scan)) != USE
3390               && GET_CODE (PATTERN (scan)) != CLOBBER
3391               && get_attr_in_delay_slot (scan) == IN_DELAY_SLOT_YES)
3392             {
3393               try &= ~regs_used (PATTERN (scan), 0);
3394               break;
3395             }
3396         }
3397       for (used = dead = 0, scan = JUMP_LABEL (jump);
3398            (scan = NEXT_INSN (scan)); )
3399         {
3400           enum rtx_code code;
3401
3402           if (INSN_DELETED_P (scan))
3403             continue;
3404           code = GET_CODE (scan);
3405           if (GET_RTX_CLASS (code) == 'i')
3406             {
3407               used |= regs_used (PATTERN (scan), 0);
3408               if (code == CALL_INSN)
3409                 used |= regs_used (CALL_INSN_FUNCTION_USAGE (scan), 0);
3410               dead |= (used >> 16) & ~used;
3411               if (dead & try)
3412                 {
3413                   dead &= try;
3414                   break;
3415                 }
3416               if (code == JUMP_INSN)
3417                 {
3418                   if (jump_left-- && simplejump_p (scan))
3419                     scan = JUMP_LABEL (scan);
3420                   else
3421                     break;
3422                 }
3423             }
3424         }
3425       /* Mask out the stack pointer again, in case it was
3426          the only 'free' register we have found.  */
3427       dead &= 0x7fff;
3428     }
3429   /* If the immediate destination is still in range, check for possible
3430      threading with a jump beyond the delay slot insn.
3431      Don't check if we are called recursively; the jump has been or will be
3432      checked in a different invocation then.  */
3433         
3434   else if (optimize && need_block >= 0)
3435     {
3436       rtx next = next_active_insn (next_active_insn (dest));
3437       if (next && GET_CODE (next) == JUMP_INSN
3438           && GET_CODE (PATTERN (next)) == SET
3439           && recog_memoized (next) == CODE_FOR_jump_compact)
3440         {
3441           dest = JUMP_LABEL (next);
3442           if (dest
3443               && (INSN_ADDRESSES (INSN_UID (dest)) - addr + (unsigned) 4092
3444                   > 4092 + 4098))
3445             gen_block_redirect (next, INSN_ADDRESSES (INSN_UID (next)), -1);
3446         }
3447     }
3448
3449   if (dead)
3450     {
3451       rtx reg = gen_rtx_REG (SImode, exact_log2 (dead & -dead));
3452
3453       /* It would be nice if we could convert the jump into an indirect
3454          jump / far branch right now, and thus exposing all constituent
3455          instructions to further optimization.  However, reorg uses
3456          simplejump_p to determine if there is an unconditional jump where
3457          it should try to schedule instructions from the target of the
3458          branch; simplejump_p fails for indirect jumps even if they have
3459          a JUMP_LABEL.  */
3460       rtx insn = emit_insn_before (gen_indirect_jump_scratch
3461                                    (reg, GEN_INT (INSN_UID (JUMP_LABEL (jump))))
3462                                    , jump);
3463       /* ??? We would like this to have the scope of the jump, but that
3464          scope will change when a delay slot insn of an inner scope is added.
3465          Hence, after delay slot scheduling, we'll have to expect
3466          NOTE_INSN_BLOCK_END notes between the indirect_jump_scratch and
3467          the jump.  */
3468          
3469       INSN_LOCATOR (insn) = INSN_LOCATOR (jump);
3470       INSN_CODE (insn) = CODE_FOR_indirect_jump_scratch;
3471       return insn;
3472     }
3473   else if (need_block)
3474     /* We can't use JUMP_LABEL here because it might be undefined
3475        when not optimizing.  */
3476     return emit_insn_before (gen_block_branch_redirect
3477                       (GEN_INT (INSN_UID (XEXP (SET_SRC (PATTERN (jump)), 0))))
3478                       , jump);
3479   return prev;
3480 }
3481
3482 #define CONDJUMP_MIN -252
3483 #define CONDJUMP_MAX 262
3484 struct far_branch
3485 {
3486   /* A label (to be placed) in front of the jump
3487      that jumps to our ultimate destination.  */
3488   rtx near_label;
3489   /* Where we are going to insert it if we cannot move the jump any farther,
3490      or the jump itself if we have picked up an existing jump.  */
3491   rtx insert_place;
3492   /* The ultimate destination.  */
3493   rtx far_label;
3494   struct far_branch *prev;
3495   /* If the branch has already been created, its address;
3496      else the address of its first prospective user.  */
3497   int address;
3498 };
3499
3500 static void gen_far_branch PARAMS ((struct far_branch *));
3501 enum mdep_reorg_phase_e mdep_reorg_phase;
3502 static void
3503 gen_far_branch (bp)
3504      struct far_branch *bp;
3505 {
3506   rtx insn = bp->insert_place;
3507   rtx jump;
3508   rtx label = gen_label_rtx ();
3509
3510   emit_label_after (label, insn);
3511   if (bp->far_label)
3512     {
3513       jump = emit_jump_insn_after (gen_jump (bp->far_label), insn);
3514       LABEL_NUSES (bp->far_label)++;
3515     }
3516   else
3517     jump = emit_jump_insn_after (gen_return (), insn);
3518   /* Emit a barrier so that reorg knows that any following instructions
3519      are not reachable via a fall-through path.
3520      But don't do this when not optimizing, since we wouldn't supress the
3521      alignment for the barrier then, and could end up with out-of-range
3522      pc-relative loads.  */
3523   if (optimize)
3524     emit_barrier_after (jump);
3525   emit_label_after (bp->near_label, insn);
3526   JUMP_LABEL (jump) = bp->far_label;
3527   if (! invert_jump (insn, label, 1))
3528     abort ();
3529   (emit_insn_after
3530    (gen_stuff_delay_slot
3531     (GEN_INT (INSN_UID (XEXP (SET_SRC (PATTERN (jump)), 0))),
3532      GEN_INT (recog_memoized (insn) == CODE_FOR_branch_false)),
3533     insn));
3534   /* Prevent reorg from undoing our splits.  */
3535   gen_block_redirect (jump, bp->address += 2, 2);
3536 }
3537
3538 /* Fix up ADDR_DIFF_VECs.  */
3539 void
3540 fixup_addr_diff_vecs (first)
3541      rtx first;
3542 {
3543   rtx insn;
3544
3545   for (insn = first; insn; insn = NEXT_INSN (insn))
3546     {
3547       rtx vec_lab, pat, prev, prevpat, x, braf_label;
3548
3549       if (GET_CODE (insn) != JUMP_INSN
3550           || GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC)
3551         continue;
3552       pat = PATTERN (insn);
3553       vec_lab = XEXP (XEXP (pat, 0), 0);
3554
3555       /* Search the matching casesi_jump_2.  */
3556       for (prev = vec_lab; ; prev = PREV_INSN (prev))
3557         {
3558           if (GET_CODE (prev) != JUMP_INSN)
3559             continue;
3560           prevpat = PATTERN (prev);
3561           if (GET_CODE (prevpat) != PARALLEL || XVECLEN (prevpat, 0) != 2)
3562             continue;
3563           x = XVECEXP (prevpat, 0, 1);
3564           if (GET_CODE (x) != USE)
3565             continue;
3566           x = XEXP (x, 0);
3567           if (GET_CODE (x) == LABEL_REF && XEXP (x, 0) == vec_lab)
3568             break;
3569         }
3570
3571       /* Emit the reference label of the braf where it belongs, right after
3572          the casesi_jump_2 (i.e. braf).  */
3573       braf_label = XEXP (XEXP (SET_SRC (XVECEXP (prevpat, 0, 0)), 1), 0);
3574       emit_label_after (braf_label, prev);
3575
3576       /* Fix up the ADDR_DIF_VEC to be relative
3577          to the reference address of the braf.  */
3578       XEXP (XEXP (pat, 0), 0) = braf_label;
3579     }
3580 }
3581
3582 /* BARRIER_OR_LABEL is either a BARRIER or a CODE_LABEL immediately following
3583    a barrier.  Return the base 2 logarithm of the desired alignment.  */
3584 int
3585 barrier_align (barrier_or_label)
3586      rtx barrier_or_label;
3587 {
3588   rtx next = next_real_insn (barrier_or_label), pat, prev;
3589   int slot, credit, jump_to_next = 0;
3590  
3591   if (! next)
3592     return 0;
3593
3594   pat = PATTERN (next);
3595
3596   if (GET_CODE (pat) == ADDR_DIFF_VEC)
3597     return 2;
3598
3599   if (GET_CODE (pat) == UNSPEC_VOLATILE && XINT (pat, 1) == UNSPECV_ALIGN)
3600     /* This is a barrier in front of a constant table.  */
3601     return 0;
3602
3603   prev = prev_real_insn (barrier_or_label);
3604   if (GET_CODE (PATTERN (prev)) == ADDR_DIFF_VEC)
3605     {
3606       pat = PATTERN (prev);
3607       /* If this is a very small table, we want to keep the alignment after
3608          the table to the minimum for proper code alignment.  */
3609       return ((TARGET_SMALLCODE
3610                || ((unsigned) XVECLEN (pat, 1) * GET_MODE_SIZE (GET_MODE (pat))
3611                    <= (unsigned)1 << (CACHE_LOG - 2)))
3612               ? 1 << TARGET_SHMEDIA : align_jumps_log);
3613     }
3614
3615   if (TARGET_SMALLCODE)
3616     return 0;
3617
3618   if (! TARGET_SH2 || ! optimize)
3619     return align_jumps_log;
3620
3621   /* When fixing up pcloads, a constant table might be inserted just before
3622      the basic block that ends with the barrier.  Thus, we can't trust the
3623      instruction lengths before that.  */
3624   if (mdep_reorg_phase > SH_FIXUP_PCLOAD)
3625     {
3626       /* Check if there is an immediately preceding branch to the insn beyond
3627          the barrier.  We must weight the cost of discarding useful information
3628          from the current cache line when executing this branch and there is
3629          an alignment, against that of fetching unneeded insn in front of the
3630          branch target when there is no alignment.  */
3631
3632       /* There are two delay_slot cases to consider.  One is the simple case 
3633          where the preceding branch is to the insn beyond the barrier (simple 
3634          delay slot filling), and the other is where the preceding branch has 
3635          a delay slot that is a duplicate of the insn after the barrier 
3636          (fill_eager_delay_slots) and the branch is to the insn after the insn 
3637          after the barrier.  */
3638
3639       /* PREV is presumed to be the JUMP_INSN for the barrier under
3640          investigation.  Skip to the insn before it.  */
3641       prev = prev_real_insn (prev);
3642
3643       for (slot = 2, credit = (1 << (CACHE_LOG - 2)) + 2;
3644            credit >= 0 && prev && GET_CODE (prev) == INSN;
3645            prev = prev_real_insn (prev))
3646         {
3647           jump_to_next = 0;
3648           if (GET_CODE (PATTERN (prev)) == USE
3649               || GET_CODE (PATTERN (prev)) == CLOBBER)
3650             continue;
3651           if (GET_CODE (PATTERN (prev)) == SEQUENCE)
3652             {
3653               prev = XVECEXP (PATTERN (prev), 0, 1);
3654               if (INSN_UID (prev) == INSN_UID (next)) 
3655                 {
3656                   /* Delay slot was filled with insn at jump target.  */
3657                   jump_to_next = 1;
3658                   continue;
3659                 }
3660             }
3661
3662           if (slot &&
3663               get_attr_in_delay_slot (prev) == IN_DELAY_SLOT_YES)
3664             slot = 0;
3665           credit -= get_attr_length (prev);
3666         }
3667       if (prev
3668           && GET_CODE (prev) == JUMP_INSN
3669           && JUMP_LABEL (prev))
3670         {
3671           rtx x;
3672           if (jump_to_next
3673               || next_real_insn (JUMP_LABEL (prev)) == next
3674               /* If relax_delay_slots() decides NEXT was redundant
3675                  with some previous instruction, it will have
3676                  redirected PREV's jump to the following insn.  */
3677               || JUMP_LABEL (prev) == next_nonnote_insn (next)
3678               /* There is no upper bound on redundant instructions
3679                  that might have been skipped, but we must not put an
3680                  alignment where none had been before.  */
3681               || (x = (NEXT_INSN (NEXT_INSN (PREV_INSN (prev)))),           
3682                   (INSN_P (x) 
3683                    && (INSN_CODE (x) == CODE_FOR_block_branch_redirect
3684                        || INSN_CODE (x) == CODE_FOR_indirect_jump_scratch
3685                        || INSN_CODE (x) == CODE_FOR_stuff_delay_slot))))
3686             {
3687               rtx pat = PATTERN (prev);
3688               if (GET_CODE (pat) == PARALLEL)
3689                 pat = XVECEXP (pat, 0, 0);
3690               if (credit - slot >= (GET_CODE (SET_SRC (pat)) == PC ? 2 : 0))
3691                 return 0;
3692             }
3693         }
3694     }
3695   
3696   return align_jumps_log;
3697 }
3698
3699 /* If we are inside a phony loop, almost any kind of label can turn up as the
3700    first one in the loop.  Aligning a braf label causes incorrect switch
3701    destination addresses; we can detect braf labels because they are
3702    followed by a BARRIER.
3703    Applying loop alignment to small constant or switch tables is a waste
3704    of space, so we suppress this too.  */
3705 int
3706 sh_loop_align (label)
3707      rtx label;
3708 {
3709   rtx next = label;
3710
3711   do
3712     next = next_nonnote_insn (next);
3713   while (next && GET_CODE (next) == CODE_LABEL);
3714
3715   if (! next
3716       || ! INSN_P (next)
3717       || GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC
3718       || recog_memoized (next) == CODE_FOR_consttable_2)
3719     return 0;
3720
3721   return align_loops_log;
3722 }
3723
3724 /* Do a final pass over the function, just before delayed branch
3725    scheduling.  */
3726
3727 static void
3728 sh_reorg ()
3729 {
3730   rtx first, insn, mova = NULL_RTX;
3731   int num_mova;
3732   rtx r0_rtx = gen_rtx_REG (Pmode, 0);
3733   rtx r0_inc_rtx = gen_rtx_POST_INC (Pmode, r0_rtx);
3734
3735   first = get_insns ();
3736
3737   /* We must split call insns before introducing `mova's.  If we're
3738      optimizing, they'll have already been split.  Otherwise, make
3739      sure we don't split them too late.  */
3740   if (! optimize)
3741     split_all_insns_noflow ();
3742
3743   if (TARGET_SHMEDIA)
3744     return;
3745
3746   /* If relaxing, generate pseudo-ops to associate function calls with
3747      the symbols they call.  It does no harm to not generate these
3748      pseudo-ops.  However, when we can generate them, it enables to
3749      linker to potentially relax the jsr to a bsr, and eliminate the
3750      register load and, possibly, the constant pool entry.  */
3751
3752   mdep_reorg_phase = SH_INSERT_USES_LABELS;
3753   if (TARGET_RELAX)
3754     {
3755       /* Remove all REG_LABEL notes.  We want to use them for our own
3756          purposes.  This works because none of the remaining passes
3757          need to look at them.
3758
3759          ??? But it may break in the future.  We should use a machine
3760          dependent REG_NOTE, or some other approach entirely.  */
3761       for (insn = first; insn; insn = NEXT_INSN (insn))
3762         {
3763           if (INSN_P (insn))
3764             {
3765               rtx note;
3766
3767               while ((note = find_reg_note (insn, REG_LABEL, NULL_RTX)) != 0)
3768                 remove_note (insn, note);
3769             }
3770         }
3771
3772       for (insn = first; insn; insn = NEXT_INSN (insn))
3773         {
3774           rtx pattern, reg, link, set, scan, dies, label;
3775           int rescan = 0, foundinsn = 0;
3776
3777           if (GET_CODE (insn) == CALL_INSN)
3778             {
3779               pattern = PATTERN (insn);
3780
3781               if (GET_CODE (pattern) == PARALLEL)
3782                 pattern = XVECEXP (pattern, 0, 0);
3783               if (GET_CODE (pattern) == SET)
3784                 pattern = SET_SRC (pattern);
3785
3786               if (GET_CODE (pattern) != CALL
3787                   || GET_CODE (XEXP (pattern, 0)) != MEM)
3788                 continue;
3789
3790               reg = XEXP (XEXP (pattern, 0), 0);
3791             }
3792           else
3793             {
3794               reg = sfunc_uses_reg (insn);
3795               if (! reg)
3796                 continue;
3797             }
3798
3799           if (GET_CODE (reg) != REG)
3800             continue;
3801
3802           /* This is a function call via REG.  If the only uses of REG
3803              between the time that it is set and the time that it dies
3804              are in function calls, then we can associate all the
3805              function calls with the setting of REG.  */
3806
3807           for (link = LOG_LINKS (insn); link; link = XEXP (link, 1))
3808             {
3809               if (REG_NOTE_KIND (link) != 0)
3810                 continue;
3811               set = single_set (XEXP (link, 0));
3812               if (set && rtx_equal_p (reg, SET_DEST (set)))
3813                 {
3814                   link = XEXP (link, 0);
3815                   break;
3816                 }
3817             }
3818
3819           if (! link)
3820             {
3821               /* ??? Sometimes global register allocation will have
3822                  deleted the insn pointed to by LOG_LINKS.  Try
3823                  scanning backward to find where the register is set.  */
3824               for (scan = PREV_INSN (insn);
3825                    scan && GET_CODE (scan) != CODE_LABEL;
3826                    scan = PREV_INSN (scan))
3827                 {
3828                   if (! INSN_P (scan))
3829                     continue;
3830
3831                   if (! reg_mentioned_p (reg, scan))
3832                     continue;
3833
3834                   if (noncall_uses_reg (reg, scan, &set))
3835                     break;
3836
3837                   if (set)
3838                     {
3839                       link = scan;
3840                       break;
3841                     }
3842                 }
3843             }
3844
3845           if (! link)
3846             continue;
3847
3848           /* The register is set at LINK.  */
3849
3850           /* We can only optimize the function call if the register is
3851              being set to a symbol.  In theory, we could sometimes
3852              optimize calls to a constant location, but the assembler
3853              and linker do not support that at present.  */
3854           if (GET_CODE (SET_SRC (set)) != SYMBOL_REF
3855               && GET_CODE (SET_SRC (set)) != LABEL_REF)
3856             continue;
3857
3858           /* Scan forward from LINK to the place where REG dies, and
3859              make sure that the only insns which use REG are
3860              themselves function calls.  */
3861
3862           /* ??? This doesn't work for call targets that were allocated
3863              by reload, since there may not be a REG_DEAD note for the
3864              register.  */
3865
3866           dies = NULL_RTX;
3867           for (scan = NEXT_INSN (link); scan; scan = NEXT_INSN (scan))
3868             {
3869               rtx scanset;
3870
3871               /* Don't try to trace forward past a CODE_LABEL if we haven't
3872                  seen INSN yet.  Ordinarily, we will only find the setting insn
3873                  in LOG_LINKS if it is in the same basic block.  However,
3874                  cross-jumping can insert code labels in between the load and
3875                  the call, and can result in situations where a single call
3876                  insn may have two targets depending on where we came from.  */
3877
3878               if (GET_CODE (scan) == CODE_LABEL && ! foundinsn)
3879                 break;
3880
3881               if (! INSN_P (scan))
3882                 continue;
3883
3884               /* Don't try to trace forward past a JUMP.  To optimize
3885                  safely, we would have to check that all the
3886                  instructions at the jump destination did not use REG.  */
3887
3888               if (GET_CODE (scan) == JUMP_INSN)
3889                 break;
3890
3891               if (! reg_mentioned_p (reg, scan))
3892                 continue;
3893
3894               if (noncall_uses_reg (reg, scan, &scanset))
3895                 break;
3896
3897               if (scan == insn)
3898                 foundinsn = 1;
3899
3900               if (scan != insn
3901                   && (GET_CODE (scan) == CALL_INSN || sfunc_uses_reg (scan)))
3902                 {
3903                   /* There is a function call to this register other
3904                      than the one we are checking.  If we optimize
3905                      this call, we need to rescan again below.  */
3906                   rescan = 1;
3907                 }
3908
3909               /* ??? We shouldn't have to worry about SCANSET here.
3910                  We should just be able to check for a REG_DEAD note
3911                  on a function call.  However, the REG_DEAD notes are
3912                  apparently not dependable around libcalls; c-torture
3913                  execute/920501-2 is a test case.  If SCANSET is set,
3914                  then this insn sets the register, so it must have
3915                  died earlier.  Unfortunately, this will only handle
3916                  the cases in which the register is, in fact, set in a
3917                  later insn.  */
3918
3919               /* ??? We shouldn't have to use FOUNDINSN here.
3920                  However, the LOG_LINKS fields are apparently not
3921                  entirely reliable around libcalls;
3922                  newlib/libm/math/e_pow.c is a test case.  Sometimes
3923                  an insn will appear in LOG_LINKS even though it is
3924                  not the most recent insn which sets the register.  */
3925
3926               if (foundinsn
3927                   && (scanset
3928                       || find_reg_note (scan, REG_DEAD, reg)))
3929                 {
3930                   dies = scan;
3931                   break;
3932                 }
3933             }
3934
3935           if (! dies)
3936             {
3937               /* Either there was a branch, or some insn used REG
3938                  other than as a function call address.  */
3939               continue;
3940             }
3941
3942           /* Create a code label, and put it in a REG_LABEL note on
3943              the insn which sets the register, and on each call insn
3944              which uses the register.  In final_prescan_insn we look
3945              for the REG_LABEL notes, and output the appropriate label
3946              or pseudo-op.  */
3947
3948           label = gen_label_rtx ();
3949           REG_NOTES (link) = gen_rtx_INSN_LIST (REG_LABEL, label,
3950                                                 REG_NOTES (link));
3951           REG_NOTES (insn) = gen_rtx_INSN_LIST (REG_LABEL, label,
3952                                                 REG_NOTES (insn));
3953           if (rescan)
3954             {
3955               scan = link;
3956               do
3957                 {
3958                   rtx reg2;
3959
3960                   scan = NEXT_INSN (scan);
3961                   if (scan != insn
3962                       && ((GET_CODE (scan) == CALL_INSN
3963                            && reg_mentioned_p (reg, scan))
3964                           || ((reg2 = sfunc_uses_reg (scan))
3965                               && REGNO (reg2) == REGNO (reg))))
3966                     REG_NOTES (scan)
3967                       = gen_rtx_INSN_LIST (REG_LABEL, label, REG_NOTES (scan));
3968                 }
3969               while (scan != dies);
3970             }
3971         }
3972     }
3973
3974   if (TARGET_SH2)
3975     fixup_addr_diff_vecs (first);
3976
3977   if (optimize)
3978     {
3979       mdep_reorg_phase = SH_SHORTEN_BRANCHES0;
3980       shorten_branches (first);
3981     }
3982   /* Scan the function looking for move instructions which have to be
3983      changed to pc-relative loads and insert the literal tables.  */
3984
3985   mdep_reorg_phase = SH_FIXUP_PCLOAD;
3986   for (insn = first, num_mova = 0; insn; insn = NEXT_INSN (insn))
3987     {
3988       if (mova_p (insn))
3989         {
3990           if (! num_mova++)
3991             mova = insn;
3992         }
3993       else if (GET_CODE (insn) == JUMP_INSN
3994                && GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
3995                && num_mova)
3996         {
3997           rtx scan;
3998           int total;
3999
4000           num_mova--;
4001
4002           /* Some code might have been inserted between the mova and
4003              its ADDR_DIFF_VEC.  Check if the mova is still in range.  */
4004           for (scan = mova, total = 0; scan != insn; scan = NEXT_INSN (scan))
4005             total += get_attr_length (scan);
4006
4007           /* range of mova is 1020, add 4 because pc counts from address of
4008              second instruction after this one, subtract 2 in case pc is 2
4009              byte aligned.  Possible alignment needed for the ADDR_DIFF_VEC
4010              cancels out with alignment effects of the mova itself.  */
4011           if (total > 1022)
4012             {
4013               /* Change the mova into a load, and restart scanning
4014                  there.  broken_move will then return true for mova.  */
4015               SET_SRC (PATTERN (mova))
4016                 = XVECEXP (SET_SRC (PATTERN (mova)), 0, 0);
4017               INSN_CODE (mova) = -1;
4018               insn = mova;
4019             }
4020         }
4021       if (broken_move (insn))
4022         {
4023           rtx scan;
4024           /* Scan ahead looking for a barrier to stick the constant table
4025              behind.  */
4026           rtx barrier = find_barrier (num_mova, mova, insn);
4027           rtx last_float_move = NULL_RTX, last_float = 0, *last_float_addr = NULL;
4028
4029           if (num_mova && ! mova_p (mova))
4030             {
4031               /* find_barrier had to change the first mova into a
4032                  pcload; thus, we have to start with this new pcload.  */
4033               insn = mova;
4034               num_mova = 0;
4035             }
4036           /* Now find all the moves between the points and modify them.  */
4037           for (scan = insn; scan != barrier; scan = NEXT_INSN (scan))
4038             {
4039               if (GET_CODE (scan) == CODE_LABEL)
4040                 last_float = 0;
4041               if (broken_move (scan))
4042                 {
4043                   rtx *patp = &PATTERN (scan), pat = *patp;
4044                   rtx src, dst;
4045                   rtx lab;
4046                   rtx newsrc;
4047                   enum machine_mode mode;
4048
4049                   if (GET_CODE (pat) == PARALLEL)
4050                     patp = &XVECEXP (pat, 0, 0), pat = *patp;
4051                   src = SET_SRC (pat);
4052                   dst = SET_DEST (pat);
4053                   mode = GET_MODE (dst);
4054
4055                   if (mode == SImode && hi_const (src)
4056                       && REGNO (dst) != FPUL_REG)
4057                     {
4058                       int offset = 0;
4059
4060                       mode = HImode;
4061                       while (GET_CODE (dst) == SUBREG)
4062                         {
4063                           offset += subreg_regno_offset (REGNO (SUBREG_REG (dst)),
4064                                                          GET_MODE (SUBREG_REG (dst)),
4065                                                          SUBREG_BYTE (dst),
4066                                                          GET_MODE (dst));
4067                           dst = SUBREG_REG (dst);
4068                         }
4069                       dst = gen_rtx_REG (HImode, REGNO (dst) + offset);
4070                     }
4071
4072                   if (GET_CODE (dst) == REG && FP_ANY_REGISTER_P (REGNO (dst)))
4073                     {
4074                       /* This must be an insn that clobbers r0.  */
4075                       rtx clobber = XVECEXP (PATTERN (scan), 0,
4076                                              XVECLEN (PATTERN (scan), 0) - 1);
4077
4078                       if (GET_CODE (clobber) != CLOBBER
4079                           || ! rtx_equal_p (XEXP (clobber, 0), r0_rtx))
4080                         abort ();
4081
4082                       if (last_float
4083                           && reg_set_between_p (r0_rtx, last_float_move, scan))
4084                         last_float = 0;
4085                       if (last_float
4086                           && TARGET_SHCOMPACT
4087                           && GET_MODE_SIZE (mode) != 4
4088                           && GET_MODE_SIZE (GET_MODE (last_float)) == 4)
4089                         last_float = 0;
4090                       lab = add_constant (src, mode, last_float);
4091                       if (lab)
4092                         emit_insn_before (gen_mova (lab), scan);
4093                       else
4094                         {
4095                           /* There will be a REG_UNUSED note for r0 on
4096                              LAST_FLOAT_MOVE; we have to change it to REG_INC,
4097                              lest reorg:mark_target_live_regs will not
4098                              consider r0 to be used, and we end up with delay
4099                              slot insn in front of SCAN that clobbers r0.  */
4100                           rtx note
4101                             = find_regno_note (last_float_move, REG_UNUSED, 0);
4102
4103                           /* If we are not optimizing, then there may not be
4104                              a note.  */
4105                           if (note)
4106                             PUT_MODE (note, REG_INC);
4107
4108                           *last_float_addr = r0_inc_rtx;
4109                         }
4110                       last_float_move = scan;
4111                       last_float = src;
4112                       newsrc = gen_rtx (MEM, mode,
4113                                         (((TARGET_SH4 && ! TARGET_FMOVD)
4114                                           || REGNO (dst) == FPUL_REG)
4115                                          ? r0_inc_rtx
4116                                          : r0_rtx));
4117                       last_float_addr = &XEXP (newsrc, 0);
4118
4119                       /* Remove the clobber of r0.  */
4120                       XEXP (clobber, 0) = gen_rtx_SCRATCH (Pmode);
4121                       RTX_UNCHANGING_P (newsrc) = 1;
4122                     }
4123                   /* This is a mova needing a label.  Create it.  */
4124                   else if (GET_CODE (src) == UNSPEC
4125                            && XINT (src, 1) == UNSPEC_MOVA
4126                            && GET_CODE (XVECEXP (src, 0, 0)) == CONST)
4127                     {
4128                       lab = add_constant (XVECEXP (src, 0, 0), mode, 0);
4129                       newsrc = gen_rtx_LABEL_REF (VOIDmode, lab);
4130                       newsrc = gen_rtx_UNSPEC (SImode,
4131                                                gen_rtvec (1, newsrc),
4132                                                UNSPEC_MOVA);
4133                     }
4134                   else
4135                     {
4136                       lab = add_constant (src, mode, 0);
4137                       newsrc = gen_rtx_MEM (mode,
4138                                             gen_rtx_LABEL_REF (VOIDmode, lab));
4139                       RTX_UNCHANGING_P (newsrc) = 1;
4140                     }
4141                   *patp = gen_rtx_SET (VOIDmode, dst, newsrc);
4142                   INSN_CODE (scan) = -1;
4143                 }
4144             }
4145           dump_table (barrier);
4146           insn = barrier;
4147         }
4148     }
4149
4150   mdep_reorg_phase = SH_SHORTEN_BRANCHES1;
4151   INSN_ADDRESSES_FREE ();
4152   split_branches (first);
4153
4154   /* The INSN_REFERENCES_ARE_DELAYED in sh.h is problematic because it
4155      also has an effect on the register that holds the address of the sfunc.
4156      Insert an extra dummy insn in front of each sfunc that pretends to
4157      use this register.  */
4158   if (flag_delayed_branch)
4159     {
4160       for (insn = first; insn; insn = NEXT_INSN (insn))
4161         {
4162           rtx reg = sfunc_uses_reg (insn);
4163
4164           if (! reg)
4165             continue;
4166           emit_insn_before (gen_use_sfunc_addr (reg), insn);
4167         }
4168     }
4169 #if 0
4170   /* fpscr is not actually a user variable, but we pretend it is for the
4171      sake of the previous optimization passes, since we want it handled like
4172      one.  However, we don't have any debugging information for it, so turn
4173      it into a non-user variable now.  */
4174   if (TARGET_SH4)
4175     REG_USERVAR_P (get_fpscr_rtx ()) = 0;
4176 #endif
4177   mdep_reorg_phase = SH_AFTER_MDEP_REORG;
4178 }
4179
4180 int
4181 get_dest_uid (label, max_uid)
4182      rtx label;
4183      int max_uid;
4184 {
4185   rtx dest = next_real_insn (label);
4186   int dest_uid;
4187   if (! dest)
4188     /* This can happen for an undefined label.  */
4189     return 0;
4190   dest_uid = INSN_UID (dest);
4191   /* If this is a newly created branch redirection blocking instruction,
4192      we cannot index the branch_uid or insn_addresses arrays with its
4193      uid.  But then, we won't need to, because the actual destination is
4194      the following branch.  */
4195   while (dest_uid >= max_uid)
4196     {
4197       dest = NEXT_INSN (dest);
4198       dest_uid = INSN_UID (dest);
4199     }
4200   if (GET_CODE (dest) == JUMP_INSN && GET_CODE (PATTERN (dest)) == RETURN)
4201     return 0;
4202   return dest_uid;
4203 }
4204
4205 /* Split condbranches that are out of range.  Also add clobbers for
4206    scratch registers that are needed in far jumps.
4207    We do this before delay slot scheduling, so that it can take our
4208    newly created instructions into account.  It also allows us to
4209    find branches with common targets more easily.  */
4210
4211 static void
4212 split_branches (first)
4213      rtx first;
4214 {
4215   rtx insn;
4216   struct far_branch **uid_branch, *far_branch_list = 0;
4217   int max_uid = get_max_uid ();
4218
4219   /* Find out which branches are out of range.  */
4220   shorten_branches (first);
4221
4222   uid_branch = (struct far_branch **) alloca (max_uid * sizeof *uid_branch);
4223   memset ((char *) uid_branch, 0, max_uid * sizeof *uid_branch);
4224
4225   for (insn = first; insn; insn = NEXT_INSN (insn))
4226     if (! INSN_P (insn))
4227       continue;
4228     else if (INSN_DELETED_P (insn))
4229       {
4230         /* Shorten_branches would split this instruction again,
4231            so transform it into a note.  */
4232         PUT_CODE (insn, NOTE);
4233         NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED;
4234         NOTE_SOURCE_FILE (insn) = 0;
4235       }
4236     else if (GET_CODE (insn) == JUMP_INSN
4237              /* Don't mess with ADDR_DIFF_VEC */
4238              && (GET_CODE (PATTERN (insn)) == SET
4239                  || GET_CODE (PATTERN (insn)) == RETURN))
4240       {
4241         enum attr_type type = get_attr_type (insn);
4242         if (type == TYPE_CBRANCH)
4243           {
4244             rtx next, beyond;
4245     
4246             if (get_attr_length (insn) > 4)
4247               {
4248                 rtx src = SET_SRC (PATTERN (insn));
4249                 rtx olabel = XEXP (XEXP (src, 1), 0);
4250                 int addr = INSN_ADDRESSES (INSN_UID (insn));
4251                 rtx label = 0;
4252                 int dest_uid = get_dest_uid (olabel, max_uid);
4253                 struct far_branch *bp = uid_branch[dest_uid];
4254     
4255                 /* redirect_jump needs a valid JUMP_LABEL, and it might delete
4256                    the label if the LABEL_NUSES count drops to zero.  There is
4257                    always a jump_optimize pass that sets these values, but it
4258                    proceeds to delete unreferenced code, and then if not
4259                    optimizing, to un-delete the deleted instructions, thus
4260                    leaving labels with too low uses counts.  */
4261                 if (! optimize)
4262                   {
4263                     JUMP_LABEL (insn) = olabel;
4264                     LABEL_NUSES (olabel)++;
4265                   }
4266                 if (! bp)
4267                   {
4268                     bp = (struct far_branch *) alloca (sizeof *bp);
4269                     uid_branch[dest_uid] = bp;
4270                     bp->prev = far_branch_list;
4271                     far_branch_list = bp;
4272                     bp->far_label
4273                       = XEXP (XEXP (SET_SRC (PATTERN (insn)), 1), 0);
4274                     LABEL_NUSES (bp->far_label)++;
4275                   }
4276                 else
4277                   {
4278                     label = bp->near_label;
4279                     if (! label && bp->address - addr >= CONDJUMP_MIN)
4280                       {
4281                         rtx block = bp->insert_place;
4282
4283                         if (GET_CODE (PATTERN (block)) == RETURN)
4284                           block = PREV_INSN (block);
4285                         else
4286                           block = gen_block_redirect (block,
4287                                                       bp->address, 2);
4288                         label = emit_label_after (gen_label_rtx (),
4289                                                   PREV_INSN (block));
4290                         bp->near_label = label;
4291                       }
4292                     else if (label && ! NEXT_INSN (label))
4293                       {
4294                         if (addr + 2 - bp->address <= CONDJUMP_MAX)
4295                           bp->insert_place = insn;
4296                         else
4297                           gen_far_branch (bp);
4298                       }
4299                   }
4300                 if (! label
4301                     || (NEXT_INSN (label) && bp->address - addr < CONDJUMP_MIN))
4302                   {
4303                     bp->near_label = label = gen_label_rtx ();
4304                     bp->insert_place = insn;
4305                     bp->address = addr;
4306                   }
4307                 if (! redirect_jump (insn, label, 1))
4308                   abort ();
4309               }
4310             else
4311               {
4312                 /* get_attr_length (insn) == 2 */
4313                 /* Check if we have a pattern where reorg wants to redirect
4314                    the branch to a label from an unconditional branch that
4315                    is too far away.  */
4316                 /* We can't use JUMP_LABEL here because it might be undefined
4317                    when not optimizing.  */
4318                 /* A syntax error might cause beyond to be NULL_RTX.  */
4319                 beyond
4320                   = next_active_insn (XEXP (XEXP (SET_SRC (PATTERN (insn)), 1),
4321                                             0));
4322         
4323                 if (beyond
4324                     && (GET_CODE (beyond) == JUMP_INSN
4325                         || ((beyond = next_active_insn (beyond))
4326                             && GET_CODE (beyond) == JUMP_INSN))
4327                     && GET_CODE (PATTERN (beyond)) == SET
4328                     && recog_memoized (beyond) == CODE_FOR_jump_compact
4329                     && ((INSN_ADDRESSES
4330                          (INSN_UID (XEXP (SET_SRC (PATTERN (beyond)), 0)))
4331                          - INSN_ADDRESSES (INSN_UID (insn)) + (unsigned) 252)
4332                         > 252 + 258 + 2))
4333                   gen_block_redirect (beyond,
4334                                       INSN_ADDRESSES (INSN_UID (beyond)), 1);
4335               }
4336     
4337             next = next_active_insn (insn);
4338
4339             if ((GET_CODE (next) == JUMP_INSN
4340                  || GET_CODE (next = next_active_insn (next)) == JUMP_INSN)
4341                 && GET_CODE (PATTERN (next)) == SET
4342                 && recog_memoized (next) == CODE_FOR_jump_compact
4343                 && ((INSN_ADDRESSES
4344                      (INSN_UID (XEXP (SET_SRC (PATTERN (next)), 0)))
4345                      - INSN_ADDRESSES (INSN_UID (insn)) + (unsigned) 252)
4346                     > 252 + 258 + 2))
4347               gen_block_redirect (next, INSN_ADDRESSES (INSN_UID (next)), 1);
4348           }
4349         else if (type == TYPE_JUMP || type == TYPE_RETURN)
4350           {
4351             int addr = INSN_ADDRESSES (INSN_UID (insn));
4352             rtx far_label = 0;
4353             int dest_uid = 0;
4354             struct far_branch *bp;
4355
4356             if (type == TYPE_JUMP)
4357               {
4358                 far_label = XEXP (SET_SRC (PATTERN (insn)), 0);
4359                 dest_uid = get_dest_uid (far_label, max_uid);
4360                 if (! dest_uid)
4361                   {
4362                     /* Parse errors can lead to labels outside
4363                       the insn stream.  */
4364                     if (! NEXT_INSN (far_label))
4365                       continue;
4366
4367                     if (! optimize)
4368                       {
4369                         JUMP_LABEL (insn) = far_label;
4370                         LABEL_NUSES (far_label)++;
4371                       }
4372                     redirect_jump (insn, NULL_RTX, 1);
4373                     far_label = 0;
4374                   }
4375               }
4376             bp = uid_branch[dest_uid];
4377             if (! bp)
4378               {
4379                 bp = (struct far_branch *) alloca (sizeof *bp);
4380                 uid_branch[dest_uid] = bp;
4381                 bp->prev = far_branch_list;
4382                 far_branch_list = bp;
4383                 bp->near_label = 0;
4384                 bp->far_label = far_label;
4385                 if (far_label)
4386                   LABEL_NUSES (far_label)++;
4387               }
4388             else if (bp->near_label && ! NEXT_INSN (bp->near_label))
4389               if (addr - bp->address <= CONDJUMP_MAX)
4390                 emit_label_after (bp->near_label, PREV_INSN (insn));
4391               else
4392                 {
4393                   gen_far_branch (bp);
4394                   bp->near_label = 0;
4395                 }
4396             else
4397               bp->near_label = 0;
4398             bp->address = addr;
4399             bp->insert_place = insn;
4400             if (! far_label)
4401               emit_insn_before (gen_block_branch_redirect (const0_rtx), insn);
4402             else
4403               gen_block_redirect (insn, addr, bp->near_label ? 2 : 0);
4404           }
4405       }
4406   /* Generate all pending far branches,
4407      and free our references to the far labels.  */
4408   while (far_branch_list)
4409     {
4410       if (far_branch_list->near_label
4411           && ! NEXT_INSN (far_branch_list->near_label))
4412         gen_far_branch (far_branch_list);
4413       if (optimize
4414           && far_branch_list->far_label
4415           && ! --LABEL_NUSES (far_branch_list->far_label))
4416         delete_insn (far_branch_list->far_label);
4417       far_branch_list = far_branch_list->prev;
4418     }
4419
4420   /* Instruction length information is no longer valid due to the new
4421      instructions that have been generated.  */
4422   init_insn_lengths ();
4423 }
4424
4425 /* Dump out instruction addresses, which is useful for debugging the
4426    constant pool table stuff.
4427
4428    If relaxing, output the label and pseudo-ops used to link together
4429    calls and the instruction which set the registers.  */
4430
4431 /* ??? The addresses printed by this routine for insns are nonsense for
4432    insns which are inside of a sequence where none of the inner insns have
4433    variable length.  This is because the second pass of shorten_branches
4434    does not bother to update them.  */
4435
4436 void
4437 final_prescan_insn (insn, opvec, noperands)
4438      rtx insn;
4439      rtx *opvec ATTRIBUTE_UNUSED;
4440      int noperands ATTRIBUTE_UNUSED;
4441 {
4442   if (TARGET_DUMPISIZE)
4443     fprintf (asm_out_file, "\n! at %04x\n", INSN_ADDRESSES (INSN_UID (insn)));
4444
4445   if (TARGET_RELAX)
4446     {
4447       rtx note;
4448
4449       note = find_reg_note (insn, REG_LABEL, NULL_RTX);
4450       if (note)
4451         {
4452           rtx pattern;
4453
4454           pattern = PATTERN (insn);
4455           if (GET_CODE (pattern) == PARALLEL)
4456             pattern = XVECEXP (pattern, 0, 0);
4457           if (GET_CODE (pattern) == CALL
4458               || (GET_CODE (pattern) == SET
4459                   && (GET_CODE (SET_SRC (pattern)) == CALL
4460                       || get_attr_type (insn) == TYPE_SFUNC)))
4461             asm_fprintf (asm_out_file, "\t.uses %LL%d\n",
4462                          CODE_LABEL_NUMBER (XEXP (note, 0)));
4463           else if (GET_CODE (pattern) == SET)
4464             (*targetm.asm_out.internal_label) (asm_out_file, "L",
4465                                        CODE_LABEL_NUMBER (XEXP (note, 0)));
4466           else
4467             abort ();
4468         }
4469     }
4470 }
4471
4472 /* Dump out any constants accumulated in the final pass.  These will
4473    only be labels.  */
4474
4475 const char *
4476 output_jump_label_table ()
4477 {
4478   int i;
4479
4480   if (pool_size)
4481     {
4482       fprintf (asm_out_file, "\t.align 2\n");
4483       for (i = 0; i < pool_size; i++)
4484         {
4485           pool_node *p = &pool_vector[i];
4486
4487           (*targetm.asm_out.internal_label) (asm_out_file, "L",
4488                                      CODE_LABEL_NUMBER (p->label));
4489           output_asm_insn (".long       %O0", &p->value);
4490         }
4491       pool_size = 0;
4492     }
4493
4494   return "";
4495 }
4496 \f
4497 /* A full frame looks like:
4498
4499    arg-5
4500    arg-4
4501    [ if current_function_anonymous_args
4502    arg-3
4503    arg-2
4504    arg-1
4505    arg-0 ]
4506    saved-fp
4507    saved-r10
4508    saved-r11
4509    saved-r12
4510    saved-pr
4511    local-n
4512    ..
4513    local-1
4514    local-0        <- fp points here.  */
4515
4516 /* Number of bytes pushed for anonymous args, used to pass information
4517    between expand_prologue and expand_epilogue.  */
4518
4519 static int extra_push;
4520
4521 /* Adjust the stack by SIZE bytes.  REG holds the rtl of the register
4522   to be adjusted, and TEMP, if nonnegative, holds the register number
4523   of a general register that we may clobber.  */
4524
4525 static void
4526 output_stack_adjust (size, reg, temp, emit_fn)
4527      int size;
4528      rtx reg;
4529      int temp;
4530      rtx (*emit_fn) PARAMS ((rtx));
4531 {
4532   if (size)
4533     {
4534       HOST_WIDE_INT align = STACK_BOUNDARY / BITS_PER_UNIT;
4535
4536       if (size % align)
4537         abort ();
4538
4539       if (CONST_OK_FOR_ADD (size))
4540         emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size)));
4541       /* Try to do it with two partial adjustments; however, we must make
4542          sure that the stack is properly aligned at all times, in case
4543          an interrupt occurs between the two partial adjustments.  */
4544       else if (CONST_OK_FOR_ADD (size / 2 & -align)
4545                && CONST_OK_FOR_ADD (size - (size / 2 & -align)))
4546         {
4547           emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size / 2 & -align)));
4548           emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size - (size / 2 & -align))));
4549         }
4550       else
4551         {
4552           rtx const_reg;
4553           rtx insn;
4554
4555           /* If TEMP is invalid, we could temporarily save a general
4556              register to MACL.  However, there is currently no need
4557              to handle this case, so just abort when we see it.  */
4558           if (temp < 0)
4559             abort ();
4560           const_reg = gen_rtx_REG (GET_MODE (reg), temp);
4561
4562           /* If SIZE is negative, subtract the positive value.
4563              This sometimes allows a constant pool entry to be shared
4564              between prologue and epilogue code.  */
4565           if (size < 0)
4566             {
4567               emit_insn (GEN_MOV (const_reg, GEN_INT (-size)));
4568               insn = emit_fn (GEN_SUB3 (reg, reg, const_reg));
4569             }
4570           else
4571             {
4572               emit_insn (GEN_MOV (const_reg, GEN_INT (size)));
4573               insn = emit_fn (GEN_ADD3 (reg, reg, const_reg));
4574             }
4575           if (emit_fn == frame_insn)
4576             REG_NOTES (insn)
4577               = (gen_rtx_EXPR_LIST
4578                  (REG_FRAME_RELATED_EXPR,
4579                   gen_rtx_SET (VOIDmode, reg,
4580                                gen_rtx_PLUS (SImode, reg, GEN_INT (size))),
4581                   REG_NOTES (insn)));
4582         }
4583     }
4584 }
4585
4586 static rtx
4587 frame_insn (x)
4588      rtx x;
4589 {
4590   x = emit_insn (x);
4591   RTX_FRAME_RELATED_P (x) = 1;
4592   return x;
4593 }
4594
4595 /* Output RTL to push register RN onto the stack.  */
4596
4597 static rtx
4598 push (rn)
4599      int rn;
4600 {
4601   rtx x;
4602   if (rn == FPUL_REG)
4603     x = gen_push_fpul ();
4604   else if (rn == FPSCR_REG)
4605     x = gen_push_fpscr ();
4606   else if (TARGET_SH4 && TARGET_FMOVD && ! TARGET_FPU_SINGLE
4607            && FP_OR_XD_REGISTER_P (rn))
4608     {
4609       if (FP_REGISTER_P (rn) && (rn - FIRST_FP_REG) & 1)
4610         return NULL_RTX;
4611       x = gen_push_4 (gen_rtx_REG (DFmode, rn));
4612     }
4613   else if (TARGET_SH2E && FP_REGISTER_P (rn))
4614     x = gen_push_e (gen_rtx_REG (SFmode, rn));
4615   else
4616     x = gen_push (gen_rtx_REG (SImode, rn));
4617
4618   x = frame_insn (x);
4619   REG_NOTES (x)
4620     = gen_rtx_EXPR_LIST (REG_INC,
4621                          gen_rtx_REG (SImode, STACK_POINTER_REGNUM), 0);
4622   return x;
4623 }
4624
4625 /* Output RTL to pop register RN from the stack.  */
4626
4627 static void
4628 pop (rn)
4629      int rn;
4630 {
4631   rtx x;
4632   if (rn == FPUL_REG)
4633     x = gen_pop_fpul ();
4634   else if (rn == FPSCR_REG)
4635     x = gen_pop_fpscr ();
4636   else if (TARGET_SH4 && TARGET_FMOVD && ! TARGET_FPU_SINGLE
4637            && FP_OR_XD_REGISTER_P (rn))
4638     {
4639       if (FP_REGISTER_P (rn) && (rn - FIRST_FP_REG) & 1)
4640         return;
4641       x = gen_pop_4 (gen_rtx_REG (DFmode, rn));
4642     }
4643   else if (TARGET_SH2E && FP_REGISTER_P (rn))
4644     x = gen_pop_e (gen_rtx_REG (SFmode, rn));
4645   else
4646     x = gen_pop (gen_rtx_REG (SImode, rn));
4647     
4648   x = emit_insn (x);
4649   REG_NOTES (x)
4650     = gen_rtx_EXPR_LIST (REG_INC,
4651                          gen_rtx_REG (SImode, STACK_POINTER_REGNUM), 0);
4652 }
4653
4654 /* Generate code to push the regs specified in the mask.  */
4655
4656 static void
4657 push_regs (mask, interrupt_handler)
4658      HARD_REG_SET *mask;
4659      int interrupt_handler;
4660 {
4661   int i;
4662   int skip_fpscr = 0;
4663
4664   /* Push PR last; this gives better latencies after the prologue, and
4665      candidates for the return delay slot when there are no general
4666      registers pushed.  */
4667   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
4668     {
4669       /* If this is an interrupt handler, and the SZ bit varies,
4670          and we have to push any floating point register, we need
4671          to switch to the correct precision first.  */
4672       if (i == FIRST_FP_REG && interrupt_handler && TARGET_FMOVD
4673           && hard_regs_intersect_p (mask, &reg_class_contents[DF_REGS]))
4674         {
4675           HARD_REG_SET unsaved;
4676
4677           push (FPSCR_REG);
4678           COMPL_HARD_REG_SET(unsaved, *mask);
4679           fpscr_set_from_mem (NORMAL_MODE (FP_MODE), unsaved);
4680           skip_fpscr = 1;
4681         }
4682       if (i != PR_REG
4683           && (i != FPSCR_REG || ! skip_fpscr)
4684           && TEST_HARD_REG_BIT (*mask, i))
4685         push (i);
4686     }
4687   if (TEST_HARD_REG_BIT (*mask, PR_REG))
4688     push (PR_REG);
4689 }
4690
4691 /* Work out the registers which need to be saved, both as a mask and a
4692    count of saved words.  Return the count.
4693
4694    If doing a pragma interrupt function, then push all regs used by the
4695    function, and if we call another function (we can tell by looking at PR),
4696    make sure that all the regs it clobbers are safe too.  */
4697
4698 static int
4699 calc_live_regs (live_regs_mask)
4700      HARD_REG_SET *live_regs_mask;
4701 {
4702   int reg;
4703   int count;
4704   int interrupt_handler;
4705   int pr_live;
4706
4707   interrupt_handler = sh_cfun_interrupt_handler_p ();
4708
4709   for (count = 0; 32 * count < FIRST_PSEUDO_REGISTER; count++)
4710     CLEAR_HARD_REG_SET (*live_regs_mask);
4711   if (TARGET_SH4 && TARGET_FMOVD && interrupt_handler
4712       && regs_ever_live[FPSCR_REG])
4713     target_flags &= ~FPU_SINGLE_BIT;
4714   /* If we can save a lot of saves by switching to double mode, do that.  */
4715   else if (TARGET_SH4 && TARGET_FMOVD && TARGET_FPU_SINGLE)
4716     for (count = 0, reg = FIRST_FP_REG; reg <= LAST_FP_REG; reg += 2)
4717       if (regs_ever_live[reg] && regs_ever_live[reg+1]
4718           && (! call_used_regs[reg] || (interrupt_handler && ! pragma_trapa))
4719           && ++count > 2)
4720         {
4721           target_flags &= ~FPU_SINGLE_BIT;
4722           break;
4723         }
4724   /* PR_MEDIA_REG is a general purpose register, thus global_alloc already
4725      knows how to use it.  That means the pseudo originally allocated for
4726      the initial value can become the PR_MEDIA_REG hard register, as seen for
4727      execute/20010122-1.c:test9.  */
4728   if (TARGET_SHMEDIA)
4729     pr_live = regs_ever_live[PR_MEDIA_REG];
4730   else
4731     {
4732       rtx pr_initial = has_hard_reg_initial_val (Pmode, PR_REG);
4733       pr_live = (pr_initial
4734                  ? (GET_CODE (pr_initial) != REG
4735                     || REGNO (pr_initial) != (PR_REG))
4736                  : regs_ever_live[PR_REG]);
4737     }
4738   /* Force PR to be live if the prologue has to call the SHmedia
4739      argument decoder or register saver.  */
4740   if (TARGET_SHCOMPACT
4741       && ((current_function_args_info.call_cookie
4742            & ~ CALL_COOKIE_RET_TRAMP (1))
4743           || current_function_has_nonlocal_label))
4744     pr_live = 1;
4745   for (count = 0, reg = FIRST_PSEUDO_REGISTER - 1; reg >= 0; reg--)
4746     {
4747       if (reg == (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG)
4748           ? pr_live
4749           : (interrupt_handler && ! pragma_trapa)
4750           ? (/* Need to save all the regs ever live.  */
4751              (regs_ever_live[reg]
4752               || (call_used_regs[reg]
4753                   && (! fixed_regs[reg] || reg == MACH_REG || reg == MACL_REG)
4754                   && pr_live))
4755              && reg != STACK_POINTER_REGNUM && reg != ARG_POINTER_REGNUM
4756              && reg != RETURN_ADDRESS_POINTER_REGNUM
4757              && reg != T_REG && reg != GBR_REG
4758              /* Push fpscr only on targets which have FPU */
4759              && (reg != FPSCR_REG || TARGET_FPU_ANY))
4760           : (/* Only push those regs which are used and need to be saved.  */
4761              (TARGET_SHCOMPACT
4762               && flag_pic
4763               && current_function_args_info.call_cookie
4764               && reg == PIC_OFFSET_TABLE_REGNUM)
4765              || (regs_ever_live[reg] && ! call_used_regs[reg])
4766              || (current_function_calls_eh_return
4767                  && (reg == EH_RETURN_DATA_REGNO (0)
4768                      || reg == EH_RETURN_DATA_REGNO (1)
4769                      || reg == EH_RETURN_DATA_REGNO (2)
4770                      || reg == EH_RETURN_DATA_REGNO (3)))))
4771         {
4772           SET_HARD_REG_BIT (*live_regs_mask, reg);
4773           count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
4774
4775           if ((TARGET_SH4 || TARGET_SH5) && TARGET_FMOVD
4776               && GET_MODE_CLASS (REGISTER_NATURAL_MODE (reg)) == MODE_FLOAT)
4777             {
4778               if (FP_REGISTER_P (reg))
4779                 {
4780                   if (! TARGET_FPU_SINGLE && ! regs_ever_live[reg ^ 1])
4781                     {
4782                       SET_HARD_REG_BIT (*live_regs_mask, (reg ^ 1));
4783                       count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg ^ 1));
4784                     }
4785                 }
4786               else if (XD_REGISTER_P (reg))
4787                 {
4788                   /* Must switch to double mode to access these registers.  */
4789                   target_flags &= ~FPU_SINGLE_BIT;
4790                 }
4791             }
4792         }
4793     }
4794
4795   return count;
4796 }
4797
4798 /* Code to generate prologue and epilogue sequences */
4799
4800 /* PUSHED is the number of bytes that are being pushed on the
4801    stack for register saves.  Return the frame size, padded
4802    appropriately so that the stack stays properly aligned.  */
4803 static HOST_WIDE_INT
4804 rounded_frame_size (pushed)
4805      int pushed;
4806 {
4807   HOST_WIDE_INT size = get_frame_size ();
4808   HOST_WIDE_INT align = STACK_BOUNDARY / BITS_PER_UNIT;
4809
4810   return ((size + pushed + align - 1) & -align) - pushed;
4811 }
4812
4813 /* Choose a call-clobbered target-branch register that remains
4814    unchanged along the whole function.  We set it up as the return
4815    value in the prologue.  */
4816 int
4817 sh_media_register_for_return ()
4818 {
4819   int regno;
4820   int tr0_used;
4821
4822   if (! current_function_is_leaf)
4823     return -1;
4824
4825   tr0_used = flag_pic && regs_ever_live[PIC_OFFSET_TABLE_REGNUM];
4826
4827   for (regno = FIRST_TARGET_REG + tr0_used; regno <= LAST_TARGET_REG; regno++)
4828     if (call_used_regs[regno] && ! regs_ever_live[regno])
4829       return regno;
4830
4831   return -1;
4832 }
4833
4834 void
4835 sh_expand_prologue ()
4836 {
4837   HARD_REG_SET live_regs_mask;
4838   int d, i;
4839   int d_rounding = 0;
4840   int save_flags = target_flags;
4841
4842   current_function_interrupt = sh_cfun_interrupt_handler_p ();
4843
4844   /* We have pretend args if we had an object sent partially in registers
4845      and partially on the stack, e.g. a large structure.  */
4846   output_stack_adjust (-current_function_pretend_args_size
4847                        - current_function_args_info.stack_regs * 8,
4848                        stack_pointer_rtx, TARGET_SH5 ? 0 : 1, frame_insn);
4849
4850   extra_push = 0;
4851
4852   if (TARGET_SHCOMPACT && flag_pic && current_function_args_info.call_cookie)
4853     /* We're going to use the PIC register to load the address of the
4854        incoming-argument decoder and/or of the return trampoline from
4855        the GOT, so make sure the PIC register is preserved and
4856        initialized.  */
4857     regs_ever_live[PIC_OFFSET_TABLE_REGNUM] = 1;
4858
4859   if (TARGET_SHCOMPACT
4860       && (current_function_args_info.call_cookie & ~ CALL_COOKIE_RET_TRAMP(1)))
4861     {
4862       int reg;
4863
4864       /* First, make all registers with incoming arguments that will
4865          be pushed onto the stack live, so that register renaming
4866          doesn't overwrite them.  */
4867       for (reg = 0; reg < NPARM_REGS (SImode); reg++)
4868         if (CALL_COOKIE_STACKSEQ_GET (current_function_args_info.call_cookie)
4869             >= NPARM_REGS (SImode) - reg)
4870           for (; reg < NPARM_REGS (SImode); reg++)
4871             emit_insn (gen_shcompact_preserve_incoming_args
4872                        (gen_rtx_REG (SImode, FIRST_PARM_REG + reg)));
4873         else if (CALL_COOKIE_INT_REG_GET
4874                  (current_function_args_info.call_cookie, reg) == 1)
4875           emit_insn (gen_shcompact_preserve_incoming_args
4876                      (gen_rtx_REG (SImode, FIRST_PARM_REG + reg)));
4877
4878       emit_move_insn (gen_rtx_REG (Pmode, MACL_REG),
4879                       stack_pointer_rtx);
4880       emit_move_insn (gen_rtx_REG (SImode, R0_REG),
4881                       GEN_INT (current_function_args_info.call_cookie));
4882       emit_move_insn (gen_rtx_REG (SImode, MACH_REG),
4883                       gen_rtx_REG (SImode, R0_REG));
4884     }
4885   else if (TARGET_SHMEDIA)
4886     {
4887       int tr = sh_media_register_for_return ();
4888
4889       if (tr >= 0)
4890         {
4891           rtx insn = emit_move_insn (gen_rtx_REG (DImode, tr),
4892                                      gen_rtx_REG (DImode, PR_MEDIA_REG));
4893
4894           /* If this function only exits with sibcalls, this copy
4895              will be flagged as dead.  */
4896           REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD,
4897                                                 const0_rtx,
4898                                                 REG_NOTES (insn));
4899         }
4900     }
4901
4902   /* Emit the code for SETUP_VARARGS.  */
4903   if (current_function_stdarg)
4904     {
4905       /* This is not used by the SH2E calling convention  */
4906       if (TARGET_SH1 && ! TARGET_SH2E && ! TARGET_SH5 && ! TARGET_HITACHI)
4907         {
4908           /* Push arg regs as if they'd been provided by caller in stack.  */
4909           for (i = 0; i < NPARM_REGS(SImode); i++)
4910             {
4911               int rn = NPARM_REGS(SImode) + FIRST_PARM_REG - i - 1;
4912               rtx insn;
4913
4914               if (i >= (NPARM_REGS(SImode) 
4915                         - current_function_args_info.arg_count[(int) SH_ARG_INT]
4916                         ))
4917                 break;
4918               insn = push (rn);
4919               RTX_FRAME_RELATED_P (insn) = 0;
4920               extra_push += 4;
4921             }
4922         }
4923     }
4924
4925   /* If we're supposed to switch stacks at function entry, do so now.  */
4926   if (sp_switch)
4927     emit_insn (gen_sp_switch_1 ());
4928
4929   d = calc_live_regs (&live_regs_mask);
4930   /* ??? Maybe we could save some switching if we can move a mode switch
4931      that already happens to be at the function start into the prologue.  */
4932   if (target_flags != save_flags && ! current_function_interrupt)
4933     emit_insn (gen_toggle_sz ());
4934     
4935   if (TARGET_SH5)
4936     {
4937       int i;
4938       int offset;
4939       int align;
4940       rtx r0 = gen_rtx_REG (Pmode, R0_REG);
4941       int offset_in_r0 = -1;
4942       int sp_in_r0 = 0;
4943
4944       if (d % (STACK_BOUNDARY / BITS_PER_UNIT))
4945         d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
4946                       - d % (STACK_BOUNDARY / BITS_PER_UNIT));
4947
4948       offset = d + d_rounding;
4949       output_stack_adjust (-offset, stack_pointer_rtx, 1, frame_insn);
4950
4951       /* We loop twice: first, we save 8-byte aligned registers in the
4952          higher addresses, that are known to be aligned.  Then, we
4953          proceed to saving 32-bit registers that don't need 8-byte
4954          alignment.  */
4955       /* Note that if you change this code in a way that affects where
4956          the return register is saved, you have to update not only
4957          sh_expand_epilogue, but also sh_set_return_address.  */
4958       for (align = 1; align >= 0; align--)
4959         for (i = FIRST_PSEUDO_REGISTER - 1; i >= 0; i--)
4960           if (TEST_HARD_REG_BIT (live_regs_mask, i))
4961             {
4962               enum machine_mode mode = REGISTER_NATURAL_MODE (i);
4963               int reg = i;
4964               rtx reg_rtx, mem_rtx, pre_dec = NULL_RTX;
4965
4966               if (mode == SFmode && (i % 2) == 1
4967                   && ! TARGET_FPU_SINGLE && FP_REGISTER_P (i)
4968                   && (TEST_HARD_REG_BIT (live_regs_mask, (i ^ 1))))
4969                 {
4970                   mode = DFmode;
4971                   i--;
4972                   reg--;
4973                 }
4974                 
4975               /* If we're doing the aligned pass and this is not aligned,
4976                  or we're doing the unaligned pass and this is aligned,
4977                  skip it.  */
4978               if ((GET_MODE_SIZE (mode) % (STACK_BOUNDARY / BITS_PER_UNIT)
4979                    == 0) != align)
4980                 continue;
4981
4982               offset -= GET_MODE_SIZE (mode);
4983
4984               reg_rtx = gen_rtx_REG (mode, reg);
4985
4986               mem_rtx = gen_rtx_MEM (mode,
4987                                      gen_rtx_PLUS (Pmode,
4988                                                    stack_pointer_rtx,
4989                                                    GEN_INT (offset)));
4990
4991               GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (mem_rtx, 0), try_pre_dec);
4992
4993               mem_rtx = NULL_RTX;
4994
4995             try_pre_dec:
4996               do
4997                 if (HAVE_PRE_DECREMENT
4998                     && (offset_in_r0 - offset == GET_MODE_SIZE (mode)
4999                         || mem_rtx == NULL_RTX
5000                         || i == PR_REG || SPECIAL_REGISTER_P (i)))
5001                   {
5002                     pre_dec = gen_rtx_MEM (mode,
5003                                            gen_rtx_PRE_DEC (Pmode, r0));
5004
5005                     GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (pre_dec, 0),
5006                                               pre_dec_ok);
5007
5008                     pre_dec = NULL_RTX;
5009
5010                     break;
5011
5012                   pre_dec_ok:
5013                     mem_rtx = NULL_RTX;
5014                     offset += GET_MODE_SIZE (mode);
5015                   }
5016               while (0);
5017
5018               if (mem_rtx != NULL_RTX)
5019                 goto addr_ok;
5020
5021               if (offset_in_r0 == -1)
5022                 {
5023                   emit_move_insn (r0, GEN_INT (offset));
5024                   offset_in_r0 = offset;
5025                 }
5026               else if (offset != offset_in_r0)
5027                 {
5028                   emit_move_insn (r0,
5029                                   gen_rtx_PLUS
5030                                   (Pmode, r0,
5031                                    GEN_INT (offset - offset_in_r0)));
5032                   offset_in_r0 += offset - offset_in_r0;
5033                 }
5034                                                   
5035               if (pre_dec != NULL_RTX)
5036                 {
5037                   if (! sp_in_r0)
5038                     {
5039                       emit_move_insn (r0,
5040                                       gen_rtx_PLUS
5041                                       (Pmode, r0, stack_pointer_rtx));
5042                       sp_in_r0 = 1;
5043                     }
5044
5045                   offset -= GET_MODE_SIZE (mode);
5046                   offset_in_r0 -= GET_MODE_SIZE (mode);
5047
5048                   mem_rtx = pre_dec;
5049                 }
5050               else if (sp_in_r0)
5051                 mem_rtx = gen_rtx_MEM (mode, r0);
5052               else
5053                 mem_rtx = gen_rtx_MEM (mode,
5054                                        gen_rtx_PLUS (Pmode,
5055                                                      stack_pointer_rtx,
5056                                                      r0));
5057
5058               /* We must not use an r0-based address for target-branch
5059                  registers or for special registers without pre-dec
5060                  memory addresses, since we store their values in r0
5061                  first.  */
5062               if (TARGET_REGISTER_P (i)
5063                   || ((i == PR_REG || SPECIAL_REGISTER_P (i))
5064                       && mem_rtx != pre_dec))
5065                 abort ();
5066
5067             addr_ok:
5068               if (TARGET_REGISTER_P (i)
5069                   || ((i == PR_REG || SPECIAL_REGISTER_P (i))
5070                       && mem_rtx != pre_dec))
5071                 {
5072                   rtx r0mode = gen_rtx_REG (GET_MODE (reg_rtx), R0_REG);
5073
5074                   emit_move_insn (r0mode, reg_rtx);
5075
5076                   offset_in_r0 = -1;
5077                   sp_in_r0 = 0;
5078
5079                   reg_rtx = r0mode;
5080                 }
5081
5082               emit_move_insn (mem_rtx, reg_rtx);
5083             }
5084
5085       if (offset != d_rounding)
5086         abort ();
5087     }
5088   else
5089     push_regs (&live_regs_mask, current_function_interrupt);
5090
5091   if (flag_pic && regs_ever_live[PIC_OFFSET_TABLE_REGNUM])
5092     {
5093       rtx insn = get_last_insn ();
5094       rtx last = emit_insn (gen_GOTaddr2picreg ());
5095
5096       /* Mark these insns as possibly dead.  Sometimes, flow2 may
5097          delete all uses of the PIC register.  In this case, let it
5098          delete the initialization too.  */
5099       do
5100         {
5101           insn = NEXT_INSN (insn);
5102
5103           REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD,
5104                                                 const0_rtx,
5105                                                 REG_NOTES (insn));
5106         }
5107       while (insn != last);
5108     }
5109
5110   if (SHMEDIA_REGS_STACK_ADJUST ())
5111     {
5112       emit_move_insn (gen_rtx_REG (Pmode, R0_REG),
5113                       gen_rtx_SYMBOL_REF (Pmode,
5114                                           TARGET_FPU_ANY
5115                                           ? "__GCC_push_shmedia_regs"
5116                                           : "__GCC_push_shmedia_regs_nofpu"));
5117       /* This must NOT go through the PLT, otherwise mach and macl
5118          may be clobbered.  */
5119       emit_insn (gen_shmedia_save_restore_regs_compact
5120                  (GEN_INT (-SHMEDIA_REGS_STACK_ADJUST ())));
5121     }
5122
5123   if (target_flags != save_flags && ! current_function_interrupt)
5124     {
5125       rtx insn = emit_insn (gen_toggle_sz ());
5126
5127       /* If we're lucky, a mode switch in the function body will
5128          overwrite fpscr, turning this insn dead.  Tell flow this
5129          insn is ok to delete.  */
5130       REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD,
5131                                             const0_rtx,
5132                                             REG_NOTES (insn));
5133     }
5134
5135   target_flags = save_flags;
5136
5137   output_stack_adjust (-rounded_frame_size (d) + d_rounding,
5138                        stack_pointer_rtx, TARGET_SH5 ? 0 : 1, frame_insn);
5139
5140   if (frame_pointer_needed)
5141     frame_insn (GEN_MOV (frame_pointer_rtx, stack_pointer_rtx));
5142
5143   if (TARGET_SHCOMPACT
5144       && (current_function_args_info.call_cookie & ~ CALL_COOKIE_RET_TRAMP(1)))
5145     {
5146       /* This must NOT go through the PLT, otherwise mach and macl
5147          may be clobbered.  */
5148       emit_move_insn (gen_rtx_REG (Pmode, R0_REG),
5149                       gen_rtx_SYMBOL_REF (Pmode,
5150                                           "__GCC_shcompact_incoming_args"));
5151       emit_insn (gen_shcompact_incoming_args ());
5152     }
5153 }
5154
5155 void
5156 sh_expand_epilogue ()
5157 {
5158   HARD_REG_SET live_regs_mask;
5159   int d, i;
5160   int d_rounding = 0;
5161
5162   int save_flags = target_flags;
5163   int frame_size;
5164   int fpscr_deferred = 0;
5165
5166   d = calc_live_regs (&live_regs_mask);
5167
5168   if (TARGET_SH5 && d % (STACK_BOUNDARY / BITS_PER_UNIT))
5169     d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
5170                   - d % (STACK_BOUNDARY / BITS_PER_UNIT));
5171
5172   frame_size = rounded_frame_size (d) - d_rounding;
5173
5174   if (frame_pointer_needed)
5175     {
5176       output_stack_adjust (frame_size, frame_pointer_rtx, 7, emit_insn);
5177
5178       /* We must avoid moving the stack pointer adjustment past code
5179          which reads from the local frame, else an interrupt could
5180          occur after the SP adjustment and clobber data in the local
5181          frame.  */
5182       emit_insn (gen_blockage ());
5183       emit_insn (GEN_MOV (stack_pointer_rtx, frame_pointer_rtx));
5184     }
5185   else if (frame_size)
5186     {
5187       /* We must avoid moving the stack pointer adjustment past code
5188          which reads from the local frame, else an interrupt could
5189          occur after the SP adjustment and clobber data in the local
5190          frame.  */
5191       emit_insn (gen_blockage ());
5192       output_stack_adjust (frame_size, stack_pointer_rtx, 7, emit_insn);
5193     }
5194
5195   if (SHMEDIA_REGS_STACK_ADJUST ())
5196     {
5197       emit_move_insn (gen_rtx_REG (Pmode, R0_REG),
5198                       gen_rtx_SYMBOL_REF (Pmode,
5199                                           TARGET_FPU_ANY
5200                                           ? "__GCC_pop_shmedia_regs"
5201                                           : "__GCC_pop_shmedia_regs_nofpu"));
5202       /* This must NOT go through the PLT, otherwise mach and macl
5203          may be clobbered.  */
5204       emit_insn (gen_shmedia_save_restore_regs_compact
5205                  (GEN_INT (SHMEDIA_REGS_STACK_ADJUST ())));
5206     }
5207
5208   /* Pop all the registers.  */
5209
5210   if (target_flags != save_flags && ! current_function_interrupt)
5211     emit_insn (gen_toggle_sz ());
5212   if (TARGET_SH5)
5213     {
5214       int offset = d_rounding;
5215       int offset_in_r0 = -1;
5216       int sp_in_r0 = 0;
5217       int align;
5218       rtx r0 = gen_rtx_REG (Pmode, R0_REG);
5219       int tmp_regno = R20_REG;
5220       
5221       /* We loop twice: first, we save 8-byte aligned registers in the
5222          higher addresses, that are known to be aligned.  Then, we
5223          proceed to saving 32-bit registers that don't need 8-byte
5224          alignment.  */
5225       for (align = 0; align <= 1; align++)
5226         for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
5227           if (TEST_HARD_REG_BIT (live_regs_mask, i))
5228             {
5229               enum machine_mode mode = REGISTER_NATURAL_MODE (i);
5230               int reg = i;
5231               rtx reg_rtx, mem_rtx, post_inc = NULL_RTX, insn;
5232
5233               if (mode == SFmode && (i % 2) == 0
5234                   && ! TARGET_FPU_SINGLE && FP_REGISTER_P (i)
5235                   && (TEST_HARD_REG_BIT (live_regs_mask, (i ^ 1))))
5236                 {
5237                   mode = DFmode;
5238                   i++;
5239                 }
5240
5241               /* If we're doing the aligned pass and this is not aligned,
5242                  or we're doing the unaligned pass and this is aligned,
5243                  skip it.  */
5244               if ((GET_MODE_SIZE (mode) % (STACK_BOUNDARY / BITS_PER_UNIT)
5245                    == 0) != align)
5246                 continue;
5247
5248               reg_rtx = gen_rtx_REG (mode, reg);
5249
5250               mem_rtx = gen_rtx_MEM (mode,
5251                                      gen_rtx_PLUS (Pmode,
5252                                                    stack_pointer_rtx,
5253                                                    GEN_INT (offset)));
5254
5255               GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (mem_rtx, 0), try_post_inc);
5256
5257               mem_rtx = NULL_RTX;
5258
5259             try_post_inc:
5260               do
5261                 if (HAVE_POST_INCREMENT
5262                     && (offset == offset_in_r0
5263                         || (offset + GET_MODE_SIZE (mode) != d + d_rounding
5264                             && mem_rtx == NULL_RTX)
5265                         || i == PR_REG || SPECIAL_REGISTER_P (i)))
5266                   {
5267                     post_inc = gen_rtx_MEM (mode,
5268                                             gen_rtx_POST_INC (Pmode, r0));
5269
5270                     GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (post_inc, 0),
5271                                               post_inc_ok);
5272
5273                     post_inc = NULL_RTX;
5274
5275                     break;
5276                     
5277                   post_inc_ok:
5278                     mem_rtx = NULL_RTX;
5279                   }
5280               while (0);
5281               
5282               if (mem_rtx != NULL_RTX)
5283                 goto addr_ok;
5284
5285               if (offset_in_r0 == -1)
5286                 {
5287                   emit_move_insn (r0, GEN_INT (offset));
5288                   offset_in_r0 = offset;
5289                 }
5290               else if (offset != offset_in_r0)
5291                 {
5292                   emit_move_insn (r0,
5293                                   gen_rtx_PLUS
5294                                   (Pmode, r0,
5295                                    GEN_INT (offset - offset_in_r0)));
5296                   offset_in_r0 += offset - offset_in_r0;
5297                 }
5298                   
5299               if (post_inc != NULL_RTX)
5300                 {
5301                   if (! sp_in_r0)
5302                     {
5303                       emit_move_insn (r0,
5304                                       gen_rtx_PLUS
5305                                       (Pmode, r0, stack_pointer_rtx));
5306                       sp_in_r0 = 1;
5307                     }
5308                   
5309                   mem_rtx = post_inc;
5310
5311                   offset_in_r0 += GET_MODE_SIZE (mode);
5312                 }
5313               else if (sp_in_r0)
5314                 mem_rtx = gen_rtx_MEM (mode, r0);
5315               else
5316                 mem_rtx = gen_rtx_MEM (mode,
5317                                        gen_rtx_PLUS (Pmode,
5318                                                      stack_pointer_rtx,
5319                                                      r0));
5320
5321               if ((i == PR_REG || SPECIAL_REGISTER_P (i))
5322                   && mem_rtx != post_inc)
5323                 abort ();
5324
5325             addr_ok:
5326               if ((i == PR_REG || SPECIAL_REGISTER_P (i))
5327                   && mem_rtx != post_inc)
5328                 {
5329                   insn = emit_move_insn (r0, mem_rtx);
5330                   mem_rtx = r0;
5331                 }
5332               else if (TARGET_REGISTER_P (i))
5333                 {
5334                   rtx tmp_reg = gen_rtx_REG (mode, tmp_regno);
5335
5336                   /* Give the scheduler a bit of freedom by using R20..R23
5337                      in a round-robin fashion.  Don't use R1 here because
5338                      we want to use it for EH_RETURN_STACKADJ_RTX.  */
5339                   insn = emit_move_insn (tmp_reg, mem_rtx);
5340                   mem_rtx = tmp_reg;
5341                   if (++tmp_regno > R23_REG)
5342                     tmp_regno = R20_REG;
5343                 }
5344
5345               insn = emit_move_insn (reg_rtx, mem_rtx);
5346
5347               offset += GET_MODE_SIZE (mode);
5348             }
5349
5350       if (offset != d + d_rounding)
5351         abort ();
5352
5353       goto finish;
5354     }
5355   else
5356     d = 0;
5357   if (TEST_HARD_REG_BIT (live_regs_mask, PR_REG))
5358     pop (PR_REG);
5359   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
5360     {
5361       int j = (FIRST_PSEUDO_REGISTER - 1) - i;
5362
5363       if (j == FPSCR_REG && current_function_interrupt && TARGET_FMOVD
5364           && hard_regs_intersect_p (&live_regs_mask,
5365                                     &reg_class_contents[DF_REGS]))
5366         fpscr_deferred = 1;
5367       else if (j != PR_REG && TEST_HARD_REG_BIT (live_regs_mask, j))
5368         pop (j);
5369       if (j == FIRST_FP_REG && fpscr_deferred)
5370         pop (FPSCR_REG);
5371     }
5372  finish:
5373   if (target_flags != save_flags && ! current_function_interrupt)
5374     emit_insn (gen_toggle_sz ());
5375   target_flags = save_flags;
5376
5377   output_stack_adjust (extra_push + current_function_pretend_args_size
5378                        + d + d_rounding
5379                        + current_function_args_info.stack_regs * 8,
5380                        stack_pointer_rtx, 7, emit_insn);
5381
5382   if (current_function_calls_eh_return)
5383     emit_insn (GEN_ADD3 (stack_pointer_rtx, stack_pointer_rtx,
5384                          EH_RETURN_STACKADJ_RTX));
5385
5386   /* Switch back to the normal stack if necessary.  */
5387   if (sp_switch)
5388     emit_insn (gen_sp_switch_2 ());
5389
5390   /* Tell flow the insn that pops PR isn't dead.  */
5391   /* PR_REG will never be live in SHmedia mode, and we don't need to
5392      USE PR_MEDIA_REG, since it will be explicitly copied to TR0_REG
5393      by the return pattern.  */
5394   if (TEST_HARD_REG_BIT (live_regs_mask, PR_REG))
5395     emit_insn (gen_rtx_USE (VOIDmode, gen_rtx_REG (SImode, PR_REG)));
5396 }
5397
5398 static int sh_need_epilogue_known = 0;
5399
5400 int
5401 sh_need_epilogue ()
5402 {
5403   if (! sh_need_epilogue_known)
5404     {
5405       rtx epilogue;
5406
5407       start_sequence ();
5408       sh_expand_epilogue ();
5409       epilogue = get_insns ();
5410       end_sequence ();
5411       sh_need_epilogue_known = (epilogue == NULL ? -1 : 1);
5412     }
5413   return sh_need_epilogue_known > 0;
5414 }
5415
5416 /* Emit code to change the current function's return address to RA.
5417    TEMP is available as a scratch register, if needed.  */
5418
5419 void
5420 sh_set_return_address (ra, tmp)
5421      rtx ra, tmp;
5422 {
5423   HARD_REG_SET live_regs_mask;
5424   int d;
5425   int d_rounding = 0;
5426   int pr_reg = TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG;
5427   int pr_offset;
5428
5429   d = calc_live_regs (&live_regs_mask);
5430
5431   /* If pr_reg isn't life, we can set it (or the register given in
5432      sh_media_register_for_return) directly.  */
5433   if (! TEST_HARD_REG_BIT (live_regs_mask, pr_reg))
5434     {
5435       rtx rr;
5436
5437       if (TARGET_SHMEDIA)
5438         {
5439           int rr_regno = sh_media_register_for_return ();
5440
5441           if (rr_regno < 0)
5442             rr_regno = pr_reg;
5443
5444           rr = gen_rtx_REG (DImode, rr_regno);
5445         }
5446       else
5447         rr = gen_rtx_REG (SImode, pr_reg);
5448
5449       emit_insn (GEN_MOV (rr, ra));
5450       /* Tell flow the register for return isn't dead.  */
5451       emit_insn (gen_rtx_USE (VOIDmode, rr));
5452       return;
5453     }
5454
5455   if (TARGET_SH5)
5456     {
5457       int i;
5458       int offset;
5459       int align;
5460       
5461       if (d % (STACK_BOUNDARY / BITS_PER_UNIT))
5462         d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
5463                       - d % (STACK_BOUNDARY / BITS_PER_UNIT));
5464
5465       offset = 0;
5466
5467       /* We loop twice: first, we save 8-byte aligned registers in the
5468          higher addresses, that are known to be aligned.  Then, we
5469          proceed to saving 32-bit registers that don't need 8-byte
5470          alignment.  */
5471       for (align = 0; align <= 1; align++)
5472         for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
5473           if (TEST_HARD_REG_BIT (live_regs_mask, i))
5474             {
5475               enum machine_mode mode = REGISTER_NATURAL_MODE (i);
5476
5477               if (mode == SFmode && (i % 2) == 0
5478                   && ! TARGET_FPU_SINGLE && FP_REGISTER_P (i)
5479                   && (TEST_HARD_REG_BIT (live_regs_mask, (i ^ 1))))
5480                 {
5481                   mode = DFmode;
5482                   i++;
5483                 }
5484
5485               /* If we're doing the aligned pass and this is not aligned,
5486                  or we're doing the unaligned pass and this is aligned,
5487                  skip it.  */
5488               if ((GET_MODE_SIZE (mode) % (STACK_BOUNDARY / BITS_PER_UNIT)
5489                    == 0) != align)
5490                 continue;
5491
5492               if (i == pr_reg)
5493                 goto found;
5494
5495               offset += GET_MODE_SIZE (mode);
5496             }
5497
5498       /* We can't find pr register.  */
5499       abort ();
5500
5501     found:
5502       pr_offset = (rounded_frame_size (d) - d_rounding + offset
5503                    + SHMEDIA_REGS_STACK_ADJUST ());
5504     }
5505   else
5506     pr_offset = rounded_frame_size (d) - d_rounding;
5507
5508   emit_insn (GEN_MOV (tmp, GEN_INT (pr_offset)));
5509   emit_insn (GEN_ADD3 (tmp, tmp, frame_pointer_rtx));
5510
5511   tmp = gen_rtx_MEM (Pmode, tmp);
5512   emit_insn (GEN_MOV (tmp, ra));
5513 }
5514
5515 /* Clear variables at function end.  */
5516
5517 static void
5518 sh_output_function_epilogue (file, size)
5519      FILE *file ATTRIBUTE_UNUSED;
5520      HOST_WIDE_INT size ATTRIBUTE_UNUSED;
5521 {
5522   trap_exit = pragma_interrupt = pragma_trapa = pragma_nosave_low_regs = 0;
5523   sh_need_epilogue_known = 0;
5524   sp_switch = NULL_RTX;
5525 }
5526
5527 rtx
5528 sh_builtin_saveregs ()
5529 {
5530   /* First unnamed integer register.  */
5531   int first_intreg = current_function_args_info.arg_count[(int) SH_ARG_INT];
5532   /* Number of integer registers we need to save.  */
5533   int n_intregs = MAX (0, NPARM_REGS (SImode) - first_intreg);
5534   /* First unnamed SFmode float reg */
5535   int first_floatreg = current_function_args_info.arg_count[(int) SH_ARG_FLOAT];
5536   /* Number of SFmode float regs to save.  */
5537   int n_floatregs = MAX (0, NPARM_REGS (SFmode) - first_floatreg);
5538   rtx regbuf, fpregs;
5539   int bufsize, regno;
5540   HOST_WIDE_INT alias_set;
5541
5542   if (TARGET_SH5)
5543     {
5544       if (n_intregs)
5545         {
5546           int pushregs = n_intregs;
5547
5548           while (pushregs < NPARM_REGS (SImode) - 1
5549                  && (CALL_COOKIE_INT_REG_GET
5550                         (current_function_args_info.call_cookie,
5551                          NPARM_REGS (SImode) - pushregs)
5552                      == 1))
5553             {
5554               current_function_args_info.call_cookie
5555                 &= ~ CALL_COOKIE_INT_REG (NPARM_REGS (SImode)
5556                                           - pushregs, 1);
5557               pushregs++;
5558             }
5559
5560           if (pushregs == NPARM_REGS (SImode))
5561             current_function_args_info.call_cookie
5562               |= (CALL_COOKIE_INT_REG (0, 1)
5563                   | CALL_COOKIE_STACKSEQ (pushregs - 1));
5564           else
5565             current_function_args_info.call_cookie
5566               |= CALL_COOKIE_STACKSEQ (pushregs);
5567
5568           current_function_pretend_args_size += 8 * n_intregs;
5569         }
5570       if (TARGET_SHCOMPACT)
5571         return const0_rtx;
5572     }
5573   
5574   if (! TARGET_SH2E && ! TARGET_SH4 && ! TARGET_SH5)
5575     {
5576       error ("__builtin_saveregs not supported by this subtarget");
5577       return const0_rtx;
5578     }
5579
5580   if (TARGET_SHMEDIA)
5581     n_floatregs = 0;
5582
5583   /* Allocate block of memory for the regs.  */
5584   /* ??? If n_intregs + n_floatregs == 0, should we allocate at least 1 byte?
5585      Or can assign_stack_local accept a 0 SIZE argument?  */
5586   bufsize = (n_intregs * UNITS_PER_WORD) + (n_floatregs * UNITS_PER_WORD);
5587
5588   if (TARGET_SHMEDIA)
5589     regbuf = gen_rtx_MEM (BLKmode,
5590                           gen_rtx_REG (Pmode, ARG_POINTER_REGNUM));
5591   else if (n_floatregs & 1)
5592     {
5593       rtx addr;
5594
5595       regbuf = assign_stack_local (BLKmode, bufsize + UNITS_PER_WORD, 0);
5596       addr = copy_to_mode_reg (Pmode, XEXP (regbuf, 0));
5597       emit_insn (gen_iorsi3 (addr, addr, GEN_INT (UNITS_PER_WORD)));
5598       regbuf = change_address (regbuf, BLKmode, addr);
5599     }
5600   else
5601     regbuf = assign_stack_local (BLKmode, bufsize, 0);
5602   alias_set = get_varargs_alias_set ();
5603   set_mem_alias_set (regbuf, alias_set);
5604
5605   /* Save int args.
5606      This is optimized to only save the regs that are necessary.  Explicitly
5607      named args need not be saved.  */
5608   if (n_intregs > 0)
5609     move_block_from_reg (BASE_ARG_REG (SImode) + first_intreg,
5610                          adjust_address (regbuf, BLKmode,
5611                                          n_floatregs * UNITS_PER_WORD),
5612                          n_intregs);
5613
5614   if (TARGET_SHMEDIA)
5615     /* Return the address of the regbuf.  */
5616     return XEXP (regbuf, 0);
5617
5618   /* Save float args.
5619      This is optimized to only save the regs that are necessary.  Explicitly
5620      named args need not be saved.
5621      We explicitly build a pointer to the buffer because it halves the insn
5622      count when not optimizing (otherwise the pointer is built for each reg
5623      saved).
5624      We emit the moves in reverse order so that we can use predecrement.  */
5625
5626   fpregs = gen_reg_rtx (Pmode);
5627   emit_move_insn (fpregs, XEXP (regbuf, 0));
5628   emit_insn (gen_addsi3 (fpregs, fpregs,
5629                          GEN_INT (n_floatregs * UNITS_PER_WORD)));
5630   if (TARGET_SH4)
5631     {
5632       rtx mem;
5633       for (regno = NPARM_REGS (DFmode) - 2; regno >= first_floatreg; regno -= 2)
5634         {
5635           emit_insn (gen_addsi3 (fpregs, fpregs,
5636                                  GEN_INT (-2 * UNITS_PER_WORD)));
5637           mem = gen_rtx_MEM (DFmode, fpregs);
5638           set_mem_alias_set (mem, alias_set);
5639           emit_move_insn (mem, 
5640                           gen_rtx (REG, DFmode, BASE_ARG_REG (DFmode) + regno));
5641         }
5642       regno = first_floatreg;
5643       if (regno & 1)
5644         {
5645           emit_insn (gen_addsi3 (fpregs, fpregs, GEN_INT (- UNITS_PER_WORD)));
5646           mem = gen_rtx_MEM (SFmode, fpregs);
5647           set_mem_alias_set (mem, alias_set);
5648           emit_move_insn (mem,
5649                           gen_rtx (REG, SFmode, BASE_ARG_REG (SFmode) + regno
5650                                                 - (TARGET_LITTLE_ENDIAN != 0)));
5651         }
5652     }
5653   else
5654     for (regno = NPARM_REGS (SFmode) - 1; regno >= first_floatreg; regno--)
5655       {
5656         rtx mem;
5657
5658         emit_insn (gen_addsi3 (fpregs, fpregs, GEN_INT (- UNITS_PER_WORD)));
5659         mem = gen_rtx_MEM (SFmode, fpregs);
5660         set_mem_alias_set (mem, alias_set);
5661         emit_move_insn (mem,
5662                         gen_rtx_REG (SFmode, BASE_ARG_REG (SFmode) + regno));
5663       }
5664
5665   /* Return the address of the regbuf.  */
5666   return XEXP (regbuf, 0);
5667 }
5668
5669 /* Define the `__builtin_va_list' type for the ABI.  */
5670
5671 tree
5672 sh_build_va_list ()
5673 {
5674   tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
5675   tree record;
5676
5677   if (TARGET_SH5 || (! TARGET_SH2E && ! TARGET_SH4) || TARGET_HITACHI)
5678     return ptr_type_node;
5679
5680   record = make_node (RECORD_TYPE);
5681
5682   f_next_o = build_decl (FIELD_DECL, get_identifier ("__va_next_o"),
5683                          ptr_type_node);
5684   f_next_o_limit = build_decl (FIELD_DECL,
5685                                get_identifier ("__va_next_o_limit"),
5686                                ptr_type_node);
5687   f_next_fp = build_decl (FIELD_DECL, get_identifier ("__va_next_fp"),
5688                           ptr_type_node);
5689   f_next_fp_limit = build_decl (FIELD_DECL,
5690                                 get_identifier ("__va_next_fp_limit"),
5691                                 ptr_type_node);
5692   f_next_stack = build_decl (FIELD_DECL, get_identifier ("__va_next_stack"),
5693                              ptr_type_node);
5694
5695   DECL_FIELD_CONTEXT (f_next_o) = record;
5696   DECL_FIELD_CONTEXT (f_next_o_limit) = record;
5697   DECL_FIELD_CONTEXT (f_next_fp) = record;
5698   DECL_FIELD_CONTEXT (f_next_fp_limit) = record;
5699   DECL_FIELD_CONTEXT (f_next_stack) = record;
5700
5701   TYPE_FIELDS (record) = f_next_o;
5702   TREE_CHAIN (f_next_o) = f_next_o_limit;
5703   TREE_CHAIN (f_next_o_limit) = f_next_fp;
5704   TREE_CHAIN (f_next_fp) = f_next_fp_limit;
5705   TREE_CHAIN (f_next_fp_limit) = f_next_stack;
5706
5707   layout_type (record);
5708
5709   return record;
5710 }
5711
5712 /* Implement `va_start' for varargs and stdarg.  */
5713
5714 void
5715 sh_va_start (valist, nextarg)
5716      tree valist;
5717      rtx nextarg;
5718 {
5719   tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
5720   tree next_o, next_o_limit, next_fp, next_fp_limit, next_stack;
5721   tree t, u;
5722   int nfp, nint;
5723
5724   if (TARGET_SH5)
5725     {
5726       expand_builtin_saveregs ();
5727       std_expand_builtin_va_start (valist, nextarg);
5728       return;
5729     }
5730
5731   if ((! TARGET_SH2E && ! TARGET_SH4) || TARGET_HITACHI)
5732     {
5733       std_expand_builtin_va_start (valist, nextarg);
5734       return;
5735     }
5736
5737   f_next_o = TYPE_FIELDS (va_list_type_node);
5738   f_next_o_limit = TREE_CHAIN (f_next_o);
5739   f_next_fp = TREE_CHAIN (f_next_o_limit);
5740   f_next_fp_limit = TREE_CHAIN (f_next_fp);
5741   f_next_stack = TREE_CHAIN (f_next_fp_limit);
5742
5743   next_o = build (COMPONENT_REF, TREE_TYPE (f_next_o), valist, f_next_o);
5744   next_o_limit = build (COMPONENT_REF, TREE_TYPE (f_next_o_limit),
5745                         valist, f_next_o_limit);
5746   next_fp = build (COMPONENT_REF, TREE_TYPE (f_next_fp), valist, f_next_fp);
5747   next_fp_limit = build (COMPONENT_REF, TREE_TYPE (f_next_fp_limit),
5748                          valist, f_next_fp_limit);
5749   next_stack = build (COMPONENT_REF, TREE_TYPE (f_next_stack),
5750                       valist, f_next_stack);
5751
5752   /* Call __builtin_saveregs.  */
5753   u = make_tree (ptr_type_node, expand_builtin_saveregs ());
5754   t = build (MODIFY_EXPR, ptr_type_node, next_fp, u);
5755   TREE_SIDE_EFFECTS (t) = 1;
5756   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5757
5758   nfp = current_function_args_info.arg_count[SH_ARG_FLOAT];
5759   if (nfp < 8)
5760     nfp = 8 - nfp;
5761   else
5762     nfp = 0;
5763   u = fold (build (PLUS_EXPR, ptr_type_node, u,
5764                    build_int_2 (UNITS_PER_WORD * nfp, 0)));
5765   t = build (MODIFY_EXPR, ptr_type_node, next_fp_limit, u);
5766   TREE_SIDE_EFFECTS (t) = 1;
5767   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5768
5769   t = build (MODIFY_EXPR, ptr_type_node, next_o, u);
5770   TREE_SIDE_EFFECTS (t) = 1;
5771   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5772
5773   nint = current_function_args_info.arg_count[SH_ARG_INT];
5774   if (nint < 4)
5775     nint = 4 - nint;
5776   else
5777     nint = 0;
5778   u = fold (build (PLUS_EXPR, ptr_type_node, u,
5779                    build_int_2 (UNITS_PER_WORD * nint, 0)));
5780   t = build (MODIFY_EXPR, ptr_type_node, next_o_limit, u);
5781   TREE_SIDE_EFFECTS (t) = 1;
5782   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5783
5784   u = make_tree (ptr_type_node, nextarg);
5785   t = build (MODIFY_EXPR, ptr_type_node, next_stack, u);
5786   TREE_SIDE_EFFECTS (t) = 1;
5787   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5788 }
5789
5790 /* Implement `va_arg'.  */
5791
5792 rtx
5793 sh_va_arg (valist, type)
5794      tree valist, type;
5795 {
5796   HOST_WIDE_INT size, rsize;
5797   tree tmp, pptr_type_node;
5798   rtx addr_rtx, r;
5799   rtx result;
5800   int pass_by_ref = MUST_PASS_IN_STACK (TYPE_MODE (type), type);
5801
5802   size = int_size_in_bytes (type);
5803   rsize = (size + UNITS_PER_WORD - 1) & -UNITS_PER_WORD;
5804   pptr_type_node = build_pointer_type (ptr_type_node);
5805
5806   if (pass_by_ref)
5807     type = build_pointer_type (type);
5808
5809   if (! TARGET_SH5 && (TARGET_SH2E || TARGET_SH4) && ! TARGET_HITACHI)
5810     {
5811       tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
5812       tree next_o, next_o_limit, next_fp, next_fp_limit, next_stack;
5813       int pass_as_float;
5814       rtx lab_false, lab_over;
5815
5816       f_next_o = TYPE_FIELDS (va_list_type_node);
5817       f_next_o_limit = TREE_CHAIN (f_next_o);
5818       f_next_fp = TREE_CHAIN (f_next_o_limit);
5819       f_next_fp_limit = TREE_CHAIN (f_next_fp);
5820       f_next_stack = TREE_CHAIN (f_next_fp_limit);
5821
5822       next_o = build (COMPONENT_REF, TREE_TYPE (f_next_o), valist, f_next_o);
5823       next_o_limit = build (COMPONENT_REF, TREE_TYPE (f_next_o_limit),
5824                             valist, f_next_o_limit);
5825       next_fp = build (COMPONENT_REF, TREE_TYPE (f_next_fp),
5826                        valist, f_next_fp);
5827       next_fp_limit = build (COMPONENT_REF, TREE_TYPE (f_next_fp_limit),
5828                              valist, f_next_fp_limit);
5829       next_stack = build (COMPONENT_REF, TREE_TYPE (f_next_stack),
5830                           valist, f_next_stack);
5831
5832       if (TARGET_SH4)
5833         {
5834           pass_as_float = ((TREE_CODE (type) == REAL_TYPE && size <= 8)
5835                            || (TREE_CODE (type) == COMPLEX_TYPE
5836                                && TREE_CODE (TREE_TYPE (type)) == REAL_TYPE
5837                                && size <= 16));
5838         }
5839       else
5840         {
5841           pass_as_float = (TREE_CODE (type) == REAL_TYPE && size == 4);
5842         }
5843
5844       addr_rtx = gen_reg_rtx (Pmode);
5845       lab_false = gen_label_rtx ();
5846       lab_over = gen_label_rtx ();
5847
5848       if (pass_as_float)
5849         {
5850           int first_floatreg
5851             = current_function_args_info.arg_count[(int) SH_ARG_FLOAT];
5852           int n_floatregs = MAX (0, NPARM_REGS (SFmode) - first_floatreg);
5853
5854           emit_cmp_and_jump_insns (expand_expr (next_fp, NULL_RTX, Pmode,
5855                                                 EXPAND_NORMAL),
5856                                    expand_expr (next_fp_limit, NULL_RTX,
5857                                                 Pmode, EXPAND_NORMAL),
5858                                    GE, const1_rtx, Pmode, 1, lab_false);
5859
5860           if (TYPE_ALIGN (type) > BITS_PER_WORD
5861               || (((TREE_CODE (type) == REAL_TYPE && size == 8) || size == 16)
5862                   && (n_floatregs & 1)))
5863             {
5864               tmp = build (BIT_AND_EXPR, ptr_type_node, next_fp,
5865                            build_int_2 (UNITS_PER_WORD, 0));
5866               tmp = build (PLUS_EXPR, ptr_type_node, next_fp, tmp);
5867               tmp = build (MODIFY_EXPR, ptr_type_node, next_fp, tmp);
5868               TREE_SIDE_EFFECTS (tmp) = 1;
5869               expand_expr (tmp, const0_rtx, VOIDmode, EXPAND_NORMAL);
5870             }
5871
5872           tmp = build1 (ADDR_EXPR, pptr_type_node, next_fp);
5873           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
5874           if (r != addr_rtx)
5875             emit_move_insn (addr_rtx, r);
5876
5877           emit_jump_insn (gen_jump (lab_over));
5878           emit_barrier ();
5879           emit_label (lab_false);
5880
5881           tmp = build1 (ADDR_EXPR, pptr_type_node, next_stack);
5882           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
5883           if (r != addr_rtx)
5884             emit_move_insn (addr_rtx, r);
5885         }
5886       else
5887         {
5888           tmp = build (PLUS_EXPR, ptr_type_node, next_o,
5889                        build_int_2 (rsize, 0));
5890           
5891           emit_cmp_and_jump_insns (expand_expr (tmp, NULL_RTX, Pmode,
5892                                                 EXPAND_NORMAL),
5893                                    expand_expr (next_o_limit, NULL_RTX,
5894                                                 Pmode, EXPAND_NORMAL),
5895                                    GT, const1_rtx, Pmode, 1, lab_false);
5896
5897           tmp = build1 (ADDR_EXPR, pptr_type_node, next_o);
5898           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
5899           if (r != addr_rtx)
5900             emit_move_insn (addr_rtx, r);
5901
5902           emit_jump_insn (gen_jump (lab_over));
5903           emit_barrier ();
5904           emit_label (lab_false);
5905
5906           if (size > 4 && ! TARGET_SH4)
5907             {
5908               tmp = build (MODIFY_EXPR, ptr_type_node, next_o, next_o_limit);
5909               TREE_SIDE_EFFECTS (tmp) = 1;
5910               expand_expr (tmp, const0_rtx, VOIDmode, EXPAND_NORMAL);
5911             }
5912
5913           tmp = build1 (ADDR_EXPR, pptr_type_node, next_stack);
5914           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
5915           if (r != addr_rtx)
5916             emit_move_insn (addr_rtx, r);
5917         }
5918
5919       emit_label (lab_over);
5920
5921       tmp = make_tree (pptr_type_node, addr_rtx);
5922       valist = build1 (INDIRECT_REF, ptr_type_node, tmp);
5923     }
5924
5925   /* ??? In va-sh.h, there had been code to make values larger than
5926      size 8 indirect.  This does not match the FUNCTION_ARG macros.  */
5927
5928   result = std_expand_builtin_va_arg (valist, type);
5929   if (pass_by_ref)
5930     {
5931 #ifdef POINTERS_EXTEND_UNSIGNED
5932       if (GET_MODE (addr) != Pmode)
5933         addr = convert_memory_address (Pmode, result);
5934 #endif
5935       result = gen_rtx_MEM (ptr_mode, force_reg (Pmode, result));
5936       set_mem_alias_set (result, get_varargs_alias_set ());
5937     }
5938   /* ??? expand_builtin_va_arg will also set the alias set of the dereferenced
5939      argument to the varargs alias set.  */
5940   return result;
5941 }
5942
5943 /* Define the offset between two registers, one to be eliminated, and
5944    the other its replacement, at the start of a routine.  */
5945
5946 int
5947 initial_elimination_offset (from, to)
5948      int from;
5949      int to;
5950 {
5951   int regs_saved;
5952   int regs_saved_rounding = 0;
5953   int total_saved_regs_space;
5954   int total_auto_space;
5955   int save_flags = target_flags;
5956   int copy_flags;
5957
5958   HARD_REG_SET live_regs_mask;
5959   regs_saved = calc_live_regs (&live_regs_mask);
5960   regs_saved += SHMEDIA_REGS_STACK_ADJUST ();
5961   if (TARGET_SH5 && regs_saved % (STACK_BOUNDARY / BITS_PER_UNIT))
5962     regs_saved_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
5963                            - regs_saved % (STACK_BOUNDARY / BITS_PER_UNIT));
5964
5965   total_auto_space = rounded_frame_size (regs_saved) - regs_saved_rounding;
5966   copy_flags = target_flags;
5967   target_flags = save_flags;
5968
5969   total_saved_regs_space = regs_saved + regs_saved_rounding;
5970
5971   if (from == ARG_POINTER_REGNUM && to == FRAME_POINTER_REGNUM)
5972     return total_saved_regs_space + total_auto_space
5973       + current_function_args_info.byref_regs * 8;
5974
5975   if (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
5976     return total_saved_regs_space + total_auto_space
5977       + current_function_args_info.byref_regs * 8;
5978
5979   /* Initial gap between fp and sp is 0.  */
5980   if (from == FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
5981     return 0;
5982
5983   if (from == RETURN_ADDRESS_POINTER_REGNUM
5984       && (to == FRAME_POINTER_REGNUM || to == STACK_POINTER_REGNUM))
5985     {
5986       if (TARGET_SH5)
5987         {
5988           int i, n = total_saved_regs_space;
5989           int align;
5990           int pr_reg = TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG;
5991           
5992           n += total_auto_space;
5993
5994           /* If it wasn't saved, there's not much we can do.  */
5995           if (! TEST_HARD_REG_BIT (live_regs_mask, pr_reg))
5996             return n;
5997
5998           target_flags = copy_flags;
5999
6000           /* We loop twice: first, check 8-byte aligned registers,
6001              that are stored in the higher addresses, that are known
6002              to be aligned.  Then, check 32-bit registers that don't
6003              need 8-byte alignment.  */
6004           for (align = 1; align >= 0; align--)
6005             for (i = FIRST_PSEUDO_REGISTER - 1; i >= 0; i--)
6006               if (TEST_HARD_REG_BIT (live_regs_mask, i))
6007                 {
6008                   enum machine_mode mode = REGISTER_NATURAL_MODE (i);
6009
6010                   if (mode == SFmode && (i % 2) == 1
6011                       && ! TARGET_FPU_SINGLE && FP_REGISTER_P (i)
6012                       && TEST_HARD_REG_BIT (live_regs_mask, (i ^ 1)))
6013                     {
6014                       mode = DFmode;
6015                       i--;
6016                     }
6017                 
6018                   /* If we're doing the aligned pass and this is not aligned,
6019                      or we're doing the unaligned pass and this is aligned,
6020                      skip it.  */
6021                   if ((GET_MODE_SIZE (mode) % (STACK_BOUNDARY / BITS_PER_UNIT)
6022                        == 0) != align)
6023                     continue;
6024
6025                   n -= GET_MODE_SIZE (mode);
6026
6027                   if (i == pr_reg)
6028                     {
6029                       target_flags = save_flags;
6030                       return n;
6031                     }
6032                 }
6033
6034           abort ();
6035         }
6036       else
6037         return total_auto_space;
6038     }
6039
6040   abort ();
6041 }
6042 \f
6043 /* Handle machine specific pragmas to be semi-compatible with Hitachi
6044    compiler.  */
6045
6046 void
6047 sh_pr_interrupt (pfile)
6048      struct cpp_reader *pfile ATTRIBUTE_UNUSED;
6049 {
6050   pragma_interrupt = 1;
6051 }
6052
6053 void
6054 sh_pr_trapa (pfile)
6055      struct cpp_reader *pfile ATTRIBUTE_UNUSED;
6056 {
6057   pragma_interrupt = pragma_trapa = 1;
6058 }
6059
6060 void
6061 sh_pr_nosave_low_regs (pfile)
6062      struct cpp_reader *pfile ATTRIBUTE_UNUSED;
6063 {
6064   pragma_nosave_low_regs = 1;
6065 }
6066
6067 /* Generate 'handle_interrupt' attribute for decls */
6068
6069 static void
6070 sh_insert_attributes (node, attributes)
6071      tree node;
6072      tree * attributes;
6073 {
6074   if (! pragma_interrupt
6075       || TREE_CODE (node) != FUNCTION_DECL)
6076     return;
6077
6078   /* We are only interested in fields.  */
6079   if (TREE_CODE_CLASS (TREE_CODE (node)) != 'd')
6080     return;
6081
6082   /* Add a 'handle_interrupt' attribute.  */
6083   * attributes = tree_cons (get_identifier ("interrupt_handler"), NULL, * attributes);
6084
6085   return;
6086 }
6087
6088 /* Supported attributes:
6089
6090    interrupt_handler -- specifies this function is an interrupt handler.
6091
6092    sp_switch -- specifies an alternate stack for an interrupt handler
6093    to run on.
6094
6095    trap_exit -- use a trapa to exit an interrupt function instead of
6096    an rte instruction.  */
6097
6098 const struct attribute_spec sh_attribute_table[] =
6099 {
6100   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
6101   { "interrupt_handler", 0, 0, true,  false, false, sh_handle_interrupt_handler_attribute },
6102   { "sp_switch",         1, 1, true,  false, false, sh_handle_sp_switch_attribute },
6103   { "trap_exit",         1, 1, true,  false, false, sh_handle_trap_exit_attribute },
6104   { NULL,                0, 0, false, false, false, NULL }
6105 };
6106
6107 /* Handle an "interrupt_handler" attribute; arguments as in
6108    struct attribute_spec.handler.  */
6109 static tree
6110 sh_handle_interrupt_handler_attribute (node, name, args, flags, no_add_attrs)
6111      tree *node;
6112      tree name;
6113      tree args ATTRIBUTE_UNUSED;
6114      int flags ATTRIBUTE_UNUSED;
6115      bool *no_add_attrs;
6116 {
6117   if (TREE_CODE (*node) != FUNCTION_DECL)
6118     {
6119       warning ("`%s' attribute only applies to functions",
6120                IDENTIFIER_POINTER (name));
6121       *no_add_attrs = true;
6122     }
6123   else if (TARGET_SHCOMPACT)
6124     {
6125       error ("attribute interrupt_handler is not compatible with -m5-compact");
6126       *no_add_attrs = true;
6127     }
6128
6129   return NULL_TREE;
6130 }
6131
6132 /* Handle an "sp_switch" attribute; arguments as in
6133    struct attribute_spec.handler.  */
6134 static tree
6135 sh_handle_sp_switch_attribute (node, name, args, flags, no_add_attrs)
6136      tree *node;
6137      tree name;
6138      tree args;
6139      int flags ATTRIBUTE_UNUSED;
6140      bool *no_add_attrs;
6141 {
6142   if (TREE_CODE (*node) != FUNCTION_DECL)
6143     {
6144       warning ("`%s' attribute only applies to functions",
6145                IDENTIFIER_POINTER (name));
6146       *no_add_attrs = true;
6147     }
6148   else if (!pragma_interrupt)
6149     {
6150       /* The sp_switch attribute only has meaning for interrupt functions.  */
6151       warning ("`%s' attribute only applies to interrupt functions",
6152                IDENTIFIER_POINTER (name));
6153       *no_add_attrs = true;
6154     }
6155   else if (TREE_CODE (TREE_VALUE (args)) != STRING_CST)
6156     {
6157       /* The argument must be a constant string.  */
6158       warning ("`%s' attribute argument not a string constant",
6159                IDENTIFIER_POINTER (name));
6160       *no_add_attrs = true;
6161     }
6162   else
6163     {
6164       sp_switch = gen_rtx_SYMBOL_REF (VOIDmode,
6165                                       TREE_STRING_POINTER (TREE_VALUE (args)));
6166     }
6167
6168   return NULL_TREE;
6169 }
6170
6171 /* Handle an "trap_exit" attribute; arguments as in
6172    struct attribute_spec.handler.  */
6173 static tree
6174 sh_handle_trap_exit_attribute (node, name, args, flags, no_add_attrs)
6175      tree *node;
6176      tree name;
6177      tree args;
6178      int flags ATTRIBUTE_UNUSED;
6179      bool *no_add_attrs;
6180 {
6181   if (TREE_CODE (*node) != FUNCTION_DECL)
6182     {
6183       warning ("`%s' attribute only applies to functions",
6184                IDENTIFIER_POINTER (name));
6185       *no_add_attrs = true;
6186     }
6187   else if (!pragma_interrupt)
6188     {
6189       /* The trap_exit attribute only has meaning for interrupt functions.  */
6190       warning ("`%s' attribute only applies to interrupt functions",
6191                IDENTIFIER_POINTER (name));
6192       *no_add_attrs = true;
6193     }
6194   else if (TREE_CODE (TREE_VALUE (args)) != INTEGER_CST)
6195     {
6196       /* The argument must be a constant integer.  */
6197       warning ("`%s' attribute argument not an integer constant",
6198                IDENTIFIER_POINTER (name));
6199       *no_add_attrs = true;
6200     }
6201   else
6202     {
6203       trap_exit = TREE_INT_CST_LOW (TREE_VALUE (args));
6204     }
6205
6206   return NULL_TREE;
6207 }
6208
6209 int
6210 sh_cfun_interrupt_handler_p ()
6211 {
6212   return (lookup_attribute ("interrupt_handler",
6213                             DECL_ATTRIBUTES (current_function_decl))
6214           != NULL_TREE);
6215 }
6216 \f
6217 /* Predicates used by the templates.  */
6218
6219 /* Returns 1 if OP is MACL, MACH or PR.  The input must be a REG rtx.
6220    Used only in general_movsrc_operand.  */
6221
6222 int
6223 system_reg_operand (op, mode)
6224      rtx op;
6225      enum machine_mode mode ATTRIBUTE_UNUSED;
6226 {
6227   switch (REGNO (op))
6228     {
6229     case PR_REG:
6230     case MACL_REG:
6231     case MACH_REG:
6232       return 1;
6233     }
6234   return 0;
6235 }
6236
6237 /* Returns 1 if OP can be source of a simple move operation.
6238    Same as general_operand, but a LABEL_REF is valid, PRE_DEC is
6239    invalid as are subregs of system registers.  */
6240
6241 int
6242 general_movsrc_operand (op, mode)
6243      rtx op;
6244      enum machine_mode mode;
6245 {
6246   if (GET_CODE (op) == MEM)
6247     {
6248       rtx inside = XEXP (op, 0);
6249       if (GET_CODE (inside) == CONST)
6250         inside = XEXP (inside, 0);
6251
6252       if (GET_CODE (inside) == LABEL_REF)
6253         return 1;
6254
6255       if (GET_CODE (inside) == PLUS
6256           && GET_CODE (XEXP (inside, 0)) == LABEL_REF
6257           && GET_CODE (XEXP (inside, 1)) == CONST_INT)
6258         return 1;
6259
6260       /* Only post inc allowed.  */
6261       if (GET_CODE (inside) == PRE_DEC)
6262         return 0;
6263     }
6264
6265   if ((mode == QImode || mode == HImode)
6266       && (GET_CODE (op) == SUBREG
6267           && GET_CODE (XEXP (op, 0)) == REG
6268           && system_reg_operand (XEXP (op, 0), mode)))
6269     return 0;
6270
6271   return general_operand (op, mode);
6272 }
6273
6274 /* Returns 1 if OP can be a destination of a move.
6275    Same as general_operand, but no preinc allowed.  */
6276
6277 int
6278 general_movdst_operand (op, mode)
6279      rtx op;
6280      enum machine_mode mode;
6281 {
6282   /* Only pre dec allowed.  */
6283   if (GET_CODE (op) == MEM && GET_CODE (XEXP (op, 0)) == POST_INC)
6284     return 0;
6285
6286   return general_operand (op, mode);
6287 }
6288
6289 /* Returns 1 if OP is a normal arithmetic register.  */
6290
6291 int
6292 arith_reg_operand (op, mode)
6293      rtx op;
6294      enum machine_mode mode;
6295 {
6296   if (register_operand (op, mode))
6297     {
6298       int regno;
6299
6300       if (GET_CODE (op) == REG)
6301         regno = REGNO (op);
6302       else if (GET_CODE (op) == SUBREG && GET_CODE (SUBREG_REG (op)) == REG)
6303         regno = REGNO (SUBREG_REG (op));
6304       else
6305         return 1;
6306
6307       return (regno != T_REG && regno != PR_REG
6308               && ! TARGET_REGISTER_P (regno)
6309               && (regno != FPUL_REG || TARGET_SH4)
6310               && regno != MACH_REG && regno != MACL_REG);
6311     }
6312   return 0;
6313 }
6314
6315 /* Like above, but for DImode destinations: forbid paradoxical DImode subregs,
6316    because this would lead to missing sign extensions when truncating from
6317    DImode to SImode.  */
6318 int
6319 arith_reg_dest (op, mode)
6320      rtx op;
6321      enum machine_mode mode;
6322 {
6323   if (mode == DImode && GET_CODE (op) == SUBREG
6324       && GET_MODE_SIZE (GET_MODE (SUBREG_REG (op))) < 8)
6325     return 0;
6326   return arith_reg_operand (op, mode);
6327 }
6328
6329 int
6330 int_gpr_dest (op, mode)
6331      rtx op;
6332      enum machine_mode mode ATTRIBUTE_UNUSED;
6333 {
6334   enum machine_mode op_mode = GET_MODE (op);
6335
6336   if (GET_MODE_CLASS (op_mode) != MODE_INT
6337       || GET_MODE_SIZE (op_mode) >= UNITS_PER_WORD)
6338     return 0;
6339   if (! reload_completed)
6340     return 0;
6341   return true_regnum (op) <= LAST_GENERAL_REG;
6342 }
6343
6344 int
6345 fp_arith_reg_operand (op, mode)
6346      rtx op;
6347      enum machine_mode mode;
6348 {
6349   if (register_operand (op, mode))
6350     {
6351       int regno;
6352
6353       if (GET_CODE (op) == REG)
6354         regno = REGNO (op);
6355       else if (GET_CODE (op) == SUBREG && GET_CODE (SUBREG_REG (op)) == REG)
6356         regno = REGNO (SUBREG_REG (op));
6357       else
6358         return 1;
6359
6360       return (regno >= FIRST_PSEUDO_REGISTER
6361               || FP_REGISTER_P (regno));
6362     }
6363   return 0;
6364 }
6365
6366 /* Returns 1 if OP is a valid source operand for an arithmetic insn.  */
6367
6368 int
6369 arith_operand (op, mode)
6370      rtx op;
6371      enum machine_mode mode;
6372 {
6373   if (arith_reg_operand (op, mode))
6374     return 1;
6375
6376   if (TARGET_SHMEDIA)
6377     {
6378       /* FIXME: We should be checking whether the CONST_INT fits in a
6379          CONST_OK_FOR_J here, but this causes reload_cse to crash when
6380          attempting to transform a sequence of two 64-bit sets of the
6381          same register from literal constants into a set and an add,
6382          when the difference is too wide for an add.  */
6383       if (GET_CODE (op) == CONST_INT
6384           || EXTRA_CONSTRAINT_S (op))
6385         return 1;
6386       else
6387         return 0;
6388     }
6389   else if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_I (INTVAL (op)))
6390     return 1;
6391
6392   return 0;
6393 }
6394
6395 /* Returns 1 if OP is a valid source operand for a compare insn.  */
6396
6397 int
6398 arith_reg_or_0_operand (op, mode)
6399      rtx op;
6400      enum machine_mode mode;
6401 {
6402   if (arith_reg_operand (op, mode))
6403     return 1;
6404
6405   if (EXTRA_CONSTRAINT_U (op))
6406     return 1;
6407
6408   return 0;
6409 }
6410
6411 /* Return 1 if OP is a valid source operand for an SHmedia operation
6412    that takes either a register or a 6-bit immediate.  */
6413
6414 int
6415 shmedia_6bit_operand (op, mode)
6416      rtx op;
6417      enum machine_mode mode;
6418 {
6419   return (arith_reg_operand (op, mode)
6420           || (GET_CODE (op) == CONST_INT && CONST_OK_FOR_O (INTVAL (op))));
6421 }
6422
6423 /* Returns 1 if OP is a valid source operand for a logical operation.  */
6424
6425 int
6426 logical_operand (op, mode)
6427      rtx op;
6428      enum machine_mode mode;
6429 {
6430   if (arith_reg_operand (op, mode))
6431     return 1;
6432
6433   if (TARGET_SHMEDIA)
6434     {
6435       if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_P (INTVAL (op)))
6436         return 1;
6437       else
6438         return 0;
6439     }
6440   else if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_L (INTVAL (op)))
6441     return 1;
6442
6443   return 0;
6444 }
6445
6446 int
6447 and_operand (op, mode)
6448      rtx op;
6449      enum machine_mode mode;
6450 {
6451   if (logical_operand (op, mode))
6452     return 1;
6453
6454   /* Check mshflo.l / mshflhi.l opportunities.  */
6455   if (TARGET_SHMEDIA
6456       && mode == DImode
6457       && GET_CODE (op) == CONST_INT
6458       && (INTVAL (op) == (unsigned) 0xffffffff
6459           || INTVAL (op) == (HOST_WIDE_INT) -1 << 32))
6460         return 1;
6461
6462   return 0;
6463 }
6464
6465 /* Nonzero if OP is a floating point value with value 0.0.  */
6466
6467 int
6468 fp_zero_operand (op)
6469      rtx op;
6470 {
6471   REAL_VALUE_TYPE r;
6472
6473   if (GET_MODE (op) != SFmode)
6474     return 0;
6475
6476   REAL_VALUE_FROM_CONST_DOUBLE (r, op);
6477   return REAL_VALUES_EQUAL (r, dconst0) && ! REAL_VALUE_MINUS_ZERO (r);
6478 }
6479
6480 /* Nonzero if OP is a floating point value with value 1.0.  */
6481
6482 int
6483 fp_one_operand (op)
6484      rtx op;
6485 {
6486   REAL_VALUE_TYPE r;
6487
6488   if (GET_MODE (op) != SFmode)
6489     return 0;
6490
6491   REAL_VALUE_FROM_CONST_DOUBLE (r, op);
6492   return REAL_VALUES_EQUAL (r, dconst1);
6493 }
6494
6495 /* For -m4 and -m4-single-only, mode switching is used.  If we are
6496    compiling without -mfmovd, movsf_ie isn't taken into account for
6497    mode switching.  We could check in machine_dependent_reorg for
6498    cases where we know we are in single precision mode, but there is
6499    interface to find that out during reload, so we must avoid
6500    choosing an fldi alternative during reload and thus failing to
6501    allocate a scratch register for the constant loading.  */
6502 int
6503 fldi_ok ()
6504 {
6505   return ! TARGET_SH4 || TARGET_FMOVD || reload_completed;
6506 }
6507
6508 int
6509 tertiary_reload_operand (op, mode)
6510      rtx op;
6511      enum machine_mode mode ATTRIBUTE_UNUSED;
6512 {
6513   enum rtx_code code = GET_CODE (op);
6514   return code == MEM || (TARGET_SH4 && code == CONST_DOUBLE);
6515 }
6516
6517 int
6518 fpscr_operand (op, mode)
6519      rtx op;
6520      enum machine_mode mode ATTRIBUTE_UNUSED;
6521 {
6522   return (GET_CODE (op) == REG && REGNO (op) == FPSCR_REG
6523           && GET_MODE (op) == PSImode);
6524 }
6525
6526 int
6527 fpul_operand (op, mode)
6528      rtx op;
6529      enum machine_mode mode;
6530 {
6531   if (TARGET_SHMEDIA)
6532     return fp_arith_reg_operand (op, mode);
6533
6534   return (GET_CODE (op) == REG
6535           && (REGNO (op) == FPUL_REG || REGNO (op) >= FIRST_PSEUDO_REGISTER)
6536           && GET_MODE (op) == mode);
6537 }
6538
6539 int
6540 symbol_ref_operand (op, mode)
6541      rtx op;
6542      enum machine_mode mode ATTRIBUTE_UNUSED;
6543 {
6544   return (GET_CODE (op) == SYMBOL_REF);
6545 }
6546
6547 /* Return the TLS type for TLS symbols, 0 for otherwise.  */
6548 int
6549 tls_symbolic_operand (op, mode)
6550      rtx op;
6551      enum machine_mode mode ATTRIBUTE_UNUSED;
6552 {
6553   if (GET_CODE (op) != SYMBOL_REF)
6554     return 0;
6555   return SYMBOL_REF_TLS_MODEL (op);
6556 }
6557
6558 int
6559 commutative_float_operator (op, mode)
6560      rtx op;
6561      enum machine_mode mode;
6562 {
6563   if (GET_MODE (op) != mode)
6564     return 0;
6565   switch (GET_CODE (op))
6566     {
6567     case PLUS:
6568     case MULT:
6569       return 1;
6570     default:
6571       break;
6572     }
6573   return 0;
6574 }
6575
6576 int
6577 noncommutative_float_operator (op, mode)
6578      rtx op;
6579      enum machine_mode mode;
6580 {
6581   if (GET_MODE (op) != mode)
6582     return 0;
6583   switch (GET_CODE (op))
6584     {
6585     case MINUS:
6586     case DIV:
6587       return 1;
6588     default:
6589       break;
6590     }
6591   return 0;
6592 }
6593
6594 int
6595 unary_float_operator (op, mode)
6596      rtx op;
6597      enum machine_mode mode;
6598 {
6599   if (GET_MODE (op) != mode)
6600     return 0;
6601   switch (GET_CODE (op))
6602     {
6603     case ABS:
6604     case NEG:
6605     case SQRT:
6606       return 1;
6607     default:
6608       break;
6609     }
6610   return 0;
6611 }
6612
6613 int
6614 binary_float_operator (op, mode)
6615      rtx op;
6616      enum machine_mode mode;
6617 {
6618   if (GET_MODE (op) != mode)
6619     return 0;
6620   switch (GET_CODE (op))
6621     {
6622     case PLUS:
6623     case MINUS:
6624     case MULT:
6625     case DIV:
6626       return 1;
6627     default:
6628       break;
6629     }
6630   return 0;
6631 }
6632
6633 int
6634 binary_logical_operator (op, mode)
6635      rtx op;
6636      enum machine_mode mode;
6637 {
6638   if (GET_MODE (op) != mode)
6639     return 0;
6640   switch (GET_CODE (op))
6641     {
6642     case IOR:
6643     case AND:
6644     case XOR:
6645       return 1;
6646     default:
6647       break;
6648     }
6649   return 0;
6650 }
6651
6652 int
6653 equality_comparison_operator (op, mode)
6654      rtx op;
6655      enum machine_mode mode;
6656 {
6657   return ((mode == VOIDmode || GET_MODE (op) == mode)
6658           && (GET_CODE (op) == EQ || GET_CODE (op) == NE));
6659 }
6660
6661 int greater_comparison_operator (op, mode)
6662      rtx op;
6663      enum machine_mode mode;
6664 {
6665   if (mode != VOIDmode && GET_MODE (op) == mode)
6666     return 0;
6667   switch (GET_CODE (op))
6668     {
6669     case GT:
6670     case GE:
6671     case GTU:
6672     case GEU:
6673       return 1;
6674     default:
6675       return 0;
6676     }
6677 }
6678
6679 int less_comparison_operator (op, mode)
6680      rtx op;
6681      enum machine_mode mode;
6682 {
6683   if (mode != VOIDmode && GET_MODE (op) == mode)
6684     return 0;
6685   switch (GET_CODE (op))
6686     {
6687     case LT:
6688     case LE:
6689     case LTU:
6690     case LEU:
6691       return 1;
6692     default:
6693       return 0;
6694     }
6695 }
6696
6697 /* Accept pseudos and branch target registers.  */
6698 int
6699 target_reg_operand (op, mode)
6700      rtx op;
6701      enum machine_mode mode;
6702 {
6703   if (mode != DImode
6704       || GET_MODE (op) != DImode)
6705     return 0;
6706
6707   if (GET_CODE (op) == SUBREG)
6708     op = XEXP (op, 0);
6709
6710   if (GET_CODE (op) != REG)
6711     return 0;
6712
6713   /* We must protect ourselves from matching pseudos that are virtual
6714      register, because they will eventually be replaced with hardware
6715      registers that aren't branch-target registers.  */
6716   if (REGNO (op) > LAST_VIRTUAL_REGISTER
6717       || TARGET_REGISTER_P (REGNO (op)))
6718     return 1;
6719
6720   return 0;
6721 }
6722
6723 /* Same as target_reg_operand, except that label_refs and symbol_refs
6724    are accepted before reload.  */
6725 int
6726 target_operand (op, mode)
6727      rtx op;
6728      enum machine_mode mode;
6729 {
6730   if (mode != DImode)
6731     return 0;
6732
6733   if ((GET_MODE (op) == DImode || GET_MODE (op) == VOIDmode)
6734       && EXTRA_CONSTRAINT_T (op))
6735     return ! reload_completed;
6736
6737   return target_reg_operand (op, mode);
6738 }
6739
6740 int
6741 mextr_bit_offset (op, mode)
6742      rtx op;
6743      enum machine_mode mode ATTRIBUTE_UNUSED;
6744 {
6745   HOST_WIDE_INT i;
6746
6747   if (GET_CODE (op) != CONST_INT)
6748     return 0;
6749   i = INTVAL (op);
6750   return i >= 1*8 && i <= 7*8 && (i & 7) == 0;
6751 }
6752
6753 int
6754 extend_reg_operand (op, mode)
6755      rtx op;
6756      enum machine_mode mode;
6757 {
6758   return (GET_CODE (op) == TRUNCATE
6759           ? arith_operand
6760           : arith_reg_operand) (op, mode);
6761 }
6762
6763 int
6764 trunc_hi_operand (op, mode)
6765      rtx op;
6766      enum machine_mode mode;
6767 {
6768   enum machine_mode op_mode = GET_MODE (op);
6769
6770   if (op_mode != SImode && op_mode != DImode
6771       && op_mode != V4HImode && op_mode != V2SImode)
6772     return 0;
6773   return extend_reg_operand (op, mode);
6774 }
6775
6776 int
6777 extend_reg_or_0_operand (op, mode)
6778      rtx op;
6779      enum machine_mode mode;
6780 {
6781   return (GET_CODE (op) == TRUNCATE
6782           ? arith_operand
6783           : arith_reg_or_0_operand) (op, mode);
6784 }
6785
6786 int
6787 general_extend_operand (op, mode)
6788      rtx op;
6789      enum machine_mode mode;
6790 {
6791   return (GET_CODE (op) == TRUNCATE
6792           ? arith_operand
6793           : nonimmediate_operand) (op, mode);
6794 }
6795
6796 int
6797 inqhi_operand (op, mode)
6798      rtx op;
6799      enum machine_mode mode;
6800 {
6801   if (GET_CODE (op) != TRUNCATE || mode != GET_MODE (op))
6802     return 0;
6803   op = XEXP (op, 0);
6804   /* Can't use true_regnum here because copy_cost wants to know about
6805      SECONDARY_INPUT_RELOAD_CLASS.  */
6806   return GET_CODE (op) == REG && FP_REGISTER_P (REGNO (op));
6807 }
6808
6809 int
6810 sh_rep_vec (v, mode)
6811      rtx v;
6812      enum machine_mode mode;
6813 {
6814   int i;
6815   rtx x, y;
6816
6817   if ((GET_CODE (v) != CONST_VECTOR && GET_CODE (v) != PARALLEL)
6818       || (GET_MODE (v) != mode && mode != VOIDmode))
6819     return 0;
6820   i = XVECLEN (v, 0) - 2;
6821   x = XVECEXP (v, 0, i + 1);
6822   if (GET_MODE_UNIT_SIZE (mode) == 1)
6823     {
6824       y = XVECEXP (v, 0, i);
6825       for (i -= 2 ; i >= 0; i -= 2)
6826         if (! rtx_equal_p (XVECEXP (v, 0, i + 1), x)
6827             || ! rtx_equal_p (XVECEXP (v, 0, i), y))
6828           return 0;
6829     }
6830   else
6831     for (; i >= 0; i--)
6832       if (XVECEXP (v, 0, i) != x)
6833         return 0;
6834   return 1;
6835 }
6836
6837 /* Determine if V is a constant vector matching MODE with only one element
6838    that is not a sign extension.  Two byte-sized elements count as one.  */
6839 int
6840 sh_1el_vec (v, mode)
6841      rtx v;
6842      enum machine_mode mode;
6843 {
6844   int unit_size;
6845   int i, last, least, sign_ix;
6846   rtx sign;
6847
6848   if (GET_CODE (v) != CONST_VECTOR
6849       || (GET_MODE (v) != mode && mode != VOIDmode))
6850     return 0;
6851   /* Determine numbers of last and of least significant elements.  */
6852   last = XVECLEN (v, 0) - 1;
6853   least = TARGET_LITTLE_ENDIAN ? 0 : last;
6854   if (GET_CODE (XVECEXP (v, 0, least)) != CONST_INT)
6855     return 0;
6856   sign_ix = least;
6857   if (GET_MODE_UNIT_SIZE (mode) == 1)
6858     sign_ix = TARGET_LITTLE_ENDIAN ? 1 : last - 1;
6859   if (GET_CODE (XVECEXP (v, 0, sign_ix)) != CONST_INT)
6860     return 0;
6861   unit_size = GET_MODE_UNIT_SIZE (GET_MODE (v));
6862   sign = (INTVAL (XVECEXP (v, 0, sign_ix)) >> (unit_size * BITS_PER_UNIT - 1)
6863           ? constm1_rtx : const0_rtx);
6864   i = XVECLEN (v, 0) - 1;
6865   do
6866     if (i != least && i != sign_ix && XVECEXP (v, 0, i) != sign)
6867       return 0;
6868   while (--i);
6869   return 1;
6870 }
6871
6872 int
6873 sh_const_vec (v, mode)
6874      rtx v;
6875      enum machine_mode mode;
6876 {
6877   int i;
6878
6879   if (GET_CODE (v) != CONST_VECTOR
6880       || (GET_MODE (v) != mode && mode != VOIDmode))
6881     return 0;
6882   i = XVECLEN (v, 0) - 1;
6883   for (; i >= 0; i--)
6884     if (GET_CODE (XVECEXP (v, 0, i)) != CONST_INT)
6885       return 0;
6886   return 1;
6887 }
6888 \f
6889 /* Return the destination address of a branch.  */
6890    
6891 static int
6892 branch_dest (branch)
6893      rtx branch;
6894 {
6895   rtx dest = SET_SRC (PATTERN (branch));
6896   int dest_uid;
6897
6898   if (GET_CODE (dest) == IF_THEN_ELSE)
6899     dest = XEXP (dest, 1);
6900   dest = XEXP (dest, 0);
6901   dest_uid = INSN_UID (dest);
6902   return INSN_ADDRESSES (dest_uid);
6903 }
6904 \f
6905 /* Return nonzero if REG is not used after INSN.
6906    We assume REG is a reload reg, and therefore does
6907    not live past labels.  It may live past calls or jumps though.  */
6908 int
6909 reg_unused_after (reg, insn)
6910      rtx reg;
6911      rtx insn;
6912 {
6913   enum rtx_code code;
6914   rtx set;
6915
6916   /* If the reg is set by this instruction, then it is safe for our
6917      case.  Disregard the case where this is a store to memory, since
6918      we are checking a register used in the store address.  */
6919   set = single_set (insn);
6920   if (set && GET_CODE (SET_DEST (set)) != MEM
6921       && reg_overlap_mentioned_p (reg, SET_DEST (set)))
6922     return 1;
6923
6924   while ((insn = NEXT_INSN (insn)))
6925     {
6926       code = GET_CODE (insn);
6927
6928 #if 0
6929       /* If this is a label that existed before reload, then the register
6930          if dead here.  However, if this is a label added by reorg, then
6931          the register may still be live here.  We can't tell the difference,
6932          so we just ignore labels completely.  */
6933       if (code == CODE_LABEL)
6934         return 1;
6935       /* else */
6936 #endif
6937
6938       if (code == JUMP_INSN)
6939         return 0;
6940
6941       /* If this is a sequence, we must handle them all at once.
6942          We could have for instance a call that sets the target register,
6943          and an insn in a delay slot that uses the register.  In this case,
6944          we must return 0.  */
6945       else if (code == INSN && GET_CODE (PATTERN (insn)) == SEQUENCE)
6946         {
6947           int i;
6948           int retval = 0;
6949
6950           for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
6951             {
6952               rtx this_insn = XVECEXP (PATTERN (insn), 0, i);
6953               rtx set = single_set (this_insn);
6954
6955               if (GET_CODE (this_insn) == CALL_INSN)
6956                 code = CALL_INSN;
6957               else if (GET_CODE (this_insn) == JUMP_INSN)
6958                 {
6959                   if (INSN_ANNULLED_BRANCH_P (this_insn))
6960                     return 0;
6961                   code = JUMP_INSN;
6962                 }
6963
6964               if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
6965                 return 0;
6966               if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
6967                 {
6968                   if (GET_CODE (SET_DEST (set)) != MEM)
6969                     retval = 1;
6970                   else
6971                     return 0;
6972                 }
6973               if (set == 0
6974                   && reg_overlap_mentioned_p (reg, PATTERN (this_insn)))
6975                 return 0;
6976             }
6977           if (retval == 1)
6978             return 1;
6979           else if (code == JUMP_INSN)
6980             return 0;
6981         }
6982       else if (GET_RTX_CLASS (code) == 'i')
6983         {
6984           rtx set = single_set (insn);
6985
6986           if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
6987             return 0;
6988           if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
6989             return GET_CODE (SET_DEST (set)) != MEM;
6990           if (set == 0 && reg_overlap_mentioned_p (reg, PATTERN (insn)))
6991             return 0;
6992         }
6993
6994       if (code == CALL_INSN && call_used_regs[REGNO (reg)])
6995         return 1;
6996     }
6997   return 1;
6998 }
6999 \f
7000 #include "ggc.h"
7001
7002 static GTY(()) rtx fpscr_rtx;
7003 rtx
7004 get_fpscr_rtx ()
7005 {
7006   if (! fpscr_rtx)
7007     {
7008       fpscr_rtx = gen_rtx (REG, PSImode, FPSCR_REG);
7009       REG_USERVAR_P (fpscr_rtx) = 1;
7010       mark_user_reg (fpscr_rtx);
7011     }
7012   if (! reload_completed || mdep_reorg_phase != SH_AFTER_MDEP_REORG)
7013     mark_user_reg (fpscr_rtx);
7014   return fpscr_rtx;
7015 }
7016
7017 void
7018 emit_sf_insn (pat)
7019      rtx pat;
7020 {
7021   emit_insn (pat);
7022 }
7023
7024 void
7025 emit_df_insn (pat)
7026      rtx pat;
7027 {
7028   emit_insn (pat);
7029 }
7030
7031 void
7032 expand_sf_unop (fun, operands)
7033      rtx (*fun) PARAMS ((rtx, rtx, rtx));
7034      rtx *operands;
7035 {
7036   emit_sf_insn ((*fun) (operands[0], operands[1], get_fpscr_rtx ()));
7037 }
7038
7039 void
7040 expand_sf_binop (fun, operands)
7041      rtx (*fun) PARAMS ((rtx, rtx, rtx, rtx));
7042      rtx *operands;
7043 {
7044   emit_sf_insn ((*fun) (operands[0], operands[1], operands[2],
7045                          get_fpscr_rtx ()));
7046 }
7047
7048 void
7049 expand_df_unop (fun, operands)
7050      rtx (*fun) PARAMS ((rtx, rtx, rtx));
7051      rtx *operands;
7052 {
7053   emit_df_insn ((*fun) (operands[0], operands[1], get_fpscr_rtx ()));
7054 }
7055
7056 void
7057 expand_df_binop (fun, operands)
7058      rtx (*fun) PARAMS ((rtx, rtx, rtx, rtx));
7059      rtx *operands;
7060 {
7061   emit_df_insn ((*fun) (operands[0], operands[1], operands[2],
7062                          get_fpscr_rtx ()));
7063 }
7064 \f
7065 /* ??? gcc does flow analysis strictly after common subexpression
7066    elimination.  As a result, common subexpression elimination fails
7067    when there are some intervening statements setting the same register.
7068    If we did nothing about this, this would hurt the precision switching
7069    for SH4 badly.  There is some cse after reload, but it is unable to
7070    undo the extra register pressure from the unused instructions, and
7071    it cannot remove auto-increment loads.
7072
7073    A C code example that shows this flow/cse weakness for (at least) SH
7074    and sparc (as of gcc ss-970706) is this:
7075
7076 double
7077 f(double a)
7078 {
7079   double d;
7080   d = 0.1;
7081   a += d;
7082   d = 1.1;
7083   d = 0.1;
7084   a *= d;
7085   return a;
7086 }
7087
7088    So we add another pass before common subexpression elimination, to
7089    remove assignments that are dead due to a following assignment in the
7090    same basic block.  */
7091
7092 static void 
7093 mark_use (x, reg_set_block)
7094      rtx x, *reg_set_block;
7095 {
7096   enum rtx_code code;
7097
7098   if (! x)
7099     return;
7100   code = GET_CODE (x);
7101   switch (code)
7102     {
7103     case REG:
7104       {
7105         int regno = REGNO (x);
7106         int nregs = (regno < FIRST_PSEUDO_REGISTER
7107                      ? HARD_REGNO_NREGS (regno, GET_MODE (x))
7108                      : 1);
7109         do
7110           {
7111             reg_set_block[regno + nregs - 1] = 0;
7112           }
7113         while (--nregs);
7114         break;
7115       }
7116     case SET:
7117       {
7118         rtx dest = SET_DEST (x);
7119
7120         if (GET_CODE (dest) == SUBREG)
7121           dest = SUBREG_REG (dest);
7122         if (GET_CODE (dest) != REG)
7123           mark_use (dest, reg_set_block);
7124         mark_use (SET_SRC (x), reg_set_block);
7125         break;
7126       }
7127     case CLOBBER:
7128       break;
7129     default:
7130       {
7131         const char *fmt = GET_RTX_FORMAT (code);
7132         int i, j;
7133         for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
7134           {
7135             if (fmt[i] == 'e')
7136               mark_use (XEXP (x, i), reg_set_block);
7137             else if (fmt[i] == 'E')
7138               for (j = XVECLEN (x, i) - 1; j >= 0; j--)
7139                 mark_use (XVECEXP (x, i, j), reg_set_block);
7140           }
7141         break;
7142       }
7143     }
7144 }
7145 \f
7146 static rtx get_free_reg PARAMS ((HARD_REG_SET));
7147
7148 /* This function returns a register to use to load the address to load
7149    the fpscr from.  Currently it always returns r1 or r7, but when we are
7150    able to use pseudo registers after combine, or have a better mechanism
7151    for choosing a register, it should be done here.  */
7152 /* REGS_LIVE is the liveness information for the point for which we
7153    need this allocation.  In some bare-bones exit blocks, r1 is live at the
7154    start.  We can even have all of r0..r3 being live:
7155 __complex__ long long f (double d) { if (d == 0) return 2; else return 3; }
7156    INSN before which new insns are placed with will clobber the register
7157    we return.  If a basic block consists only of setting the return value
7158    register to a pseudo and using that register, the return value is not
7159    live before or after this block, yet we we'll insert our insns right in
7160    the middle.  */
7161
7162 static rtx
7163 get_free_reg (regs_live)
7164      HARD_REG_SET regs_live;
7165 {
7166   if (! TEST_HARD_REG_BIT (regs_live, 1))
7167     return gen_rtx_REG (Pmode, 1);
7168
7169   /* Hard reg 1 is live; since this is a SMALL_REGISTER_CLASSES target,
7170      there shouldn't be anything but a jump before the function end.  */
7171   if (! TEST_HARD_REG_BIT (regs_live, 7))
7172     return gen_rtx_REG (Pmode, 7);
7173
7174   abort ();
7175 }
7176
7177 /* This function will set the fpscr from memory. 
7178    MODE is the mode we are setting it to.  */
7179 void
7180 fpscr_set_from_mem (mode, regs_live)
7181      int mode;
7182      HARD_REG_SET regs_live;
7183 {
7184   enum attr_fp_mode fp_mode = mode;
7185   rtx addr_reg = get_free_reg (regs_live);
7186
7187   if (fp_mode == (enum attr_fp_mode) ACTUAL_NORMAL_MODE (FP_MODE))
7188     emit_insn (gen_fpu_switch1 (addr_reg));
7189   else
7190     emit_insn (gen_fpu_switch0 (addr_reg));
7191 }
7192
7193 /* Is the given character a logical line separator for the assembler?  */
7194 #ifndef IS_ASM_LOGICAL_LINE_SEPARATOR
7195 #define IS_ASM_LOGICAL_LINE_SEPARATOR(C) ((C) == ';')
7196 #endif
7197
7198 int
7199 sh_insn_length_adjustment (insn)
7200      rtx insn;
7201 {
7202   /* Instructions with unfilled delay slots take up an extra two bytes for
7203      the nop in the delay slot.  */
7204   if (((GET_CODE (insn) == INSN
7205         && GET_CODE (PATTERN (insn)) != USE
7206         && GET_CODE (PATTERN (insn)) != CLOBBER)
7207        || GET_CODE (insn) == CALL_INSN
7208        || (GET_CODE (insn) == JUMP_INSN
7209            && GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC
7210            && GET_CODE (PATTERN (insn)) != ADDR_VEC))
7211       && GET_CODE (PATTERN (NEXT_INSN (PREV_INSN (insn)))) != SEQUENCE
7212       && get_attr_needs_delay_slot (insn) == NEEDS_DELAY_SLOT_YES)
7213     return 2;
7214
7215   /* SH2e has a bug that prevents the use of annulled branches, so if
7216      the delay slot is not filled, we'll have to put a NOP in it.  */
7217   if (sh_cpu == CPU_SH2E
7218       && GET_CODE (insn) == JUMP_INSN
7219       && GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC
7220       && GET_CODE (PATTERN (insn)) != ADDR_VEC
7221       && get_attr_type (insn) == TYPE_CBRANCH
7222       && GET_CODE (PATTERN (NEXT_INSN (PREV_INSN (insn)))) != SEQUENCE)
7223     return 2;
7224
7225   /* sh-dsp parallel processing insn take four bytes instead of two.  */
7226      
7227   if (GET_CODE (insn) == INSN)
7228     {
7229       int sum = 0;
7230       rtx body = PATTERN (insn);
7231       const char *template;
7232       char c;
7233       int maybe_label = 1;
7234
7235       if (GET_CODE (body) == ASM_INPUT)
7236         template = XSTR (body, 0);
7237       else if (asm_noperands (body) >= 0)
7238         template
7239           = decode_asm_operands (body, NULL, NULL, NULL, NULL);
7240       else
7241         return 0;
7242       do
7243         {
7244           int ppi_adjust = 0;
7245
7246           do
7247             c = *template++;
7248           while (c == ' ' || c == '\t');
7249           /* all sh-dsp parallel-processing insns start with p.
7250              The only non-ppi sh insn starting with p is pref.
7251              The only ppi starting with pr is prnd.  */
7252           if ((c == 'p' || c == 'P') && strncasecmp ("re", template, 2))
7253             ppi_adjust = 2;
7254           /* The repeat pseudo-insn expands two three insns, a total of
7255              six bytes in size.  */
7256           else if ((c == 'r' || c == 'R')
7257                    && ! strncasecmp ("epeat", template, 5))
7258             ppi_adjust = 4;
7259           while (c && c != '\n' && ! IS_ASM_LOGICAL_LINE_SEPARATOR (c))
7260             {
7261               /* If this is a label, it is obviously not a ppi insn.  */
7262               if (c == ':' && maybe_label)
7263                 {
7264                   ppi_adjust = 0;
7265                   break;
7266                 }
7267               else if (c == '\'' || c == '"')
7268                 maybe_label = 0;
7269               c = *template++;
7270             }
7271           sum += ppi_adjust;
7272           maybe_label = c != ':';
7273         }
7274       while (c);
7275       return sum;
7276     }
7277   return 0;
7278 }
7279 \f
7280 /* Return TRUE if X references a SYMBOL_REF or LABEL_REF whose symbol
7281    isn't protected by a PIC unspec.  */
7282 int
7283 nonpic_symbol_mentioned_p (x)
7284      rtx x;
7285 {
7286   register const char *fmt;
7287   register int i;
7288
7289   if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF
7290       || GET_CODE (x) == PC)
7291     return 1;
7292
7293   /* We don't want to look into the possible MEM location of a
7294      CONST_DOUBLE, since we're not going to use it, in general.  */
7295   if (GET_CODE (x) == CONST_DOUBLE)
7296     return 0;
7297
7298   if (GET_CODE (x) == UNSPEC
7299       && (XINT (x, 1) == UNSPEC_PIC
7300           || XINT (x, 1) == UNSPEC_GOT
7301           || XINT (x, 1) == UNSPEC_GOTOFF
7302           || XINT (x, 1) == UNSPEC_GOTPLT
7303           || XINT (x, 1) == UNSPEC_GOTTPOFF
7304           || XINT (x, 1) == UNSPEC_DTPOFF
7305           || XINT (x, 1) == UNSPEC_PLT))
7306       return 0;
7307
7308   fmt = GET_RTX_FORMAT (GET_CODE (x));
7309   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
7310     {
7311       if (fmt[i] == 'E')
7312         {
7313           register int j;
7314
7315           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
7316             if (nonpic_symbol_mentioned_p (XVECEXP (x, i, j)))
7317               return 1;
7318         }
7319       else if (fmt[i] == 'e' && nonpic_symbol_mentioned_p (XEXP (x, i)))
7320         return 1;
7321     }
7322
7323   return 0;
7324 }
7325
7326 /* Convert a non-PIC address in `orig' to a PIC address using @GOT or
7327    @GOTOFF in `reg'.  */
7328 rtx
7329 legitimize_pic_address (orig, mode, reg)
7330      rtx orig;
7331      enum machine_mode mode ATTRIBUTE_UNUSED;
7332      rtx reg;
7333 {
7334   if (tls_symbolic_operand (orig, Pmode))
7335     return orig;
7336
7337   if (GET_CODE (orig) == LABEL_REF
7338       || (GET_CODE (orig) == SYMBOL_REF && SYMBOL_REF_LOCAL_P (orig)))
7339     {
7340       if (reg == 0)
7341         reg = gen_reg_rtx (Pmode);
7342
7343       emit_insn (gen_symGOTOFF2reg (reg, orig));
7344       return reg;
7345     }
7346   else if (GET_CODE (orig) == SYMBOL_REF)
7347     {
7348       if (reg == 0)
7349         reg = gen_reg_rtx (Pmode);
7350
7351       emit_insn (gen_symGOT2reg (reg, orig));
7352       return reg;
7353     }
7354   return orig;
7355 }
7356
7357 /* Mark the use of a constant in the literal table. If the constant
7358    has multiple labels, make it unique.  */
7359 static rtx
7360 mark_constant_pool_use (x)
7361      rtx x;
7362 {
7363   rtx insn, lab, pattern;
7364
7365   if (x == NULL)
7366     return x;
7367
7368   switch (GET_CODE (x))
7369     {
7370     case LABEL_REF:
7371       x = XEXP (x, 0);
7372     case CODE_LABEL:
7373       break;
7374     default:
7375       return x;
7376     }
7377
7378   /* Get the first label in the list of labels for the same constant
7379      and delete another labels in the list.  */
7380   lab = x;
7381   for (insn = PREV_INSN (x); insn; insn = PREV_INSN (insn))
7382     {
7383       if (GET_CODE (insn) != CODE_LABEL
7384           || LABEL_REFS (insn) != NEXT_INSN (insn))
7385         break;
7386       lab = insn;
7387     }
7388
7389   for (insn = LABEL_REFS (lab); insn; insn = LABEL_REFS (insn))
7390     INSN_DELETED_P (insn) = 1;
7391
7392   /* Mark constants in a window.  */
7393   for (insn = NEXT_INSN (x); insn; insn = NEXT_INSN (insn))
7394     {
7395       if (GET_CODE (insn) != INSN)
7396         continue;
7397
7398       pattern = PATTERN (insn);
7399       if (GET_CODE (pattern) != UNSPEC_VOLATILE)
7400         continue;
7401
7402       switch (XINT (pattern, 1))
7403         {
7404         case UNSPECV_CONST2:
7405         case UNSPECV_CONST4:
7406         case UNSPECV_CONST8:
7407           XVECEXP (pattern, 0, 1) = const1_rtx;
7408           break;
7409         case UNSPECV_WINDOW_END:
7410           if (XVECEXP (pattern, 0, 0) == x)
7411             return lab;
7412           break;
7413         case UNSPECV_CONST_END:
7414           return lab;
7415         default:
7416           break;
7417         }
7418     }
7419
7420   return lab;
7421 }
7422 \f
7423 /* Return true if it's possible to redirect BRANCH1 to the destination
7424    of an unconditional jump BRANCH2.  We only want to do this if the
7425    resulting branch will have a short displacement.  */
7426 int 
7427 sh_can_redirect_branch (branch1, branch2)
7428      rtx branch1;
7429      rtx branch2;
7430 {
7431   if (flag_expensive_optimizations && simplejump_p (branch2))
7432     {
7433       rtx dest = XEXP (SET_SRC (single_set (branch2)), 0);
7434       rtx insn;
7435       int distance;
7436       
7437       for (distance = 0, insn = NEXT_INSN (branch1); 
7438            insn && distance < 256; 
7439            insn = PREV_INSN (insn))
7440         {
7441           if (insn == dest)    
7442             return 1;
7443           else
7444             distance += get_attr_length (insn);
7445         }
7446       for (distance = 0, insn = NEXT_INSN (branch1); 
7447            insn && distance < 256; 
7448            insn = NEXT_INSN (insn))
7449         {
7450           if (insn == dest)    
7451             return 1;
7452           else
7453             distance += get_attr_length (insn);
7454         }
7455     }
7456   return 0;
7457 }
7458
7459 /* Return nonzero if register old_reg can be renamed to register new_reg.  */
7460 int
7461 sh_hard_regno_rename_ok (old_reg, new_reg)
7462      unsigned int old_reg ATTRIBUTE_UNUSED;
7463      unsigned int new_reg;
7464 {
7465
7466 /* Interrupt functions can only use registers that have already been
7467    saved by the prologue, even if they would normally be
7468    call-clobbered.  */
7469
7470   if (sh_cfun_interrupt_handler_p () && !regs_ever_live[new_reg])
7471      return 0;
7472
7473    return 1;
7474 }
7475
7476 /* Function to update the integer COST
7477    based on the relationship between INSN that is dependent on
7478    DEP_INSN through the dependence LINK.  The default is to make no
7479    adjustment to COST.  This can be used for example to specify to
7480    the scheduler that an output- or anti-dependence does not incur
7481    the same cost as a data-dependence.  The return value should be
7482    the new value for COST.  */
7483 static int
7484 sh_adjust_cost (insn, link, dep_insn, cost)
7485      rtx insn;
7486      rtx link ATTRIBUTE_UNUSED;
7487      rtx dep_insn;
7488      int cost;
7489 {
7490   rtx reg, use_pat;
7491
7492   if (TARGET_SHMEDIA)
7493     {
7494       /* On SHmedia, if the dependence is an anti-dependence or
7495          output-dependence, there is no cost. */              
7496       if (REG_NOTE_KIND (link) != 0)
7497         cost = 0;
7498
7499       if (get_attr_is_mac_media (insn)
7500           && get_attr_is_mac_media (dep_insn))
7501         cost = 1;
7502     }
7503   else if (REG_NOTE_KIND (link) == 0)
7504     {
7505       enum attr_type dep_type, type;
7506
7507       if (recog_memoized (insn) < 0
7508           || recog_memoized (dep_insn) < 0)
7509         return cost;
7510
7511       dep_type = get_attr_type (dep_insn);
7512       if (dep_type == TYPE_FLOAD || dep_type == TYPE_PCFLOAD)
7513         cost--;
7514       if ((dep_type == TYPE_LOAD_SI || dep_type == TYPE_PCLOAD_SI)
7515           && (type = get_attr_type (insn)) != TYPE_CALL
7516           && type != TYPE_SFUNC)
7517         cost--;
7518
7519       /* The only input for a call that is timing-critical is the
7520          function's address.  */
7521       if (GET_CODE(insn) == CALL_INSN)
7522         {
7523           rtx call = PATTERN (insn);
7524
7525           if (GET_CODE (call) == PARALLEL)
7526             call = XVECEXP (call, 0 ,0);
7527           if (GET_CODE (call) == SET)
7528             call = SET_SRC (call);
7529           if (GET_CODE (call) == CALL && GET_CODE (XEXP (call, 0)) == MEM
7530               && ! reg_set_p (XEXP (XEXP (call, 0), 0), dep_insn))
7531             cost = 0;
7532         }
7533       /* Likewise, the most timing critical input for an sfuncs call
7534          is the function address.  However, sfuncs typically start
7535          using their arguments pretty quickly.
7536          Assume a four cycle delay before they are needed.  */
7537       /* All sfunc calls are parallels with at least four components.
7538          Exploit this to avoid unnecessary calls to sfunc_uses_reg.  */
7539       else if (GET_CODE (PATTERN (insn)) == PARALLEL
7540                && XVECLEN (PATTERN (insn), 0) >= 4
7541                && (reg = sfunc_uses_reg (insn)))
7542         {
7543           if (! reg_set_p (reg, dep_insn))
7544             cost -= 4;
7545         }
7546       /* When the preceding instruction loads the shift amount of
7547          the following SHAD/SHLD, the latency of the load is increased
7548          by 1 cycle.  */
7549       else if (TARGET_SH4
7550                && get_attr_type (insn) == TYPE_DYN_SHIFT
7551                && get_attr_any_int_load (dep_insn) == ANY_INT_LOAD_YES
7552                && reg_overlap_mentioned_p (SET_DEST (PATTERN (dep_insn)),
7553                                            XEXP (SET_SRC (single_set(insn)),
7554                                                  1)))
7555         cost++;
7556       /* When an LS group instruction with a latency of less than
7557          3 cycles is followed by a double-precision floating-point
7558          instruction, FIPR, or FTRV, the latency of the first
7559          instruction is increased to 3 cycles.  */
7560       else if (cost < 3
7561                && get_attr_insn_class (dep_insn) == INSN_CLASS_LS_GROUP
7562                && get_attr_dfp_comp (insn) == DFP_COMP_YES)
7563         cost = 3;
7564       /* The lsw register of a double-precision computation is ready one
7565          cycle earlier.  */
7566       else if (reload_completed
7567                && get_attr_dfp_comp (dep_insn) == DFP_COMP_YES
7568                && (use_pat = single_set (insn))
7569                && ! regno_use_in (REGNO (SET_DEST (single_set (dep_insn))),
7570                                   SET_SRC (use_pat)))
7571         cost -= 1;
7572
7573       if (get_attr_any_fp_comp (dep_insn) == ANY_FP_COMP_YES
7574           && get_attr_late_fp_use (insn) == LATE_FP_USE_YES)
7575         cost -= 1;
7576     }
7577   /* An anti-dependence penalty of two applies if the first insn is a double
7578      precision fadd / fsub / fmul.  */
7579   else if (REG_NOTE_KIND (link) == REG_DEP_ANTI
7580            && recog_memoized (dep_insn) >= 0
7581            && get_attr_type (dep_insn) == TYPE_DFP_ARITH
7582            /* A lot of alleged anti-flow dependences are fake,
7583               so check this one is real.  */
7584            && flow_dependent_p (dep_insn, insn))
7585     cost = 2;
7586
7587
7588   return cost;
7589 }
7590
7591 /* Check if INSN is flow-dependent on DEP_INSN.  Can also be used to check
7592    if DEP_INSN is anti-flow dependent on INSN.  */
7593 static int
7594 flow_dependent_p (insn, dep_insn)
7595      rtx insn, dep_insn;
7596 {
7597   rtx tmp = PATTERN (insn);
7598
7599   note_stores (PATTERN (dep_insn), flow_dependent_p_1, &tmp);
7600   return tmp == NULL_RTX;
7601 }
7602
7603 /* A helper function for flow_dependent_p called through note_stores.  */
7604 static void
7605 flow_dependent_p_1 (x, pat, data)
7606      rtx x;
7607      rtx pat ATTRIBUTE_UNUSED;
7608      void *data;
7609 {
7610   rtx * pinsn = (rtx *) data;
7611
7612   if (*pinsn && reg_referenced_p (x, *pinsn))
7613     *pinsn = NULL_RTX;
7614 }
7615
7616 /* For use by ALLOCATE_INITIAL_VALUE.  Note that sh.md contains some
7617    'special function' patterns (type sfunc) that clobber pr, but that
7618    do not look like function calls to leaf_function_p.  Hence we must
7619    do this extra check.  */
7620 int
7621 sh_pr_n_sets ()
7622 {
7623   return REG_N_SETS (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG);
7624 }
7625
7626 /* This Function returns nonzero if the DFA based scheduler interface
7627    is to be used.  At present this is supported for the SH4 only.  */
7628 static int
7629 sh_use_dfa_interface()
7630 {
7631   if (TARGET_HARD_SH4)
7632     return 1;
7633   else
7634     return 0;
7635 }
7636
7637 /* This function returns "2" to indicate dual issue for the SH4
7638    processor.  To be used by the DFA pipeline description.  */
7639 static int
7640 sh_issue_rate()
7641 {
7642   if (TARGET_SUPERSCALAR)
7643     return 2;
7644   else
7645     return 1;
7646 }
7647
7648 /* SHmedia requires registers for branches, so we can't generate new
7649    branches past reload.  */
7650 static bool
7651 sh_cannot_modify_jumps_p ()
7652 {
7653   return (TARGET_SHMEDIA && (reload_in_progress || reload_completed));
7654 }
7655
7656 static bool
7657 sh_ms_bitfield_layout_p (record_type)
7658      tree record_type ATTRIBUTE_UNUSED;
7659 {
7660   return TARGET_SH5;
7661 }
7662 \f
7663 /* 
7664    On the SH1..SH4, the trampoline looks like
7665    2 0002 D202                  mov.l   l2,r2
7666    1 0000 D301                  mov.l   l1,r3
7667    3 0004 422B                  jmp     @r2
7668    4 0006 0009                  nop
7669    5 0008 00000000      l1:     .long   area
7670    6 000c 00000000      l2:     .long   function
7671
7672    SH5 (compact) uses r1 instead of r3 for the static chain.  */
7673
7674
7675 /* Emit RTL insns to initialize the variable parts of a trampoline.
7676    FNADDR is an RTX for the address of the function's pure code.
7677    CXT is an RTX for the static chain value for the function.  */
7678
7679 void
7680 sh_initialize_trampoline (tramp, fnaddr, cxt)
7681      rtx tramp, fnaddr, cxt;
7682 {
7683   if (TARGET_SHMEDIA64)
7684     {
7685       rtx tramp_templ;
7686       int fixed_len;
7687
7688       rtx movi1 = GEN_INT (0xcc000010);
7689       rtx shori1 = GEN_INT (0xc8000010);
7690       rtx src, dst;
7691
7692       /* The following trampoline works within a +- 128 KB range for cxt:
7693          ptb/u cxt,tr1; movi fnaddr >> 48,r0; shori fnaddr >> 32,r0;
7694          shori fnaddr >> 16,r0; shori fnaddr,r0; ptabs/l r0,tr0
7695          gettr tr1,r1; blink tr0,r63  */
7696       /* Address rounding makes it hard to compute the exact bounds of the
7697          offset for this trampoline, but we have a rather generous offset
7698          range, so frame_offset should do fine as an upper bound.  */
7699       if (cxt == virtual_stack_vars_rtx && frame_offset < 0x20000)
7700         {
7701           /* ??? could optimize this trampoline initialization
7702              by writing DImode words with two insns each.  */
7703           rtx mask = force_reg (DImode, GEN_INT (0x3fffc00));
7704           rtx insn = gen_rtx_MINUS (DImode, cxt, tramp);
7705           insn = gen_rtx_ASHIFT (DImode, insn, GEN_INT (10-2));
7706           insn = gen_rtx_AND (DImode, insn, mask);
7707           /* Or in ptb/u .,tr1 pattern */
7708           insn = gen_rtx_IOR (DImode, insn, gen_int_mode (0xec000010, SImode));
7709           insn = force_operand (insn, NULL_RTX);
7710           insn = gen_lowpart (SImode, insn);
7711           emit_move_insn (gen_rtx_MEM (SImode, tramp), insn);
7712           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (38));
7713           insn = gen_rtx_AND (DImode, insn, mask);
7714           insn = force_operand (gen_rtx_IOR (DImode, movi1, insn), NULL_RTX);
7715           insn = gen_lowpart (SImode, insn);
7716           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 4)), insn);
7717           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (22));
7718           insn = gen_rtx_AND (DImode, insn, mask);
7719           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
7720           insn = gen_lowpart (SImode, insn);
7721           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 8)), insn);
7722           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (6));
7723           insn = gen_rtx_AND (DImode, insn, mask);
7724           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
7725           insn = gen_lowpart (SImode, insn);
7726           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 12)),
7727                           insn);
7728           insn = gen_rtx_ASHIFT (DImode, fnaddr, GEN_INT (10));
7729           insn = gen_rtx_AND (DImode, insn, mask);
7730           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
7731           insn = gen_lowpart (SImode, insn);
7732           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 16)),
7733                           insn);
7734           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 20)),
7735                           GEN_INT (0x6bf10600));
7736           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 24)),
7737                           GEN_INT (0x4415fc10));
7738           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 28)),
7739                           GEN_INT (0x4401fff0));
7740           emit_insn (gen_ic_invalidate_line (tramp));
7741           return;
7742         }
7743       tramp_templ = gen_rtx_SYMBOL_REF (Pmode,"__GCC_nested_trampoline");
7744       fixed_len = TRAMPOLINE_SIZE - 2 * GET_MODE_SIZE (Pmode);
7745
7746       tramp_templ = gen_datalabel_ref (tramp_templ);
7747       dst = gen_rtx_MEM (BLKmode, tramp);
7748       src = gen_rtx_MEM (BLKmode, tramp_templ);
7749       set_mem_align (dst, 256);
7750       set_mem_align (src, 64);
7751       emit_block_move (dst, src, GEN_INT (fixed_len), BLOCK_OP_NORMAL);
7752
7753       emit_move_insn (gen_rtx_MEM (Pmode, plus_constant (tramp, fixed_len)),
7754                       fnaddr);
7755       emit_move_insn (gen_rtx_MEM (Pmode,
7756                                    plus_constant (tramp,
7757                                                   fixed_len
7758                                                   + GET_MODE_SIZE (Pmode))), 
7759                       cxt);
7760       emit_insn (gen_ic_invalidate_line (tramp));
7761       return;
7762     }
7763   else if (TARGET_SHMEDIA)
7764     {
7765       /* movi fnaddr >> 16,r1; shori fnaddr,r1; ptabs/l r1,tr0
7766          movi cxt >> 16,r1; shori cxt,r1; blink tr0,r63  */
7767       rtx quad0 = gen_reg_rtx (DImode), cxtload = gen_reg_rtx (DImode);
7768       rtx quad1 = gen_reg_rtx (DImode), quad2 = gen_reg_rtx (DImode);
7769       /* movi 0,r1: 0xcc000010 shori 0,r1: c8000010  concatenated,
7770          rotated 10 right, and higher 16 bit of every 32 selected.  */
7771       rtx movishori
7772         = force_reg (V2HImode, (simplify_gen_subreg
7773                                 (V2HImode, GEN_INT (0x4330432), SImode, 0)));
7774       rtx ptabs = force_reg (DImode, GEN_INT (0x6bf10600));
7775       rtx blink = force_reg (DImode, GEN_INT (0x4401fff0));
7776
7777       tramp = force_reg (Pmode, tramp);
7778       fnaddr = force_reg (SImode, fnaddr);
7779       cxt = force_reg (SImode, cxt);
7780       emit_insn (gen_mshflo_w_x (gen_rtx_SUBREG (V4HImode, quad0, 0),
7781                                  gen_rtx_SUBREG (V2HImode, fnaddr, 0),
7782                                  movishori));
7783       emit_insn (gen_rotrdi3_mextr (quad0, quad0,
7784                                     GEN_INT (TARGET_LITTLE_ENDIAN ? 24 : 56)));
7785       emit_insn (gen_ashldi3_media (quad0, quad0, GEN_INT (2)));
7786       emit_move_insn (gen_rtx_MEM (DImode, tramp), quad0);
7787       emit_insn (gen_mshflo_w_x (gen_rtx_SUBREG (V4HImode, cxtload, 0),
7788                                  gen_rtx_SUBREG (V2HImode, cxt, 0),
7789                                  movishori));
7790       emit_insn (gen_rotrdi3_mextr (cxtload, cxtload,
7791                                     GEN_INT (TARGET_LITTLE_ENDIAN ? 24 : 56)));
7792       emit_insn (gen_ashldi3_media (cxtload, cxtload, GEN_INT (2)));
7793       if (TARGET_LITTLE_ENDIAN)
7794         {
7795           emit_insn (gen_mshflo_l_di (quad1, ptabs, cxtload));
7796           emit_insn (gen_mextr4 (quad2, cxtload, blink));
7797         }
7798       else
7799         {
7800           emit_insn (gen_mextr4 (quad1, cxtload, ptabs));
7801           emit_insn (gen_mshflo_l_di (quad2, blink, cxtload));
7802         }
7803       emit_move_insn (gen_rtx_MEM (DImode, plus_constant (tramp, 8)), quad1);
7804       emit_move_insn (gen_rtx_MEM (DImode, plus_constant (tramp, 16)), quad2);
7805       emit_insn (gen_ic_invalidate_line (tramp));
7806       return;
7807     }
7808   else if (TARGET_SHCOMPACT)
7809     {
7810       emit_insn (gen_initialize_trampoline (tramp, cxt, fnaddr));
7811       return;
7812     }
7813   emit_move_insn (gen_rtx_MEM (SImode, tramp),
7814                   gen_int_mode (TARGET_LITTLE_ENDIAN ? 0xd301d202 : 0xd202d301,
7815                                 SImode));
7816   emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 4)),
7817                   gen_int_mode (TARGET_LITTLE_ENDIAN ? 0x0009422b : 0x422b0009,
7818                                 SImode));
7819   emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 8)),
7820                   cxt);
7821   emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 12)),
7822                   fnaddr);
7823   if (TARGET_HARVARD)
7824     {
7825       if (TARGET_USERMODE)
7826         emit_library_call (gen_rtx_SYMBOL_REF (Pmode, "__ic_invalidate"),
7827                            0, VOIDmode, 1, tramp, SImode);
7828       else
7829         emit_insn (gen_ic_invalidate_line (tramp));
7830     }
7831 }
7832
7833 /* FIXME: This is overly conservative.  A SHcompact function that
7834    receives arguments ``by reference'' will have them stored in its
7835    own stack frame, so it must not pass pointers or references to
7836    these arguments to other functions by means of sibling calls.  */
7837 static bool
7838 sh_function_ok_for_sibcall (decl, exp)
7839      tree decl;
7840      tree exp ATTRIBUTE_UNUSED;
7841 {
7842   return (decl 
7843           && (! TARGET_SHCOMPACT
7844               || current_function_args_info.stack_regs == 0)
7845           && ! sh_cfun_interrupt_handler_p ());
7846 }
7847 \f
7848 /* Machine specific built-in functions.  */
7849
7850 struct builtin_description
7851 {
7852   const enum insn_code icode;
7853   const char *const name;
7854   int signature;
7855 };
7856
7857 /* describe number and signedness of arguments; arg[0] == result
7858    (1: unsigned, 2: signed, 4: don't care, 8: pointer 0: no argument */
7859 static const char signature_args[][4] =
7860 {
7861 #define SH_BLTIN_V2SI2 0
7862   { 4, 4 },
7863 #define SH_BLTIN_V4HI2 1
7864   { 4, 4 },
7865 #define SH_BLTIN_V2SI3 2
7866   { 4, 4, 4 },
7867 #define SH_BLTIN_V4HI3 3
7868   { 4, 4, 4 },
7869 #define SH_BLTIN_V8QI3 4
7870   { 4, 4, 4 },
7871 #define SH_BLTIN_MAC_HISI 5
7872   { 1, 4, 4, 1 },
7873 #define SH_BLTIN_SH_HI 6
7874   { 4, 4, 1 },
7875 #define SH_BLTIN_SH_SI 7
7876   { 4, 4, 1 },
7877 #define SH_BLTIN_V4HI2V2SI 8
7878   { 4, 4, 4 },
7879 #define SH_BLTIN_V4HI2V8QI 9
7880   { 4, 4, 4 },
7881 #define SH_BLTIN_SISF 10
7882   { 4, 2 },
7883 #define SH_BLTIN_LDUA_L 11
7884   { 2, 8 },
7885 #define SH_BLTIN_LDUA_Q 12
7886   { 1, 8 },
7887 #define SH_BLTIN_STUA_L 13
7888   { 0, 8, 2 },
7889 #define SH_BLTIN_STUA_Q 14
7890   { 0, 8, 1 },
7891 #define SH_BLTIN_UDI 15
7892   { 0, 8, 1 },
7893 #define SH_BLTIN_NUM_SHARED_SIGNATURES 16
7894 #define SH_BLTIN_2 16
7895 #define SH_BLTIN_SU 16
7896   { 1, 2 },
7897 #define SH_BLTIN_3 17
7898 #define SH_BLTIN_SUS 17
7899   { 2, 2, 1 },
7900 #define SH_BLTIN_PSSV 18
7901   { 0, 8, 2, 2 },
7902 #define SH_BLTIN_XXUU 19
7903 #define SH_BLTIN_UUUU 19
7904   { 1, 1, 1, 1 },
7905 #define SH_BLTIN_PV 20
7906   { 0, 8 },
7907 };
7908 /* mcmv: operands considered unsigned. */
7909 /* mmulsum_wq, msad_ubq: result considered unsigned long long.  */
7910 /* mperm: control value considered unsigned int. */
7911 /* mshalds, mshard, mshards, mshlld, mshlrd: shift count is unsigned int. */
7912 /* mshards_q: returns signed short.  */
7913 /* nsb: takes long long arg, returns unsigned char.  */
7914 static const struct builtin_description bdesc[] =
7915 {
7916   { CODE_FOR_absv2si2,  "__builtin_absv2si2", SH_BLTIN_V2SI2 },
7917   { CODE_FOR_absv4hi2,  "__builtin_absv4hi2", SH_BLTIN_V4HI2 },
7918   { CODE_FOR_addv2si3,  "__builtin_addv2si3", SH_BLTIN_V2SI3 },
7919   { CODE_FOR_addv4hi3,  "__builtin_addv4hi3", SH_BLTIN_V4HI3 },
7920   { CODE_FOR_ssaddv2si3,"__builtin_ssaddv2si3", SH_BLTIN_V2SI3 },
7921   { CODE_FOR_usaddv8qi3,"__builtin_usaddv8qi3", SH_BLTIN_V8QI3 },
7922   { CODE_FOR_ssaddv4hi3,"__builtin_ssaddv4hi3", SH_BLTIN_V4HI3 },
7923 #if 0
7924   { CODE_FOR_alloco32,  "__builtin_sh_media_ALLOCO", SH_BLTIN_PV },
7925   { CODE_FOR_alloco64,  "__builtin_sh_media_ALLOCO", SH_BLTIN_PV },
7926 #endif
7927   { CODE_FOR_negcmpeqv8qi,"__builtin_sh_media_MCMPEQ_B", SH_BLTIN_V8QI3 },
7928   { CODE_FOR_negcmpeqv2si,"__builtin_sh_media_MCMPEQ_L", SH_BLTIN_V2SI3 },
7929   { CODE_FOR_negcmpeqv4hi,"__builtin_sh_media_MCMPEQ_W", SH_BLTIN_V4HI3 },
7930   { CODE_FOR_negcmpgtuv8qi,"__builtin_sh_media_MCMPGT_UB", SH_BLTIN_V8QI3 },
7931   { CODE_FOR_negcmpgtv2si,"__builtin_sh_media_MCMPGT_L", SH_BLTIN_V2SI3 },
7932   { CODE_FOR_negcmpgtv4hi,"__builtin_sh_media_MCMPGT_W", SH_BLTIN_V4HI3 },
7933   { CODE_FOR_mcmv,      "__builtin_sh_media_MCMV", SH_BLTIN_UUUU },
7934   { CODE_FOR_mcnvs_lw,  "__builtin_sh_media_MCNVS_LW", SH_BLTIN_3 },
7935   { CODE_FOR_mcnvs_wb,  "__builtin_sh_media_MCNVS_WB", SH_BLTIN_V4HI2V8QI },
7936   { CODE_FOR_mcnvs_wub, "__builtin_sh_media_MCNVS_WUB", SH_BLTIN_V4HI2V8QI },
7937   { CODE_FOR_mextr1,    "__builtin_sh_media_MEXTR1", SH_BLTIN_UDI },
7938   { CODE_FOR_mextr2,    "__builtin_sh_media_MEXTR2", SH_BLTIN_UDI },
7939   { CODE_FOR_mextr3,    "__builtin_sh_media_MEXTR3", SH_BLTIN_UDI },
7940   { CODE_FOR_mextr4,    "__builtin_sh_media_MEXTR4", SH_BLTIN_UDI },
7941   { CODE_FOR_mextr5,    "__builtin_sh_media_MEXTR5", SH_BLTIN_UDI },
7942   { CODE_FOR_mextr6,    "__builtin_sh_media_MEXTR6", SH_BLTIN_UDI },
7943   { CODE_FOR_mextr7,    "__builtin_sh_media_MEXTR7", SH_BLTIN_UDI },
7944   { CODE_FOR_mmacfx_wl, "__builtin_sh_media_MMACFX_WL", SH_BLTIN_MAC_HISI },
7945   { CODE_FOR_mmacnfx_wl,"__builtin_sh_media_MMACNFX_WL", SH_BLTIN_MAC_HISI },
7946   { CODE_FOR_mulv2si3,  "__builtin_mulv2si3", SH_BLTIN_V2SI3, },
7947   { CODE_FOR_mulv4hi3,  "__builtin_mulv4hi3", SH_BLTIN_V4HI3 },
7948   { CODE_FOR_mmulfx_l,  "__builtin_sh_media_MMULFX_L", SH_BLTIN_V2SI3 },
7949   { CODE_FOR_mmulfx_w,  "__builtin_sh_media_MMULFX_W", SH_BLTIN_V4HI3 },
7950   { CODE_FOR_mmulfxrp_w,"__builtin_sh_media_MMULFXRP_W", SH_BLTIN_V4HI3 },
7951   { CODE_FOR_mmulhi_wl, "__builtin_sh_media_MMULHI_WL", SH_BLTIN_V4HI2V2SI },
7952   { CODE_FOR_mmullo_wl, "__builtin_sh_media_MMULLO_WL", SH_BLTIN_V4HI2V2SI },
7953   { CODE_FOR_mmulsum_wq,"__builtin_sh_media_MMULSUM_WQ", SH_BLTIN_XXUU },
7954   { CODE_FOR_mperm_w,   "__builtin_sh_media_MPERM_W", SH_BLTIN_SH_HI },
7955   { CODE_FOR_msad_ubq,  "__builtin_sh_media_MSAD_UBQ", SH_BLTIN_XXUU },
7956   { CODE_FOR_mshalds_l, "__builtin_sh_media_MSHALDS_L", SH_BLTIN_SH_SI },
7957   { CODE_FOR_mshalds_w, "__builtin_sh_media_MSHALDS_W", SH_BLTIN_SH_HI },
7958   { CODE_FOR_ashrv2si3, "__builtin_ashrv2si3", SH_BLTIN_SH_SI },
7959   { CODE_FOR_ashrv4hi3, "__builtin_ashrv4hi3", SH_BLTIN_SH_HI },
7960   { CODE_FOR_mshards_q, "__builtin_sh_media_MSHARDS_Q", SH_BLTIN_SUS },
7961   { CODE_FOR_mshfhi_b,  "__builtin_sh_media_MSHFHI_B", SH_BLTIN_V8QI3 },
7962   { CODE_FOR_mshfhi_l,  "__builtin_sh_media_MSHFHI_L", SH_BLTIN_V2SI3 },
7963   { CODE_FOR_mshfhi_w,  "__builtin_sh_media_MSHFHI_W", SH_BLTIN_V4HI3 },
7964   { CODE_FOR_mshflo_b,  "__builtin_sh_media_MSHFLO_B", SH_BLTIN_V8QI3 },
7965   { CODE_FOR_mshflo_l,  "__builtin_sh_media_MSHFLO_L", SH_BLTIN_V2SI3 },
7966   { CODE_FOR_mshflo_w,  "__builtin_sh_media_MSHFLO_W", SH_BLTIN_V4HI3 },
7967   { CODE_FOR_ashlv2si3, "__builtin_ashlv2si3", SH_BLTIN_SH_SI },
7968   { CODE_FOR_ashlv4hi3, "__builtin_ashlv4hi3", SH_BLTIN_SH_HI },
7969   { CODE_FOR_lshrv2si3, "__builtin_lshrv2si3", SH_BLTIN_SH_SI },
7970   { CODE_FOR_lshrv4hi3, "__builtin_lshrv4hi3", SH_BLTIN_SH_HI },
7971   { CODE_FOR_subv2si3,  "__builtin_subv2si3", SH_BLTIN_V2SI3 },
7972   { CODE_FOR_subv4hi3,  "__builtin_subv4hi3", SH_BLTIN_V4HI3 },
7973   { CODE_FOR_sssubv2si3,"__builtin_sssubv2si3", SH_BLTIN_V2SI3 },
7974   { CODE_FOR_ussubv8qi3,"__builtin_ussubv8qi3", SH_BLTIN_V8QI3 },
7975   { CODE_FOR_sssubv4hi3,"__builtin_sssubv4hi3", SH_BLTIN_V4HI3 },
7976   { CODE_FOR_fcosa_s,   "__builtin_sh_media_FCOSA_S", SH_BLTIN_SISF },
7977   { CODE_FOR_fsina_s,   "__builtin_sh_media_FSINA_S", SH_BLTIN_SISF },
7978   { CODE_FOR_fipr,      "__builtin_sh_media_FIPR_S", SH_BLTIN_3 },
7979   { CODE_FOR_ftrv,      "__builtin_sh_media_FTRV_S", SH_BLTIN_3 },
7980   { CODE_FOR_fsrra_s,   "__builtin_sh_media_FSRRA_S", SH_BLTIN_2 },
7981 #if 0
7982   { CODE_FOR_ldhi_l,    "__builtin_sh_media_LDHI_L", SH_BLTIN_LDUA_L },
7983   { CODE_FOR_ldhi_q,    "__builtin_sh_media_LDHI_Q", SH_BLTIN_LDUA_Q },
7984   { CODE_FOR_ldlo_l,    "__builtin_sh_media_LDLO_L", SH_BLTIN_LDUA_L },
7985   { CODE_FOR_ldlo_q,    "__builtin_sh_media_LDLO_Q", SH_BLTIN_LDUA_Q },
7986   { CODE_FOR_sthi_l,    "__builtin_sh_media_STHI_L", SH_BLTIN_STUA_L },
7987   { CODE_FOR_sthi_q,    "__builtin_sh_media_STHI_Q", SH_BLTIN_STUA_Q },
7988   { CODE_FOR_stlo_l,    "__builtin_sh_media_STLO_L", SH_BLTIN_STUA_L },
7989   { CODE_FOR_stlo_q,    "__builtin_sh_media_STLO_Q", SH_BLTIN_STUA_Q },
7990   { CODE_FOR_ldhi_l64,  "__builtin_sh_media_LDHI_L", SH_BLTIN_LDUA_L },
7991   { CODE_FOR_ldhi_q64,  "__builtin_sh_media_LDHI_Q", SH_BLTIN_LDUA_Q },
7992   { CODE_FOR_ldlo_l64,  "__builtin_sh_media_LDLO_L", SH_BLTIN_LDUA_L },
7993   { CODE_FOR_ldlo_q64,  "__builtin_sh_media_LDLO_Q", SH_BLTIN_LDUA_Q },
7994   { CODE_FOR_sthi_l64,  "__builtin_sh_media_STHI_L", SH_BLTIN_STUA_L },
7995   { CODE_FOR_sthi_q64,  "__builtin_sh_media_STHI_Q", SH_BLTIN_STUA_Q },
7996   { CODE_FOR_stlo_l64,  "__builtin_sh_media_STLO_L", SH_BLTIN_STUA_L },
7997   { CODE_FOR_stlo_q64,  "__builtin_sh_media_STLO_Q", SH_BLTIN_STUA_Q },
7998 #endif
7999   { CODE_FOR_nsb,       "__builtin_sh_media_NSB", SH_BLTIN_SU },
8000   { CODE_FOR_byterev,   "__builtin_sh_media_BYTEREV", SH_BLTIN_2 },
8001 #if 0
8002   { CODE_FOR_prefetch32,"__builtin_sh_media_PREFO", SH_BLTIN_PSSV },
8003   { CODE_FOR_prefetch64,"__builtin_sh_media_PREFO", SH_BLTIN_PSSV }
8004 #endif
8005 };
8006
8007 static void
8008 sh_media_init_builtins ()
8009 {
8010   tree shared[SH_BLTIN_NUM_SHARED_SIGNATURES];
8011   const struct builtin_description *d;
8012
8013   memset (shared, 0, sizeof shared);
8014   for (d = bdesc; d - bdesc < (int) (sizeof bdesc / sizeof bdesc[0]); d++)
8015     {
8016       tree type, arg_type;
8017       int signature = d->signature;
8018       int i;
8019
8020       if (signature < SH_BLTIN_NUM_SHARED_SIGNATURES && shared[signature])
8021         type = shared[signature];
8022       else
8023         {
8024           int has_result = signature_args[signature][0] != 0;
8025
8026           if (signature_args[signature][1] == 8
8027               && (insn_data[d->icode].operand[has_result].mode != Pmode))
8028             continue;
8029           if (! TARGET_FPU_ANY
8030               && FLOAT_MODE_P (insn_data[d->icode].operand[0].mode))
8031             continue;
8032           type = void_list_node;
8033           for (i = 3; ; i--)
8034             {
8035               int arg = signature_args[signature][i];
8036               int opno = i - 1 + has_result;
8037
8038               if (arg == 8)
8039                 arg_type = ptr_type_node;
8040               else if (arg)
8041                 arg_type = ((*lang_hooks.types.type_for_mode)
8042                             (insn_data[d->icode].operand[opno].mode,
8043                              (arg & 1)));
8044               else if (i)
8045                 continue;
8046               else
8047                 arg_type = void_type_node;
8048               if (i == 0)
8049                 break;
8050               type = tree_cons (NULL_TREE, arg_type, type);
8051             }
8052           type = build_function_type (arg_type, type);
8053           if (signature < SH_BLTIN_NUM_SHARED_SIGNATURES)
8054             shared[signature] = type;
8055         }
8056       builtin_function (d->name, type, d - bdesc, BUILT_IN_MD,
8057                         NULL, NULL_TREE);
8058     }
8059 }
8060
8061 static void
8062 sh_init_builtins ()
8063 {
8064   if (TARGET_SHMEDIA)
8065     sh_media_init_builtins ();
8066 }
8067
8068 /* Expand an expression EXP that calls a built-in function,
8069    with result going to TARGET if that's convenient
8070    (and in mode MODE if that's convenient).
8071    SUBTARGET may be used as the target for computing one of EXP's operands.
8072    IGNORE is nonzero if the value is to be ignored.  */
8073
8074 static rtx
8075 sh_expand_builtin (exp, target, subtarget, mode, ignore)
8076      tree exp;
8077      rtx target;
8078      rtx subtarget ATTRIBUTE_UNUSED;
8079      enum machine_mode mode ATTRIBUTE_UNUSED;
8080      int ignore;
8081 {
8082   tree fndecl = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
8083   tree arglist = TREE_OPERAND (exp, 1);
8084   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
8085   const struct builtin_description *d = &bdesc[fcode];
8086   enum insn_code icode = d->icode;
8087   int signature = d->signature;
8088   enum machine_mode tmode = VOIDmode;
8089   int nop = 0, i;
8090   rtx op[4];
8091   rtx pat;
8092
8093   if (signature_args[signature][0])
8094     {
8095       if (ignore)
8096         return 0;
8097
8098       tmode = insn_data[icode].operand[0].mode;
8099       if (! target
8100           || GET_MODE (target) != tmode
8101           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
8102         target = gen_reg_rtx (tmode);
8103       op[nop++] = target;
8104     }
8105   else
8106     target = 0;
8107
8108   for (i = 1; i <= 3; i++, nop++)
8109     {
8110       tree arg;
8111       enum machine_mode opmode, argmode;
8112
8113       if (! signature_args[signature][i])
8114         break;
8115       arg = TREE_VALUE (arglist);
8116       if (arg == error_mark_node)
8117         return const0_rtx;
8118       arglist = TREE_CHAIN (arglist);
8119       opmode = insn_data[icode].operand[nop].mode;
8120       argmode = TYPE_MODE (TREE_TYPE (arg));
8121       if (argmode != opmode)
8122         arg = build1 (NOP_EXPR,
8123                       (*lang_hooks.types.type_for_mode) (opmode, 0), arg);
8124       op[nop] = expand_expr (arg, NULL_RTX, opmode, 0);
8125       if (! (*insn_data[icode].operand[nop].predicate) (op[nop], opmode))
8126         op[nop] = copy_to_mode_reg (opmode, op[nop]);
8127     }
8128
8129   switch (nop)
8130     {
8131     case 1:
8132       pat = (*insn_data[d->icode].genfun) (op[0]);
8133       break;
8134     case 2:
8135       pat = (*insn_data[d->icode].genfun) (op[0], op[1]);
8136       break;
8137     case 3:
8138       pat = (*insn_data[d->icode].genfun) (op[0], op[1], op[2]);
8139       break;
8140     case 4:
8141       pat = (*insn_data[d->icode].genfun) (op[0], op[1], op[2], op[3]);
8142       break;
8143     default:
8144       abort ();
8145     }
8146   if (! pat)
8147     return 0;
8148   emit_insn (pat);
8149   return target;
8150 }
8151
8152 void
8153 sh_expand_unop_v2sf (code, op0, op1)
8154      enum rtx_code code;
8155      rtx op0, op1;
8156 {
8157   rtx sel0 = const0_rtx;
8158   rtx sel1 = const1_rtx;
8159   rtx (*fn) PARAMS ((rtx, rtx, rtx, rtx, rtx)) = gen_unary_sf_op;
8160   rtx op = gen_rtx_fmt_e (code, SFmode, op1);
8161
8162   emit_insn ((*fn) (op0, op1, op, sel0, sel0));
8163   emit_insn ((*fn) (op0, op1, op, sel1, sel1));
8164 }
8165
8166 void
8167 sh_expand_binop_v2sf (code, op0, op1, op2)
8168      enum rtx_code code;
8169      rtx op0, op1, op2;
8170 {
8171   rtx sel0 = const0_rtx;
8172   rtx sel1 = const1_rtx;
8173   rtx (*fn) PARAMS ((rtx, rtx, rtx, rtx, rtx, rtx, rtx, rtx))
8174     = gen_binary_sf_op;
8175   rtx op = gen_rtx_fmt_ee (code, SFmode, op1, op2);
8176
8177   emit_insn ((*fn) (op0, op1, op2, op, sel0, sel0, sel0, sel1));
8178   emit_insn ((*fn) (op0, op1, op2, op, sel1, sel1, sel1, sel0));
8179 }
8180
8181 /* Return the class of registers for which a mode change from FROM to TO
8182    is invalid.  */
8183 bool
8184 sh_cannot_change_mode_class (from, to, class)
8185      enum machine_mode from, to;
8186      enum reg_class class;
8187 {
8188   if (GET_MODE_SIZE (from) != GET_MODE_SIZE (to))
8189     {
8190        if (TARGET_LITTLE_ENDIAN)
8191          {
8192            if (GET_MODE_SIZE (to) < 8 || GET_MODE_SIZE (from) < 8)
8193              return reg_classes_intersect_p (DF_REGS, class);
8194          }
8195        else
8196          {
8197            if (GET_MODE_SIZE (from) < 8)
8198              return reg_classes_intersect_p (DF_HI_REGS, class);
8199          }
8200     }
8201   return 0;
8202 }
8203
8204
8205 /* If ADDRESS refers to a CODE_LABEL, add NUSES to the number of times
8206    that label is used.  */
8207
8208 void
8209 sh_mark_label (address, nuses)
8210      rtx address;
8211      int nuses;
8212 {
8213   if (GOTOFF_P (address))
8214     {
8215       /* Extract the label or symbol.  */
8216       address = XEXP (address, 0);
8217       if (GET_CODE (address) == PLUS)
8218         address = XEXP (address, 0);
8219       address = XVECEXP (address, 0, 0);
8220     }
8221   if (GET_CODE (address) == LABEL_REF
8222       && GET_CODE (XEXP (address, 0)) == CODE_LABEL)
8223     LABEL_NUSES (XEXP (address, 0)) += nuses;
8224 }
8225
8226 /* Compute extra cost of moving data between one register class
8227    and another.  */
8228
8229 /* If SECONDARY*_RELOAD_CLASS says something about the src/dst pair, regclass
8230    uses this information.  Hence, the general register <-> floating point
8231    register information here is not used for SFmode.  */
8232
8233 int
8234 sh_register_move_cost (mode, srcclass, dstclass)
8235      enum machine_mode mode;
8236      enum reg_class srcclass, dstclass;
8237 {
8238   if (dstclass == T_REGS || dstclass == PR_REGS)
8239     return 10;
8240
8241   if (mode == SImode && ! TARGET_SHMEDIA && TARGET_FMOVD
8242       && REGCLASS_HAS_FP_REG (srcclass)
8243       && REGCLASS_HAS_FP_REG (dstclass))
8244     return 4;
8245
8246   if ((REGCLASS_HAS_FP_REG (dstclass) && srcclass == MAC_REGS)
8247       || (dstclass== MAC_REGS && REGCLASS_HAS_FP_REG (srcclass)))
8248     return 9;
8249
8250   if ((REGCLASS_HAS_FP_REG (dstclass)
8251        && REGCLASS_HAS_GENERAL_REG (srcclass))
8252       || (REGCLASS_HAS_GENERAL_REG (dstclass)
8253           && REGCLASS_HAS_FP_REG (srcclass)))
8254    return ((TARGET_SHMEDIA ? 4 : TARGET_FMOVD ? 8 : 12)
8255            * ((GET_MODE_SIZE (mode) + 7) / 8U));
8256
8257   if ((dstclass == FPUL_REGS
8258        && REGCLASS_HAS_GENERAL_REG (srcclass))
8259       || (srcclass == FPUL_REGS
8260           && REGCLASS_HAS_GENERAL_REG (dstclass)))
8261     return 5;
8262
8263   if ((dstclass == FPUL_REGS
8264        && (srcclass == PR_REGS || srcclass == MAC_REGS || srcclass == T_REGS))
8265       || (srcclass == FPUL_REGS         
8266           && (dstclass == PR_REGS || dstclass == MAC_REGS)))
8267     return 7;
8268
8269   if ((srcclass == TARGET_REGS && ! REGCLASS_HAS_GENERAL_REG (dstclass))
8270       || ((dstclass) == TARGET_REGS && ! REGCLASS_HAS_GENERAL_REG (srcclass)))
8271     return 20;
8272
8273   if ((srcclass == FPSCR_REGS && ! REGCLASS_HAS_GENERAL_REG (dstclass))
8274       || (dstclass == FPSCR_REGS && ! REGCLASS_HAS_GENERAL_REG (srcclass)))
8275   return 4;
8276
8277   if (TARGET_SHMEDIA
8278       || (TARGET_FMOVD
8279           && ! REGCLASS_HAS_GENERAL_REG (srcclass)
8280           && ! REGCLASS_HAS_GENERAL_REG (dstclass)))
8281     return 2 * ((GET_MODE_SIZE (mode) + 7) / 8U);
8282
8283   return 2 * ((GET_MODE_SIZE (mode) + 3) / 4U);
8284 }
8285
8286 /* Like register_operand, but take into account that SHMEDIA can use
8287    the constant zero like a general register.  */
8288 int
8289 sh_register_operand (op, mode)
8290      rtx op;
8291      enum machine_mode mode;
8292 {
8293   if (op == CONST0_RTX (mode) && TARGET_SHMEDIA)
8294     return 1;
8295   return register_operand (op, mode);
8296 }
8297
8298 static rtx emit_load_ptr PARAMS ((rtx, rtx));
8299
8300 static rtx
8301 emit_load_ptr (reg, addr)
8302      rtx reg, addr;
8303 {
8304   rtx mem = gen_rtx_MEM (ptr_mode, addr);
8305
8306   if (Pmode != ptr_mode)
8307     mem = gen_rtx_SIGN_EXTEND (Pmode, mem);
8308   return emit_move_insn (reg, mem);
8309 }
8310
8311 void
8312 sh_output_mi_thunk (file, thunk_fndecl, delta, vcall_offset, function)
8313      FILE *file;
8314      tree thunk_fndecl ATTRIBUTE_UNUSED;
8315      HOST_WIDE_INT delta;
8316      HOST_WIDE_INT vcall_offset;
8317      tree function;
8318 {
8319   CUMULATIVE_ARGS cum;
8320   int structure_value_byref = 0;
8321   rtx this, this_value, sibcall, insns, funexp;
8322   tree funtype = TREE_TYPE (function);
8323   int simple_add
8324     = (TARGET_SHMEDIA ? CONST_OK_FOR_J (delta) : CONST_OK_FOR_I (delta));
8325   int did_load = 0;
8326   rtx scratch0, scratch1, scratch2;
8327
8328   insn_locators_initialize ();
8329   reload_completed = 1;
8330   no_new_pseudos = 1;
8331   current_function_uses_only_leaf_regs = 1;
8332
8333   emit_note (NULL, NOTE_INSN_PROLOGUE_END);
8334
8335   /* Find the "this" pointer.  We have such a wide range of ABIs for the
8336      SH that it's best to do this completely machine independently.
8337      "this" is passed as first argument, unless a structure return pointer 
8338      comes first, in which case "this" comes second.  */
8339   INIT_CUMULATIVE_ARGS (cum, funtype, NULL_RTX, 0);
8340 #ifndef PCC_STATIC_STRUCT_RETURN
8341   if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function))))
8342     structure_value_byref = 1;
8343 #endif /* not PCC_STATIC_STRUCT_RETURN */
8344   if (structure_value_byref && struct_value_rtx == 0)
8345     { 
8346       tree ptype = build_pointer_type (TREE_TYPE (funtype));
8347
8348       FUNCTION_ARG_ADVANCE (cum, Pmode, ptype, 1);
8349     }
8350   this = FUNCTION_ARG (cum, Pmode, ptr_type_node, 1);
8351
8352   /* For SHcompact, we only have r0 for a scratch register: r1 is the
8353      static chain pointer (even if you can't have nested virtual functions
8354      right now, someone might implement them sometime), and the rest of the
8355      registers are used for argument passing, are callee-saved, or reserved.  */
8356   scratch0 = scratch1 = scratch2 = gen_rtx_REG (Pmode, 0);
8357   if (! TARGET_SH5)
8358     {
8359       scratch1 = gen_rtx_REG (ptr_mode, 1);
8360       /* N.B., if not TARGET_HITACHI, register 2 is used to pass the pointer
8361          pointing where to return struct values.  */
8362       scratch2 = gen_rtx_REG (Pmode, 3);
8363     }
8364   else if (TARGET_SHMEDIA)
8365     {
8366       scratch1 = gen_rtx_REG (ptr_mode, 21);
8367       scratch2 = gen_rtx_REG (Pmode, TR0_REG);
8368     }
8369
8370   this_value = plus_constant (this, delta);
8371   if (vcall_offset
8372       && (simple_add || scratch0 != scratch1)
8373       && strict_memory_address_p (ptr_mode, this_value))
8374     {
8375       emit_load_ptr (scratch0, this_value);
8376       did_load = 1;
8377     }
8378
8379   if (!delta)
8380     ; /* Do nothing.  */
8381   else if (simple_add)
8382     emit_move_insn (this, this_value);
8383   else
8384     {
8385       emit_move_insn (scratch1, GEN_INT (delta));
8386       emit_insn (gen_add2_insn (this, scratch1));
8387     }
8388
8389   if (vcall_offset)
8390     {
8391       rtx offset_addr;
8392
8393       if (!did_load)
8394         emit_load_ptr (scratch0, this);
8395
8396       offset_addr = plus_constant (scratch0, vcall_offset);
8397       if (strict_memory_address_p (ptr_mode, offset_addr))
8398         ; /* Do nothing.  */
8399       else if (! TARGET_SH5)
8400         {
8401           /* scratch0 != scratch1, and we have indexed loads.  Get better
8402              schedule by loading the offset into r1 and using an indexed
8403              load - then the load of r1 can issue before the load from
8404              (this + delta) finishes.  */
8405           emit_move_insn (scratch1, GEN_INT (vcall_offset));
8406           offset_addr = gen_rtx_PLUS (Pmode, scratch0, scratch1);
8407         }
8408       else if (TARGET_SHMEDIA
8409                ? CONST_OK_FOR_J (vcall_offset)
8410                : CONST_OK_FOR_I (vcall_offset))
8411         {
8412           emit_insn (gen_add2_insn (scratch0, GEN_INT (vcall_offset)));
8413           offset_addr = scratch0;
8414         }
8415       else if (scratch0 != scratch1)
8416         {
8417           emit_move_insn (scratch1, GEN_INT (vcall_offset));
8418           emit_insn (gen_add2_insn (scratch0, scratch1));
8419           offset_addr = scratch0;
8420         }
8421       else
8422         abort (); /* FIXME */
8423       emit_load_ptr (scratch0, offset_addr);
8424
8425      if (Pmode != ptr_mode)
8426         scratch0 = gen_rtx_TRUNCATE (ptr_mode, scratch0);
8427       emit_insn (gen_add2_insn (this, scratch0));
8428     }
8429
8430   /* Generate a tail call to the target function.  */
8431   if (! TREE_USED (function))
8432     {
8433       assemble_external (function);
8434       TREE_USED (function) = 1;
8435     }
8436   funexp = XEXP (DECL_RTL (function), 0);
8437   emit_move_insn (scratch2, funexp);
8438   funexp = gen_rtx_MEM (FUNCTION_MODE, scratch2);
8439   sibcall = emit_call_insn (gen_sibcall (funexp, const0_rtx, NULL_RTX));
8440   SIBLING_CALL_P (sibcall) = 1;
8441   use_reg (&CALL_INSN_FUNCTION_USAGE (sibcall), this);
8442   emit_barrier ();
8443
8444     /* Run just enough of rest_of_compilation to do scheduling and get
8445      the insns emitted.  Note that use_thunk calls
8446      assemble_start_function and assemble_end_function.  */
8447   insns = get_insns ();
8448
8449   if (optimize > 0 && flag_schedule_insns_after_reload)
8450     {
8451
8452       find_basic_blocks (insns, max_reg_num (), rtl_dump_file);
8453       life_analysis (insns, rtl_dump_file, PROP_FINAL);
8454
8455       split_all_insns (1);
8456
8457       schedule_insns (rtl_dump_file);
8458     }
8459
8460   sh_reorg ();
8461
8462   if (optimize > 0 && flag_delayed_branch)
8463       dbr_schedule (insns, rtl_dump_file);
8464   shorten_branches (insns);
8465   final_start_function (insns, file, 1);
8466   final (insns, file, 1, 0);
8467   final_end_function ();
8468
8469   if (optimize > 0 && flag_schedule_insns_after_reload)
8470     {
8471       /* Release all memory allocated by flow.  */
8472       free_basic_block_vars (0);
8473
8474       /* Release all memory held by regsets now.  */
8475       regset_release_memory ();
8476     }
8477
8478   reload_completed = 0;
8479   no_new_pseudos = 0;
8480 }
8481
8482 #include "gt-sh.h"