OSDN Git Service

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