OSDN Git Service

2003-04-24 H.J. Lu <hjl@gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / config / ia64 / ia64.c
1 /* Definitions of target machine for GNU compiler.
2    Copyright (C) 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
3    Contributed by James E. Wilson <wilson@cygnus.com> and
4                   David Mosberger <davidm@hpl.hp.com>.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to
20 the Free Software Foundation, 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "regs.h"
30 #include "hard-reg-set.h"
31 #include "real.h"
32 #include "insn-config.h"
33 #include "conditions.h"
34 #include "output.h"
35 #include "insn-attr.h"
36 #include "flags.h"
37 #include "recog.h"
38 #include "expr.h"
39 #include "optabs.h"
40 #include "except.h"
41 #include "function.h"
42 #include "ggc.h"
43 #include "basic-block.h"
44 #include "toplev.h"
45 #include "sched-int.h"
46 #include "timevar.h"
47 #include "target.h"
48 #include "target-def.h"
49 #include "tm_p.h"
50 #include "hashtab.h"
51 #include "langhooks.h"
52
53 /* This is used for communication between ASM_OUTPUT_LABEL and
54    ASM_OUTPUT_LABELREF.  */
55 int ia64_asm_output_label = 0;
56
57 /* Define the information needed to generate branch and scc insns.  This is
58    stored from the compare operation.  */
59 struct rtx_def * ia64_compare_op0;
60 struct rtx_def * ia64_compare_op1;
61
62 /* Register names for ia64_expand_prologue.  */
63 static const char * const ia64_reg_numbers[96] =
64 { "r32", "r33", "r34", "r35", "r36", "r37", "r38", "r39",
65   "r40", "r41", "r42", "r43", "r44", "r45", "r46", "r47",
66   "r48", "r49", "r50", "r51", "r52", "r53", "r54", "r55",
67   "r56", "r57", "r58", "r59", "r60", "r61", "r62", "r63",
68   "r64", "r65", "r66", "r67", "r68", "r69", "r70", "r71",
69   "r72", "r73", "r74", "r75", "r76", "r77", "r78", "r79",
70   "r80", "r81", "r82", "r83", "r84", "r85", "r86", "r87",
71   "r88", "r89", "r90", "r91", "r92", "r93", "r94", "r95",
72   "r96", "r97", "r98", "r99", "r100","r101","r102","r103",
73   "r104","r105","r106","r107","r108","r109","r110","r111",
74   "r112","r113","r114","r115","r116","r117","r118","r119",
75   "r120","r121","r122","r123","r124","r125","r126","r127"};
76
77 /* ??? These strings could be shared with REGISTER_NAMES.  */
78 static const char * const ia64_input_reg_names[8] =
79 { "in0",  "in1",  "in2",  "in3",  "in4",  "in5",  "in6",  "in7" };
80
81 /* ??? These strings could be shared with REGISTER_NAMES.  */
82 static const char * const ia64_local_reg_names[80] =
83 { "loc0", "loc1", "loc2", "loc3", "loc4", "loc5", "loc6", "loc7",
84   "loc8", "loc9", "loc10","loc11","loc12","loc13","loc14","loc15",
85   "loc16","loc17","loc18","loc19","loc20","loc21","loc22","loc23",
86   "loc24","loc25","loc26","loc27","loc28","loc29","loc30","loc31",
87   "loc32","loc33","loc34","loc35","loc36","loc37","loc38","loc39",
88   "loc40","loc41","loc42","loc43","loc44","loc45","loc46","loc47",
89   "loc48","loc49","loc50","loc51","loc52","loc53","loc54","loc55",
90   "loc56","loc57","loc58","loc59","loc60","loc61","loc62","loc63",
91   "loc64","loc65","loc66","loc67","loc68","loc69","loc70","loc71",
92   "loc72","loc73","loc74","loc75","loc76","loc77","loc78","loc79" };
93
94 /* ??? These strings could be shared with REGISTER_NAMES.  */
95 static const char * const ia64_output_reg_names[8] =
96 { "out0", "out1", "out2", "out3", "out4", "out5", "out6", "out7" };
97
98 /* String used with the -mfixed-range= option.  */
99 const char *ia64_fixed_range_string;
100
101 /* Determines whether we use adds, addl, or movl to generate our
102    TLS immediate offsets.  */
103 int ia64_tls_size = 22;
104
105 /* String used with the -mtls-size= option.  */
106 const char *ia64_tls_size_string;
107
108 /* Which cpu are we scheduling for.  */
109 enum processor_type ia64_tune;
110
111 /* String used with the -tune= option.  */
112 const char *ia64_tune_string;
113
114 /* Determines whether we run our final scheduling pass or not.  We always
115    avoid the normal second scheduling pass.  */
116 static int ia64_flag_schedule_insns2;
117
118 /* Variables which are this size or smaller are put in the sdata/sbss
119    sections.  */
120
121 unsigned int ia64_section_threshold;
122
123 /* The following variable is used by the DFA insn scheduler.  The value is
124    TRUE if we do insn bundling instead of insn scheduling.  */
125 int bundling_p = 0;
126
127 /* Structure to be filled in by ia64_compute_frame_size with register
128    save masks and offsets for the current function.  */
129
130 struct ia64_frame_info
131 {
132   HOST_WIDE_INT total_size;     /* size of the stack frame, not including
133                                    the caller's scratch area.  */
134   HOST_WIDE_INT spill_cfa_off;  /* top of the reg spill area from the cfa.  */
135   HOST_WIDE_INT spill_size;     /* size of the gr/br/fr spill area.  */
136   HOST_WIDE_INT extra_spill_size;  /* size of spill area for others.  */
137   HARD_REG_SET mask;            /* mask of saved registers.  */
138   unsigned int gr_used_mask;    /* mask of registers in use as gr spill 
139                                    registers or long-term scratches.  */
140   int n_spilled;                /* number of spilled registers.  */
141   int reg_fp;                   /* register for fp.  */
142   int reg_save_b0;              /* save register for b0.  */
143   int reg_save_pr;              /* save register for prs.  */
144   int reg_save_ar_pfs;          /* save register for ar.pfs.  */
145   int reg_save_ar_unat;         /* save register for ar.unat.  */
146   int reg_save_ar_lc;           /* save register for ar.lc.  */
147   int reg_save_gp;              /* save register for gp.  */
148   int n_input_regs;             /* number of input registers used.  */
149   int n_local_regs;             /* number of local registers used.  */
150   int n_output_regs;            /* number of output registers used.  */
151   int n_rotate_regs;            /* number of rotating registers used.  */
152
153   char need_regstk;             /* true if a .regstk directive needed.  */
154   char initialized;             /* true if the data is finalized.  */
155 };
156
157 /* Current frame information calculated by ia64_compute_frame_size.  */
158 static struct ia64_frame_info current_frame_info;
159 \f
160 static int ia64_use_dfa_pipeline_interface PARAMS ((void));
161 static int ia64_first_cycle_multipass_dfa_lookahead PARAMS ((void));
162 static void ia64_dependencies_evaluation_hook PARAMS ((rtx, rtx));
163 static void ia64_init_dfa_pre_cycle_insn PARAMS ((void));
164 static rtx ia64_dfa_pre_cycle_insn PARAMS ((void));
165 static int ia64_first_cycle_multipass_dfa_lookahead_guard PARAMS ((rtx));
166 static int ia64_dfa_new_cycle PARAMS ((FILE *, int, rtx, int, int, int *));
167 static rtx gen_tls_get_addr PARAMS ((void));
168 static rtx gen_thread_pointer PARAMS ((void));
169 static rtx ia64_expand_tls_address PARAMS ((enum tls_model, rtx, rtx));
170 static int find_gr_spill PARAMS ((int));
171 static int next_scratch_gr_reg PARAMS ((void));
172 static void mark_reg_gr_used_mask PARAMS ((rtx, void *));
173 static void ia64_compute_frame_size PARAMS ((HOST_WIDE_INT));
174 static void setup_spill_pointers PARAMS ((int, rtx, HOST_WIDE_INT));
175 static void finish_spill_pointers PARAMS ((void));
176 static rtx spill_restore_mem PARAMS ((rtx, HOST_WIDE_INT));
177 static void do_spill PARAMS ((rtx (*)(rtx, rtx, rtx), rtx, HOST_WIDE_INT, rtx));
178 static void do_restore PARAMS ((rtx (*)(rtx, rtx, rtx), rtx, HOST_WIDE_INT));
179 static rtx gen_movdi_x PARAMS ((rtx, rtx, rtx));
180 static rtx gen_fr_spill_x PARAMS ((rtx, rtx, rtx));
181 static rtx gen_fr_restore_x PARAMS ((rtx, rtx, rtx));
182
183 static enum machine_mode hfa_element_mode PARAMS ((tree, int));
184 static bool ia64_function_ok_for_sibcall PARAMS ((tree, tree));
185 static bool ia64_rtx_costs PARAMS ((rtx, int, int, int *));
186 static void fix_range PARAMS ((const char *));
187 static struct machine_function * ia64_init_machine_status PARAMS ((void));
188 static void emit_insn_group_barriers PARAMS ((FILE *, rtx));
189 static void emit_all_insn_group_barriers PARAMS ((FILE *, rtx));
190 static void final_emit_insn_group_barriers PARAMS ((FILE *));
191 static void emit_predicate_relation_info PARAMS ((void));
192 static bool ia64_in_small_data_p PARAMS ((tree));
193 static void process_epilogue PARAMS ((void));
194 static int process_set PARAMS ((FILE *, rtx));
195
196 static rtx ia64_expand_fetch_and_op PARAMS ((optab, enum machine_mode,
197                                              tree, rtx));
198 static rtx ia64_expand_op_and_fetch PARAMS ((optab, enum machine_mode,
199                                              tree, rtx));
200 static rtx ia64_expand_compare_and_swap PARAMS ((enum machine_mode, int,
201                                                  tree, rtx));
202 static rtx ia64_expand_lock_test_and_set PARAMS ((enum machine_mode,
203                                                   tree, rtx));
204 static rtx ia64_expand_lock_release PARAMS ((enum machine_mode, tree, rtx));
205 static bool ia64_assemble_integer PARAMS ((rtx, unsigned int, int));
206 static void ia64_output_function_prologue PARAMS ((FILE *, HOST_WIDE_INT));
207 static void ia64_output_function_epilogue PARAMS ((FILE *, HOST_WIDE_INT));
208 static void ia64_output_function_end_prologue PARAMS ((FILE *));
209
210 static int ia64_issue_rate PARAMS ((void));
211 static int ia64_adjust_cost PARAMS ((rtx, rtx, rtx, int));
212 static void ia64_sched_init PARAMS ((FILE *, int, int));
213 static void ia64_sched_finish PARAMS ((FILE *, int));
214 static int ia64_dfa_sched_reorder PARAMS ((FILE *, int, rtx *, int *,
215                                            int, int));
216 static int ia64_sched_reorder PARAMS ((FILE *, int, rtx *, int *, int));
217 static int ia64_sched_reorder2 PARAMS ((FILE *, int, rtx *, int *, int));
218 static int ia64_variable_issue PARAMS ((FILE *, int, rtx, int));
219
220 static struct bundle_state *get_free_bundle_state PARAMS ((void));
221 static void free_bundle_state PARAMS ((struct bundle_state *));
222 static void initiate_bundle_states PARAMS ((void));
223 static void finish_bundle_states PARAMS ((void));
224 static unsigned bundle_state_hash PARAMS ((const void *));
225 static int bundle_state_eq_p PARAMS ((const void *, const void *));
226 static int insert_bundle_state PARAMS ((struct bundle_state *));
227 static void initiate_bundle_state_table PARAMS ((void));
228 static void finish_bundle_state_table PARAMS ((void));
229 static int try_issue_nops PARAMS ((struct bundle_state *, int));
230 static int try_issue_insn PARAMS ((struct bundle_state *, rtx));
231 static void issue_nops_and_insn PARAMS ((struct bundle_state *, int,
232                                          rtx, int, int));
233 static int get_max_pos PARAMS ((state_t));
234 static int get_template PARAMS ((state_t, int));
235
236 static rtx get_next_important_insn PARAMS ((rtx, rtx));
237 static void bundling PARAMS ((FILE *, int, rtx, rtx));
238
239 static void ia64_output_mi_thunk PARAMS ((FILE *, tree, HOST_WIDE_INT,
240                                           HOST_WIDE_INT, tree));
241
242 static void ia64_select_rtx_section PARAMS ((enum machine_mode, rtx,
243                                              unsigned HOST_WIDE_INT));
244 static void ia64_rwreloc_select_section PARAMS ((tree, int,
245                                                  unsigned HOST_WIDE_INT))
246      ATTRIBUTE_UNUSED;
247 static void ia64_rwreloc_unique_section PARAMS ((tree, int))
248      ATTRIBUTE_UNUSED;
249 static void ia64_rwreloc_select_rtx_section PARAMS ((enum machine_mode, rtx,
250                                                      unsigned HOST_WIDE_INT))
251      ATTRIBUTE_UNUSED;
252 static unsigned int ia64_rwreloc_section_type_flags
253      PARAMS ((tree, const char *, int))
254      ATTRIBUTE_UNUSED;
255
256 static void ia64_hpux_add_extern_decl PARAMS ((const char *name))
257      ATTRIBUTE_UNUSED;
258 \f
259 /* Table of valid machine attributes.  */
260 static const struct attribute_spec ia64_attribute_table[] =
261 {
262   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
263   { "syscall_linkage", 0, 0, false, true,  true,  NULL },
264   { NULL,              0, 0, false, false, false, NULL }
265 };
266
267 /* Initialize the GCC target structure.  */
268 #undef TARGET_ATTRIBUTE_TABLE
269 #define TARGET_ATTRIBUTE_TABLE ia64_attribute_table
270
271 #undef TARGET_INIT_BUILTINS
272 #define TARGET_INIT_BUILTINS ia64_init_builtins
273
274 #undef TARGET_EXPAND_BUILTIN
275 #define TARGET_EXPAND_BUILTIN ia64_expand_builtin
276
277 #undef TARGET_ASM_BYTE_OP
278 #define TARGET_ASM_BYTE_OP "\tdata1\t"
279 #undef TARGET_ASM_ALIGNED_HI_OP
280 #define TARGET_ASM_ALIGNED_HI_OP "\tdata2\t"
281 #undef TARGET_ASM_ALIGNED_SI_OP
282 #define TARGET_ASM_ALIGNED_SI_OP "\tdata4\t"
283 #undef TARGET_ASM_ALIGNED_DI_OP
284 #define TARGET_ASM_ALIGNED_DI_OP "\tdata8\t"
285 #undef TARGET_ASM_UNALIGNED_HI_OP
286 #define TARGET_ASM_UNALIGNED_HI_OP "\tdata2.ua\t"
287 #undef TARGET_ASM_UNALIGNED_SI_OP
288 #define TARGET_ASM_UNALIGNED_SI_OP "\tdata4.ua\t"
289 #undef TARGET_ASM_UNALIGNED_DI_OP
290 #define TARGET_ASM_UNALIGNED_DI_OP "\tdata8.ua\t"
291 #undef TARGET_ASM_INTEGER
292 #define TARGET_ASM_INTEGER ia64_assemble_integer
293
294 #undef TARGET_ASM_FUNCTION_PROLOGUE
295 #define TARGET_ASM_FUNCTION_PROLOGUE ia64_output_function_prologue
296 #undef TARGET_ASM_FUNCTION_END_PROLOGUE
297 #define TARGET_ASM_FUNCTION_END_PROLOGUE ia64_output_function_end_prologue
298 #undef TARGET_ASM_FUNCTION_EPILOGUE
299 #define TARGET_ASM_FUNCTION_EPILOGUE ia64_output_function_epilogue
300
301 #undef TARGET_IN_SMALL_DATA_P
302 #define TARGET_IN_SMALL_DATA_P  ia64_in_small_data_p
303
304 #undef TARGET_SCHED_ADJUST_COST
305 #define TARGET_SCHED_ADJUST_COST ia64_adjust_cost
306 #undef TARGET_SCHED_ISSUE_RATE
307 #define TARGET_SCHED_ISSUE_RATE ia64_issue_rate
308 #undef TARGET_SCHED_VARIABLE_ISSUE
309 #define TARGET_SCHED_VARIABLE_ISSUE ia64_variable_issue
310 #undef TARGET_SCHED_INIT
311 #define TARGET_SCHED_INIT ia64_sched_init
312 #undef TARGET_SCHED_FINISH
313 #define TARGET_SCHED_FINISH ia64_sched_finish
314 #undef TARGET_SCHED_REORDER
315 #define TARGET_SCHED_REORDER ia64_sched_reorder
316 #undef TARGET_SCHED_REORDER2
317 #define TARGET_SCHED_REORDER2 ia64_sched_reorder2
318
319 #undef TARGET_SCHED_DEPENDENCIES_EVALUATION_HOOK
320 #define TARGET_SCHED_DEPENDENCIES_EVALUATION_HOOK ia64_dependencies_evaluation_hook
321
322 #undef TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE
323 #define TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE ia64_use_dfa_pipeline_interface
324
325 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
326 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD ia64_first_cycle_multipass_dfa_lookahead
327
328 #undef TARGET_SCHED_INIT_DFA_PRE_CYCLE_INSN
329 #define TARGET_SCHED_INIT_DFA_PRE_CYCLE_INSN ia64_init_dfa_pre_cycle_insn
330 #undef TARGET_SCHED_DFA_PRE_CYCLE_INSN
331 #define TARGET_SCHED_DFA_PRE_CYCLE_INSN ia64_dfa_pre_cycle_insn
332
333 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD
334 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD\
335   ia64_first_cycle_multipass_dfa_lookahead_guard
336
337 #undef TARGET_SCHED_DFA_NEW_CYCLE
338 #define TARGET_SCHED_DFA_NEW_CYCLE ia64_dfa_new_cycle
339
340 #ifdef HAVE_AS_TLS
341 #undef TARGET_HAVE_TLS
342 #define TARGET_HAVE_TLS true
343 #endif
344
345 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
346 #define TARGET_FUNCTION_OK_FOR_SIBCALL ia64_function_ok_for_sibcall
347
348 #undef TARGET_ASM_OUTPUT_MI_THUNK
349 #define TARGET_ASM_OUTPUT_MI_THUNK ia64_output_mi_thunk
350 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
351 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_tree_hwi_hwi_tree_true
352
353 #undef TARGET_RTX_COSTS
354 #define TARGET_RTX_COSTS ia64_rtx_costs
355 #undef TARGET_ADDRESS_COST
356 #define TARGET_ADDRESS_COST hook_int_rtx_0
357
358 struct gcc_target targetm = TARGET_INITIALIZER;
359 \f
360 /* Return 1 if OP is a valid operand for the MEM of a CALL insn.  */
361
362 int
363 call_operand (op, mode)
364      rtx op;
365      enum machine_mode mode;
366 {
367   if (mode != GET_MODE (op) && mode != VOIDmode)
368     return 0;
369
370   return (GET_CODE (op) == SYMBOL_REF || GET_CODE (op) == REG
371           || (GET_CODE (op) == SUBREG && GET_CODE (XEXP (op, 0)) == REG));
372 }
373
374 /* Return 1 if OP refers to a symbol in the sdata section.  */
375
376 int
377 sdata_symbolic_operand (op, mode)
378      rtx op;
379      enum machine_mode mode ATTRIBUTE_UNUSED;
380 {
381   switch (GET_CODE (op))
382     {
383     case CONST:
384       if (GET_CODE (XEXP (op, 0)) != PLUS
385           || GET_CODE (XEXP (XEXP (op, 0), 0)) != SYMBOL_REF)
386         break;
387       op = XEXP (XEXP (op, 0), 0);
388       /* FALLTHRU */
389
390     case SYMBOL_REF:
391       if (CONSTANT_POOL_ADDRESS_P (op))
392         return GET_MODE_SIZE (get_pool_mode (op)) <= ia64_section_threshold;
393       else
394         return SYMBOL_REF_LOCAL_P (op) && SYMBOL_REF_SMALL_P (op);
395
396     default:
397       break;
398     }
399
400   return 0;
401 }
402
403 /* Return 1 if OP refers to a symbol, and is appropriate for a GOT load.  */
404
405 int
406 got_symbolic_operand (op, mode)
407      rtx op;
408      enum machine_mode mode ATTRIBUTE_UNUSED;
409 {
410   switch (GET_CODE (op))
411     {
412     case CONST:
413       op = XEXP (op, 0);
414       if (GET_CODE (op) != PLUS)
415         return 0;
416       if (GET_CODE (XEXP (op, 0)) != SYMBOL_REF)
417         return 0;
418       op = XEXP (op, 1);
419       if (GET_CODE (op) != CONST_INT)
420         return 0;
421
422         return 1;
423
424       /* Ok if we're not using GOT entries at all.  */
425       if (TARGET_NO_PIC || TARGET_AUTO_PIC)
426         return 1;
427
428       /* "Ok" while emitting rtl, since otherwise we won't be provided
429          with the entire offset during emission, which makes it very
430          hard to split the offset into high and low parts.  */
431       if (rtx_equal_function_value_matters)
432         return 1;
433
434       /* Force the low 14 bits of the constant to zero so that we do not
435          use up so many GOT entries.  */
436       return (INTVAL (op) & 0x3fff) == 0;
437
438     case SYMBOL_REF:
439     case LABEL_REF:
440       return 1;
441
442     default:
443       break;
444     }
445   return 0;
446 }
447
448 /* Return 1 if OP refers to a symbol.  */
449
450 int
451 symbolic_operand (op, mode)
452      rtx op;
453      enum machine_mode mode ATTRIBUTE_UNUSED;
454 {
455   switch (GET_CODE (op))
456     {
457     case CONST:
458     case SYMBOL_REF:
459     case LABEL_REF:
460       return 1;
461
462     default:
463       break;
464     }
465   return 0;
466 }
467
468 /* Return tls_model if OP refers to a TLS symbol.  */
469
470 int
471 tls_symbolic_operand (op, mode)
472      rtx op;
473      enum machine_mode mode ATTRIBUTE_UNUSED;
474 {
475   if (GET_CODE (op) != SYMBOL_REF)
476     return 0;
477   return SYMBOL_REF_TLS_MODEL (op);
478 }
479
480
481 /* Return 1 if OP refers to a function.  */
482
483 int
484 function_operand (op, mode)
485      rtx op;
486      enum machine_mode mode ATTRIBUTE_UNUSED;
487 {
488   if (GET_CODE (op) == SYMBOL_REF && SYMBOL_REF_FUNCTION_P (op))
489     return 1;
490   else
491     return 0;
492 }
493
494 /* Return 1 if OP is setjmp or a similar function.  */
495
496 /* ??? This is an unsatisfying solution.  Should rethink.  */
497
498 int
499 setjmp_operand (op, mode)
500      rtx op;
501      enum machine_mode mode ATTRIBUTE_UNUSED;
502 {
503   const char *name;
504   int retval = 0;
505
506   if (GET_CODE (op) != SYMBOL_REF)
507     return 0;
508
509   name = XSTR (op, 0);
510
511   /* The following code is borrowed from special_function_p in calls.c.  */
512
513   /* Disregard prefix _, __ or __x.  */
514   if (name[0] == '_')
515     {
516       if (name[1] == '_' && name[2] == 'x')
517         name += 3;
518       else if (name[1] == '_')
519         name += 2;
520       else
521         name += 1;
522     }
523
524   if (name[0] == 's')
525     {
526       retval
527         = ((name[1] == 'e'
528             && (! strcmp (name, "setjmp")
529                 || ! strcmp (name, "setjmp_syscall")))
530            || (name[1] == 'i'
531                && ! strcmp (name, "sigsetjmp"))
532            || (name[1] == 'a'
533                && ! strcmp (name, "savectx")));
534     }
535   else if ((name[0] == 'q' && name[1] == 's'
536             && ! strcmp (name, "qsetjmp"))
537            || (name[0] == 'v' && name[1] == 'f'
538                && ! strcmp (name, "vfork")))
539     retval = 1;
540
541   return retval;
542 }
543
544 /* Return 1 if OP is a general operand, excluding tls symbolic operands.  */
545
546 int
547 move_operand (op, mode)
548      rtx op;
549      enum machine_mode mode;
550 {
551   return general_operand (op, mode) && !tls_symbolic_operand (op, mode);
552 }
553
554 /* Return 1 if OP is a register operand that is (or could be) a GR reg.  */
555
556 int
557 gr_register_operand (op, mode)
558      rtx op;
559      enum machine_mode mode;
560 {
561   if (! register_operand (op, mode))
562     return 0;
563   if (GET_CODE (op) == SUBREG)
564     op = SUBREG_REG (op);
565   if (GET_CODE (op) == REG)
566     {
567       unsigned int regno = REGNO (op);
568       if (regno < FIRST_PSEUDO_REGISTER)
569         return GENERAL_REGNO_P (regno);
570     }
571   return 1;
572 }
573
574 /* Return 1 if OP is a register operand that is (or could be) an FR reg.  */
575
576 int
577 fr_register_operand (op, mode)
578      rtx op;
579      enum machine_mode mode;
580 {
581   if (! register_operand (op, mode))
582     return 0;
583   if (GET_CODE (op) == SUBREG)
584     op = SUBREG_REG (op);
585   if (GET_CODE (op) == REG)
586     {
587       unsigned int regno = REGNO (op);
588       if (regno < FIRST_PSEUDO_REGISTER)
589         return FR_REGNO_P (regno);
590     }
591   return 1;
592 }
593
594 /* Return 1 if OP is a register operand that is (or could be) a GR/FR reg.  */
595
596 int
597 grfr_register_operand (op, mode)
598      rtx op;
599      enum machine_mode mode;
600 {
601   if (! register_operand (op, mode))
602     return 0;
603   if (GET_CODE (op) == SUBREG)
604     op = SUBREG_REG (op);
605   if (GET_CODE (op) == REG)
606     {
607       unsigned int regno = REGNO (op);
608       if (regno < FIRST_PSEUDO_REGISTER)
609         return GENERAL_REGNO_P (regno) || FR_REGNO_P (regno);
610     }
611   return 1;
612 }
613
614 /* Return 1 if OP is a nonimmediate operand that is (or could be) a GR reg.  */
615
616 int
617 gr_nonimmediate_operand (op, mode)
618      rtx op;
619      enum machine_mode mode;
620 {
621   if (! nonimmediate_operand (op, mode))
622     return 0;
623   if (GET_CODE (op) == SUBREG)
624     op = SUBREG_REG (op);
625   if (GET_CODE (op) == REG)
626     {
627       unsigned int regno = REGNO (op);
628       if (regno < FIRST_PSEUDO_REGISTER)
629         return GENERAL_REGNO_P (regno);
630     }
631   return 1;
632 }
633
634 /* Return 1 if OP is a nonimmediate operand that is (or could be) a FR reg.  */
635
636 int
637 fr_nonimmediate_operand (op, mode)
638      rtx op;
639      enum machine_mode mode;
640 {
641   if (! nonimmediate_operand (op, mode))
642     return 0;
643   if (GET_CODE (op) == SUBREG)
644     op = SUBREG_REG (op);
645   if (GET_CODE (op) == REG)
646     {
647       unsigned int regno = REGNO (op);
648       if (regno < FIRST_PSEUDO_REGISTER)
649         return FR_REGNO_P (regno);
650     }
651   return 1;
652 }
653
654 /* Return 1 if OP is a nonimmediate operand that is a GR/FR reg.  */
655
656 int
657 grfr_nonimmediate_operand (op, mode)
658      rtx op;
659      enum machine_mode mode;
660 {
661   if (! nonimmediate_operand (op, mode))
662     return 0;
663   if (GET_CODE (op) == SUBREG)
664     op = SUBREG_REG (op);
665   if (GET_CODE (op) == REG)
666     {
667       unsigned int regno = REGNO (op);
668       if (regno < FIRST_PSEUDO_REGISTER)
669         return GENERAL_REGNO_P (regno) || FR_REGNO_P (regno);
670     }
671   return 1;
672 }
673
674 /* Return 1 if OP is a GR register operand, or zero.  */
675
676 int
677 gr_reg_or_0_operand (op, mode)
678      rtx op;
679      enum machine_mode mode;
680 {
681   return (op == const0_rtx || gr_register_operand (op, mode));
682 }
683
684 /* Return 1 if OP is a GR register operand, or a 5 bit immediate operand.  */
685
686 int
687 gr_reg_or_5bit_operand (op, mode)
688      rtx op;
689      enum machine_mode mode;
690 {
691   return ((GET_CODE (op) == CONST_INT && INTVAL (op) >= 0 && INTVAL (op) < 32)
692           || GET_CODE (op) == CONSTANT_P_RTX
693           || gr_register_operand (op, mode));
694 }
695
696 /* Return 1 if OP is a GR register operand, or a 6 bit immediate operand.  */
697
698 int
699 gr_reg_or_6bit_operand (op, mode)
700      rtx op;
701      enum machine_mode mode;
702 {
703   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_M (INTVAL (op)))
704           || GET_CODE (op) == CONSTANT_P_RTX
705           || gr_register_operand (op, mode));
706 }
707
708 /* Return 1 if OP is a GR register operand, or an 8 bit immediate operand.  */
709
710 int
711 gr_reg_or_8bit_operand (op, mode)
712      rtx op;
713      enum machine_mode mode;
714 {
715   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_K (INTVAL (op)))
716           || GET_CODE (op) == CONSTANT_P_RTX
717           || gr_register_operand (op, mode));
718 }
719
720 /* Return 1 if OP is a GR/FR register operand, or an 8 bit immediate.  */
721
722 int
723 grfr_reg_or_8bit_operand (op, mode)
724      rtx op;
725      enum machine_mode mode;
726 {
727   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_K (INTVAL (op)))
728           || GET_CODE (op) == CONSTANT_P_RTX
729           || grfr_register_operand (op, mode));
730 }
731
732 /* Return 1 if OP is a register operand, or an 8 bit adjusted immediate
733    operand.  */
734
735 int
736 gr_reg_or_8bit_adjusted_operand (op, mode)
737      rtx op;
738      enum machine_mode mode;
739 {
740   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_L (INTVAL (op)))
741           || GET_CODE (op) == CONSTANT_P_RTX
742           || gr_register_operand (op, mode));
743 }
744
745 /* Return 1 if OP is a register operand, or is valid for both an 8 bit
746    immediate and an 8 bit adjusted immediate operand.  This is necessary
747    because when we emit a compare, we don't know what the condition will be,
748    so we need the union of the immediates accepted by GT and LT.  */
749
750 int
751 gr_reg_or_8bit_and_adjusted_operand (op, mode)
752      rtx op;
753      enum machine_mode mode;
754 {
755   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_K (INTVAL (op))
756            && CONST_OK_FOR_L (INTVAL (op)))
757           || GET_CODE (op) == CONSTANT_P_RTX
758           || gr_register_operand (op, mode));
759 }
760
761 /* Return 1 if OP is a register operand, or a 14 bit immediate operand.  */
762
763 int
764 gr_reg_or_14bit_operand (op, mode)
765      rtx op;
766      enum machine_mode mode;
767 {
768   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_I (INTVAL (op)))
769           || GET_CODE (op) == CONSTANT_P_RTX
770           || gr_register_operand (op, mode));
771 }
772
773 /* Return 1 if OP is a register operand, or a 22 bit immediate operand.  */
774
775 int
776 gr_reg_or_22bit_operand (op, mode)
777      rtx op;
778      enum machine_mode mode;
779 {
780   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_J (INTVAL (op)))
781           || GET_CODE (op) == CONSTANT_P_RTX
782           || gr_register_operand (op, mode));
783 }
784
785 /* Return 1 if OP is a 6 bit immediate operand.  */
786
787 int
788 shift_count_operand (op, mode)
789      rtx op;
790      enum machine_mode mode ATTRIBUTE_UNUSED;
791 {
792   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_M (INTVAL (op)))
793           || GET_CODE (op) == CONSTANT_P_RTX);
794 }
795
796 /* Return 1 if OP is a 5 bit immediate operand.  */
797
798 int
799 shift_32bit_count_operand (op, mode)
800      rtx op;
801      enum machine_mode mode ATTRIBUTE_UNUSED;
802 {
803   return ((GET_CODE (op) == CONST_INT
804            && (INTVAL (op) >= 0 && INTVAL (op) < 32))
805           || GET_CODE (op) == CONSTANT_P_RTX);
806 }
807
808 /* Return 1 if OP is a 2, 4, 8, or 16 immediate operand.  */
809
810 int
811 shladd_operand (op, mode)
812      rtx op;
813      enum machine_mode mode ATTRIBUTE_UNUSED;
814 {
815   return (GET_CODE (op) == CONST_INT
816           && (INTVAL (op) == 2 || INTVAL (op) == 4
817               || INTVAL (op) == 8 || INTVAL (op) == 16));
818 }
819
820 /* Return 1 if OP is a -16, -8, -4, -1, 1, 4, 8, or 16 immediate operand.  */
821
822 int
823 fetchadd_operand (op, mode)
824      rtx op;
825      enum machine_mode mode ATTRIBUTE_UNUSED;
826 {
827   return (GET_CODE (op) == CONST_INT
828           && (INTVAL (op) == -16 || INTVAL (op) == -8 ||
829               INTVAL (op) == -4  || INTVAL (op) == -1 ||
830               INTVAL (op) == 1   || INTVAL (op) == 4  ||
831               INTVAL (op) == 8   || INTVAL (op) == 16));
832 }
833
834 /* Return 1 if OP is a floating-point constant zero, one, or a register.  */
835
836 int
837 fr_reg_or_fp01_operand (op, mode)
838      rtx op;
839      enum machine_mode mode;
840 {
841   return ((GET_CODE (op) == CONST_DOUBLE && CONST_DOUBLE_OK_FOR_G (op))
842           || fr_register_operand (op, mode));
843 }
844
845 /* Like nonimmediate_operand, but don't allow MEMs that try to use a
846    POST_MODIFY with a REG as displacement.  */
847
848 int
849 destination_operand (op, mode)
850      rtx op;
851      enum machine_mode mode;
852 {
853   if (! nonimmediate_operand (op, mode))
854     return 0;
855   if (GET_CODE (op) == MEM
856       && GET_CODE (XEXP (op, 0)) == POST_MODIFY
857       && GET_CODE (XEXP (XEXP (XEXP (op, 0), 1), 1)) == REG)
858     return 0;
859   return 1;
860 }
861
862 /* Like memory_operand, but don't allow post-increments.  */
863
864 int
865 not_postinc_memory_operand (op, mode)
866      rtx op;
867      enum machine_mode mode;
868 {
869   return (memory_operand (op, mode)
870           && GET_RTX_CLASS (GET_CODE (XEXP (op, 0))) != 'a');
871 }
872
873 /* Return 1 if this is a comparison operator, which accepts a normal 8-bit
874    signed immediate operand.  */
875
876 int
877 normal_comparison_operator (op, mode)
878     register rtx op;
879     enum machine_mode mode;
880 {
881   enum rtx_code code = GET_CODE (op);
882   return ((mode == VOIDmode || GET_MODE (op) == mode)
883           && (code == EQ || code == NE
884               || code == GT || code == LE || code == GTU || code == LEU));
885 }
886
887 /* Return 1 if this is a comparison operator, which accepts an adjusted 8-bit
888    signed immediate operand.  */
889
890 int
891 adjusted_comparison_operator (op, mode)
892     register rtx op;
893     enum machine_mode mode;
894 {
895   enum rtx_code code = GET_CODE (op);
896   return ((mode == VOIDmode || GET_MODE (op) == mode)
897           && (code == LT || code == GE || code == LTU || code == GEU));
898 }
899
900 /* Return 1 if this is a signed inequality operator.  */
901
902 int
903 signed_inequality_operator (op, mode)
904     register rtx op;
905     enum machine_mode mode;
906 {
907   enum rtx_code code = GET_CODE (op);
908   return ((mode == VOIDmode || GET_MODE (op) == mode)
909           && (code == GE || code == GT
910               || code == LE || code == LT));
911 }
912
913 /* Return 1 if this operator is valid for predication.  */
914
915 int
916 predicate_operator (op, mode)
917     register rtx op;
918     enum machine_mode mode;
919 {
920   enum rtx_code code = GET_CODE (op);
921   return ((GET_MODE (op) == mode || mode == VOIDmode)
922           && (code == EQ || code == NE));
923 }
924
925 /* Return 1 if this operator can be used in a conditional operation.  */
926
927 int
928 condop_operator (op, mode)
929     register rtx op;
930     enum machine_mode mode;
931 {
932   enum rtx_code code = GET_CODE (op);
933   return ((GET_MODE (op) == mode || mode == VOIDmode)
934           && (code == PLUS || code == MINUS || code == AND
935               || code == IOR || code == XOR));
936 }
937
938 /* Return 1 if this is the ar.lc register.  */
939
940 int
941 ar_lc_reg_operand (op, mode)
942      register rtx op;
943      enum machine_mode mode;
944 {
945   return (GET_MODE (op) == DImode
946           && (mode == DImode || mode == VOIDmode)
947           && GET_CODE (op) == REG
948           && REGNO (op) == AR_LC_REGNUM);
949 }
950
951 /* Return 1 if this is the ar.ccv register.  */
952
953 int
954 ar_ccv_reg_operand (op, mode)
955      register rtx op;
956      enum machine_mode mode;
957 {
958   return ((GET_MODE (op) == mode || mode == VOIDmode)
959           && GET_CODE (op) == REG
960           && REGNO (op) == AR_CCV_REGNUM);
961 }
962
963 /* Return 1 if this is the ar.pfs register.  */
964
965 int
966 ar_pfs_reg_operand (op, mode)
967      register rtx op;
968      enum machine_mode mode;
969 {
970   return ((GET_MODE (op) == mode || mode == VOIDmode)
971           && GET_CODE (op) == REG
972           && REGNO (op) == AR_PFS_REGNUM);
973 }
974
975 /* Like general_operand, but don't allow (mem (addressof)).  */
976
977 int
978 general_tfmode_operand (op, mode)
979      rtx op;
980      enum machine_mode mode;
981 {
982   if (! general_operand (op, mode))
983     return 0;
984   if (GET_CODE (op) == MEM && GET_CODE (XEXP (op, 0)) == ADDRESSOF)
985     return 0;
986   return 1;
987 }
988
989 /* Similarly.  */
990
991 int
992 destination_tfmode_operand (op, mode)
993      rtx op;
994      enum machine_mode mode;
995 {
996   if (! destination_operand (op, mode))
997     return 0;
998   if (GET_CODE (op) == MEM && GET_CODE (XEXP (op, 0)) == ADDRESSOF)
999     return 0;
1000   return 1;
1001 }
1002
1003 /* Similarly.  */
1004
1005 int
1006 tfreg_or_fp01_operand (op, mode)
1007      rtx op;
1008      enum machine_mode mode;
1009 {
1010   if (GET_CODE (op) == SUBREG)
1011     return 0;
1012   return fr_reg_or_fp01_operand (op, mode);
1013 }
1014
1015 /* Return 1 if OP is valid as a base register in a reg + offset address.  */
1016
1017 int
1018 basereg_operand (op, mode)
1019      rtx op;
1020      enum machine_mode mode;
1021 {
1022   /* ??? Should I copy the flag_omit_frame_pointer and cse_not_expected
1023      checks from pa.c basereg_operand as well?  Seems to be OK without them
1024      in test runs.  */
1025
1026   return (register_operand (op, mode) &&
1027           REG_POINTER ((GET_CODE (op) == SUBREG) ? SUBREG_REG (op) : op));
1028 }
1029 \f
1030 /* Return 1 if the operands of a move are ok.  */
1031
1032 int
1033 ia64_move_ok (dst, src)
1034      rtx dst, src;
1035 {
1036   /* If we're under init_recog_no_volatile, we'll not be able to use
1037      memory_operand.  So check the code directly and don't worry about
1038      the validity of the underlying address, which should have been
1039      checked elsewhere anyway.  */
1040   if (GET_CODE (dst) != MEM)
1041     return 1;
1042   if (GET_CODE (src) == MEM)
1043     return 0;
1044   if (register_operand (src, VOIDmode))
1045     return 1;
1046
1047   /* Otherwise, this must be a constant, and that either 0 or 0.0 or 1.0.  */
1048   if (INTEGRAL_MODE_P (GET_MODE (dst)))
1049     return src == const0_rtx;
1050   else
1051     return GET_CODE (src) == CONST_DOUBLE && CONST_DOUBLE_OK_FOR_G (src);
1052 }
1053
1054 /* Return 0 if we are doing C++ code.  This optimization fails with
1055    C++ because of GNAT c++/6685.  */
1056
1057 int
1058 addp4_optimize_ok (op1, op2)
1059      rtx op1, op2;
1060 {
1061
1062   if (!strcmp (lang_hooks.name, "GNU C++"))
1063     return 0;
1064
1065   return (basereg_operand (op1, GET_MODE(op1)) !=
1066           basereg_operand (op2, GET_MODE(op2)));
1067 }
1068
1069 /* Check if OP is a mask suitable for use with SHIFT in a dep.z instruction.
1070    Return the length of the field, or <= 0 on failure.  */
1071
1072 int
1073 ia64_depz_field_mask (rop, rshift)
1074      rtx rop, rshift;
1075 {
1076   unsigned HOST_WIDE_INT op = INTVAL (rop);
1077   unsigned HOST_WIDE_INT shift = INTVAL (rshift);
1078
1079   /* Get rid of the zero bits we're shifting in.  */
1080   op >>= shift;
1081
1082   /* We must now have a solid block of 1's at bit 0.  */
1083   return exact_log2 (op + 1);
1084 }
1085
1086 /* Expand a symbolic constant load.  */
1087
1088 void
1089 ia64_expand_load_address (dest, src)
1090       rtx dest, src;
1091 {
1092   if (tls_symbolic_operand (src, VOIDmode))
1093     abort ();
1094   if (GET_CODE (dest) != REG)
1095     abort ();
1096
1097   if (TARGET_AUTO_PIC)
1098     {
1099       emit_insn (gen_load_gprel64 (dest, src));
1100       return;
1101     }
1102   else if (GET_CODE (src) == SYMBOL_REF && SYMBOL_REF_FUNCTION_P (src))
1103     {
1104       emit_insn (gen_load_fptr (dest, src));
1105       return;
1106     }
1107   else if (sdata_symbolic_operand (src, VOIDmode))
1108     {
1109       emit_insn (gen_load_gprel (dest, src));
1110       return;
1111     }
1112
1113   if (GET_CODE (src) == CONST
1114       && GET_CODE (XEXP (src, 0)) == PLUS
1115       && GET_CODE (XEXP (XEXP (src, 0), 1)) == CONST_INT
1116       && (INTVAL (XEXP (XEXP (src, 0), 1)) & 0x1fff) != 0)
1117     {
1118       rtx sym = XEXP (XEXP (src, 0), 0);
1119       HOST_WIDE_INT ofs, hi, lo;
1120
1121       /* Split the offset into a sign extended 14-bit low part
1122          and a complementary high part.  */
1123       ofs = INTVAL (XEXP (XEXP (src, 0), 1));
1124       lo = ((ofs & 0x3fff) ^ 0x2000) - 0x2000;
1125       hi = ofs - lo;
1126
1127       emit_insn (gen_load_symptr (dest, plus_constant (sym, hi), dest));
1128       emit_insn (gen_adddi3 (dest, dest, GEN_INT (lo)));
1129     }
1130   else
1131     emit_insn (gen_load_symptr (dest, src, dest));
1132 }
1133
1134 static GTY(()) rtx gen_tls_tga;
1135 static rtx
1136 gen_tls_get_addr ()
1137 {
1138   if (!gen_tls_tga)
1139     gen_tls_tga = init_one_libfunc ("__tls_get_addr");
1140   return gen_tls_tga;
1141 }
1142
1143 static GTY(()) rtx thread_pointer_rtx;
1144 static rtx
1145 gen_thread_pointer ()
1146 {
1147   if (!thread_pointer_rtx)
1148     {
1149       thread_pointer_rtx = gen_rtx_REG (Pmode, 13);
1150       RTX_UNCHANGING_P (thread_pointer_rtx) = 1;
1151     }
1152   return thread_pointer_rtx;
1153 }
1154
1155 static rtx
1156 ia64_expand_tls_address (tls_kind, op0, op1)
1157      enum tls_model tls_kind;
1158      rtx op0, op1;
1159 {
1160   rtx tga_op1, tga_op2, tga_ret, tga_eqv, tmp, insns;
1161
1162   switch (tls_kind)
1163     {
1164     case TLS_MODEL_GLOBAL_DYNAMIC:
1165       start_sequence ();
1166
1167       tga_op1 = gen_reg_rtx (Pmode);
1168       emit_insn (gen_load_ltoff_dtpmod (tga_op1, op1));
1169       tga_op1 = gen_rtx_MEM (Pmode, tga_op1);
1170       RTX_UNCHANGING_P (tga_op1) = 1;
1171
1172       tga_op2 = gen_reg_rtx (Pmode);
1173       emit_insn (gen_load_ltoff_dtprel (tga_op2, op1));
1174       tga_op2 = gen_rtx_MEM (Pmode, tga_op2);
1175       RTX_UNCHANGING_P (tga_op2) = 1;
1176               
1177       tga_ret = emit_library_call_value (gen_tls_get_addr (), NULL_RTX,
1178                                          LCT_CONST, Pmode, 2, tga_op1,
1179                                          Pmode, tga_op2, Pmode);
1180
1181       insns = get_insns ();
1182       end_sequence ();
1183
1184       emit_libcall_block (insns, op0, tga_ret, op1);
1185       return NULL_RTX;
1186
1187     case TLS_MODEL_LOCAL_DYNAMIC:
1188       /* ??? This isn't the completely proper way to do local-dynamic
1189          If the call to __tls_get_addr is used only by a single symbol,
1190          then we should (somehow) move the dtprel to the second arg
1191          to avoid the extra add.  */
1192       start_sequence ();
1193
1194       tga_op1 = gen_reg_rtx (Pmode);
1195       emit_insn (gen_load_ltoff_dtpmod (tga_op1, op1));
1196       tga_op1 = gen_rtx_MEM (Pmode, tga_op1);
1197       RTX_UNCHANGING_P (tga_op1) = 1;
1198
1199       tga_op2 = const0_rtx;
1200
1201       tga_ret = emit_library_call_value (gen_tls_get_addr (), NULL_RTX,
1202                                          LCT_CONST, Pmode, 2, tga_op1,
1203                                          Pmode, tga_op2, Pmode);
1204
1205       insns = get_insns ();
1206       end_sequence ();
1207
1208       tga_eqv = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx),
1209                                 UNSPEC_LD_BASE);
1210       tmp = gen_reg_rtx (Pmode);
1211       emit_libcall_block (insns, tmp, tga_ret, tga_eqv);
1212
1213       if (register_operand (op0, Pmode))
1214         tga_ret = op0;
1215       else
1216         tga_ret = gen_reg_rtx (Pmode);
1217       if (TARGET_TLS64)
1218         {
1219           emit_insn (gen_load_dtprel (tga_ret, op1));
1220           emit_insn (gen_adddi3 (tga_ret, tmp, tga_ret));
1221         }
1222       else
1223         emit_insn (gen_add_dtprel (tga_ret, tmp, op1));
1224
1225       return (tga_ret == op0 ? NULL_RTX : tga_ret);
1226
1227     case TLS_MODEL_INITIAL_EXEC:
1228       tmp = gen_reg_rtx (Pmode);
1229       emit_insn (gen_load_ltoff_tprel (tmp, op1));
1230       tmp = gen_rtx_MEM (Pmode, tmp);
1231       RTX_UNCHANGING_P (tmp) = 1;
1232       tmp = force_reg (Pmode, tmp);
1233
1234       if (register_operand (op0, Pmode))
1235         op1 = op0;
1236       else
1237         op1 = gen_reg_rtx (Pmode);
1238       emit_insn (gen_adddi3 (op1, tmp, gen_thread_pointer ()));
1239
1240       return (op1 == op0 ? NULL_RTX : op1);
1241
1242     case TLS_MODEL_LOCAL_EXEC:
1243       if (register_operand (op0, Pmode))
1244         tmp = op0;
1245       else
1246         tmp = gen_reg_rtx (Pmode);
1247       if (TARGET_TLS64)
1248         {
1249           emit_insn (gen_load_tprel (tmp, op1));
1250           emit_insn (gen_adddi3 (tmp, gen_thread_pointer (), tmp));
1251         }
1252       else
1253         emit_insn (gen_add_tprel (tmp, gen_thread_pointer (), op1));
1254
1255       return (tmp == op0 ? NULL_RTX : tmp);
1256
1257     default:
1258       abort ();
1259     }
1260 }
1261
1262 rtx
1263 ia64_expand_move (op0, op1)
1264      rtx op0, op1;
1265 {
1266   enum machine_mode mode = GET_MODE (op0);
1267
1268   if (!reload_in_progress && !reload_completed && !ia64_move_ok (op0, op1))
1269     op1 = force_reg (mode, op1);
1270
1271   if ((mode == Pmode || mode == ptr_mode) && symbolic_operand (op1, VOIDmode))
1272     {
1273       enum tls_model tls_kind;
1274       if ((tls_kind = tls_symbolic_operand (op1, VOIDmode)))
1275         return ia64_expand_tls_address (tls_kind, op0, op1);
1276
1277       if (!TARGET_NO_PIC && reload_completed)
1278         {
1279           ia64_expand_load_address (op0, op1);
1280           return NULL_RTX;
1281         }
1282     }
1283
1284   return op1;
1285 }
1286
1287 /* Split a move from OP1 to OP0 conditional on COND.  */
1288
1289 void
1290 ia64_emit_cond_move (op0, op1, cond)
1291      rtx op0, op1, cond;
1292 {
1293   rtx insn, first = get_last_insn ();
1294
1295   emit_move_insn (op0, op1);
1296
1297   for (insn = get_last_insn (); insn != first; insn = PREV_INSN (insn))
1298     if (INSN_P (insn))
1299       PATTERN (insn) = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (cond),
1300                                           PATTERN (insn));
1301 }
1302
1303 /* Split a post-reload TImode reference into two DImode components.  */
1304
1305 rtx
1306 ia64_split_timode (out, in, scratch)
1307      rtx out[2];
1308      rtx in, scratch;
1309 {
1310   switch (GET_CODE (in))
1311     {
1312     case REG:
1313       out[0] = gen_rtx_REG (DImode, REGNO (in));
1314       out[1] = gen_rtx_REG (DImode, REGNO (in) + 1);
1315       return NULL_RTX;
1316
1317     case MEM:
1318       {
1319         rtx base = XEXP (in, 0);
1320
1321         switch (GET_CODE (base))
1322           {
1323           case REG:
1324             out[0] = adjust_address (in, DImode, 0);
1325             break;
1326           case POST_MODIFY:
1327             base = XEXP (base, 0);
1328             out[0] = adjust_address (in, DImode, 0);
1329             break;
1330
1331           /* Since we're changing the mode, we need to change to POST_MODIFY
1332              as well to preserve the size of the increment.  Either that or
1333              do the update in two steps, but we've already got this scratch
1334              register handy so let's use it.  */
1335           case POST_INC:
1336             base = XEXP (base, 0);
1337             out[0]
1338               = change_address (in, DImode,
1339                                 gen_rtx_POST_MODIFY
1340                                 (Pmode, base, plus_constant (base, 16)));
1341             break;
1342           case POST_DEC:
1343             base = XEXP (base, 0);
1344             out[0]
1345               = change_address (in, DImode,
1346                                 gen_rtx_POST_MODIFY
1347                                 (Pmode, base, plus_constant (base, -16)));
1348             break;
1349           default:
1350             abort ();
1351           }
1352
1353         if (scratch == NULL_RTX)
1354           abort ();
1355         out[1] = change_address (in, DImode, scratch);
1356         return gen_adddi3 (scratch, base, GEN_INT (8));
1357       }
1358
1359     case CONST_INT:
1360     case CONST_DOUBLE:
1361       split_double (in, &out[0], &out[1]);
1362       return NULL_RTX;
1363
1364     default:
1365       abort ();
1366     }
1367 }
1368
1369 /* ??? Fixing GR->FR TFmode moves during reload is hard.  You need to go
1370    through memory plus an extra GR scratch register.  Except that you can
1371    either get the first from SECONDARY_MEMORY_NEEDED or the second from
1372    SECONDARY_RELOAD_CLASS, but not both.
1373
1374    We got into problems in the first place by allowing a construct like
1375    (subreg:TF (reg:TI)), which we got from a union containing a long double.  
1376    This solution attempts to prevent this situation from occurring.  When
1377    we see something like the above, we spill the inner register to memory.  */
1378
1379 rtx
1380 spill_tfmode_operand (in, force)
1381      rtx in;
1382      int force;
1383 {
1384   if (GET_CODE (in) == SUBREG
1385       && GET_MODE (SUBREG_REG (in)) == TImode
1386       && GET_CODE (SUBREG_REG (in)) == REG)
1387     {
1388       rtx mem = gen_mem_addressof (SUBREG_REG (in), NULL_TREE, /*rescan=*/true);
1389       return gen_rtx_MEM (TFmode, copy_to_reg (XEXP (mem, 0)));
1390     }
1391   else if (force && GET_CODE (in) == REG)
1392     {
1393       rtx mem = gen_mem_addressof (in, NULL_TREE, /*rescan=*/true);
1394       return gen_rtx_MEM (TFmode, copy_to_reg (XEXP (mem, 0)));
1395     }
1396   else if (GET_CODE (in) == MEM
1397            && GET_CODE (XEXP (in, 0)) == ADDRESSOF)
1398     return change_address (in, TFmode, copy_to_reg (XEXP (in, 0)));
1399   else
1400     return in;
1401 }
1402
1403 /* Emit comparison instruction if necessary, returning the expression
1404    that holds the compare result in the proper mode.  */
1405
1406 rtx
1407 ia64_expand_compare (code, mode)
1408      enum rtx_code code;
1409      enum machine_mode mode;
1410 {
1411   rtx op0 = ia64_compare_op0, op1 = ia64_compare_op1;
1412   rtx cmp;
1413
1414   /* If we have a BImode input, then we already have a compare result, and
1415      do not need to emit another comparison.  */
1416   if (GET_MODE (op0) == BImode)
1417     {
1418       if ((code == NE || code == EQ) && op1 == const0_rtx)
1419         cmp = op0;
1420       else
1421         abort ();
1422     }
1423   else
1424     {
1425       cmp = gen_reg_rtx (BImode);
1426       emit_insn (gen_rtx_SET (VOIDmode, cmp,
1427                               gen_rtx_fmt_ee (code, BImode, op0, op1)));
1428       code = NE;
1429     }
1430
1431   return gen_rtx_fmt_ee (code, mode, cmp, const0_rtx);
1432 }
1433
1434 /* Emit the appropriate sequence for a call.  */
1435
1436 void
1437 ia64_expand_call (retval, addr, nextarg, sibcall_p)
1438      rtx retval;
1439      rtx addr;
1440      rtx nextarg ATTRIBUTE_UNUSED;
1441      int sibcall_p;
1442 {
1443   rtx insn, b0;
1444
1445   addr = XEXP (addr, 0);
1446   b0 = gen_rtx_REG (DImode, R_BR (0));
1447
1448   /* ??? Should do this for functions known to bind local too.  */
1449   if (TARGET_NO_PIC || TARGET_AUTO_PIC)
1450     {
1451       if (sibcall_p)
1452         insn = gen_sibcall_nogp (addr);
1453       else if (! retval)
1454         insn = gen_call_nogp (addr, b0);
1455       else
1456         insn = gen_call_value_nogp (retval, addr, b0);
1457       insn = emit_call_insn (insn);
1458     }
1459   else
1460     {
1461       if (sibcall_p)
1462         insn = gen_sibcall_gp (addr);
1463       else if (! retval)
1464         insn = gen_call_gp (addr, b0);
1465       else
1466         insn = gen_call_value_gp (retval, addr, b0);
1467       insn = emit_call_insn (insn);
1468
1469       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
1470     }
1471
1472   if (sibcall_p)
1473     {
1474       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), b0);
1475       use_reg (&CALL_INSN_FUNCTION_USAGE (insn),
1476                gen_rtx_REG (DImode, AR_PFS_REGNUM));
1477     }
1478 }
1479
1480 void
1481 ia64_reload_gp ()
1482 {
1483   rtx tmp;
1484
1485   if (current_frame_info.reg_save_gp)
1486     tmp = gen_rtx_REG (DImode, current_frame_info.reg_save_gp);
1487   else
1488     {
1489       HOST_WIDE_INT offset;
1490
1491       offset = (current_frame_info.spill_cfa_off
1492                 + current_frame_info.spill_size);
1493       if (frame_pointer_needed)
1494         {
1495           tmp = hard_frame_pointer_rtx;
1496           offset = -offset;
1497         }
1498       else
1499         {
1500           tmp = stack_pointer_rtx;
1501           offset = current_frame_info.total_size - offset;
1502         }
1503
1504       if (CONST_OK_FOR_I (offset))
1505         emit_insn (gen_adddi3 (pic_offset_table_rtx,
1506                                tmp, GEN_INT (offset)));
1507       else
1508         {
1509           emit_move_insn (pic_offset_table_rtx, GEN_INT (offset));
1510           emit_insn (gen_adddi3 (pic_offset_table_rtx,
1511                                  pic_offset_table_rtx, tmp));
1512         }
1513
1514       tmp = gen_rtx_MEM (DImode, pic_offset_table_rtx);
1515     }
1516
1517   emit_move_insn (pic_offset_table_rtx, tmp);
1518 }
1519
1520 void
1521 ia64_split_call (retval, addr, retaddr, scratch_r, scratch_b,
1522                  noreturn_p, sibcall_p)
1523      rtx retval, addr, retaddr, scratch_r, scratch_b;
1524      int noreturn_p, sibcall_p;
1525 {
1526   rtx insn;
1527   bool is_desc = false;
1528
1529   /* If we find we're calling through a register, then we're actually
1530      calling through a descriptor, so load up the values.  */
1531   if (REG_P (addr))
1532     {
1533       rtx tmp;
1534       bool addr_dead_p;
1535
1536       /* ??? We are currently constrained to *not* use peep2, because
1537          we can legitimiately change the global lifetime of the GP
1538          (in the form of killing where previously live).  This is 
1539          because a call through a descriptor doesn't use the previous
1540          value of the GP, while a direct call does, and we do not
1541          commit to either form until the split here.
1542
1543          That said, this means that we lack precise life info for
1544          whether ADDR is dead after this call.  This is not terribly
1545          important, since we can fix things up essentially for free
1546          with the POST_DEC below, but it's nice to not use it when we
1547          can immediately tell it's not necessary.  */
1548       addr_dead_p = ((noreturn_p || sibcall_p
1549                       || TEST_HARD_REG_BIT (regs_invalidated_by_call,
1550                                             REGNO (addr)))
1551                      && !FUNCTION_ARG_REGNO_P (REGNO (addr)));
1552
1553       /* Load the code address into scratch_b.  */
1554       tmp = gen_rtx_POST_INC (Pmode, addr);
1555       tmp = gen_rtx_MEM (Pmode, tmp);
1556       emit_move_insn (scratch_r, tmp);
1557       emit_move_insn (scratch_b, scratch_r);
1558
1559       /* Load the GP address.  If ADDR is not dead here, then we must
1560          revert the change made above via the POST_INCREMENT.  */
1561       if (!addr_dead_p)
1562         tmp = gen_rtx_POST_DEC (Pmode, addr);
1563       else
1564         tmp = addr;
1565       tmp = gen_rtx_MEM (Pmode, tmp);
1566       emit_move_insn (pic_offset_table_rtx, tmp);
1567
1568       is_desc = true;
1569       addr = scratch_b;
1570     }
1571
1572   if (sibcall_p)
1573     insn = gen_sibcall_nogp (addr);
1574   else if (retval)
1575     insn = gen_call_value_nogp (retval, addr, retaddr);
1576   else
1577     insn = gen_call_nogp (addr, retaddr);
1578   emit_call_insn (insn);
1579
1580   if ((!TARGET_CONST_GP || is_desc) && !noreturn_p && !sibcall_p)
1581     ia64_reload_gp ();
1582 }
1583 \f
1584 /* Begin the assembly file.  */
1585
1586 void
1587 emit_safe_across_calls (f)
1588      FILE *f;
1589 {
1590   unsigned int rs, re;
1591   int out_state;
1592
1593   rs = 1;
1594   out_state = 0;
1595   while (1)
1596     {
1597       while (rs < 64 && call_used_regs[PR_REG (rs)])
1598         rs++;
1599       if (rs >= 64)
1600         break;
1601       for (re = rs + 1; re < 64 && ! call_used_regs[PR_REG (re)]; re++)
1602         continue;
1603       if (out_state == 0)
1604         {
1605           fputs ("\t.pred.safe_across_calls ", f);
1606           out_state = 1;
1607         }
1608       else
1609         fputc (',', f);
1610       if (re == rs + 1)
1611         fprintf (f, "p%u", rs);
1612       else
1613         fprintf (f, "p%u-p%u", rs, re - 1);
1614       rs = re + 1;
1615     }
1616   if (out_state)
1617     fputc ('\n', f);
1618 }
1619
1620 /* Helper function for ia64_compute_frame_size: find an appropriate general
1621    register to spill some special register to.  SPECIAL_SPILL_MASK contains
1622    bits in GR0 to GR31 that have already been allocated by this routine.
1623    TRY_LOCALS is true if we should attempt to locate a local regnum.  */
1624
1625 static int
1626 find_gr_spill (try_locals)
1627      int try_locals;
1628 {
1629   int regno;
1630
1631   /* If this is a leaf function, first try an otherwise unused
1632      call-clobbered register.  */
1633   if (current_function_is_leaf)
1634     {
1635       for (regno = GR_REG (1); regno <= GR_REG (31); regno++)
1636         if (! regs_ever_live[regno]
1637             && call_used_regs[regno]
1638             && ! fixed_regs[regno]
1639             && ! global_regs[regno]
1640             && ((current_frame_info.gr_used_mask >> regno) & 1) == 0)
1641           {
1642             current_frame_info.gr_used_mask |= 1 << regno;
1643             return regno;
1644           }
1645     }
1646
1647   if (try_locals)
1648     {
1649       regno = current_frame_info.n_local_regs;
1650       /* If there is a frame pointer, then we can't use loc79, because
1651          that is HARD_FRAME_POINTER_REGNUM.  In particular, see the
1652          reg_name switching code in ia64_expand_prologue.  */
1653       if (regno < (80 - frame_pointer_needed))
1654         {
1655           current_frame_info.n_local_regs = regno + 1;
1656           return LOC_REG (0) + regno;
1657         }
1658     }
1659
1660   /* Failed to find a general register to spill to.  Must use stack.  */
1661   return 0;
1662 }
1663
1664 /* In order to make for nice schedules, we try to allocate every temporary
1665    to a different register.  We must of course stay away from call-saved,
1666    fixed, and global registers.  We must also stay away from registers
1667    allocated in current_frame_info.gr_used_mask, since those include regs
1668    used all through the prologue.
1669
1670    Any register allocated here must be used immediately.  The idea is to
1671    aid scheduling, not to solve data flow problems.  */
1672
1673 static int last_scratch_gr_reg;
1674
1675 static int
1676 next_scratch_gr_reg ()
1677 {
1678   int i, regno;
1679
1680   for (i = 0; i < 32; ++i)
1681     {
1682       regno = (last_scratch_gr_reg + i + 1) & 31;
1683       if (call_used_regs[regno]
1684           && ! fixed_regs[regno]
1685           && ! global_regs[regno]
1686           && ((current_frame_info.gr_used_mask >> regno) & 1) == 0)
1687         {
1688           last_scratch_gr_reg = regno;
1689           return regno;
1690         }
1691     }
1692
1693   /* There must be _something_ available.  */
1694   abort ();
1695 }
1696
1697 /* Helper function for ia64_compute_frame_size, called through
1698    diddle_return_value.  Mark REG in current_frame_info.gr_used_mask.  */
1699
1700 static void
1701 mark_reg_gr_used_mask (reg, data)
1702      rtx reg;
1703      void *data ATTRIBUTE_UNUSED;
1704 {
1705   unsigned int regno = REGNO (reg);
1706   if (regno < 32)
1707     {
1708       unsigned int i, n = HARD_REGNO_NREGS (regno, GET_MODE (reg));
1709       for (i = 0; i < n; ++i)
1710         current_frame_info.gr_used_mask |= 1 << (regno + i);
1711     }
1712 }
1713
1714 /* Returns the number of bytes offset between the frame pointer and the stack
1715    pointer for the current function.  SIZE is the number of bytes of space
1716    needed for local variables.  */
1717
1718 static void
1719 ia64_compute_frame_size (size)
1720      HOST_WIDE_INT size;
1721 {
1722   HOST_WIDE_INT total_size;
1723   HOST_WIDE_INT spill_size = 0;
1724   HOST_WIDE_INT extra_spill_size = 0;
1725   HOST_WIDE_INT pretend_args_size;
1726   HARD_REG_SET mask;
1727   int n_spilled = 0;
1728   int spilled_gr_p = 0;
1729   int spilled_fr_p = 0;
1730   unsigned int regno;
1731   int i;
1732
1733   if (current_frame_info.initialized)
1734     return;
1735
1736   memset (&current_frame_info, 0, sizeof current_frame_info);
1737   CLEAR_HARD_REG_SET (mask);
1738
1739   /* Don't allocate scratches to the return register.  */
1740   diddle_return_value (mark_reg_gr_used_mask, NULL);
1741
1742   /* Don't allocate scratches to the EH scratch registers.  */
1743   if (cfun->machine->ia64_eh_epilogue_sp)
1744     mark_reg_gr_used_mask (cfun->machine->ia64_eh_epilogue_sp, NULL);
1745   if (cfun->machine->ia64_eh_epilogue_bsp)
1746     mark_reg_gr_used_mask (cfun->machine->ia64_eh_epilogue_bsp, NULL);
1747
1748   /* Find the size of the register stack frame.  We have only 80 local
1749      registers, because we reserve 8 for the inputs and 8 for the
1750      outputs.  */
1751
1752   /* Skip HARD_FRAME_POINTER_REGNUM (loc79) when frame_pointer_needed,
1753      since we'll be adjusting that down later.  */
1754   regno = LOC_REG (78) + ! frame_pointer_needed;
1755   for (; regno >= LOC_REG (0); regno--)
1756     if (regs_ever_live[regno])
1757       break;
1758   current_frame_info.n_local_regs = regno - LOC_REG (0) + 1;
1759
1760   /* For functions marked with the syscall_linkage attribute, we must mark
1761      all eight input registers as in use, so that locals aren't visible to
1762      the caller.  */
1763
1764   if (cfun->machine->n_varargs > 0
1765       || lookup_attribute ("syscall_linkage",
1766                            TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))))
1767     current_frame_info.n_input_regs = 8;
1768   else
1769     {
1770       for (regno = IN_REG (7); regno >= IN_REG (0); regno--)
1771         if (regs_ever_live[regno])
1772           break;
1773       current_frame_info.n_input_regs = regno - IN_REG (0) + 1;
1774     }
1775
1776   for (regno = OUT_REG (7); regno >= OUT_REG (0); regno--)
1777     if (regs_ever_live[regno])
1778       break;
1779   i = regno - OUT_REG (0) + 1;
1780
1781   /* When -p profiling, we need one output register for the mcount argument.
1782      Likewise for -a profiling for the bb_init_func argument.  For -ax
1783      profiling, we need two output registers for the two bb_init_trace_func
1784      arguments.  */
1785   if (current_function_profile)
1786     i = MAX (i, 1);
1787   current_frame_info.n_output_regs = i;
1788
1789   /* ??? No rotating register support yet.  */
1790   current_frame_info.n_rotate_regs = 0;
1791
1792   /* Discover which registers need spilling, and how much room that
1793      will take.  Begin with floating point and general registers, 
1794      which will always wind up on the stack.  */
1795
1796   for (regno = FR_REG (2); regno <= FR_REG (127); regno++)
1797     if (regs_ever_live[regno] && ! call_used_regs[regno])
1798       {
1799         SET_HARD_REG_BIT (mask, regno);
1800         spill_size += 16;
1801         n_spilled += 1;
1802         spilled_fr_p = 1;
1803       }
1804
1805   for (regno = GR_REG (1); regno <= GR_REG (31); regno++)
1806     if (regs_ever_live[regno] && ! call_used_regs[regno])
1807       {
1808         SET_HARD_REG_BIT (mask, regno);
1809         spill_size += 8;
1810         n_spilled += 1;
1811         spilled_gr_p = 1;
1812       }
1813
1814   for (regno = BR_REG (1); regno <= BR_REG (7); regno++)
1815     if (regs_ever_live[regno] && ! call_used_regs[regno])
1816       {
1817         SET_HARD_REG_BIT (mask, regno);
1818         spill_size += 8;
1819         n_spilled += 1;
1820       }
1821
1822   /* Now come all special registers that might get saved in other
1823      general registers.  */
1824   
1825   if (frame_pointer_needed)
1826     {
1827       current_frame_info.reg_fp = find_gr_spill (1);
1828       /* If we did not get a register, then we take LOC79.  This is guaranteed
1829          to be free, even if regs_ever_live is already set, because this is
1830          HARD_FRAME_POINTER_REGNUM.  This requires incrementing n_local_regs,
1831          as we don't count loc79 above.  */
1832       if (current_frame_info.reg_fp == 0)
1833         {
1834           current_frame_info.reg_fp = LOC_REG (79);
1835           current_frame_info.n_local_regs++;
1836         }
1837     }
1838
1839   if (! current_function_is_leaf)
1840     {
1841       /* Emit a save of BR0 if we call other functions.  Do this even
1842          if this function doesn't return, as EH depends on this to be
1843          able to unwind the stack.  */
1844       SET_HARD_REG_BIT (mask, BR_REG (0));
1845
1846       current_frame_info.reg_save_b0 = find_gr_spill (1);
1847       if (current_frame_info.reg_save_b0 == 0)
1848         {
1849           spill_size += 8;
1850           n_spilled += 1;
1851         }
1852
1853       /* Similarly for ar.pfs.  */
1854       SET_HARD_REG_BIT (mask, AR_PFS_REGNUM);
1855       current_frame_info.reg_save_ar_pfs = find_gr_spill (1);
1856       if (current_frame_info.reg_save_ar_pfs == 0)
1857         {
1858           extra_spill_size += 8;
1859           n_spilled += 1;
1860         }
1861
1862       /* Similarly for gp.  Note that if we're calling setjmp, the stacked
1863          registers are clobbered, so we fall back to the stack.  */
1864       current_frame_info.reg_save_gp
1865         = (current_function_calls_setjmp ? 0 : find_gr_spill (1));
1866       if (current_frame_info.reg_save_gp == 0)
1867         {
1868           SET_HARD_REG_BIT (mask, GR_REG (1));
1869           spill_size += 8;
1870           n_spilled += 1;
1871         }
1872     }
1873   else
1874     {
1875       if (regs_ever_live[BR_REG (0)] && ! call_used_regs[BR_REG (0)])
1876         {
1877           SET_HARD_REG_BIT (mask, BR_REG (0));
1878           spill_size += 8;
1879           n_spilled += 1;
1880         }
1881     }
1882
1883   /* Unwind descriptor hackery: things are most efficient if we allocate
1884      consecutive GR save registers for RP, PFS, FP in that order. However,
1885      it is absolutely critical that FP get the only hard register that's
1886      guaranteed to be free, so we allocated it first.  If all three did
1887      happen to be allocated hard regs, and are consecutive, rearrange them
1888      into the preferred order now.  */
1889   if (current_frame_info.reg_fp != 0
1890       && current_frame_info.reg_save_b0 == current_frame_info.reg_fp + 1
1891       && current_frame_info.reg_save_ar_pfs == current_frame_info.reg_fp + 2)
1892     {
1893       current_frame_info.reg_save_b0 = current_frame_info.reg_fp;
1894       current_frame_info.reg_save_ar_pfs = current_frame_info.reg_fp + 1;
1895       current_frame_info.reg_fp = current_frame_info.reg_fp + 2;
1896     }
1897
1898   /* See if we need to store the predicate register block.  */
1899   for (regno = PR_REG (0); regno <= PR_REG (63); regno++)
1900     if (regs_ever_live[regno] && ! call_used_regs[regno])
1901       break;
1902   if (regno <= PR_REG (63))
1903     {
1904       SET_HARD_REG_BIT (mask, PR_REG (0));
1905       current_frame_info.reg_save_pr = find_gr_spill (1);
1906       if (current_frame_info.reg_save_pr == 0)
1907         {
1908           extra_spill_size += 8;
1909           n_spilled += 1;
1910         }
1911
1912       /* ??? Mark them all as used so that register renaming and such
1913          are free to use them.  */
1914       for (regno = PR_REG (0); regno <= PR_REG (63); regno++)
1915         regs_ever_live[regno] = 1;
1916     }
1917
1918   /* If we're forced to use st8.spill, we're forced to save and restore
1919      ar.unat as well.  */
1920   if (spilled_gr_p || cfun->machine->n_varargs)
1921     {
1922       regs_ever_live[AR_UNAT_REGNUM] = 1;
1923       SET_HARD_REG_BIT (mask, AR_UNAT_REGNUM);
1924       current_frame_info.reg_save_ar_unat = find_gr_spill (spill_size == 0);
1925       if (current_frame_info.reg_save_ar_unat == 0)
1926         {
1927           extra_spill_size += 8;
1928           n_spilled += 1;
1929         }
1930     }
1931
1932   if (regs_ever_live[AR_LC_REGNUM])
1933     {
1934       SET_HARD_REG_BIT (mask, AR_LC_REGNUM);
1935       current_frame_info.reg_save_ar_lc = find_gr_spill (spill_size == 0);
1936       if (current_frame_info.reg_save_ar_lc == 0)
1937         {
1938           extra_spill_size += 8;
1939           n_spilled += 1;
1940         }
1941     }
1942
1943   /* If we have an odd number of words of pretend arguments written to
1944      the stack, then the FR save area will be unaligned.  We round the
1945      size of this area up to keep things 16 byte aligned.  */
1946   if (spilled_fr_p)
1947     pretend_args_size = IA64_STACK_ALIGN (current_function_pretend_args_size);
1948   else
1949     pretend_args_size = current_function_pretend_args_size;
1950
1951   total_size = (spill_size + extra_spill_size + size + pretend_args_size
1952                 + current_function_outgoing_args_size);
1953   total_size = IA64_STACK_ALIGN (total_size);
1954
1955   /* We always use the 16-byte scratch area provided by the caller, but
1956      if we are a leaf function, there's no one to which we need to provide
1957      a scratch area.  */
1958   if (current_function_is_leaf)
1959     total_size = MAX (0, total_size - 16);
1960
1961   current_frame_info.total_size = total_size;
1962   current_frame_info.spill_cfa_off = pretend_args_size - 16;
1963   current_frame_info.spill_size = spill_size;
1964   current_frame_info.extra_spill_size = extra_spill_size;
1965   COPY_HARD_REG_SET (current_frame_info.mask, mask);
1966   current_frame_info.n_spilled = n_spilled;
1967   current_frame_info.initialized = reload_completed;
1968 }
1969
1970 /* Compute the initial difference between the specified pair of registers.  */
1971
1972 HOST_WIDE_INT
1973 ia64_initial_elimination_offset (from, to)
1974      int from, to;
1975 {
1976   HOST_WIDE_INT offset;
1977
1978   ia64_compute_frame_size (get_frame_size ());
1979   switch (from)
1980     {
1981     case FRAME_POINTER_REGNUM:
1982       if (to == HARD_FRAME_POINTER_REGNUM)
1983         {
1984           if (current_function_is_leaf)
1985             offset = -current_frame_info.total_size;
1986           else
1987             offset = -(current_frame_info.total_size
1988                        - current_function_outgoing_args_size - 16);
1989         }
1990       else if (to == STACK_POINTER_REGNUM)
1991         {
1992           if (current_function_is_leaf)
1993             offset = 0;
1994           else
1995             offset = 16 + current_function_outgoing_args_size;
1996         }
1997       else
1998         abort ();
1999       break;
2000
2001     case ARG_POINTER_REGNUM:
2002       /* Arguments start above the 16 byte save area, unless stdarg
2003          in which case we store through the 16 byte save area.  */
2004       if (to == HARD_FRAME_POINTER_REGNUM)
2005         offset = 16 - current_function_pretend_args_size;
2006       else if (to == STACK_POINTER_REGNUM)
2007         offset = (current_frame_info.total_size
2008                   + 16 - current_function_pretend_args_size);
2009       else
2010         abort ();
2011       break;
2012
2013     case RETURN_ADDRESS_POINTER_REGNUM:
2014       offset = 0;
2015       break;
2016
2017     default:
2018       abort ();
2019     }
2020
2021   return offset;
2022 }
2023
2024 /* If there are more than a trivial number of register spills, we use
2025    two interleaved iterators so that we can get two memory references
2026    per insn group.
2027
2028    In order to simplify things in the prologue and epilogue expanders,
2029    we use helper functions to fix up the memory references after the
2030    fact with the appropriate offsets to a POST_MODIFY memory mode.
2031    The following data structure tracks the state of the two iterators
2032    while insns are being emitted.  */
2033
2034 struct spill_fill_data
2035 {
2036   rtx init_after;               /* point at which to emit initializations */
2037   rtx init_reg[2];              /* initial base register */
2038   rtx iter_reg[2];              /* the iterator registers */
2039   rtx *prev_addr[2];            /* address of last memory use */
2040   rtx prev_insn[2];             /* the insn corresponding to prev_addr */
2041   HOST_WIDE_INT prev_off[2];    /* last offset */
2042   int n_iter;                   /* number of iterators in use */
2043   int next_iter;                /* next iterator to use */
2044   unsigned int save_gr_used_mask;
2045 };
2046
2047 static struct spill_fill_data spill_fill_data;
2048
2049 static void
2050 setup_spill_pointers (n_spills, init_reg, cfa_off)
2051      int n_spills;
2052      rtx init_reg;
2053      HOST_WIDE_INT cfa_off;
2054 {
2055   int i;
2056
2057   spill_fill_data.init_after = get_last_insn ();
2058   spill_fill_data.init_reg[0] = init_reg;
2059   spill_fill_data.init_reg[1] = init_reg;
2060   spill_fill_data.prev_addr[0] = NULL;
2061   spill_fill_data.prev_addr[1] = NULL;
2062   spill_fill_data.prev_insn[0] = NULL;
2063   spill_fill_data.prev_insn[1] = NULL;
2064   spill_fill_data.prev_off[0] = cfa_off;
2065   spill_fill_data.prev_off[1] = cfa_off;
2066   spill_fill_data.next_iter = 0;
2067   spill_fill_data.save_gr_used_mask = current_frame_info.gr_used_mask;
2068
2069   spill_fill_data.n_iter = 1 + (n_spills > 2);
2070   for (i = 0; i < spill_fill_data.n_iter; ++i)
2071     {
2072       int regno = next_scratch_gr_reg ();
2073       spill_fill_data.iter_reg[i] = gen_rtx_REG (DImode, regno);
2074       current_frame_info.gr_used_mask |= 1 << regno;
2075     }
2076 }
2077
2078 static void
2079 finish_spill_pointers ()
2080 {
2081   current_frame_info.gr_used_mask = spill_fill_data.save_gr_used_mask;
2082 }
2083
2084 static rtx
2085 spill_restore_mem (reg, cfa_off)
2086      rtx reg;
2087      HOST_WIDE_INT cfa_off;
2088 {
2089   int iter = spill_fill_data.next_iter;
2090   HOST_WIDE_INT disp = spill_fill_data.prev_off[iter] - cfa_off;
2091   rtx disp_rtx = GEN_INT (disp);
2092   rtx mem;
2093
2094   if (spill_fill_data.prev_addr[iter])
2095     {
2096       if (CONST_OK_FOR_N (disp))
2097         {
2098           *spill_fill_data.prev_addr[iter]
2099             = gen_rtx_POST_MODIFY (DImode, spill_fill_data.iter_reg[iter],
2100                                    gen_rtx_PLUS (DImode,
2101                                                  spill_fill_data.iter_reg[iter],
2102                                                  disp_rtx));
2103           REG_NOTES (spill_fill_data.prev_insn[iter])
2104             = gen_rtx_EXPR_LIST (REG_INC, spill_fill_data.iter_reg[iter],
2105                                  REG_NOTES (spill_fill_data.prev_insn[iter]));
2106         }
2107       else
2108         {
2109           /* ??? Could use register post_modify for loads.  */
2110           if (! CONST_OK_FOR_I (disp))
2111             {
2112               rtx tmp = gen_rtx_REG (DImode, next_scratch_gr_reg ());
2113               emit_move_insn (tmp, disp_rtx);
2114               disp_rtx = tmp;
2115             }
2116           emit_insn (gen_adddi3 (spill_fill_data.iter_reg[iter],
2117                                  spill_fill_data.iter_reg[iter], disp_rtx));
2118         }
2119     }
2120   /* Micro-optimization: if we've created a frame pointer, it's at
2121      CFA 0, which may allow the real iterator to be initialized lower,
2122      slightly increasing parallelism.  Also, if there are few saves
2123      it may eliminate the iterator entirely.  */
2124   else if (disp == 0
2125            && spill_fill_data.init_reg[iter] == stack_pointer_rtx
2126            && frame_pointer_needed)
2127     {
2128       mem = gen_rtx_MEM (GET_MODE (reg), hard_frame_pointer_rtx);
2129       set_mem_alias_set (mem, get_varargs_alias_set ());
2130       return mem;
2131     }
2132   else
2133     {
2134       rtx seq, insn;
2135
2136       if (disp == 0)
2137         seq = gen_movdi (spill_fill_data.iter_reg[iter],
2138                          spill_fill_data.init_reg[iter]);
2139       else
2140         {
2141           start_sequence ();
2142
2143           if (! CONST_OK_FOR_I (disp))
2144             {
2145               rtx tmp = gen_rtx_REG (DImode, next_scratch_gr_reg ());
2146               emit_move_insn (tmp, disp_rtx);
2147               disp_rtx = tmp;
2148             }
2149
2150           emit_insn (gen_adddi3 (spill_fill_data.iter_reg[iter],
2151                                  spill_fill_data.init_reg[iter],
2152                                  disp_rtx));
2153
2154           seq = get_insns ();
2155           end_sequence ();
2156         }
2157
2158       /* Careful for being the first insn in a sequence.  */
2159       if (spill_fill_data.init_after)
2160         insn = emit_insn_after (seq, spill_fill_data.init_after);
2161       else
2162         {
2163           rtx first = get_insns ();
2164           if (first)
2165             insn = emit_insn_before (seq, first);
2166           else
2167             insn = emit_insn (seq);
2168         }
2169       spill_fill_data.init_after = insn;
2170
2171       /* If DISP is 0, we may or may not have a further adjustment
2172          afterward.  If we do, then the load/store insn may be modified
2173          to be a post-modify.  If we don't, then this copy may be
2174          eliminated by copyprop_hardreg_forward, which makes this
2175          insn garbage, which runs afoul of the sanity check in
2176          propagate_one_insn.  So mark this insn as legal to delete.  */
2177       if (disp == 0)
2178         REG_NOTES(insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD, const0_rtx,
2179                                              REG_NOTES (insn));
2180     }
2181
2182   mem = gen_rtx_MEM (GET_MODE (reg), spill_fill_data.iter_reg[iter]);
2183
2184   /* ??? Not all of the spills are for varargs, but some of them are.
2185      The rest of the spills belong in an alias set of their own.  But
2186      it doesn't actually hurt to include them here.  */
2187   set_mem_alias_set (mem, get_varargs_alias_set ());
2188
2189   spill_fill_data.prev_addr[iter] = &XEXP (mem, 0);
2190   spill_fill_data.prev_off[iter] = cfa_off;
2191
2192   if (++iter >= spill_fill_data.n_iter)
2193     iter = 0;
2194   spill_fill_data.next_iter = iter;
2195
2196   return mem;
2197 }
2198
2199 static void
2200 do_spill (move_fn, reg, cfa_off, frame_reg)
2201      rtx (*move_fn) PARAMS ((rtx, rtx, rtx));
2202      rtx reg, frame_reg;
2203      HOST_WIDE_INT cfa_off;
2204 {
2205   int iter = spill_fill_data.next_iter;
2206   rtx mem, insn;
2207
2208   mem = spill_restore_mem (reg, cfa_off);
2209   insn = emit_insn ((*move_fn) (mem, reg, GEN_INT (cfa_off)));
2210   spill_fill_data.prev_insn[iter] = insn;
2211
2212   if (frame_reg)
2213     {
2214       rtx base;
2215       HOST_WIDE_INT off;
2216
2217       RTX_FRAME_RELATED_P (insn) = 1;
2218
2219       /* Don't even pretend that the unwind code can intuit its way 
2220          through a pair of interleaved post_modify iterators.  Just
2221          provide the correct answer.  */
2222
2223       if (frame_pointer_needed)
2224         {
2225           base = hard_frame_pointer_rtx;
2226           off = - cfa_off;
2227         }
2228       else
2229         {
2230           base = stack_pointer_rtx;
2231           off = current_frame_info.total_size - cfa_off;
2232         }
2233
2234       REG_NOTES (insn)
2235         = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
2236                 gen_rtx_SET (VOIDmode,
2237                              gen_rtx_MEM (GET_MODE (reg),
2238                                           plus_constant (base, off)),
2239                              frame_reg),
2240                 REG_NOTES (insn));
2241     }
2242 }
2243
2244 static void
2245 do_restore (move_fn, reg, cfa_off)
2246      rtx (*move_fn) PARAMS ((rtx, rtx, rtx));
2247      rtx reg;
2248      HOST_WIDE_INT cfa_off;
2249 {
2250   int iter = spill_fill_data.next_iter;
2251   rtx insn;
2252
2253   insn = emit_insn ((*move_fn) (reg, spill_restore_mem (reg, cfa_off),
2254                                 GEN_INT (cfa_off)));
2255   spill_fill_data.prev_insn[iter] = insn;
2256 }
2257
2258 /* Wrapper functions that discards the CONST_INT spill offset.  These
2259    exist so that we can give gr_spill/gr_fill the offset they need and
2260    use a consistent function interface.  */
2261
2262 static rtx
2263 gen_movdi_x (dest, src, offset)
2264      rtx dest, src;
2265      rtx offset ATTRIBUTE_UNUSED;
2266 {
2267   return gen_movdi (dest, src);
2268 }
2269
2270 static rtx
2271 gen_fr_spill_x (dest, src, offset)
2272      rtx dest, src;
2273      rtx offset ATTRIBUTE_UNUSED;
2274 {
2275   return gen_fr_spill (dest, src);
2276 }
2277
2278 static rtx
2279 gen_fr_restore_x (dest, src, offset)
2280      rtx dest, src;
2281      rtx offset ATTRIBUTE_UNUSED;
2282 {
2283   return gen_fr_restore (dest, src);
2284 }
2285
2286 /* Called after register allocation to add any instructions needed for the
2287    prologue.  Using a prologue insn is favored compared to putting all of the
2288    instructions in output_function_prologue(), since it allows the scheduler
2289    to intermix instructions with the saves of the caller saved registers.  In
2290    some cases, it might be necessary to emit a barrier instruction as the last
2291    insn to prevent such scheduling.
2292
2293    Also any insns generated here should have RTX_FRAME_RELATED_P(insn) = 1
2294    so that the debug info generation code can handle them properly.
2295
2296    The register save area is layed out like so:
2297    cfa+16
2298         [ varargs spill area ]
2299         [ fr register spill area ]
2300         [ br register spill area ]
2301         [ ar register spill area ]
2302         [ pr register spill area ]
2303         [ gr register spill area ] */
2304
2305 /* ??? Get inefficient code when the frame size is larger than can fit in an
2306    adds instruction.  */
2307
2308 void
2309 ia64_expand_prologue ()
2310 {
2311   rtx insn, ar_pfs_save_reg, ar_unat_save_reg;
2312   int i, epilogue_p, regno, alt_regno, cfa_off, n_varargs;
2313   rtx reg, alt_reg;
2314
2315   ia64_compute_frame_size (get_frame_size ());
2316   last_scratch_gr_reg = 15;
2317
2318   /* If there is no epilogue, then we don't need some prologue insns.
2319      We need to avoid emitting the dead prologue insns, because flow
2320      will complain about them.  */
2321   if (optimize)
2322     {
2323       edge e;
2324
2325       for (e = EXIT_BLOCK_PTR->pred; e ; e = e->pred_next)
2326         if ((e->flags & EDGE_FAKE) == 0
2327             && (e->flags & EDGE_FALLTHRU) != 0)
2328           break;
2329       epilogue_p = (e != NULL);
2330     }
2331   else
2332     epilogue_p = 1;
2333
2334   /* Set the local, input, and output register names.  We need to do this
2335      for GNU libc, which creates crti.S/crtn.S by splitting initfini.c in
2336      half.  If we use in/loc/out register names, then we get assembler errors
2337      in crtn.S because there is no alloc insn or regstk directive in there.  */
2338   if (! TARGET_REG_NAMES)
2339     {
2340       int inputs = current_frame_info.n_input_regs;
2341       int locals = current_frame_info.n_local_regs;
2342       int outputs = current_frame_info.n_output_regs;
2343
2344       for (i = 0; i < inputs; i++)
2345         reg_names[IN_REG (i)] = ia64_reg_numbers[i];
2346       for (i = 0; i < locals; i++)
2347         reg_names[LOC_REG (i)] = ia64_reg_numbers[inputs + i];
2348       for (i = 0; i < outputs; i++)
2349         reg_names[OUT_REG (i)] = ia64_reg_numbers[inputs + locals + i];
2350     }
2351
2352   /* Set the frame pointer register name.  The regnum is logically loc79,
2353      but of course we'll not have allocated that many locals.  Rather than
2354      worrying about renumbering the existing rtxs, we adjust the name.  */
2355   /* ??? This code means that we can never use one local register when
2356      there is a frame pointer.  loc79 gets wasted in this case, as it is
2357      renamed to a register that will never be used.  See also the try_locals
2358      code in find_gr_spill.  */
2359   if (current_frame_info.reg_fp)
2360     {
2361       const char *tmp = reg_names[HARD_FRAME_POINTER_REGNUM];
2362       reg_names[HARD_FRAME_POINTER_REGNUM]
2363         = reg_names[current_frame_info.reg_fp];
2364       reg_names[current_frame_info.reg_fp] = tmp;
2365     }
2366
2367   /* Fix up the return address placeholder.  */
2368   /* ??? We can fail if __builtin_return_address is used, and we didn't
2369      allocate a register in which to save b0.  I can't think of a way to
2370      eliminate RETURN_ADDRESS_POINTER_REGNUM to a local register and
2371      then be sure that I got the right one.  Further, reload doesn't seem
2372      to care if an eliminable register isn't used, and "eliminates" it
2373      anyway.  */
2374   if (regs_ever_live[RETURN_ADDRESS_POINTER_REGNUM]
2375       && current_frame_info.reg_save_b0 != 0)
2376     XINT (return_address_pointer_rtx, 0) = current_frame_info.reg_save_b0;
2377
2378   /* We don't need an alloc instruction if we've used no outputs or locals.  */
2379   if (current_frame_info.n_local_regs == 0
2380       && current_frame_info.n_output_regs == 0
2381       && current_frame_info.n_input_regs <= current_function_args_info.int_regs)
2382     {
2383       /* If there is no alloc, but there are input registers used, then we
2384          need a .regstk directive.  */
2385       current_frame_info.need_regstk = (TARGET_REG_NAMES != 0);
2386       ar_pfs_save_reg = NULL_RTX;
2387     }
2388   else
2389     {
2390       current_frame_info.need_regstk = 0;
2391
2392       if (current_frame_info.reg_save_ar_pfs)
2393         regno = current_frame_info.reg_save_ar_pfs;
2394       else
2395         regno = next_scratch_gr_reg ();
2396       ar_pfs_save_reg = gen_rtx_REG (DImode, regno);
2397
2398       insn = emit_insn (gen_alloc (ar_pfs_save_reg, 
2399                                    GEN_INT (current_frame_info.n_input_regs),
2400                                    GEN_INT (current_frame_info.n_local_regs),
2401                                    GEN_INT (current_frame_info.n_output_regs),
2402                                    GEN_INT (current_frame_info.n_rotate_regs)));
2403       RTX_FRAME_RELATED_P (insn) = (current_frame_info.reg_save_ar_pfs != 0);
2404     }
2405
2406   /* Set up frame pointer, stack pointer, and spill iterators.  */
2407
2408   n_varargs = cfun->machine->n_varargs;
2409   setup_spill_pointers (current_frame_info.n_spilled + n_varargs,
2410                         stack_pointer_rtx, 0);
2411
2412   if (frame_pointer_needed)
2413     {
2414       insn = emit_move_insn (hard_frame_pointer_rtx, stack_pointer_rtx);
2415       RTX_FRAME_RELATED_P (insn) = 1;
2416     }
2417
2418   if (current_frame_info.total_size != 0)
2419     {
2420       rtx frame_size_rtx = GEN_INT (- current_frame_info.total_size);
2421       rtx offset;
2422
2423       if (CONST_OK_FOR_I (- current_frame_info.total_size))
2424         offset = frame_size_rtx;
2425       else
2426         {
2427           regno = next_scratch_gr_reg ();
2428           offset = gen_rtx_REG (DImode, regno);
2429           emit_move_insn (offset, frame_size_rtx);
2430         }
2431
2432       insn = emit_insn (gen_adddi3 (stack_pointer_rtx,
2433                                     stack_pointer_rtx, offset));
2434
2435       if (! frame_pointer_needed)
2436         {
2437           RTX_FRAME_RELATED_P (insn) = 1;
2438           if (GET_CODE (offset) != CONST_INT)
2439             {
2440               REG_NOTES (insn)
2441                 = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
2442                         gen_rtx_SET (VOIDmode,
2443                                      stack_pointer_rtx,
2444                                      gen_rtx_PLUS (DImode,
2445                                                    stack_pointer_rtx,
2446                                                    frame_size_rtx)),
2447                         REG_NOTES (insn));
2448             }
2449         }
2450
2451       /* ??? At this point we must generate a magic insn that appears to
2452          modify the stack pointer, the frame pointer, and all spill
2453          iterators.  This would allow the most scheduling freedom.  For
2454          now, just hard stop.  */
2455       emit_insn (gen_blockage ());
2456     }
2457
2458   /* Must copy out ar.unat before doing any integer spills.  */
2459   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
2460     {
2461       if (current_frame_info.reg_save_ar_unat)
2462         ar_unat_save_reg
2463           = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_unat);
2464       else
2465         {
2466           alt_regno = next_scratch_gr_reg ();
2467           ar_unat_save_reg = gen_rtx_REG (DImode, alt_regno);
2468           current_frame_info.gr_used_mask |= 1 << alt_regno;
2469         }
2470
2471       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
2472       insn = emit_move_insn (ar_unat_save_reg, reg);
2473       RTX_FRAME_RELATED_P (insn) = (current_frame_info.reg_save_ar_unat != 0);
2474
2475       /* Even if we're not going to generate an epilogue, we still
2476          need to save the register so that EH works.  */
2477       if (! epilogue_p && current_frame_info.reg_save_ar_unat)
2478         emit_insn (gen_prologue_use (ar_unat_save_reg));
2479     }
2480   else
2481     ar_unat_save_reg = NULL_RTX;
2482
2483   /* Spill all varargs registers.  Do this before spilling any GR registers,
2484      since we want the UNAT bits for the GR registers to override the UNAT
2485      bits from varargs, which we don't care about.  */
2486
2487   cfa_off = -16;
2488   for (regno = GR_ARG_FIRST + 7; n_varargs > 0; --n_varargs, --regno)
2489     {
2490       reg = gen_rtx_REG (DImode, regno);
2491       do_spill (gen_gr_spill, reg, cfa_off += 8, NULL_RTX);
2492     }
2493
2494   /* Locate the bottom of the register save area.  */
2495   cfa_off = (current_frame_info.spill_cfa_off
2496              + current_frame_info.spill_size
2497              + current_frame_info.extra_spill_size);
2498
2499   /* Save the predicate register block either in a register or in memory.  */
2500   if (TEST_HARD_REG_BIT (current_frame_info.mask, PR_REG (0)))
2501     {
2502       reg = gen_rtx_REG (DImode, PR_REG (0));
2503       if (current_frame_info.reg_save_pr != 0)
2504         {
2505           alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_pr);
2506           insn = emit_move_insn (alt_reg, reg);
2507
2508           /* ??? Denote pr spill/fill by a DImode move that modifies all
2509              64 hard registers.  */
2510           RTX_FRAME_RELATED_P (insn) = 1;
2511           REG_NOTES (insn)
2512             = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
2513                         gen_rtx_SET (VOIDmode, alt_reg, reg),
2514                         REG_NOTES (insn));
2515
2516           /* Even if we're not going to generate an epilogue, we still
2517              need to save the register so that EH works.  */
2518           if (! epilogue_p)
2519             emit_insn (gen_prologue_use (alt_reg));
2520         }
2521       else
2522         {
2523           alt_regno = next_scratch_gr_reg ();
2524           alt_reg = gen_rtx_REG (DImode, alt_regno);
2525           insn = emit_move_insn (alt_reg, reg);
2526           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
2527           cfa_off -= 8;
2528         }
2529     }
2530
2531   /* Handle AR regs in numerical order.  All of them get special handling.  */
2532   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM)
2533       && current_frame_info.reg_save_ar_unat == 0)
2534     {
2535       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
2536       do_spill (gen_movdi_x, ar_unat_save_reg, cfa_off, reg);
2537       cfa_off -= 8;
2538     }
2539
2540   /* The alloc insn already copied ar.pfs into a general register.  The
2541      only thing we have to do now is copy that register to a stack slot
2542      if we'd not allocated a local register for the job.  */
2543   if (current_frame_info.reg_save_ar_pfs == 0
2544       && ! current_function_is_leaf)
2545     {
2546       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
2547       do_spill (gen_movdi_x, ar_pfs_save_reg, cfa_off, reg);
2548       cfa_off -= 8;
2549     }
2550
2551   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_LC_REGNUM))
2552     {
2553       reg = gen_rtx_REG (DImode, AR_LC_REGNUM);
2554       if (current_frame_info.reg_save_ar_lc != 0)
2555         {
2556           alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_lc);
2557           insn = emit_move_insn (alt_reg, reg);
2558           RTX_FRAME_RELATED_P (insn) = 1;
2559
2560           /* Even if we're not going to generate an epilogue, we still
2561              need to save the register so that EH works.  */
2562           if (! epilogue_p)
2563             emit_insn (gen_prologue_use (alt_reg));
2564         }
2565       else
2566         {
2567           alt_regno = next_scratch_gr_reg ();
2568           alt_reg = gen_rtx_REG (DImode, alt_regno);
2569           emit_move_insn (alt_reg, reg);
2570           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
2571           cfa_off -= 8;
2572         }
2573     }
2574
2575   if (current_frame_info.reg_save_gp)
2576     {
2577       insn = emit_move_insn (gen_rtx_REG (DImode,
2578                                           current_frame_info.reg_save_gp),
2579                              pic_offset_table_rtx);
2580       /* We don't know for sure yet if this is actually needed, since
2581          we've not split the PIC call patterns.  If all of the calls
2582          are indirect, and not followed by any uses of the gp, then
2583          this save is dead.  Allow it to go away.  */
2584       REG_NOTES (insn)
2585         = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD, const0_rtx, REG_NOTES (insn));
2586     }
2587
2588   /* We should now be at the base of the gr/br/fr spill area.  */
2589   if (cfa_off != (current_frame_info.spill_cfa_off
2590                   + current_frame_info.spill_size))
2591     abort ();
2592
2593   /* Spill all general registers.  */
2594   for (regno = GR_REG (1); regno <= GR_REG (31); ++regno)
2595     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
2596       {
2597         reg = gen_rtx_REG (DImode, regno);
2598         do_spill (gen_gr_spill, reg, cfa_off, reg);
2599         cfa_off -= 8;
2600       }
2601
2602   /* Handle BR0 specially -- it may be getting stored permanently in
2603      some GR register.  */
2604   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
2605     {
2606       reg = gen_rtx_REG (DImode, BR_REG (0));
2607       if (current_frame_info.reg_save_b0 != 0)
2608         {
2609           alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_b0);
2610           insn = emit_move_insn (alt_reg, reg);
2611           RTX_FRAME_RELATED_P (insn) = 1;
2612
2613           /* Even if we're not going to generate an epilogue, we still
2614              need to save the register so that EH works.  */
2615           if (! epilogue_p)
2616             emit_insn (gen_prologue_use (alt_reg));
2617         }
2618       else
2619         {
2620           alt_regno = next_scratch_gr_reg ();
2621           alt_reg = gen_rtx_REG (DImode, alt_regno);
2622           emit_move_insn (alt_reg, reg);
2623           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
2624           cfa_off -= 8;
2625         }
2626     }
2627
2628   /* Spill the rest of the BR registers.  */
2629   for (regno = BR_REG (1); regno <= BR_REG (7); ++regno)
2630     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
2631       {
2632         alt_regno = next_scratch_gr_reg ();
2633         alt_reg = gen_rtx_REG (DImode, alt_regno);
2634         reg = gen_rtx_REG (DImode, regno);
2635         emit_move_insn (alt_reg, reg);
2636         do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
2637         cfa_off -= 8;
2638       }
2639
2640   /* Align the frame and spill all FR registers.  */
2641   for (regno = FR_REG (2); regno <= FR_REG (127); ++regno)
2642     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
2643       {
2644         if (cfa_off & 15)
2645           abort ();
2646         reg = gen_rtx_REG (TFmode, regno);
2647         do_spill (gen_fr_spill_x, reg, cfa_off, reg);
2648         cfa_off -= 16;
2649       }
2650
2651   if (cfa_off != current_frame_info.spill_cfa_off)
2652     abort ();
2653
2654   finish_spill_pointers ();
2655 }
2656
2657 /* Called after register allocation to add any instructions needed for the
2658    epilogue.  Using an epilogue insn is favored compared to putting all of the
2659    instructions in output_function_prologue(), since it allows the scheduler
2660    to intermix instructions with the saves of the caller saved registers.  In
2661    some cases, it might be necessary to emit a barrier instruction as the last
2662    insn to prevent such scheduling.  */
2663
2664 void
2665 ia64_expand_epilogue (sibcall_p)
2666      int sibcall_p;
2667 {
2668   rtx insn, reg, alt_reg, ar_unat_save_reg;
2669   int regno, alt_regno, cfa_off;
2670
2671   ia64_compute_frame_size (get_frame_size ());
2672
2673   /* If there is a frame pointer, then we use it instead of the stack
2674      pointer, so that the stack pointer does not need to be valid when
2675      the epilogue starts.  See EXIT_IGNORE_STACK.  */
2676   if (frame_pointer_needed)
2677     setup_spill_pointers (current_frame_info.n_spilled,
2678                           hard_frame_pointer_rtx, 0);
2679   else
2680     setup_spill_pointers (current_frame_info.n_spilled, stack_pointer_rtx, 
2681                           current_frame_info.total_size);
2682
2683   if (current_frame_info.total_size != 0)
2684     {
2685       /* ??? At this point we must generate a magic insn that appears to
2686          modify the spill iterators and the frame pointer.  This would
2687          allow the most scheduling freedom.  For now, just hard stop.  */
2688       emit_insn (gen_blockage ());
2689     }
2690
2691   /* Locate the bottom of the register save area.  */
2692   cfa_off = (current_frame_info.spill_cfa_off
2693              + current_frame_info.spill_size
2694              + current_frame_info.extra_spill_size);
2695
2696   /* Restore the predicate registers.  */
2697   if (TEST_HARD_REG_BIT (current_frame_info.mask, PR_REG (0)))
2698     {
2699       if (current_frame_info.reg_save_pr != 0)
2700         alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_pr);
2701       else
2702         {
2703           alt_regno = next_scratch_gr_reg ();
2704           alt_reg = gen_rtx_REG (DImode, alt_regno);
2705           do_restore (gen_movdi_x, alt_reg, cfa_off);
2706           cfa_off -= 8;
2707         }
2708       reg = gen_rtx_REG (DImode, PR_REG (0));
2709       emit_move_insn (reg, alt_reg);
2710     }
2711
2712   /* Restore the application registers.  */
2713
2714   /* Load the saved unat from the stack, but do not restore it until
2715      after the GRs have been restored.  */
2716   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
2717     {
2718       if (current_frame_info.reg_save_ar_unat != 0)
2719         ar_unat_save_reg
2720           = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_unat);
2721       else
2722         {
2723           alt_regno = next_scratch_gr_reg ();
2724           ar_unat_save_reg = gen_rtx_REG (DImode, alt_regno);
2725           current_frame_info.gr_used_mask |= 1 << alt_regno;
2726           do_restore (gen_movdi_x, ar_unat_save_reg, cfa_off);
2727           cfa_off -= 8;
2728         }
2729     }
2730   else
2731     ar_unat_save_reg = NULL_RTX;
2732       
2733   if (current_frame_info.reg_save_ar_pfs != 0)
2734     {
2735       alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_pfs);
2736       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
2737       emit_move_insn (reg, alt_reg);
2738     }
2739   else if (! current_function_is_leaf)
2740     {
2741       alt_regno = next_scratch_gr_reg ();
2742       alt_reg = gen_rtx_REG (DImode, alt_regno);
2743       do_restore (gen_movdi_x, alt_reg, cfa_off);
2744       cfa_off -= 8;
2745       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
2746       emit_move_insn (reg, alt_reg);
2747     }
2748
2749   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_LC_REGNUM))
2750     {
2751       if (current_frame_info.reg_save_ar_lc != 0)
2752         alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_lc);
2753       else
2754         {
2755           alt_regno = next_scratch_gr_reg ();
2756           alt_reg = gen_rtx_REG (DImode, alt_regno);
2757           do_restore (gen_movdi_x, alt_reg, cfa_off);
2758           cfa_off -= 8;
2759         }
2760       reg = gen_rtx_REG (DImode, AR_LC_REGNUM);
2761       emit_move_insn (reg, alt_reg);
2762     }
2763
2764   /* We should now be at the base of the gr/br/fr spill area.  */
2765   if (cfa_off != (current_frame_info.spill_cfa_off
2766                   + current_frame_info.spill_size))
2767     abort ();
2768
2769   /* The GP may be stored on the stack in the prologue, but it's
2770      never restored in the epilogue.  Skip the stack slot.  */
2771   if (TEST_HARD_REG_BIT (current_frame_info.mask, GR_REG (1)))
2772     cfa_off -= 8;
2773
2774   /* Restore all general registers.  */
2775   for (regno = GR_REG (2); regno <= GR_REG (31); ++regno)
2776     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
2777       {
2778         reg = gen_rtx_REG (DImode, regno);
2779         do_restore (gen_gr_restore, reg, cfa_off);
2780         cfa_off -= 8;
2781       }
2782   
2783   /* Restore the branch registers.  Handle B0 specially, as it may
2784      have gotten stored in some GR register.  */
2785   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
2786     {
2787       if (current_frame_info.reg_save_b0 != 0)
2788         alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_b0);
2789       else
2790         {
2791           alt_regno = next_scratch_gr_reg ();
2792           alt_reg = gen_rtx_REG (DImode, alt_regno);
2793           do_restore (gen_movdi_x, alt_reg, cfa_off);
2794           cfa_off -= 8;
2795         }
2796       reg = gen_rtx_REG (DImode, BR_REG (0));
2797       emit_move_insn (reg, alt_reg);
2798     }
2799     
2800   for (regno = BR_REG (1); regno <= BR_REG (7); ++regno)
2801     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
2802       {
2803         alt_regno = next_scratch_gr_reg ();
2804         alt_reg = gen_rtx_REG (DImode, alt_regno);
2805         do_restore (gen_movdi_x, alt_reg, cfa_off);
2806         cfa_off -= 8;
2807         reg = gen_rtx_REG (DImode, regno);
2808         emit_move_insn (reg, alt_reg);
2809       }
2810
2811   /* Restore floating point registers.  */
2812   for (regno = FR_REG (2); regno <= FR_REG (127); ++regno)
2813     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
2814       {
2815         if (cfa_off & 15)
2816           abort ();
2817         reg = gen_rtx_REG (TFmode, regno);
2818         do_restore (gen_fr_restore_x, reg, cfa_off);
2819         cfa_off -= 16;
2820       }
2821
2822   /* Restore ar.unat for real.  */
2823   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
2824     {
2825       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
2826       emit_move_insn (reg, ar_unat_save_reg);
2827     }
2828
2829   if (cfa_off != current_frame_info.spill_cfa_off)
2830     abort ();
2831
2832   finish_spill_pointers ();
2833
2834   if (current_frame_info.total_size || cfun->machine->ia64_eh_epilogue_sp)
2835     {
2836       /* ??? At this point we must generate a magic insn that appears to
2837          modify the spill iterators, the stack pointer, and the frame
2838          pointer.  This would allow the most scheduling freedom.  For now,
2839          just hard stop.  */
2840       emit_insn (gen_blockage ());
2841     }
2842
2843   if (cfun->machine->ia64_eh_epilogue_sp)
2844     emit_move_insn (stack_pointer_rtx, cfun->machine->ia64_eh_epilogue_sp);
2845   else if (frame_pointer_needed)
2846     {
2847       insn = emit_move_insn (stack_pointer_rtx, hard_frame_pointer_rtx);
2848       RTX_FRAME_RELATED_P (insn) = 1;
2849     }
2850   else if (current_frame_info.total_size)
2851     {
2852       rtx offset, frame_size_rtx;
2853
2854       frame_size_rtx = GEN_INT (current_frame_info.total_size);
2855       if (CONST_OK_FOR_I (current_frame_info.total_size))
2856         offset = frame_size_rtx;
2857       else
2858         {
2859           regno = next_scratch_gr_reg ();
2860           offset = gen_rtx_REG (DImode, regno);
2861           emit_move_insn (offset, frame_size_rtx);
2862         }
2863
2864       insn = emit_insn (gen_adddi3 (stack_pointer_rtx, stack_pointer_rtx,
2865                                     offset));
2866
2867       RTX_FRAME_RELATED_P (insn) = 1;
2868       if (GET_CODE (offset) != CONST_INT)
2869         {
2870           REG_NOTES (insn)
2871             = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
2872                         gen_rtx_SET (VOIDmode,
2873                                      stack_pointer_rtx,
2874                                      gen_rtx_PLUS (DImode,
2875                                                    stack_pointer_rtx,
2876                                                    frame_size_rtx)),
2877                         REG_NOTES (insn));
2878         }
2879     }
2880
2881   if (cfun->machine->ia64_eh_epilogue_bsp)
2882     emit_insn (gen_set_bsp (cfun->machine->ia64_eh_epilogue_bsp));
2883  
2884   if (! sibcall_p)
2885     emit_jump_insn (gen_return_internal (gen_rtx_REG (DImode, BR_REG (0))));
2886   else
2887     {
2888       int fp = GR_REG (2);
2889       /* We need a throw away register here, r0 and r1 are reserved, so r2 is the
2890          first available call clobbered register.  If there was a frame_pointer 
2891          register, we may have swapped the names of r2 and HARD_FRAME_POINTER_REGNUM, 
2892          so we have to make sure we're using the string "r2" when emitting
2893          the register name for the assembler.  */
2894       if (current_frame_info.reg_fp && current_frame_info.reg_fp == GR_REG (2))
2895         fp = HARD_FRAME_POINTER_REGNUM;
2896
2897       /* We must emit an alloc to force the input registers to become output
2898          registers.  Otherwise, if the callee tries to pass its parameters
2899          through to another call without an intervening alloc, then these
2900          values get lost.  */
2901       /* ??? We don't need to preserve all input registers.  We only need to
2902          preserve those input registers used as arguments to the sibling call.
2903          It is unclear how to compute that number here.  */
2904       if (current_frame_info.n_input_regs != 0)
2905         emit_insn (gen_alloc (gen_rtx_REG (DImode, fp),
2906                               GEN_INT (0), GEN_INT (0),
2907                               GEN_INT (current_frame_info.n_input_regs),
2908                               GEN_INT (0)));
2909     }
2910 }
2911
2912 /* Return 1 if br.ret can do all the work required to return from a
2913    function.  */
2914
2915 int
2916 ia64_direct_return ()
2917 {
2918   if (reload_completed && ! frame_pointer_needed)
2919     {
2920       ia64_compute_frame_size (get_frame_size ());
2921
2922       return (current_frame_info.total_size == 0
2923               && current_frame_info.n_spilled == 0
2924               && current_frame_info.reg_save_b0 == 0
2925               && current_frame_info.reg_save_pr == 0
2926               && current_frame_info.reg_save_ar_pfs == 0
2927               && current_frame_info.reg_save_ar_unat == 0
2928               && current_frame_info.reg_save_ar_lc == 0);
2929     }
2930   return 0;
2931 }
2932
2933 int
2934 ia64_hard_regno_rename_ok (from, to)
2935      int from;
2936      int to;
2937 {
2938   /* Don't clobber any of the registers we reserved for the prologue.  */
2939   if (to == current_frame_info.reg_fp
2940       || to == current_frame_info.reg_save_b0
2941       || to == current_frame_info.reg_save_pr
2942       || to == current_frame_info.reg_save_ar_pfs
2943       || to == current_frame_info.reg_save_ar_unat
2944       || to == current_frame_info.reg_save_ar_lc)
2945     return 0;
2946
2947   if (from == current_frame_info.reg_fp
2948       || from == current_frame_info.reg_save_b0
2949       || from == current_frame_info.reg_save_pr
2950       || from == current_frame_info.reg_save_ar_pfs
2951       || from == current_frame_info.reg_save_ar_unat
2952       || from == current_frame_info.reg_save_ar_lc)
2953     return 0;
2954
2955   /* Don't use output registers outside the register frame.  */
2956   if (OUT_REGNO_P (to) && to >= OUT_REG (current_frame_info.n_output_regs))
2957     return 0;
2958
2959   /* Retain even/oddness on predicate register pairs.  */
2960   if (PR_REGNO_P (from) && PR_REGNO_P (to))
2961     return (from & 1) == (to & 1);
2962
2963   return 1;
2964 }
2965
2966 /* Target hook for assembling integer objects.  Handle word-sized
2967    aligned objects and detect the cases when @fptr is needed.  */
2968
2969 static bool
2970 ia64_assemble_integer (x, size, aligned_p)
2971      rtx x;
2972      unsigned int size;
2973      int aligned_p;
2974 {
2975   if (size == (TARGET_ILP32 ? 4 : 8)
2976       && aligned_p
2977       && !(TARGET_NO_PIC || TARGET_AUTO_PIC)
2978       && GET_CODE (x) == SYMBOL_REF
2979       && SYMBOL_REF_FUNCTION_P (x))
2980     {
2981       if (TARGET_ILP32)
2982         fputs ("\tdata4\t@fptr(", asm_out_file);
2983       else
2984         fputs ("\tdata8\t@fptr(", asm_out_file);
2985       output_addr_const (asm_out_file, x);
2986       fputs (")\n", asm_out_file);
2987       return true;
2988     }
2989   return default_assemble_integer (x, size, aligned_p);
2990 }
2991
2992 /* Emit the function prologue.  */
2993
2994 static void
2995 ia64_output_function_prologue (file, size)
2996      FILE *file;
2997      HOST_WIDE_INT size ATTRIBUTE_UNUSED;
2998 {
2999   int mask, grsave, grsave_prev;
3000
3001   if (current_frame_info.need_regstk)
3002     fprintf (file, "\t.regstk %d, %d, %d, %d\n",
3003              current_frame_info.n_input_regs,
3004              current_frame_info.n_local_regs,
3005              current_frame_info.n_output_regs,
3006              current_frame_info.n_rotate_regs);
3007
3008   if (!flag_unwind_tables && (!flag_exceptions || USING_SJLJ_EXCEPTIONS))
3009     return;
3010
3011   /* Emit the .prologue directive.  */
3012
3013   mask = 0;
3014   grsave = grsave_prev = 0;
3015   if (current_frame_info.reg_save_b0 != 0)
3016     {
3017       mask |= 8;
3018       grsave = grsave_prev = current_frame_info.reg_save_b0;
3019     }
3020   if (current_frame_info.reg_save_ar_pfs != 0
3021       && (grsave_prev == 0
3022           || current_frame_info.reg_save_ar_pfs == grsave_prev + 1))
3023     {
3024       mask |= 4;
3025       if (grsave_prev == 0)
3026         grsave = current_frame_info.reg_save_ar_pfs;
3027       grsave_prev = current_frame_info.reg_save_ar_pfs;
3028     }
3029   if (current_frame_info.reg_fp != 0
3030       && (grsave_prev == 0
3031           || current_frame_info.reg_fp == grsave_prev + 1))
3032     {
3033       mask |= 2;
3034       if (grsave_prev == 0)
3035         grsave = HARD_FRAME_POINTER_REGNUM;
3036       grsave_prev = current_frame_info.reg_fp;
3037     }
3038   if (current_frame_info.reg_save_pr != 0
3039       && (grsave_prev == 0
3040           || current_frame_info.reg_save_pr == grsave_prev + 1))
3041     {
3042       mask |= 1;
3043       if (grsave_prev == 0)
3044         grsave = current_frame_info.reg_save_pr;
3045     }
3046
3047   if (mask)
3048     fprintf (file, "\t.prologue %d, %d\n", mask,
3049              ia64_dbx_register_number (grsave));
3050   else
3051     fputs ("\t.prologue\n", file);
3052
3053   /* Emit a .spill directive, if necessary, to relocate the base of
3054      the register spill area.  */
3055   if (current_frame_info.spill_cfa_off != -16)
3056     fprintf (file, "\t.spill %ld\n",
3057              (long) (current_frame_info.spill_cfa_off
3058                      + current_frame_info.spill_size));
3059 }
3060
3061 /* Emit the .body directive at the scheduled end of the prologue.  */
3062
3063 static void
3064 ia64_output_function_end_prologue (file)
3065      FILE *file;
3066 {
3067   if (!flag_unwind_tables && (!flag_exceptions || USING_SJLJ_EXCEPTIONS))
3068     return;
3069
3070   fputs ("\t.body\n", file);
3071 }
3072
3073 /* Emit the function epilogue.  */
3074
3075 static void
3076 ia64_output_function_epilogue (file, size)
3077      FILE *file ATTRIBUTE_UNUSED;
3078      HOST_WIDE_INT size ATTRIBUTE_UNUSED;
3079 {
3080   int i;
3081
3082   /* Reset from the function's potential modifications.  */
3083   XINT (return_address_pointer_rtx, 0) = RETURN_ADDRESS_POINTER_REGNUM;
3084
3085   if (current_frame_info.reg_fp)
3086     {
3087       const char *tmp = reg_names[HARD_FRAME_POINTER_REGNUM];
3088       reg_names[HARD_FRAME_POINTER_REGNUM]
3089         = reg_names[current_frame_info.reg_fp];
3090       reg_names[current_frame_info.reg_fp] = tmp;
3091     }
3092   if (! TARGET_REG_NAMES)
3093     {
3094       for (i = 0; i < current_frame_info.n_input_regs; i++)
3095         reg_names[IN_REG (i)] = ia64_input_reg_names[i];
3096       for (i = 0; i < current_frame_info.n_local_regs; i++)
3097         reg_names[LOC_REG (i)] = ia64_local_reg_names[i];
3098       for (i = 0; i < current_frame_info.n_output_regs; i++)
3099         reg_names[OUT_REG (i)] = ia64_output_reg_names[i];
3100     }
3101
3102   current_frame_info.initialized = 0;
3103 }
3104
3105 int
3106 ia64_dbx_register_number (regno)
3107      int regno;
3108 {
3109   /* In ia64_expand_prologue we quite literally renamed the frame pointer
3110      from its home at loc79 to something inside the register frame.  We
3111      must perform the same renumbering here for the debug info.  */
3112   if (current_frame_info.reg_fp)
3113     {
3114       if (regno == HARD_FRAME_POINTER_REGNUM)
3115         regno = current_frame_info.reg_fp;
3116       else if (regno == current_frame_info.reg_fp)
3117         regno = HARD_FRAME_POINTER_REGNUM;
3118     }
3119
3120   if (IN_REGNO_P (regno))
3121     return 32 + regno - IN_REG (0);
3122   else if (LOC_REGNO_P (regno))
3123     return 32 + current_frame_info.n_input_regs + regno - LOC_REG (0);
3124   else if (OUT_REGNO_P (regno))
3125     return (32 + current_frame_info.n_input_regs
3126             + current_frame_info.n_local_regs + regno - OUT_REG (0));
3127   else
3128     return regno;
3129 }
3130
3131 void
3132 ia64_initialize_trampoline (addr, fnaddr, static_chain)
3133      rtx addr, fnaddr, static_chain;
3134 {
3135   rtx addr_reg, eight = GEN_INT (8);
3136
3137   /* Load up our iterator.  */
3138   addr_reg = gen_reg_rtx (Pmode);
3139   emit_move_insn (addr_reg, addr);
3140
3141   /* The first two words are the fake descriptor:
3142      __ia64_trampoline, ADDR+16.  */
3143   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg),
3144                   gen_rtx_SYMBOL_REF (Pmode, "__ia64_trampoline"));
3145   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
3146
3147   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg),
3148                   copy_to_reg (plus_constant (addr, 16)));
3149   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
3150
3151   /* The third word is the target descriptor.  */
3152   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg), fnaddr);
3153   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
3154
3155   /* The fourth word is the static chain.  */
3156   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg), static_chain);
3157 }
3158 \f
3159 /* Do any needed setup for a variadic function.  CUM has not been updated
3160    for the last named argument which has type TYPE and mode MODE.
3161
3162    We generate the actual spill instructions during prologue generation.  */
3163
3164 void
3165 ia64_setup_incoming_varargs (cum, int_mode, type, pretend_size, second_time)
3166      CUMULATIVE_ARGS cum;
3167      int             int_mode;
3168      tree            type;
3169      int *           pretend_size;
3170      int             second_time ATTRIBUTE_UNUSED;
3171 {
3172   /* Skip the current argument.  */
3173   ia64_function_arg_advance (&cum, int_mode, type, 1);
3174
3175   if (cum.words < MAX_ARGUMENT_SLOTS)
3176     {
3177       int n = MAX_ARGUMENT_SLOTS - cum.words;
3178       *pretend_size = n * UNITS_PER_WORD;
3179       cfun->machine->n_varargs = n;
3180     }
3181 }
3182
3183 /* Check whether TYPE is a homogeneous floating point aggregate.  If
3184    it is, return the mode of the floating point type that appears
3185    in all leafs.  If it is not, return VOIDmode.
3186
3187    An aggregate is a homogeneous floating point aggregate is if all
3188    fields/elements in it have the same floating point type (e.g,
3189    SFmode).  128-bit quad-precision floats are excluded.  */
3190
3191 static enum machine_mode
3192 hfa_element_mode (type, nested)
3193      tree type;
3194      int nested;
3195 {
3196   enum machine_mode element_mode = VOIDmode;
3197   enum machine_mode mode;
3198   enum tree_code code = TREE_CODE (type);
3199   int know_element_mode = 0;
3200   tree t;
3201
3202   switch (code)
3203     {
3204     case VOID_TYPE:     case INTEGER_TYPE:      case ENUMERAL_TYPE:
3205     case BOOLEAN_TYPE:  case CHAR_TYPE:         case POINTER_TYPE:
3206     case OFFSET_TYPE:   case REFERENCE_TYPE:    case METHOD_TYPE:
3207     case FILE_TYPE:     case SET_TYPE:          case LANG_TYPE:
3208     case FUNCTION_TYPE:
3209       return VOIDmode;
3210
3211       /* Fortran complex types are supposed to be HFAs, so we need to handle
3212          gcc's COMPLEX_TYPEs as HFAs.  We need to exclude the integral complex
3213          types though.  */
3214     case COMPLEX_TYPE:
3215       if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_COMPLEX_FLOAT
3216           && (TYPE_MODE (type) != TCmode || INTEL_EXTENDED_IEEE_FORMAT))
3217         return mode_for_size (GET_MODE_UNIT_SIZE (TYPE_MODE (type))
3218                               * BITS_PER_UNIT, MODE_FLOAT, 0);
3219       else
3220         return VOIDmode;
3221
3222     case REAL_TYPE:
3223       /* We want to return VOIDmode for raw REAL_TYPEs, but the actual
3224          mode if this is contained within an aggregate.  */
3225       if (nested && (TYPE_MODE (type) != TFmode || INTEL_EXTENDED_IEEE_FORMAT))
3226         return TYPE_MODE (type);
3227       else
3228         return VOIDmode;
3229
3230     case ARRAY_TYPE:
3231       return hfa_element_mode (TREE_TYPE (type), 1);
3232
3233     case RECORD_TYPE:
3234     case UNION_TYPE:
3235     case QUAL_UNION_TYPE:
3236       for (t = TYPE_FIELDS (type); t; t = TREE_CHAIN (t))
3237         {
3238           if (TREE_CODE (t) != FIELD_DECL)
3239             continue;
3240
3241           mode = hfa_element_mode (TREE_TYPE (t), 1);
3242           if (know_element_mode)
3243             {
3244               if (mode != element_mode)
3245                 return VOIDmode;
3246             }
3247           else if (GET_MODE_CLASS (mode) != MODE_FLOAT)
3248             return VOIDmode;
3249           else
3250             {
3251               know_element_mode = 1;
3252               element_mode = mode;
3253             }
3254         }
3255       return element_mode;
3256
3257     default:
3258       /* If we reach here, we probably have some front-end specific type
3259          that the backend doesn't know about.  This can happen via the
3260          aggregate_value_p call in init_function_start.  All we can do is
3261          ignore unknown tree types.  */
3262       return VOIDmode;
3263     }
3264
3265   return VOIDmode;
3266 }
3267
3268 /* Return rtx for register where argument is passed, or zero if it is passed
3269    on the stack.  */
3270
3271 /* ??? 128-bit quad-precision floats are always passed in general
3272    registers.  */
3273
3274 rtx
3275 ia64_function_arg (cum, mode, type, named, incoming)
3276      CUMULATIVE_ARGS *cum;
3277      enum machine_mode mode;
3278      tree type;
3279      int named;
3280      int incoming;
3281 {
3282   int basereg = (incoming ? GR_ARG_FIRST : AR_ARG_FIRST);
3283   int words = (((mode == BLKmode ? int_size_in_bytes (type)
3284                  : GET_MODE_SIZE (mode)) + UNITS_PER_WORD - 1)
3285                / UNITS_PER_WORD);
3286   int offset = 0;
3287   enum machine_mode hfa_mode = VOIDmode;
3288
3289   /* Integer and float arguments larger than 8 bytes start at the next even
3290      boundary.  Aggregates larger than 8 bytes start at the next even boundary
3291      if the aggregate has 16 byte alignment.  Net effect is that types with
3292      alignment greater than 8 start at the next even boundary.  */
3293   /* ??? The ABI does not specify how to handle aggregates with alignment from
3294      9 to 15 bytes, or greater than 16.   We handle them all as if they had
3295      16 byte alignment.  Such aggregates can occur only if gcc extensions are
3296      used.  */
3297   if ((type ? (TYPE_ALIGN (type) > 8 * BITS_PER_UNIT)
3298        : (words > 1))
3299       && (cum->words & 1))
3300     offset = 1;
3301
3302   /* If all argument slots are used, then it must go on the stack.  */
3303   if (cum->words + offset >= MAX_ARGUMENT_SLOTS)
3304     return 0;
3305
3306   /* Check for and handle homogeneous FP aggregates.  */
3307   if (type)
3308     hfa_mode = hfa_element_mode (type, 0);
3309
3310   /* Unnamed prototyped hfas are passed as usual.  Named prototyped hfas
3311      and unprototyped hfas are passed specially.  */
3312   if (hfa_mode != VOIDmode && (! cum->prototype || named))
3313     {
3314       rtx loc[16];
3315       int i = 0;
3316       int fp_regs = cum->fp_regs;
3317       int int_regs = cum->words + offset;
3318       int hfa_size = GET_MODE_SIZE (hfa_mode);
3319       int byte_size;
3320       int args_byte_size;
3321
3322       /* If prototyped, pass it in FR regs then GR regs.
3323          If not prototyped, pass it in both FR and GR regs.
3324
3325          If this is an SFmode aggregate, then it is possible to run out of
3326          FR regs while GR regs are still left.  In that case, we pass the
3327          remaining part in the GR regs.  */
3328
3329       /* Fill the FP regs.  We do this always.  We stop if we reach the end
3330          of the argument, the last FP register, or the last argument slot.  */
3331
3332       byte_size = ((mode == BLKmode)
3333                    ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
3334       args_byte_size = int_regs * UNITS_PER_WORD;
3335       offset = 0;
3336       for (; (offset < byte_size && fp_regs < MAX_ARGUMENT_SLOTS
3337               && args_byte_size < (MAX_ARGUMENT_SLOTS * UNITS_PER_WORD)); i++)
3338         {
3339           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
3340                                       gen_rtx_REG (hfa_mode, (FR_ARG_FIRST
3341                                                               + fp_regs)),
3342                                       GEN_INT (offset));
3343           offset += hfa_size;
3344           args_byte_size += hfa_size;
3345           fp_regs++;
3346         }
3347
3348       /* If no prototype, then the whole thing must go in GR regs.  */
3349       if (! cum->prototype)
3350         offset = 0;
3351       /* If this is an SFmode aggregate, then we might have some left over
3352          that needs to go in GR regs.  */
3353       else if (byte_size != offset)
3354         int_regs += offset / UNITS_PER_WORD;
3355
3356       /* Fill in the GR regs.  We must use DImode here, not the hfa mode.  */
3357
3358       for (; offset < byte_size && int_regs < MAX_ARGUMENT_SLOTS; i++)
3359         {
3360           enum machine_mode gr_mode = DImode;
3361
3362           /* If we have an odd 4 byte hunk because we ran out of FR regs,
3363              then this goes in a GR reg left adjusted/little endian, right
3364              adjusted/big endian.  */
3365           /* ??? Currently this is handled wrong, because 4-byte hunks are
3366              always right adjusted/little endian.  */
3367           if (offset & 0x4)
3368             gr_mode = SImode;
3369           /* If we have an even 4 byte hunk because the aggregate is a
3370              multiple of 4 bytes in size, then this goes in a GR reg right
3371              adjusted/little endian.  */
3372           else if (byte_size - offset == 4)
3373             gr_mode = SImode;
3374           /* Complex floats need to have float mode.  */
3375           if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
3376             gr_mode = hfa_mode;
3377
3378           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
3379                                       gen_rtx_REG (gr_mode, (basereg
3380                                                              + int_regs)),
3381                                       GEN_INT (offset));
3382           offset += GET_MODE_SIZE (gr_mode);
3383           int_regs += GET_MODE_SIZE (gr_mode) <= UNITS_PER_WORD
3384                       ? 1 : GET_MODE_SIZE (gr_mode) / UNITS_PER_WORD;
3385         }
3386
3387       /* If we ended up using just one location, just return that one loc.  */
3388       if (i == 1)
3389         return XEXP (loc[0], 0);
3390       else
3391         return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
3392     }
3393
3394   /* Integral and aggregates go in general registers.  If we have run out of
3395      FR registers, then FP values must also go in general registers.  This can
3396      happen when we have a SFmode HFA.  */
3397   else if (((mode == TFmode) && ! INTEL_EXTENDED_IEEE_FORMAT)
3398           || (! FLOAT_MODE_P (mode) || cum->fp_regs == MAX_ARGUMENT_SLOTS))
3399     {
3400       int byte_size = ((mode == BLKmode)
3401                        ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
3402       if (BYTES_BIG_ENDIAN
3403         && (mode == BLKmode || (type && AGGREGATE_TYPE_P (type)))
3404         && byte_size < UNITS_PER_WORD
3405         && byte_size > 0)
3406         {
3407           rtx gr_reg = gen_rtx_EXPR_LIST (VOIDmode,
3408                                           gen_rtx_REG (DImode,
3409                                                        (basereg + cum->words
3410                                                         + offset)),
3411                                           const0_rtx);
3412           return gen_rtx_PARALLEL (mode, gen_rtvec (1, gr_reg));
3413         }
3414       else
3415         return gen_rtx_REG (mode, basereg + cum->words + offset);
3416
3417     }
3418
3419   /* If there is a prototype, then FP values go in a FR register when
3420      named, and in a GR register when unnamed.  */
3421   else if (cum->prototype)
3422     {
3423       if (! named)
3424         return gen_rtx_REG (mode, basereg + cum->words + offset);
3425       else
3426         return gen_rtx_REG (mode, FR_ARG_FIRST + cum->fp_regs);
3427     }
3428   /* If there is no prototype, then FP values go in both FR and GR
3429      registers.  */
3430   else
3431     {
3432       rtx fp_reg = gen_rtx_EXPR_LIST (VOIDmode,
3433                                       gen_rtx_REG (mode, (FR_ARG_FIRST
3434                                                           + cum->fp_regs)),
3435                                       const0_rtx);
3436       rtx gr_reg = gen_rtx_EXPR_LIST (VOIDmode,
3437                                       gen_rtx_REG (mode,
3438                                                    (basereg + cum->words
3439                                                     + offset)),
3440                                       const0_rtx);
3441
3442       return gen_rtx_PARALLEL (mode, gen_rtvec (2, fp_reg, gr_reg));
3443     }
3444 }
3445
3446 /* Return number of words, at the beginning of the argument, that must be
3447    put in registers.  0 is the argument is entirely in registers or entirely
3448    in memory.  */
3449
3450 int
3451 ia64_function_arg_partial_nregs (cum, mode, type, named)
3452      CUMULATIVE_ARGS *cum;
3453      enum machine_mode mode;
3454      tree type;
3455      int named ATTRIBUTE_UNUSED;
3456 {
3457   int words = (((mode == BLKmode ? int_size_in_bytes (type)
3458                  : GET_MODE_SIZE (mode)) + UNITS_PER_WORD - 1)
3459                / UNITS_PER_WORD);
3460   int offset = 0;
3461
3462   /* Arguments with alignment larger than 8 bytes start at the next even
3463      boundary.  */
3464   if ((type ? (TYPE_ALIGN (type) > 8 * BITS_PER_UNIT)
3465        : (words > 1))
3466       && (cum->words & 1))
3467     offset = 1;
3468
3469   /* If all argument slots are used, then it must go on the stack.  */
3470   if (cum->words + offset >= MAX_ARGUMENT_SLOTS)
3471     return 0;
3472
3473   /* It doesn't matter whether the argument goes in FR or GR regs.  If
3474      it fits within the 8 argument slots, then it goes entirely in
3475      registers.  If it extends past the last argument slot, then the rest
3476      goes on the stack.  */
3477
3478   if (words + cum->words + offset <= MAX_ARGUMENT_SLOTS)
3479     return 0;
3480
3481   return MAX_ARGUMENT_SLOTS - cum->words - offset;
3482 }
3483
3484 /* Update CUM to point after this argument.  This is patterned after
3485    ia64_function_arg.  */
3486
3487 void
3488 ia64_function_arg_advance (cum, mode, type, named)
3489      CUMULATIVE_ARGS *cum;
3490      enum machine_mode mode;
3491      tree type;
3492      int named;
3493 {
3494   int words = (((mode == BLKmode ? int_size_in_bytes (type)
3495                  : GET_MODE_SIZE (mode)) + UNITS_PER_WORD - 1)
3496                / UNITS_PER_WORD);
3497   int offset = 0;
3498   enum machine_mode hfa_mode = VOIDmode;
3499
3500   /* If all arg slots are already full, then there is nothing to do.  */
3501   if (cum->words >= MAX_ARGUMENT_SLOTS)
3502     return;
3503
3504   /* Arguments with alignment larger than 8 bytes start at the next even
3505      boundary.  */
3506   if ((type ? (TYPE_ALIGN (type) > 8 * BITS_PER_UNIT)
3507        : (words > 1))
3508       && (cum->words & 1))
3509     offset = 1;
3510
3511   cum->words += words + offset;
3512
3513   /* Check for and handle homogeneous FP aggregates.  */
3514   if (type)
3515     hfa_mode = hfa_element_mode (type, 0);
3516
3517   /* Unnamed prototyped hfas are passed as usual.  Named prototyped hfas
3518      and unprototyped hfas are passed specially.  */
3519   if (hfa_mode != VOIDmode && (! cum->prototype || named))
3520     {
3521       int fp_regs = cum->fp_regs;
3522       /* This is the original value of cum->words + offset.  */
3523       int int_regs = cum->words - words;
3524       int hfa_size = GET_MODE_SIZE (hfa_mode);
3525       int byte_size;
3526       int args_byte_size;
3527
3528       /* If prototyped, pass it in FR regs then GR regs.
3529          If not prototyped, pass it in both FR and GR regs.
3530
3531          If this is an SFmode aggregate, then it is possible to run out of
3532          FR regs while GR regs are still left.  In that case, we pass the
3533          remaining part in the GR regs.  */
3534
3535       /* Fill the FP regs.  We do this always.  We stop if we reach the end
3536          of the argument, the last FP register, or the last argument slot.  */
3537
3538       byte_size = ((mode == BLKmode)
3539                    ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
3540       args_byte_size = int_regs * UNITS_PER_WORD;
3541       offset = 0;
3542       for (; (offset < byte_size && fp_regs < MAX_ARGUMENT_SLOTS
3543               && args_byte_size < (MAX_ARGUMENT_SLOTS * UNITS_PER_WORD));)
3544         {
3545           offset += hfa_size;
3546           args_byte_size += hfa_size;
3547           fp_regs++;
3548         }
3549
3550       cum->fp_regs = fp_regs;
3551     }
3552
3553   /* Integral and aggregates go in general registers.  If we have run out of
3554      FR registers, then FP values must also go in general registers.  This can
3555      happen when we have a SFmode HFA.  */
3556   else if (! FLOAT_MODE_P (mode) || cum->fp_regs == MAX_ARGUMENT_SLOTS)
3557     cum->int_regs = cum->words;
3558
3559   /* If there is a prototype, then FP values go in a FR register when
3560      named, and in a GR register when unnamed.  */
3561   else if (cum->prototype)
3562     {
3563       if (! named)
3564         cum->int_regs = cum->words;
3565       else
3566         /* ??? Complex types should not reach here.  */
3567         cum->fp_regs += (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT ? 2 : 1);
3568     }
3569   /* If there is no prototype, then FP values go in both FR and GR
3570      registers.  */
3571   else
3572     { 
3573       /* ??? Complex types should not reach here.  */
3574       cum->fp_regs += (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT ? 2 : 1);
3575       cum->int_regs = cum->words;
3576     }
3577 }
3578
3579 /* Variable sized types are passed by reference.  */
3580 /* ??? At present this is a GCC extension to the IA-64 ABI.  */
3581
3582 int
3583 ia64_function_arg_pass_by_reference (cum, mode, type, named)
3584      CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED;
3585      enum machine_mode mode ATTRIBUTE_UNUSED;
3586      tree type;
3587      int named ATTRIBUTE_UNUSED;
3588 {
3589   return type && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST;
3590 }
3591
3592 /* True if it is OK to do sibling call optimization for the specified
3593    call expression EXP.  DECL will be the called function, or NULL if
3594    this is an indirect call.  */
3595 static bool
3596 ia64_function_ok_for_sibcall (decl, exp)
3597      tree decl, exp;
3598 {
3599   /* Direct calls are always ok.  */
3600   if (decl)
3601     return true;
3602
3603   /* If TARGET_CONST_GP is in effect, then our caller expects us to
3604      return with our current GP.  This means that we'll always have
3605      a GP reload after an indirect call.  */
3606   return !ia64_epilogue_uses (R_GR (1));
3607 }
3608 \f
3609
3610 /* Implement va_arg.  */
3611
3612 rtx
3613 ia64_va_arg (valist, type)
3614      tree valist, type;
3615 {
3616   tree t;
3617
3618   /* Variable sized types are passed by reference.  */
3619   if (TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
3620     {
3621       rtx addr = std_expand_builtin_va_arg (valist, build_pointer_type (type));
3622       return gen_rtx_MEM (ptr_mode, force_reg (Pmode, addr));
3623     }
3624
3625   /* Arguments with alignment larger than 8 bytes start at the next even
3626      boundary.  */
3627   if (TYPE_ALIGN (type) > 8 * BITS_PER_UNIT)
3628     {
3629       t = build (PLUS_EXPR, TREE_TYPE (valist), valist,
3630                  build_int_2 (2 * UNITS_PER_WORD - 1, 0));
3631       t = build (BIT_AND_EXPR, TREE_TYPE (t), t,
3632                  build_int_2 (-2 * UNITS_PER_WORD, -1));
3633       t = build (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
3634       TREE_SIDE_EFFECTS (t) = 1;
3635       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
3636     }
3637
3638   return std_expand_builtin_va_arg (valist, type);
3639 }
3640 \f
3641 /* Return 1 if function return value returned in memory.  Return 0 if it is
3642    in a register.  */
3643
3644 int
3645 ia64_return_in_memory (valtype)
3646      tree valtype;
3647 {
3648   enum machine_mode mode;
3649   enum machine_mode hfa_mode;
3650   HOST_WIDE_INT byte_size;
3651
3652   mode = TYPE_MODE (valtype);
3653   byte_size = GET_MODE_SIZE (mode);
3654   if (mode == BLKmode)
3655     {
3656       byte_size = int_size_in_bytes (valtype);
3657       if (byte_size < 0)
3658         return 1;
3659     }
3660
3661   /* Hfa's with up to 8 elements are returned in the FP argument registers.  */
3662
3663   hfa_mode = hfa_element_mode (valtype, 0);
3664   if (hfa_mode != VOIDmode)
3665     {
3666       int hfa_size = GET_MODE_SIZE (hfa_mode);
3667
3668       if (byte_size / hfa_size > MAX_ARGUMENT_SLOTS)
3669         return 1;
3670       else
3671         return 0;
3672     }
3673   else if (byte_size > UNITS_PER_WORD * MAX_INT_RETURN_SLOTS)
3674     return 1;
3675   else
3676     return 0;
3677 }
3678
3679 /* Return rtx for register that holds the function return value.  */
3680
3681 rtx
3682 ia64_function_value (valtype, func)
3683      tree valtype;
3684      tree func ATTRIBUTE_UNUSED;
3685 {
3686   enum machine_mode mode;
3687   enum machine_mode hfa_mode;
3688
3689   mode = TYPE_MODE (valtype);
3690   hfa_mode = hfa_element_mode (valtype, 0);
3691
3692   if (hfa_mode != VOIDmode)
3693     {
3694       rtx loc[8];
3695       int i;
3696       int hfa_size;
3697       int byte_size;
3698       int offset;
3699
3700       hfa_size = GET_MODE_SIZE (hfa_mode);
3701       byte_size = ((mode == BLKmode)
3702                    ? int_size_in_bytes (valtype) : GET_MODE_SIZE (mode));
3703       offset = 0;
3704       for (i = 0; offset < byte_size; i++)
3705         {
3706           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
3707                                       gen_rtx_REG (hfa_mode, FR_ARG_FIRST + i),
3708                                       GEN_INT (offset));
3709           offset += hfa_size;
3710         }
3711
3712       if (i == 1)
3713         return XEXP (loc[0], 0);
3714       else
3715         return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
3716     }
3717   else if (FLOAT_TYPE_P (valtype) &&
3718            ((mode != TFmode) || INTEL_EXTENDED_IEEE_FORMAT))
3719     return gen_rtx_REG (mode, FR_ARG_FIRST);
3720   else
3721     {
3722       if (BYTES_BIG_ENDIAN
3723           && (mode == BLKmode || (valtype && AGGREGATE_TYPE_P (valtype))))
3724         {
3725           rtx loc[8];
3726           int offset;
3727           int bytesize;
3728           int i;
3729
3730           offset = 0;
3731           bytesize = int_size_in_bytes (valtype);
3732           for (i = 0; offset < bytesize; i++)
3733             {
3734               loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
3735                                           gen_rtx_REG (DImode,
3736                                                        GR_RET_FIRST + i),
3737                                           GEN_INT (offset));
3738               offset += UNITS_PER_WORD;
3739             }
3740           return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
3741         }
3742       else
3743         return gen_rtx_REG (mode, GR_RET_FIRST);
3744     }
3745 }
3746
3747 /* This is called from dwarf2out.c via ASM_OUTPUT_DWARF_DTPREL.
3748    We need to emit DTP-relative relocations.  */
3749
3750 void
3751 ia64_output_dwarf_dtprel (file, size, x)
3752      FILE *file;
3753      int size;
3754      rtx x;
3755 {
3756   if (size != 8)
3757     abort ();
3758   fputs ("\tdata8.ua\t@dtprel(", file);
3759   output_addr_const (file, x);
3760   fputs (")", file);
3761 }
3762
3763 /* Print a memory address as an operand to reference that memory location.  */
3764
3765 /* ??? Do we need this?  It gets used only for 'a' operands.  We could perhaps
3766    also call this from ia64_print_operand for memory addresses.  */
3767
3768 void
3769 ia64_print_operand_address (stream, address)
3770      FILE * stream ATTRIBUTE_UNUSED;
3771      rtx    address ATTRIBUTE_UNUSED;
3772 {
3773 }
3774
3775 /* Print an operand to an assembler instruction.
3776    C    Swap and print a comparison operator.
3777    D    Print an FP comparison operator.
3778    E    Print 32 - constant, for SImode shifts as extract.
3779    e    Print 64 - constant, for DImode rotates.
3780    F    A floating point constant 0.0 emitted as f0, or 1.0 emitted as f1, or
3781         a floating point register emitted normally.
3782    I    Invert a predicate register by adding 1.
3783    J    Select the proper predicate register for a condition.
3784    j    Select the inverse predicate register for a condition.
3785    O    Append .acq for volatile load.
3786    P    Postincrement of a MEM.
3787    Q    Append .rel for volatile store.
3788    S    Shift amount for shladd instruction.
3789    T    Print an 8-bit sign extended number (K) as a 32-bit unsigned number
3790         for Intel assembler.
3791    U    Print an 8-bit sign extended number (K) as a 64-bit unsigned number
3792         for Intel assembler.
3793    r    Print register name, or constant 0 as r0.  HP compatibility for
3794         Linux kernel.  */
3795 void
3796 ia64_print_operand (file, x, code)
3797      FILE * file;
3798      rtx    x;
3799      int    code;
3800 {
3801   const char *str;
3802
3803   switch (code)
3804     {
3805     case 0:
3806       /* Handled below.  */
3807       break;
3808
3809     case 'C':
3810       {
3811         enum rtx_code c = swap_condition (GET_CODE (x));
3812         fputs (GET_RTX_NAME (c), file);
3813         return;
3814       }
3815
3816     case 'D':
3817       switch (GET_CODE (x))
3818         {
3819         case NE:
3820           str = "neq";
3821           break;
3822         case UNORDERED:
3823           str = "unord";
3824           break;
3825         case ORDERED:
3826           str = "ord";
3827           break;
3828         default:
3829           str = GET_RTX_NAME (GET_CODE (x));
3830           break;
3831         }
3832       fputs (str, file);
3833       return;
3834
3835     case 'E':
3836       fprintf (file, HOST_WIDE_INT_PRINT_DEC, 32 - INTVAL (x));
3837       return;
3838
3839     case 'e':
3840       fprintf (file, HOST_WIDE_INT_PRINT_DEC, 64 - INTVAL (x));
3841       return;
3842
3843     case 'F':
3844       if (x == CONST0_RTX (GET_MODE (x)))
3845         str = reg_names [FR_REG (0)];
3846       else if (x == CONST1_RTX (GET_MODE (x)))
3847         str = reg_names [FR_REG (1)];
3848       else if (GET_CODE (x) == REG)
3849         str = reg_names [REGNO (x)];
3850       else
3851         abort ();
3852       fputs (str, file);
3853       return;
3854
3855     case 'I':
3856       fputs (reg_names [REGNO (x) + 1], file);
3857       return;
3858
3859     case 'J':
3860     case 'j':
3861       {
3862         unsigned int regno = REGNO (XEXP (x, 0));
3863         if (GET_CODE (x) == EQ)
3864           regno += 1;
3865         if (code == 'j')
3866           regno ^= 1;
3867         fputs (reg_names [regno], file);
3868       }
3869       return;
3870
3871     case 'O':
3872       if (MEM_VOLATILE_P (x))
3873         fputs(".acq", file);
3874       return;
3875
3876     case 'P':
3877       {
3878         HOST_WIDE_INT value;
3879
3880         switch (GET_CODE (XEXP (x, 0)))
3881           {
3882           default:
3883             return;
3884
3885           case POST_MODIFY:
3886             x = XEXP (XEXP (XEXP (x, 0), 1), 1);
3887             if (GET_CODE (x) == CONST_INT)
3888               value = INTVAL (x);
3889             else if (GET_CODE (x) == REG)
3890               {
3891                 fprintf (file, ", %s", reg_names[REGNO (x)]);
3892                 return;
3893               }
3894             else
3895               abort ();
3896             break;
3897
3898           case POST_INC:
3899             value = GET_MODE_SIZE (GET_MODE (x));
3900             break;
3901
3902           case POST_DEC:
3903             value = - (HOST_WIDE_INT) GET_MODE_SIZE (GET_MODE (x));
3904             break;
3905           }
3906
3907         putc (',', file);
3908         putc (' ', file);
3909         fprintf (file, HOST_WIDE_INT_PRINT_DEC, value);
3910         return;
3911       }
3912
3913     case 'Q':
3914       if (MEM_VOLATILE_P (x))
3915         fputs(".rel", file);
3916       return;
3917
3918     case 'S':
3919       fprintf (file, "%d", exact_log2 (INTVAL (x)));
3920       return;
3921
3922     case 'T':
3923       if (! TARGET_GNU_AS && GET_CODE (x) == CONST_INT)
3924         {
3925           fprintf (file, "0x%x", (int) INTVAL (x) & 0xffffffff);
3926           return;
3927         }
3928       break;
3929
3930     case 'U':
3931       if (! TARGET_GNU_AS && GET_CODE (x) == CONST_INT)
3932         {
3933           const char *prefix = "0x";
3934           if (INTVAL (x) & 0x80000000)
3935             {
3936               fprintf (file, "0xffffffff");
3937               prefix = "";
3938             }
3939           fprintf (file, "%s%x", prefix, (int) INTVAL (x) & 0xffffffff);
3940           return;
3941         }
3942       break;
3943
3944     case 'r':
3945       /* If this operand is the constant zero, write it as register zero.
3946          Any register, zero, or CONST_INT value is OK here.  */
3947       if (GET_CODE (x) == REG)
3948         fputs (reg_names[REGNO (x)], file);
3949       else if (x == CONST0_RTX (GET_MODE (x)))
3950         fputs ("r0", file);
3951       else if (GET_CODE (x) == CONST_INT)
3952         output_addr_const (file, x);
3953       else
3954         output_operand_lossage ("invalid %%r value");
3955       return;
3956
3957     case '+':
3958       {
3959         const char *which;
3960         
3961         /* For conditional branches, returns or calls, substitute
3962            sptk, dptk, dpnt, or spnt for %s.  */
3963         x = find_reg_note (current_output_insn, REG_BR_PROB, 0);
3964         if (x)
3965           {
3966             int pred_val = INTVAL (XEXP (x, 0));
3967
3968             /* Guess top and bottom 10% statically predicted.  */
3969             if (pred_val < REG_BR_PROB_BASE / 50)
3970               which = ".spnt";
3971             else if (pred_val < REG_BR_PROB_BASE / 2)
3972               which = ".dpnt";
3973             else if (pred_val < REG_BR_PROB_BASE / 100 * 98)
3974               which = ".dptk";
3975             else
3976               which = ".sptk";
3977           }
3978         else if (GET_CODE (current_output_insn) == CALL_INSN)
3979           which = ".sptk";
3980         else
3981           which = ".dptk";
3982
3983         fputs (which, file);
3984         return;
3985       }
3986
3987     case ',':
3988       x = current_insn_predicate;
3989       if (x)
3990         {
3991           unsigned int regno = REGNO (XEXP (x, 0));
3992           if (GET_CODE (x) == EQ)
3993             regno += 1;
3994           fprintf (file, "(%s) ", reg_names [regno]);
3995         }
3996       return;
3997
3998     default:
3999       output_operand_lossage ("ia64_print_operand: unknown code");
4000       return;
4001     }
4002
4003   switch (GET_CODE (x))
4004     {
4005       /* This happens for the spill/restore instructions.  */
4006     case POST_INC:
4007     case POST_DEC:
4008     case POST_MODIFY:
4009       x = XEXP (x, 0);
4010       /* ... fall through ...  */
4011
4012     case REG:
4013       fputs (reg_names [REGNO (x)], file);
4014       break;
4015
4016     case MEM:
4017       {
4018         rtx addr = XEXP (x, 0);
4019         if (GET_RTX_CLASS (GET_CODE (addr)) == 'a')
4020           addr = XEXP (addr, 0);
4021         fprintf (file, "[%s]", reg_names [REGNO (addr)]);
4022         break;
4023       }
4024
4025     default:
4026       output_addr_const (file, x);
4027       break;
4028     }
4029
4030   return;
4031 }
4032 \f
4033 /* Compute a (partial) cost for rtx X.  Return true if the complete
4034    cost has been computed, and false if subexpressions should be
4035    scanned.  In either case, *TOTAL contains the cost result.  */
4036 /* ??? This is incomplete.  */
4037
4038 static bool
4039 ia64_rtx_costs (x, code, outer_code, total)
4040      rtx x;
4041      int code, outer_code;
4042      int *total;
4043 {
4044   switch (code)
4045     {
4046     case CONST_INT:
4047       switch (outer_code)
4048         {
4049         case SET:
4050           *total = CONST_OK_FOR_J (INTVAL (x)) ? 0 : COSTS_N_INSNS (1);
4051           return true;
4052         case PLUS:
4053           if (CONST_OK_FOR_I (INTVAL (x)))
4054             *total = 0;
4055           else if (CONST_OK_FOR_J (INTVAL (x)))
4056             *total = 1;
4057           else
4058             *total = COSTS_N_INSNS (1);
4059           return true;
4060         default:
4061           if (CONST_OK_FOR_K (INTVAL (x)) || CONST_OK_FOR_L (INTVAL (x)))
4062             *total = 0;
4063           else
4064             *total = COSTS_N_INSNS (1);
4065           return true;
4066         }
4067
4068     case CONST_DOUBLE:
4069       *total = COSTS_N_INSNS (1);
4070       return true;
4071
4072     case CONST:
4073     case SYMBOL_REF:
4074     case LABEL_REF:
4075       *total = COSTS_N_INSNS (3);
4076       return true;
4077
4078     case MULT:
4079       /* For multiplies wider than HImode, we have to go to the FPU,
4080          which normally involves copies.  Plus there's the latency
4081          of the multiply itself, and the latency of the instructions to
4082          transfer integer regs to FP regs.  */
4083       /* ??? Check for FP mode.  */
4084       if (GET_MODE_SIZE (GET_MODE (x)) > 2)
4085         *total = COSTS_N_INSNS (10);
4086       else
4087         *total = COSTS_N_INSNS (2);
4088       return true;
4089
4090     case PLUS:
4091     case MINUS:
4092     case ASHIFT:
4093     case ASHIFTRT:
4094     case LSHIFTRT:
4095       *total = COSTS_N_INSNS (1);
4096       return true;
4097
4098     case DIV:
4099     case UDIV:
4100     case MOD:
4101     case UMOD:
4102       /* We make divide expensive, so that divide-by-constant will be
4103          optimized to a multiply.  */
4104       *total = COSTS_N_INSNS (60);
4105       return true;
4106
4107     default:
4108       return false;
4109     }
4110 }
4111
4112 /* Calculate the cost of moving data from a register in class FROM to
4113    one in class TO, using MODE.  */
4114
4115 int
4116 ia64_register_move_cost (mode, from, to)
4117      enum machine_mode mode;
4118      enum reg_class from, to;
4119 {
4120   /* ADDL_REGS is the same as GR_REGS for movement purposes.  */
4121   if (to == ADDL_REGS)
4122     to = GR_REGS;
4123   if (from == ADDL_REGS)
4124     from = GR_REGS;
4125
4126   /* All costs are symmetric, so reduce cases by putting the
4127      lower number class as the destination.  */
4128   if (from < to)
4129     {
4130       enum reg_class tmp = to;
4131       to = from, from = tmp;
4132     }
4133
4134   /* Moving from FR<->GR in TFmode must be more expensive than 2,
4135      so that we get secondary memory reloads.  Between FR_REGS,
4136      we have to make this at least as expensive as MEMORY_MOVE_COST
4137      to avoid spectacularly poor register class preferencing.  */
4138   if (mode == TFmode)
4139     {
4140       if (to != GR_REGS || from != GR_REGS)
4141         return MEMORY_MOVE_COST (mode, to, 0);
4142       else
4143         return 3;
4144     }
4145
4146   switch (to)
4147     {
4148     case PR_REGS:
4149       /* Moving between PR registers takes two insns.  */
4150       if (from == PR_REGS)
4151         return 3;
4152       /* Moving between PR and anything but GR is impossible.  */
4153       if (from != GR_REGS)
4154         return MEMORY_MOVE_COST (mode, to, 0);
4155       break;
4156
4157     case BR_REGS:
4158       /* Moving between BR and anything but GR is impossible.  */
4159       if (from != GR_REGS && from != GR_AND_BR_REGS)
4160         return MEMORY_MOVE_COST (mode, to, 0);
4161       break;
4162
4163     case AR_I_REGS:
4164     case AR_M_REGS:
4165       /* Moving between AR and anything but GR is impossible.  */
4166       if (from != GR_REGS)
4167         return MEMORY_MOVE_COST (mode, to, 0);
4168       break;
4169
4170     case GR_REGS:
4171     case FR_REGS:
4172     case GR_AND_FR_REGS:
4173     case GR_AND_BR_REGS:
4174     case ALL_REGS:
4175       break;
4176
4177     default:
4178       abort ();
4179     }
4180
4181   return 2;
4182 }
4183
4184 /* This function returns the register class required for a secondary
4185    register when copying between one of the registers in CLASS, and X,
4186    using MODE.  A return value of NO_REGS means that no secondary register
4187    is required.  */
4188
4189 enum reg_class
4190 ia64_secondary_reload_class (class, mode, x)
4191      enum reg_class class;
4192      enum machine_mode mode ATTRIBUTE_UNUSED;
4193      rtx x;
4194 {
4195   int regno = -1;
4196
4197   if (GET_CODE (x) == REG || GET_CODE (x) == SUBREG)
4198     regno = true_regnum (x);
4199
4200   switch (class)
4201     {
4202     case BR_REGS:
4203     case AR_M_REGS:
4204     case AR_I_REGS:
4205       /* ??? BR<->BR register copies can happen due to a bad gcse/cse/global
4206          interaction.  We end up with two pseudos with overlapping lifetimes
4207          both of which are equiv to the same constant, and both which need
4208          to be in BR_REGS.  This seems to be a cse bug.  cse_basic_block_end
4209          changes depending on the path length, which means the qty_first_reg
4210          check in make_regs_eqv can give different answers at different times.
4211          At some point I'll probably need a reload_indi pattern to handle
4212          this.
4213
4214          We can also get GR_AND_FR_REGS to BR_REGS/AR_REGS copies, where we
4215          wound up with a FP register from GR_AND_FR_REGS.  Extend that to all
4216          non-general registers for good measure.  */
4217       if (regno >= 0 && ! GENERAL_REGNO_P (regno))
4218         return GR_REGS;
4219
4220       /* This is needed if a pseudo used as a call_operand gets spilled to a
4221          stack slot.  */
4222       if (GET_CODE (x) == MEM)
4223         return GR_REGS;
4224       break;
4225
4226     case FR_REGS:
4227       /* Need to go through general regsters to get to other class regs.  */
4228       if (regno >= 0 && ! (FR_REGNO_P (regno) || GENERAL_REGNO_P (regno)))
4229         return GR_REGS;
4230  
4231       /* This can happen when a paradoxical subreg is an operand to the
4232          muldi3 pattern.  */
4233       /* ??? This shouldn't be necessary after instruction scheduling is
4234          enabled, because paradoxical subregs are not accepted by
4235          register_operand when INSN_SCHEDULING is defined.  Or alternatively,
4236          stop the paradoxical subreg stupidity in the *_operand functions
4237          in recog.c.  */
4238       if (GET_CODE (x) == MEM
4239           && (GET_MODE (x) == SImode || GET_MODE (x) == HImode
4240               || GET_MODE (x) == QImode))
4241         return GR_REGS;
4242
4243       /* This can happen because of the ior/and/etc patterns that accept FP
4244          registers as operands.  If the third operand is a constant, then it
4245          needs to be reloaded into a FP register.  */
4246       if (GET_CODE (x) == CONST_INT)
4247         return GR_REGS;
4248
4249       /* This can happen because of register elimination in a muldi3 insn.
4250          E.g. `26107 * (unsigned long)&u'.  */
4251       if (GET_CODE (x) == PLUS)
4252         return GR_REGS;
4253       break;
4254
4255     case PR_REGS:
4256       /* ??? This happens if we cse/gcse a BImode value across a call,
4257          and the function has a nonlocal goto.  This is because global
4258          does not allocate call crossing pseudos to hard registers when
4259          current_function_has_nonlocal_goto is true.  This is relatively
4260          common for C++ programs that use exceptions.  To reproduce,
4261          return NO_REGS and compile libstdc++.  */
4262       if (GET_CODE (x) == MEM)
4263         return GR_REGS;
4264
4265       /* This can happen when we take a BImode subreg of a DImode value,
4266          and that DImode value winds up in some non-GR register.  */
4267       if (regno >= 0 && ! GENERAL_REGNO_P (regno) && ! PR_REGNO_P (regno))
4268         return GR_REGS;
4269       break;
4270
4271     case GR_REGS:
4272       /* Since we have no offsettable memory addresses, we need a temporary
4273          to hold the address of the second word.  */
4274       if (mode == TImode)
4275         return GR_REGS;
4276       break;
4277
4278     default:
4279       break;
4280     }
4281
4282   return NO_REGS;
4283 }
4284
4285 \f
4286 /* Emit text to declare externally defined variables and functions, because
4287    the Intel assembler does not support undefined externals.  */
4288
4289 void
4290 ia64_asm_output_external (file, decl, name)
4291      FILE *file;
4292      tree decl;
4293      const char *name;
4294 {
4295   int save_referenced;
4296
4297   /* GNU as does not need anything here, but the HP linker does need
4298      something for external functions.  */
4299
4300   if (TARGET_GNU_AS
4301       && (!TARGET_HPUX_LD
4302           || TREE_CODE (decl) != FUNCTION_DECL
4303           || strstr(name, "__builtin_") == name))
4304     return;
4305
4306   /* ??? The Intel assembler creates a reference that needs to be satisfied by
4307      the linker when we do this, so we need to be careful not to do this for
4308      builtin functions which have no library equivalent.  Unfortunately, we
4309      can't tell here whether or not a function will actually be called by
4310      expand_expr, so we pull in library functions even if we may not need
4311      them later.  */
4312   if (! strcmp (name, "__builtin_next_arg")
4313       || ! strcmp (name, "alloca")
4314       || ! strcmp (name, "__builtin_constant_p")
4315       || ! strcmp (name, "__builtin_args_info"))
4316     return;
4317
4318   if (TARGET_HPUX_LD)
4319     ia64_hpux_add_extern_decl (name);
4320   else
4321     {
4322       /* assemble_name will set TREE_SYMBOL_REFERENCED, so we must save and
4323          restore it.  */
4324       save_referenced = TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl));
4325       if (TREE_CODE (decl) == FUNCTION_DECL)
4326         ASM_OUTPUT_TYPE_DIRECTIVE (file, name, "function");
4327       (*targetm.asm_out.globalize_label) (file, name);
4328       TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)) = save_referenced;
4329     }
4330 }
4331 \f
4332 /* Parse the -mfixed-range= option string.  */
4333
4334 static void
4335 fix_range (const_str)
4336      const char *const_str;
4337 {
4338   int i, first, last;
4339   char *str, *dash, *comma;
4340
4341   /* str must be of the form REG1'-'REG2{,REG1'-'REG} where REG1 and
4342      REG2 are either register names or register numbers.  The effect
4343      of this option is to mark the registers in the range from REG1 to
4344      REG2 as ``fixed'' so they won't be used by the compiler.  This is
4345      used, e.g., to ensure that kernel mode code doesn't use f32-f127.  */
4346
4347   i = strlen (const_str);
4348   str = (char *) alloca (i + 1);
4349   memcpy (str, const_str, i + 1);
4350
4351   while (1)
4352     {
4353       dash = strchr (str, '-');
4354       if (!dash)
4355         {
4356           warning ("value of -mfixed-range must have form REG1-REG2");
4357           return;
4358         }
4359       *dash = '\0';
4360
4361       comma = strchr (dash + 1, ',');
4362       if (comma)
4363         *comma = '\0';
4364
4365       first = decode_reg_name (str);
4366       if (first < 0)
4367         {
4368           warning ("unknown register name: %s", str);
4369           return;
4370         }
4371
4372       last = decode_reg_name (dash + 1);
4373       if (last < 0)
4374         {
4375           warning ("unknown register name: %s", dash + 1);
4376           return;
4377         }
4378
4379       *dash = '-';
4380
4381       if (first > last)
4382         {
4383           warning ("%s-%s is an empty range", str, dash + 1);
4384           return;
4385         }
4386
4387       for (i = first; i <= last; ++i)
4388         fixed_regs[i] = call_used_regs[i] = 1;
4389
4390       if (!comma)
4391         break;
4392
4393       *comma = ',';
4394       str = comma + 1;
4395     }
4396 }
4397
4398 static struct machine_function *
4399 ia64_init_machine_status ()
4400 {
4401   return ggc_alloc_cleared (sizeof (struct machine_function));
4402 }
4403
4404 /* Handle TARGET_OPTIONS switches.  */
4405
4406 void
4407 ia64_override_options ()
4408 {
4409   static struct pta
4410     {
4411       const char *const name;           /* processor name or nickname.  */
4412       const enum processor_type processor;
4413     }
4414   const processor_alias_table[] =
4415     {
4416       {"itanium", PROCESSOR_ITANIUM},
4417       {"itanium1", PROCESSOR_ITANIUM},
4418       {"merced", PROCESSOR_ITANIUM},
4419       {"itanium2", PROCESSOR_ITANIUM2},
4420       {"mckinley", PROCESSOR_ITANIUM2},
4421     };
4422
4423   int const pta_size = ARRAY_SIZE (processor_alias_table);
4424   int i;
4425
4426   if (TARGET_AUTO_PIC)
4427     target_flags |= MASK_CONST_GP;
4428
4429   if (TARGET_INLINE_FLOAT_DIV_LAT && TARGET_INLINE_FLOAT_DIV_THR)
4430     {
4431       warning ("cannot optimize floating point division for both latency and throughput");
4432       target_flags &= ~MASK_INLINE_FLOAT_DIV_THR;
4433     }
4434
4435   if (TARGET_INLINE_INT_DIV_LAT && TARGET_INLINE_INT_DIV_THR)
4436     {
4437       warning ("cannot optimize integer division for both latency and throughput");
4438       target_flags &= ~MASK_INLINE_INT_DIV_THR;
4439     }
4440
4441   if (ia64_fixed_range_string)
4442     fix_range (ia64_fixed_range_string);
4443
4444   if (ia64_tls_size_string)
4445     {
4446       char *end;
4447       unsigned long tmp = strtoul (ia64_tls_size_string, &end, 10);
4448       if (*end || (tmp != 14 && tmp != 22 && tmp != 64))
4449         error ("bad value (%s) for -mtls-size= switch", ia64_tls_size_string);
4450       else
4451         ia64_tls_size = tmp;
4452     }
4453
4454   if (!ia64_tune_string)
4455     ia64_tune_string = "itanium2";
4456
4457   for (i = 0; i < pta_size; i++)
4458     if (! strcmp (ia64_tune_string, processor_alias_table[i].name))
4459       {
4460         ia64_tune = processor_alias_table[i].processor;
4461         break;
4462       }
4463
4464   if (i == pta_size)
4465     error ("bad value (%s) for -tune= switch", ia64_tune_string);
4466
4467   ia64_flag_schedule_insns2 = flag_schedule_insns_after_reload;
4468   flag_schedule_insns_after_reload = 0;
4469
4470   ia64_section_threshold = g_switch_set ? g_switch_value : IA64_DEFAULT_GVALUE;
4471
4472   init_machine_status = ia64_init_machine_status;
4473
4474   /* Tell the compiler which flavor of TFmode we're using.  */
4475   if (INTEL_EXTENDED_IEEE_FORMAT)
4476     real_format_for_mode[TFmode - QFmode] = &ieee_extended_intel_128_format;
4477 }
4478 \f
4479 static enum attr_itanium_class ia64_safe_itanium_class PARAMS((rtx));
4480 static enum attr_type ia64_safe_type PARAMS((rtx));
4481
4482 static enum attr_itanium_class
4483 ia64_safe_itanium_class (insn)
4484      rtx insn;
4485 {
4486   if (recog_memoized (insn) >= 0)
4487     return get_attr_itanium_class (insn);
4488   else
4489     return ITANIUM_CLASS_UNKNOWN;
4490 }
4491
4492 static enum attr_type
4493 ia64_safe_type (insn)
4494      rtx insn;
4495 {
4496   if (recog_memoized (insn) >= 0)
4497     return get_attr_type (insn);
4498   else
4499     return TYPE_UNKNOWN;
4500 }
4501 \f
4502 /* The following collection of routines emit instruction group stop bits as
4503    necessary to avoid dependencies.  */
4504
4505 /* Need to track some additional registers as far as serialization is
4506    concerned so we can properly handle br.call and br.ret.  We could
4507    make these registers visible to gcc, but since these registers are
4508    never explicitly used in gcc generated code, it seems wasteful to
4509    do so (plus it would make the call and return patterns needlessly
4510    complex).  */
4511 #define REG_GP          (GR_REG (1))
4512 #define REG_RP          (BR_REG (0))
4513 #define REG_AR_CFM      (FIRST_PSEUDO_REGISTER + 1)
4514 /* This is used for volatile asms which may require a stop bit immediately
4515    before and after them.  */
4516 #define REG_VOLATILE    (FIRST_PSEUDO_REGISTER + 2)
4517 #define AR_UNAT_BIT_0   (FIRST_PSEUDO_REGISTER + 3)
4518 #define NUM_REGS        (AR_UNAT_BIT_0 + 64)
4519
4520 /* For each register, we keep track of how it has been written in the
4521    current instruction group.
4522
4523    If a register is written unconditionally (no qualifying predicate),
4524    WRITE_COUNT is set to 2 and FIRST_PRED is ignored.
4525
4526    If a register is written if its qualifying predicate P is true, we
4527    set WRITE_COUNT to 1 and FIRST_PRED to P.  Later on, the same register
4528    may be written again by the complement of P (P^1) and when this happens,
4529    WRITE_COUNT gets set to 2.
4530
4531    The result of this is that whenever an insn attempts to write a register
4532    whose WRITE_COUNT is two, we need to issue an insn group barrier first.
4533
4534    If a predicate register is written by a floating-point insn, we set
4535    WRITTEN_BY_FP to true.
4536
4537    If a predicate register is written by an AND.ORCM we set WRITTEN_BY_AND
4538    to true; if it was written by an OR.ANDCM we set WRITTEN_BY_OR to true.  */
4539
4540 struct reg_write_state
4541 {
4542   unsigned int write_count : 2;
4543   unsigned int first_pred : 16;
4544   unsigned int written_by_fp : 1;
4545   unsigned int written_by_and : 1;
4546   unsigned int written_by_or : 1;
4547 };
4548
4549 /* Cumulative info for the current instruction group.  */
4550 struct reg_write_state rws_sum[NUM_REGS];
4551 /* Info for the current instruction.  This gets copied to rws_sum after a
4552    stop bit is emitted.  */
4553 struct reg_write_state rws_insn[NUM_REGS];
4554
4555 /* Indicates whether this is the first instruction after a stop bit,
4556    in which case we don't need another stop bit.  Without this, we hit
4557    the abort in ia64_variable_issue when scheduling an alloc.  */
4558 static int first_instruction;
4559
4560 /* Misc flags needed to compute RAW/WAW dependencies while we are traversing
4561    RTL for one instruction.  */
4562 struct reg_flags
4563 {
4564   unsigned int is_write : 1;    /* Is register being written?  */
4565   unsigned int is_fp : 1;       /* Is register used as part of an fp op?  */
4566   unsigned int is_branch : 1;   /* Is register used as part of a branch?  */
4567   unsigned int is_and : 1;      /* Is register used as part of and.orcm?  */
4568   unsigned int is_or : 1;       /* Is register used as part of or.andcm?  */
4569   unsigned int is_sibcall : 1;  /* Is this a sibling or normal call?  */
4570 };
4571
4572 static void rws_update PARAMS ((struct reg_write_state *, int,
4573                                 struct reg_flags, int));
4574 static int rws_access_regno PARAMS ((int, struct reg_flags, int));
4575 static int rws_access_reg PARAMS ((rtx, struct reg_flags, int));
4576 static void update_set_flags PARAMS ((rtx, struct reg_flags *, int *, rtx *));
4577 static int set_src_needs_barrier PARAMS ((rtx, struct reg_flags, int, rtx));
4578 static int rtx_needs_barrier PARAMS ((rtx, struct reg_flags, int));
4579 static void init_insn_group_barriers PARAMS ((void));
4580 static int group_barrier_needed_p PARAMS ((rtx));
4581 static int safe_group_barrier_needed_p PARAMS ((rtx));
4582
4583 /* Update *RWS for REGNO, which is being written by the current instruction,
4584    with predicate PRED, and associated register flags in FLAGS.  */
4585
4586 static void
4587 rws_update (rws, regno, flags, pred)
4588      struct reg_write_state *rws;
4589      int regno;
4590      struct reg_flags flags;
4591      int pred;
4592 {
4593   if (pred)
4594     rws[regno].write_count++;
4595   else
4596     rws[regno].write_count = 2;
4597   rws[regno].written_by_fp |= flags.is_fp;
4598   /* ??? Not tracking and/or across differing predicates.  */
4599   rws[regno].written_by_and = flags.is_and;
4600   rws[regno].written_by_or = flags.is_or;
4601   rws[regno].first_pred = pred;
4602 }
4603
4604 /* Handle an access to register REGNO of type FLAGS using predicate register
4605    PRED.  Update rws_insn and rws_sum arrays.  Return 1 if this access creates
4606    a dependency with an earlier instruction in the same group.  */
4607
4608 static int
4609 rws_access_regno (regno, flags, pred)
4610      int regno;
4611      struct reg_flags flags;
4612      int pred;
4613 {
4614   int need_barrier = 0;
4615
4616   if (regno >= NUM_REGS)
4617     abort ();
4618
4619   if (! PR_REGNO_P (regno))
4620     flags.is_and = flags.is_or = 0;
4621
4622   if (flags.is_write)
4623     {
4624       int write_count;
4625
4626       /* One insn writes same reg multiple times?  */
4627       if (rws_insn[regno].write_count > 0)
4628         abort ();
4629
4630       /* Update info for current instruction.  */
4631       rws_update (rws_insn, regno, flags, pred);
4632       write_count = rws_sum[regno].write_count;
4633
4634       switch (write_count)
4635         {
4636         case 0:
4637           /* The register has not been written yet.  */
4638           rws_update (rws_sum, regno, flags, pred);
4639           break;
4640
4641         case 1:
4642           /* The register has been written via a predicate.  If this is
4643              not a complementary predicate, then we need a barrier.  */
4644           /* ??? This assumes that P and P+1 are always complementary
4645              predicates for P even.  */
4646           if (flags.is_and && rws_sum[regno].written_by_and)
4647             ; 
4648           else if (flags.is_or && rws_sum[regno].written_by_or)
4649             ;
4650           else if ((rws_sum[regno].first_pred ^ 1) != pred)
4651             need_barrier = 1;
4652           rws_update (rws_sum, regno, flags, pred);
4653           break;
4654
4655         case 2:
4656           /* The register has been unconditionally written already.  We
4657              need a barrier.  */
4658           if (flags.is_and && rws_sum[regno].written_by_and)
4659             ;
4660           else if (flags.is_or && rws_sum[regno].written_by_or)
4661             ;
4662           else
4663             need_barrier = 1;
4664           rws_sum[regno].written_by_and = flags.is_and;
4665           rws_sum[regno].written_by_or = flags.is_or;
4666           break;
4667
4668         default:
4669           abort ();
4670         }
4671     }
4672   else
4673     {
4674       if (flags.is_branch)
4675         {
4676           /* Branches have several RAW exceptions that allow to avoid
4677              barriers.  */
4678
4679           if (REGNO_REG_CLASS (regno) == BR_REGS || regno == AR_PFS_REGNUM)
4680             /* RAW dependencies on branch regs are permissible as long
4681                as the writer is a non-branch instruction.  Since we
4682                never generate code that uses a branch register written
4683                by a branch instruction, handling this case is
4684                easy.  */
4685             return 0;
4686
4687           if (REGNO_REG_CLASS (regno) == PR_REGS
4688               && ! rws_sum[regno].written_by_fp)
4689             /* The predicates of a branch are available within the
4690                same insn group as long as the predicate was written by
4691                something other than a floating-point instruction.  */
4692             return 0;
4693         }
4694
4695       if (flags.is_and && rws_sum[regno].written_by_and)
4696         return 0;
4697       if (flags.is_or && rws_sum[regno].written_by_or)
4698         return 0;
4699
4700       switch (rws_sum[regno].write_count)
4701         {
4702         case 0:
4703           /* The register has not been written yet.  */
4704           break;
4705
4706         case 1:
4707           /* The register has been written via a predicate.  If this is
4708              not a complementary predicate, then we need a barrier.  */
4709           /* ??? This assumes that P and P+1 are always complementary
4710              predicates for P even.  */
4711           if ((rws_sum[regno].first_pred ^ 1) != pred)
4712             need_barrier = 1;
4713           break;
4714
4715         case 2:
4716           /* The register has been unconditionally written already.  We
4717              need a barrier.  */
4718           need_barrier = 1;
4719           break;
4720
4721         default:
4722           abort ();
4723         }
4724     }
4725
4726   return need_barrier;
4727 }
4728
4729 static int
4730 rws_access_reg (reg, flags, pred)
4731      rtx reg;
4732      struct reg_flags flags;
4733      int pred;
4734 {
4735   int regno = REGNO (reg);
4736   int n = HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg));
4737
4738   if (n == 1)
4739     return rws_access_regno (regno, flags, pred);
4740   else
4741     {
4742       int need_barrier = 0;
4743       while (--n >= 0)
4744         need_barrier |= rws_access_regno (regno + n, flags, pred);
4745       return need_barrier;
4746     }
4747 }
4748
4749 /* Examine X, which is a SET rtx, and update the flags, the predicate, and
4750    the condition, stored in *PFLAGS, *PPRED and *PCOND.  */
4751
4752 static void
4753 update_set_flags (x, pflags, ppred, pcond)
4754      rtx x;
4755      struct reg_flags *pflags;
4756      int *ppred;
4757      rtx *pcond;
4758 {
4759   rtx src = SET_SRC (x);
4760
4761   *pcond = 0;
4762
4763   switch (GET_CODE (src))
4764     {
4765     case CALL:
4766       return;
4767
4768     case IF_THEN_ELSE:
4769       if (SET_DEST (x) == pc_rtx)
4770         /* X is a conditional branch.  */
4771         return; 
4772       else
4773         {
4774           int is_complemented = 0;
4775
4776           /* X is a conditional move.  */
4777           rtx cond = XEXP (src, 0);
4778           if (GET_CODE (cond) == EQ)
4779             is_complemented = 1;
4780           cond = XEXP (cond, 0);
4781           if (GET_CODE (cond) != REG
4782               && REGNO_REG_CLASS (REGNO (cond)) != PR_REGS)
4783             abort ();
4784           *pcond = cond;
4785           if (XEXP (src, 1) == SET_DEST (x)
4786               || XEXP (src, 2) == SET_DEST (x))
4787             {
4788               /* X is a conditional move that conditionally writes the
4789                  destination.  */
4790
4791               /* We need another complement in this case.  */
4792               if (XEXP (src, 1) == SET_DEST (x))
4793                 is_complemented = ! is_complemented;
4794
4795               *ppred = REGNO (cond);
4796               if (is_complemented)
4797                 ++*ppred;
4798             }
4799
4800           /* ??? If this is a conditional write to the dest, then this
4801              instruction does not actually read one source.  This probably
4802              doesn't matter, because that source is also the dest.  */
4803           /* ??? Multiple writes to predicate registers are allowed
4804              if they are all AND type compares, or if they are all OR
4805              type compares.  We do not generate such instructions
4806              currently.  */
4807         }
4808       /* ... fall through ...  */
4809
4810     default:
4811       if (GET_RTX_CLASS (GET_CODE (src)) == '<'
4812           && GET_MODE_CLASS (GET_MODE (XEXP (src, 0))) == MODE_FLOAT)
4813         /* Set pflags->is_fp to 1 so that we know we're dealing
4814            with a floating point comparison when processing the
4815            destination of the SET.  */
4816         pflags->is_fp = 1;
4817
4818       /* Discover if this is a parallel comparison.  We only handle
4819          and.orcm and or.andcm at present, since we must retain a
4820          strict inverse on the predicate pair.  */
4821       else if (GET_CODE (src) == AND)
4822         pflags->is_and = 1;
4823       else if (GET_CODE (src) == IOR)
4824         pflags->is_or = 1;
4825
4826       break;
4827     }
4828 }
4829
4830 /* Subroutine of rtx_needs_barrier; this function determines whether the
4831    source of a given SET rtx found in X needs a barrier.  FLAGS and PRED
4832    are as in rtx_needs_barrier.  COND is an rtx that holds the condition
4833    for this insn.  */
4834    
4835 static int
4836 set_src_needs_barrier (x, flags, pred, cond)
4837      rtx x;
4838      struct reg_flags flags;
4839      int pred;
4840      rtx cond;
4841 {
4842   int need_barrier = 0;
4843   rtx dst;
4844   rtx src = SET_SRC (x);
4845
4846   if (GET_CODE (src) == CALL)
4847     /* We don't need to worry about the result registers that
4848        get written by subroutine call.  */
4849     return rtx_needs_barrier (src, flags, pred);
4850   else if (SET_DEST (x) == pc_rtx)
4851     {
4852       /* X is a conditional branch.  */
4853       /* ??? This seems redundant, as the caller sets this bit for
4854          all JUMP_INSNs.  */
4855       flags.is_branch = 1;
4856       return rtx_needs_barrier (src, flags, pred);
4857     }
4858
4859   need_barrier = rtx_needs_barrier (src, flags, pred);
4860
4861   /* This instruction unconditionally uses a predicate register.  */
4862   if (cond)
4863     need_barrier |= rws_access_reg (cond, flags, 0);
4864
4865   dst = SET_DEST (x);
4866   if (GET_CODE (dst) == ZERO_EXTRACT)
4867     {
4868       need_barrier |= rtx_needs_barrier (XEXP (dst, 1), flags, pred);
4869       need_barrier |= rtx_needs_barrier (XEXP (dst, 2), flags, pred);
4870       dst = XEXP (dst, 0);
4871     }
4872   return need_barrier;
4873 }
4874
4875 /* Handle an access to rtx X of type FLAGS using predicate register PRED.
4876    Return 1 is this access creates a dependency with an earlier instruction
4877    in the same group.  */
4878
4879 static int
4880 rtx_needs_barrier (x, flags, pred)
4881      rtx x;
4882      struct reg_flags flags;
4883      int pred;
4884 {
4885   int i, j;
4886   int is_complemented = 0;
4887   int need_barrier = 0;
4888   const char *format_ptr;
4889   struct reg_flags new_flags;
4890   rtx cond = 0;
4891
4892   if (! x)
4893     return 0;
4894
4895   new_flags = flags;
4896
4897   switch (GET_CODE (x))
4898     {
4899     case SET:      
4900       update_set_flags (x, &new_flags, &pred, &cond);
4901       need_barrier = set_src_needs_barrier (x, new_flags, pred, cond);
4902       if (GET_CODE (SET_SRC (x)) != CALL)
4903         {
4904           new_flags.is_write = 1;
4905           need_barrier |= rtx_needs_barrier (SET_DEST (x), new_flags, pred);
4906         }
4907       break;
4908
4909     case CALL:
4910       new_flags.is_write = 0;
4911       need_barrier |= rws_access_regno (AR_EC_REGNUM, new_flags, pred);
4912
4913       /* Avoid multiple register writes, in case this is a pattern with
4914          multiple CALL rtx.  This avoids an abort in rws_access_reg.  */
4915       if (! flags.is_sibcall && ! rws_insn[REG_AR_CFM].write_count)
4916         {
4917           new_flags.is_write = 1;
4918           need_barrier |= rws_access_regno (REG_RP, new_flags, pred);
4919           need_barrier |= rws_access_regno (AR_PFS_REGNUM, new_flags, pred);
4920           need_barrier |= rws_access_regno (REG_AR_CFM, new_flags, pred);
4921         }
4922       break;
4923
4924     case COND_EXEC:
4925       /* X is a predicated instruction.  */
4926
4927       cond = COND_EXEC_TEST (x);
4928       if (pred)
4929         abort ();
4930       need_barrier = rtx_needs_barrier (cond, flags, 0);
4931
4932       if (GET_CODE (cond) == EQ)
4933         is_complemented = 1;
4934       cond = XEXP (cond, 0);
4935       if (GET_CODE (cond) != REG
4936           && REGNO_REG_CLASS (REGNO (cond)) != PR_REGS)
4937         abort ();
4938       pred = REGNO (cond);
4939       if (is_complemented)
4940         ++pred;
4941
4942       need_barrier |= rtx_needs_barrier (COND_EXEC_CODE (x), flags, pred);
4943       return need_barrier;
4944
4945     case CLOBBER:
4946     case USE:
4947       /* Clobber & use are for earlier compiler-phases only.  */
4948       break;
4949
4950     case ASM_OPERANDS:
4951     case ASM_INPUT:
4952       /* We always emit stop bits for traditional asms.  We emit stop bits
4953          for volatile extended asms if TARGET_VOL_ASM_STOP is true.  */
4954       if (GET_CODE (x) != ASM_OPERANDS
4955           || (MEM_VOLATILE_P (x) && TARGET_VOL_ASM_STOP))
4956         {
4957           /* Avoid writing the register multiple times if we have multiple
4958              asm outputs.  This avoids an abort in rws_access_reg.  */
4959           if (! rws_insn[REG_VOLATILE].write_count)
4960             {
4961               new_flags.is_write = 1;
4962               rws_access_regno (REG_VOLATILE, new_flags, pred);
4963             }
4964           return 1;
4965         }
4966
4967       /* For all ASM_OPERANDS, we must traverse the vector of input operands.
4968          We can not just fall through here since then we would be confused
4969          by the ASM_INPUT rtx inside ASM_OPERANDS, which do not indicate
4970          traditional asms unlike their normal usage.  */
4971
4972       for (i = ASM_OPERANDS_INPUT_LENGTH (x) - 1; i >= 0; --i)
4973         if (rtx_needs_barrier (ASM_OPERANDS_INPUT (x, i), flags, pred))
4974           need_barrier = 1;
4975       break;
4976
4977     case PARALLEL:
4978       for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
4979         {
4980           rtx pat = XVECEXP (x, 0, i);
4981           if (GET_CODE (pat) == SET)
4982             {
4983               update_set_flags (pat, &new_flags, &pred, &cond);
4984               need_barrier |= set_src_needs_barrier (pat, new_flags, pred, cond);
4985             }
4986           else if (GET_CODE (pat) == USE
4987                    || GET_CODE (pat) == CALL
4988                    || GET_CODE (pat) == ASM_OPERANDS)
4989             need_barrier |= rtx_needs_barrier (pat, flags, pred);
4990           else if (GET_CODE (pat) != CLOBBER && GET_CODE (pat) != RETURN)
4991             abort ();
4992         }
4993       for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
4994         {
4995           rtx pat = XVECEXP (x, 0, i);
4996           if (GET_CODE (pat) == SET)
4997             {
4998               if (GET_CODE (SET_SRC (pat)) != CALL)
4999                 {
5000                   new_flags.is_write = 1;
5001                   need_barrier |= rtx_needs_barrier (SET_DEST (pat), new_flags,
5002                                                      pred);
5003                 }
5004             }
5005           else if (GET_CODE (pat) == CLOBBER || GET_CODE (pat) == RETURN)
5006             need_barrier |= rtx_needs_barrier (pat, flags, pred);
5007         }
5008       break;
5009
5010     case SUBREG:
5011       x = SUBREG_REG (x);
5012       /* FALLTHRU */
5013     case REG:
5014       if (REGNO (x) == AR_UNAT_REGNUM)
5015         {
5016           for (i = 0; i < 64; ++i)
5017             need_barrier |= rws_access_regno (AR_UNAT_BIT_0 + i, flags, pred);
5018         }
5019       else
5020         need_barrier = rws_access_reg (x, flags, pred);
5021       break;
5022
5023     case MEM:
5024       /* Find the regs used in memory address computation.  */
5025       new_flags.is_write = 0;
5026       need_barrier = rtx_needs_barrier (XEXP (x, 0), new_flags, pred);
5027       break;
5028
5029     case CONST_INT:   case CONST_DOUBLE:
5030     case SYMBOL_REF:  case LABEL_REF:     case CONST:
5031       break;
5032
5033       /* Operators with side-effects.  */
5034     case POST_INC:    case POST_DEC:
5035       if (GET_CODE (XEXP (x, 0)) != REG)
5036         abort ();
5037
5038       new_flags.is_write = 0;
5039       need_barrier  = rws_access_reg (XEXP (x, 0), new_flags, pred);
5040       new_flags.is_write = 1;
5041       need_barrier |= rws_access_reg (XEXP (x, 0), new_flags, pred);
5042       break;
5043
5044     case POST_MODIFY:
5045       if (GET_CODE (XEXP (x, 0)) != REG)
5046         abort ();
5047
5048       new_flags.is_write = 0;
5049       need_barrier  = rws_access_reg (XEXP (x, 0), new_flags, pred);
5050       need_barrier |= rtx_needs_barrier (XEXP (x, 1), new_flags, pred);
5051       new_flags.is_write = 1;
5052       need_barrier |= rws_access_reg (XEXP (x, 0), new_flags, pred);
5053       break;
5054
5055       /* Handle common unary and binary ops for efficiency.  */
5056     case COMPARE:  case PLUS:    case MINUS:   case MULT:      case DIV:
5057     case MOD:      case UDIV:    case UMOD:    case AND:       case IOR:
5058     case XOR:      case ASHIFT:  case ROTATE:  case ASHIFTRT:  case LSHIFTRT:
5059     case ROTATERT: case SMIN:    case SMAX:    case UMIN:      case UMAX:
5060     case NE:       case EQ:      case GE:      case GT:        case LE:
5061     case LT:       case GEU:     case GTU:     case LEU:       case LTU:
5062       need_barrier = rtx_needs_barrier (XEXP (x, 0), new_flags, pred);
5063       need_barrier |= rtx_needs_barrier (XEXP (x, 1), new_flags, pred);
5064       break;
5065
5066     case NEG:      case NOT:            case SIGN_EXTEND:     case ZERO_EXTEND:
5067     case TRUNCATE: case FLOAT_EXTEND:   case FLOAT_TRUNCATE:  case FLOAT:
5068     case FIX:      case UNSIGNED_FLOAT: case UNSIGNED_FIX:    case ABS:
5069     case SQRT:     case FFS:            case POPCOUNT:
5070       need_barrier = rtx_needs_barrier (XEXP (x, 0), flags, pred);
5071       break;
5072
5073     case UNSPEC:
5074       switch (XINT (x, 1))
5075         {
5076         case UNSPEC_LTOFF_DTPMOD:
5077         case UNSPEC_LTOFF_DTPREL:
5078         case UNSPEC_DTPREL:
5079         case UNSPEC_LTOFF_TPREL:
5080         case UNSPEC_TPREL:
5081         case UNSPEC_PRED_REL_MUTEX:
5082         case UNSPEC_PIC_CALL:
5083         case UNSPEC_MF:
5084         case UNSPEC_FETCHADD_ACQ:
5085         case UNSPEC_BSP_VALUE:
5086         case UNSPEC_FLUSHRS:
5087         case UNSPEC_BUNDLE_SELECTOR:
5088           break;
5089
5090         case UNSPEC_GR_SPILL:
5091         case UNSPEC_GR_RESTORE:
5092           {
5093             HOST_WIDE_INT offset = INTVAL (XVECEXP (x, 0, 1));
5094             HOST_WIDE_INT bit = (offset >> 3) & 63;
5095
5096             need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
5097             new_flags.is_write = (XINT (x, 1) == 1);
5098             need_barrier |= rws_access_regno (AR_UNAT_BIT_0 + bit,
5099                                               new_flags, pred);
5100             break;
5101           }
5102           
5103         case UNSPEC_FR_SPILL:
5104         case UNSPEC_FR_RESTORE:
5105         case UNSPEC_GETF_EXP:
5106         case UNSPEC_ADDP4:
5107           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
5108           break;
5109
5110         case UNSPEC_FR_RECIP_APPROX:
5111           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
5112           need_barrier |= rtx_needs_barrier (XVECEXP (x, 0, 1), flags, pred);
5113           break;
5114
5115         case UNSPEC_CMPXCHG_ACQ:
5116           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 1), flags, pred);
5117           need_barrier |= rtx_needs_barrier (XVECEXP (x, 0, 2), flags, pred);
5118           break;
5119
5120         default:
5121           abort ();
5122         }
5123       break;
5124
5125     case UNSPEC_VOLATILE:
5126       switch (XINT (x, 1))
5127         {
5128         case UNSPECV_ALLOC:
5129           /* Alloc must always be the first instruction of a group.
5130              We force this by always returning true.  */
5131           /* ??? We might get better scheduling if we explicitly check for
5132              input/local/output register dependencies, and modify the
5133              scheduler so that alloc is always reordered to the start of
5134              the current group.  We could then eliminate all of the
5135              first_instruction code.  */
5136           rws_access_regno (AR_PFS_REGNUM, flags, pred);
5137
5138           new_flags.is_write = 1;
5139           rws_access_regno (REG_AR_CFM, new_flags, pred);
5140           return 1;
5141
5142         case UNSPECV_SET_BSP:
5143           need_barrier = 1;
5144           break;
5145
5146         case UNSPECV_BLOCKAGE:
5147         case UNSPECV_INSN_GROUP_BARRIER:
5148         case UNSPECV_BREAK:
5149         case UNSPECV_PSAC_ALL:
5150         case UNSPECV_PSAC_NORMAL:
5151           return 0;
5152
5153         default:
5154           abort ();
5155         }
5156       break;
5157
5158     case RETURN:
5159       new_flags.is_write = 0;
5160       need_barrier  = rws_access_regno (REG_RP, flags, pred);
5161       need_barrier |= rws_access_regno (AR_PFS_REGNUM, flags, pred);
5162
5163       new_flags.is_write = 1;
5164       need_barrier |= rws_access_regno (AR_EC_REGNUM, new_flags, pred);
5165       need_barrier |= rws_access_regno (REG_AR_CFM, new_flags, pred);
5166       break;
5167
5168     default:
5169       format_ptr = GET_RTX_FORMAT (GET_CODE (x));
5170       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
5171         switch (format_ptr[i])
5172           {
5173           case '0':     /* unused field */
5174           case 'i':     /* integer */
5175           case 'n':     /* note */
5176           case 'w':     /* wide integer */
5177           case 's':     /* pointer to string */
5178           case 'S':     /* optional pointer to string */
5179             break;
5180
5181           case 'e':
5182             if (rtx_needs_barrier (XEXP (x, i), flags, pred))
5183               need_barrier = 1;
5184             break;
5185
5186           case 'E':
5187             for (j = XVECLEN (x, i) - 1; j >= 0; --j)
5188               if (rtx_needs_barrier (XVECEXP (x, i, j), flags, pred))
5189                 need_barrier = 1;
5190             break;
5191
5192           default:
5193             abort ();
5194           }
5195       break;
5196     }
5197   return need_barrier;
5198 }
5199
5200 /* Clear out the state for group_barrier_needed_p at the start of a
5201    sequence of insns.  */
5202
5203 static void
5204 init_insn_group_barriers ()
5205 {
5206   memset (rws_sum, 0, sizeof (rws_sum));
5207   first_instruction = 1;
5208 }
5209
5210 /* Given the current state, recorded by previous calls to this function,
5211    determine whether a group barrier (a stop bit) is necessary before INSN.
5212    Return nonzero if so.  */
5213
5214 static int
5215 group_barrier_needed_p (insn)
5216      rtx insn;
5217 {
5218   rtx pat;
5219   int need_barrier = 0;
5220   struct reg_flags flags;
5221
5222   memset (&flags, 0, sizeof (flags));
5223   switch (GET_CODE (insn))
5224     {
5225     case NOTE:
5226       break;
5227
5228     case BARRIER:
5229       /* A barrier doesn't imply an instruction group boundary.  */
5230       break;
5231
5232     case CODE_LABEL:
5233       memset (rws_insn, 0, sizeof (rws_insn));
5234       return 1;
5235
5236     case CALL_INSN:
5237       flags.is_branch = 1;
5238       flags.is_sibcall = SIBLING_CALL_P (insn);
5239       memset (rws_insn, 0, sizeof (rws_insn));
5240
5241       /* Don't bundle a call following another call.  */
5242       if ((pat = prev_active_insn (insn))
5243           && GET_CODE (pat) == CALL_INSN)
5244         {
5245           need_barrier = 1;
5246           break;
5247         }
5248
5249       need_barrier = rtx_needs_barrier (PATTERN (insn), flags, 0);
5250       break;
5251
5252     case JUMP_INSN:
5253       flags.is_branch = 1;
5254
5255       /* Don't bundle a jump following a call.  */
5256       if ((pat = prev_active_insn (insn))
5257           && GET_CODE (pat) == CALL_INSN)
5258         {
5259           need_barrier = 1;
5260           break;
5261         }
5262       /* FALLTHRU */
5263
5264     case INSN:
5265       if (GET_CODE (PATTERN (insn)) == USE
5266           || GET_CODE (PATTERN (insn)) == CLOBBER)
5267         /* Don't care about USE and CLOBBER "insns"---those are used to
5268            indicate to the optimizer that it shouldn't get rid of
5269            certain operations.  */
5270         break;
5271
5272       pat = PATTERN (insn);
5273
5274       /* Ug.  Hack hacks hacked elsewhere.  */
5275       switch (recog_memoized (insn))
5276         {
5277           /* We play dependency tricks with the epilogue in order
5278              to get proper schedules.  Undo this for dv analysis.  */
5279         case CODE_FOR_epilogue_deallocate_stack:
5280         case CODE_FOR_prologue_allocate_stack:
5281           pat = XVECEXP (pat, 0, 0);
5282           break;
5283
5284           /* The pattern we use for br.cloop confuses the code above.
5285              The second element of the vector is representative.  */
5286         case CODE_FOR_doloop_end_internal:
5287           pat = XVECEXP (pat, 0, 1);
5288           break;
5289
5290           /* Doesn't generate code.  */
5291         case CODE_FOR_pred_rel_mutex:
5292         case CODE_FOR_prologue_use:
5293           return 0;
5294
5295         default:
5296           break;
5297         }
5298
5299       memset (rws_insn, 0, sizeof (rws_insn));
5300       need_barrier = rtx_needs_barrier (pat, flags, 0);
5301
5302       /* Check to see if the previous instruction was a volatile
5303          asm.  */
5304       if (! need_barrier)
5305         need_barrier = rws_access_regno (REG_VOLATILE, flags, 0);
5306       break;
5307
5308     default:
5309       abort ();
5310     }
5311
5312   if (first_instruction && INSN_P (insn)
5313       && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
5314       && GET_CODE (PATTERN (insn)) != USE
5315       && GET_CODE (PATTERN (insn)) != CLOBBER)
5316     {
5317       need_barrier = 0;
5318       first_instruction = 0;
5319     }
5320
5321   return need_barrier;
5322 }
5323
5324 /* Like group_barrier_needed_p, but do not clobber the current state.  */
5325
5326 static int
5327 safe_group_barrier_needed_p (insn)
5328      rtx insn;
5329 {
5330   struct reg_write_state rws_saved[NUM_REGS];
5331   int saved_first_instruction;
5332   int t;
5333
5334   memcpy (rws_saved, rws_sum, NUM_REGS * sizeof *rws_saved);
5335   saved_first_instruction = first_instruction;
5336
5337   t = group_barrier_needed_p (insn);
5338
5339   memcpy (rws_sum, rws_saved, NUM_REGS * sizeof *rws_saved);
5340   first_instruction = saved_first_instruction;
5341
5342   return t;
5343 }
5344
5345 /* INSNS is a chain of instructions.  Scan the chain, and insert stop bits
5346    as necessary to eliminate dependencies.  This function assumes that
5347    a final instruction scheduling pass has been run which has already
5348    inserted most of the necessary stop bits.  This function only inserts
5349    new ones at basic block boundaries, since these are invisible to the
5350    scheduler.  */
5351
5352 static void
5353 emit_insn_group_barriers (dump, insns)
5354      FILE *dump;
5355      rtx insns;
5356 {
5357   rtx insn;
5358   rtx last_label = 0;
5359   int insns_since_last_label = 0;
5360
5361   init_insn_group_barriers ();
5362
5363   for (insn = insns; insn; insn = NEXT_INSN (insn))
5364     {
5365       if (GET_CODE (insn) == CODE_LABEL)
5366         {
5367           if (insns_since_last_label)
5368             last_label = insn;
5369           insns_since_last_label = 0;
5370         }
5371       else if (GET_CODE (insn) == NOTE
5372                && NOTE_LINE_NUMBER (insn) == NOTE_INSN_BASIC_BLOCK)
5373         {
5374           if (insns_since_last_label)
5375             last_label = insn;
5376           insns_since_last_label = 0;
5377         }
5378       else if (GET_CODE (insn) == INSN
5379                && GET_CODE (PATTERN (insn)) == UNSPEC_VOLATILE
5380                && XINT (PATTERN (insn), 1) == UNSPECV_INSN_GROUP_BARRIER)
5381         {
5382           init_insn_group_barriers ();
5383           last_label = 0;
5384         }
5385       else if (INSN_P (insn))
5386         {
5387           insns_since_last_label = 1;
5388
5389           if (group_barrier_needed_p (insn))
5390             {
5391               if (last_label)
5392                 {
5393                   if (dump)
5394                     fprintf (dump, "Emitting stop before label %d\n",
5395                              INSN_UID (last_label));
5396                   emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), last_label);
5397                   insn = last_label;
5398
5399                   init_insn_group_barriers ();
5400                   last_label = 0;
5401                 }
5402             }
5403         }
5404     }
5405 }
5406
5407 /* Like emit_insn_group_barriers, but run if no final scheduling pass was run.
5408    This function has to emit all necessary group barriers.  */
5409
5410 static void
5411 emit_all_insn_group_barriers (dump, insns)
5412      FILE *dump ATTRIBUTE_UNUSED;
5413      rtx insns;
5414 {
5415   rtx insn;
5416
5417   init_insn_group_barriers ();
5418
5419   for (insn = insns; insn; insn = NEXT_INSN (insn))
5420     {
5421       if (GET_CODE (insn) == BARRIER)
5422         {
5423           rtx last = prev_active_insn (insn);
5424
5425           if (! last)
5426             continue;
5427           if (GET_CODE (last) == JUMP_INSN
5428               && GET_CODE (PATTERN (last)) == ADDR_DIFF_VEC)
5429             last = prev_active_insn (last);
5430           if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
5431             emit_insn_after (gen_insn_group_barrier (GEN_INT (3)), last);
5432
5433           init_insn_group_barriers ();
5434         }
5435       else if (INSN_P (insn))
5436         {
5437           if (recog_memoized (insn) == CODE_FOR_insn_group_barrier)
5438             init_insn_group_barriers ();
5439           else if (group_barrier_needed_p (insn))
5440             {
5441               emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), insn);
5442               init_insn_group_barriers ();
5443               group_barrier_needed_p (insn);
5444             }
5445         }
5446     }
5447 }
5448
5449 \f
5450 static int errata_find_address_regs PARAMS ((rtx *, void *));
5451 static void errata_emit_nops PARAMS ((rtx));
5452 static void fixup_errata PARAMS ((void));
5453
5454 /* This structure is used to track some details about the previous insns
5455    groups so we can determine if it may be necessary to insert NOPs to
5456    workaround hardware errata.  */
5457 static struct group
5458 {
5459   HARD_REG_SET p_reg_set;
5460   HARD_REG_SET gr_reg_conditionally_set;
5461 } last_group[2];
5462
5463 /* Index into the last_group array.  */
5464 static int group_idx;
5465
5466 /* Called through for_each_rtx; determines if a hard register that was
5467    conditionally set in the previous group is used as an address register.
5468    It ensures that for_each_rtx returns 1 in that case.  */
5469 static int
5470 errata_find_address_regs (xp, data)
5471      rtx *xp;
5472      void *data ATTRIBUTE_UNUSED;
5473 {
5474   rtx x = *xp;
5475   if (GET_CODE (x) != MEM)
5476     return 0;
5477   x = XEXP (x, 0);
5478   if (GET_CODE (x) == POST_MODIFY)
5479     x = XEXP (x, 0);
5480   if (GET_CODE (x) == REG)
5481     {
5482       struct group *prev_group = last_group + (group_idx ^ 1);
5483       if (TEST_HARD_REG_BIT (prev_group->gr_reg_conditionally_set,
5484                              REGNO (x)))
5485         return 1;
5486       return -1;
5487     }
5488   return 0;
5489 }
5490
5491 /* Called for each insn; this function keeps track of the state in
5492    last_group and emits additional NOPs if necessary to work around
5493    an Itanium A/B step erratum.  */
5494 static void
5495 errata_emit_nops (insn)
5496      rtx insn;
5497 {
5498   struct group *this_group = last_group + group_idx;
5499   struct group *prev_group = last_group + (group_idx ^ 1);
5500   rtx pat = PATTERN (insn);
5501   rtx cond = GET_CODE (pat) == COND_EXEC ? COND_EXEC_TEST (pat) : 0;
5502   rtx real_pat = cond ? COND_EXEC_CODE (pat) : pat;
5503   enum attr_type type;
5504   rtx set = real_pat;
5505
5506   if (GET_CODE (real_pat) == USE
5507       || GET_CODE (real_pat) == CLOBBER
5508       || GET_CODE (real_pat) == ASM_INPUT
5509       || GET_CODE (real_pat) == ADDR_VEC
5510       || GET_CODE (real_pat) == ADDR_DIFF_VEC
5511       || asm_noperands (PATTERN (insn)) >= 0)
5512     return;
5513
5514   /* single_set doesn't work for COND_EXEC insns, so we have to duplicate
5515      parts of it.  */
5516
5517   if (GET_CODE (set) == PARALLEL)
5518     {
5519       int i;
5520       set = XVECEXP (real_pat, 0, 0);
5521       for (i = 1; i < XVECLEN (real_pat, 0); i++)
5522         if (GET_CODE (XVECEXP (real_pat, 0, i)) != USE
5523             && GET_CODE (XVECEXP (real_pat, 0, i)) != CLOBBER)
5524           {
5525             set = 0;
5526             break;
5527           }
5528     }
5529
5530   if (set && GET_CODE (set) != SET)
5531     set = 0;
5532
5533   type  = get_attr_type (insn);
5534
5535   if (type == TYPE_F
5536       && set && REG_P (SET_DEST (set)) && PR_REGNO_P (REGNO (SET_DEST (set))))
5537     SET_HARD_REG_BIT (this_group->p_reg_set, REGNO (SET_DEST (set)));
5538
5539   if ((type == TYPE_M || type == TYPE_A) && cond && set
5540       && REG_P (SET_DEST (set))
5541       && GET_CODE (SET_SRC (set)) != PLUS
5542       && GET_CODE (SET_SRC (set)) != MINUS
5543       && (GET_CODE (SET_SRC (set)) != ASHIFT
5544           || !shladd_operand (XEXP (SET_SRC (set), 1), VOIDmode))
5545       && (GET_CODE (SET_SRC (set)) != MEM
5546           || GET_CODE (XEXP (SET_SRC (set), 0)) != POST_MODIFY)
5547       && GENERAL_REGNO_P (REGNO (SET_DEST (set))))
5548     {
5549       if (GET_RTX_CLASS (GET_CODE (cond)) != '<'
5550           || ! REG_P (XEXP (cond, 0)))
5551         abort ();
5552
5553       if (TEST_HARD_REG_BIT (prev_group->p_reg_set, REGNO (XEXP (cond, 0))))
5554         SET_HARD_REG_BIT (this_group->gr_reg_conditionally_set, REGNO (SET_DEST (set)));
5555     }
5556   if (for_each_rtx (&real_pat, errata_find_address_regs, NULL))
5557     {
5558       emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), insn);
5559       emit_insn_before (gen_nop (), insn);
5560       emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), insn);
5561       group_idx = 0;
5562       memset (last_group, 0, sizeof last_group);
5563     }
5564 }
5565
5566 /* Emit extra nops if they are required to work around hardware errata.  */
5567
5568 static void
5569 fixup_errata ()
5570 {
5571   rtx insn;
5572
5573   if (! TARGET_B_STEP)
5574     return;
5575
5576   group_idx = 0;
5577   memset (last_group, 0, sizeof last_group);
5578
5579   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
5580     {
5581       if (!INSN_P (insn))
5582         continue;
5583
5584       if (ia64_safe_type (insn) == TYPE_S)
5585         {
5586           group_idx ^= 1;
5587           memset (last_group + group_idx, 0, sizeof last_group[group_idx]);
5588         }
5589       else
5590         errata_emit_nops (insn);
5591     }
5592 }
5593 \f
5594
5595 /* Instruction scheduling support.  */
5596
5597 #define NR_BUNDLES 10
5598
5599 /* A list of names of all available bundles.  */
5600
5601 static const char *bundle_name [NR_BUNDLES] =
5602 {
5603   ".mii",
5604   ".mmi",
5605   ".mfi",
5606   ".mmf",
5607 #if NR_BUNDLES == 10
5608   ".bbb",
5609   ".mbb",
5610 #endif
5611   ".mib",
5612   ".mmb",
5613   ".mfb",
5614   ".mlx"
5615 };
5616
5617 /* Nonzero if we should insert stop bits into the schedule.  */
5618
5619 int ia64_final_schedule = 0;
5620
5621 /* Codes of the corresponding quieryied units: */
5622
5623 static int _0mii_, _0mmi_, _0mfi_, _0mmf_;
5624 static int _0bbb_, _0mbb_, _0mib_, _0mmb_, _0mfb_, _0mlx_;
5625
5626 static int _1mii_, _1mmi_, _1mfi_, _1mmf_;
5627 static int _1bbb_, _1mbb_, _1mib_, _1mmb_, _1mfb_, _1mlx_;
5628
5629 static int pos_1, pos_2, pos_3, pos_4, pos_5, pos_6;
5630
5631 /* The following variable value is an insn group barrier.  */
5632
5633 static rtx dfa_stop_insn;
5634
5635 /* The following variable value is the last issued insn.  */
5636
5637 static rtx last_scheduled_insn;
5638
5639 /* The following variable value is size of the DFA state.  */
5640
5641 static size_t dfa_state_size;
5642
5643 /* The following variable value is pointer to a DFA state used as
5644    temporary variable.  */
5645
5646 static state_t temp_dfa_state = NULL;
5647
5648 /* The following variable value is DFA state after issuing the last
5649    insn.  */
5650
5651 static state_t prev_cycle_state = NULL;
5652
5653 /* The following array element values are TRUE if the corresponding
5654    insn requires to add stop bits before it.  */
5655
5656 static char *stops_p;
5657
5658 /* The following variable is used to set up the mentioned above array.  */
5659
5660 static int stop_before_p = 0;
5661
5662 /* The following variable value is length of the arrays `clocks' and
5663    `add_cycles'. */
5664
5665 static int clocks_length;
5666
5667 /* The following array element values are cycles on which the
5668    corresponding insn will be issued.  The array is used only for
5669    Itanium1.  */
5670
5671 static int *clocks;
5672
5673 /* The following array element values are numbers of cycles should be
5674    added to improve insn scheduling for MM_insns for Itanium1.  */
5675
5676 static int *add_cycles;
5677
5678 static rtx ia64_single_set PARAMS ((rtx));
5679 static void ia64_emit_insn_before PARAMS ((rtx, rtx));
5680
5681 /* Map a bundle number to its pseudo-op.  */
5682
5683 const char *
5684 get_bundle_name (b)
5685      int b;
5686 {
5687   return bundle_name[b];
5688 }
5689
5690
5691 /* Return the maximum number of instructions a cpu can issue.  */
5692
5693 static int
5694 ia64_issue_rate ()
5695 {
5696   return 6;
5697 }
5698
5699 /* Helper function - like single_set, but look inside COND_EXEC.  */
5700
5701 static rtx
5702 ia64_single_set (insn)
5703      rtx insn;
5704 {
5705   rtx x = PATTERN (insn), ret;
5706   if (GET_CODE (x) == COND_EXEC)
5707     x = COND_EXEC_CODE (x);
5708   if (GET_CODE (x) == SET)
5709     return x;
5710
5711   /* Special case here prologue_allocate_stack and epilogue_deallocate_stack.
5712      Although they are not classical single set, the second set is there just
5713      to protect it from moving past FP-relative stack accesses.  */
5714   switch (recog_memoized (insn))
5715     {
5716     case CODE_FOR_prologue_allocate_stack:
5717     case CODE_FOR_epilogue_deallocate_stack:
5718       ret = XVECEXP (x, 0, 0);
5719       break;
5720
5721     default:
5722       ret = single_set_2 (insn, x);
5723       break;
5724     }
5725
5726   return ret;
5727 }
5728
5729 /* Adjust the cost of a scheduling dependency.  Return the new cost of
5730    a dependency LINK or INSN on DEP_INSN.  COST is the current cost.  */
5731
5732 static int
5733 ia64_adjust_cost (insn, link, dep_insn, cost)
5734      rtx insn, link, dep_insn;
5735      int cost;
5736 {
5737   enum attr_itanium_class dep_class;
5738   enum attr_itanium_class insn_class;
5739
5740   if (REG_NOTE_KIND (link) != REG_DEP_OUTPUT)
5741     return cost;
5742
5743   insn_class = ia64_safe_itanium_class (insn);
5744   dep_class = ia64_safe_itanium_class (dep_insn);
5745   if (dep_class == ITANIUM_CLASS_ST || dep_class == ITANIUM_CLASS_STF
5746       || insn_class == ITANIUM_CLASS_ST || insn_class == ITANIUM_CLASS_STF)
5747     return 0;
5748
5749   return cost;
5750 }
5751
5752 /* Like emit_insn_before, but skip cycle_display notes.
5753    ??? When cycle display notes are implemented, update this.  */
5754
5755 static void
5756 ia64_emit_insn_before (insn, before)
5757      rtx insn, before;
5758 {
5759   emit_insn_before (insn, before);
5760 }
5761
5762 /* The following function marks insns who produce addresses for load
5763    and store insns.  Such insns will be placed into M slots because it
5764    decrease latency time for Itanium1 (see function
5765    `ia64_produce_address_p' and the DFA descriptions).  */
5766
5767 static void
5768 ia64_dependencies_evaluation_hook (head, tail)
5769      rtx head, tail;
5770 {
5771   rtx insn, link, next, next_tail;
5772   
5773   next_tail = NEXT_INSN (tail);
5774   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
5775     if (INSN_P (insn))
5776       insn->call = 0;
5777   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
5778     if (INSN_P (insn)
5779         && ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IALU)
5780       {
5781         for (link = INSN_DEPEND (insn); link != 0; link = XEXP (link, 1))
5782           {
5783             next = XEXP (link, 0);
5784             if ((ia64_safe_itanium_class (next) == ITANIUM_CLASS_ST
5785                  || ia64_safe_itanium_class (next) == ITANIUM_CLASS_STF)
5786                 && ia64_st_address_bypass_p (insn, next))
5787               break;
5788             else if ((ia64_safe_itanium_class (next) == ITANIUM_CLASS_LD
5789                       || ia64_safe_itanium_class (next)
5790                       == ITANIUM_CLASS_FLD)
5791                      && ia64_ld_address_bypass_p (insn, next))
5792               break;
5793           }
5794         insn->call = link != 0;
5795       }
5796 }
5797
5798 /* We're beginning a new block.  Initialize data structures as necessary.  */
5799
5800 static void
5801 ia64_sched_init (dump, sched_verbose, max_ready)
5802      FILE *dump ATTRIBUTE_UNUSED;
5803      int sched_verbose ATTRIBUTE_UNUSED;
5804      int max_ready ATTRIBUTE_UNUSED;
5805 {
5806 #ifdef ENABLE_CHECKING
5807   rtx insn;
5808   
5809   if (reload_completed)
5810     for (insn = NEXT_INSN (current_sched_info->prev_head);
5811          insn != current_sched_info->next_tail;
5812          insn = NEXT_INSN (insn))
5813       if (SCHED_GROUP_P (insn))
5814         abort ();
5815 #endif
5816   last_scheduled_insn = NULL_RTX;
5817   init_insn_group_barriers ();
5818 }
5819
5820 /* We are about to being issuing insns for this clock cycle.
5821    Override the default sort algorithm to better slot instructions.  */
5822
5823 static int
5824 ia64_dfa_sched_reorder (dump, sched_verbose, ready, pn_ready,
5825                         clock_var, reorder_type)
5826      FILE *dump;
5827      int sched_verbose;
5828      rtx *ready;
5829      int *pn_ready;
5830      int clock_var  ATTRIBUTE_UNUSED;
5831      int reorder_type;
5832 {
5833   int n_asms;
5834   int n_ready = *pn_ready;
5835   rtx *e_ready = ready + n_ready;
5836   rtx *insnp;
5837
5838   if (sched_verbose)
5839     fprintf (dump, "// ia64_dfa_sched_reorder (type %d):\n", reorder_type);
5840
5841   if (reorder_type == 0)
5842     {
5843       /* First, move all USEs, CLOBBERs and other crud out of the way.  */
5844       n_asms = 0;
5845       for (insnp = ready; insnp < e_ready; insnp++)
5846         if (insnp < e_ready)
5847           {
5848             rtx insn = *insnp;
5849             enum attr_type t = ia64_safe_type (insn);
5850             if (t == TYPE_UNKNOWN)
5851               {
5852                 if (GET_CODE (PATTERN (insn)) == ASM_INPUT
5853                     || asm_noperands (PATTERN (insn)) >= 0)
5854                   {
5855                     rtx lowest = ready[n_asms];
5856                     ready[n_asms] = insn;
5857                     *insnp = lowest;
5858                     n_asms++;
5859                   }
5860                 else
5861                   {
5862                     rtx highest = ready[n_ready - 1];
5863                     ready[n_ready - 1] = insn;
5864                     *insnp = highest;
5865                     return 1;
5866                   }
5867               }
5868           }
5869
5870       if (n_asms < n_ready)
5871         {
5872           /* Some normal insns to process.  Skip the asms.  */
5873           ready += n_asms;
5874           n_ready -= n_asms;
5875         }
5876       else if (n_ready > 0)
5877         return 1;
5878     }
5879
5880   if (ia64_final_schedule)
5881     {
5882       int deleted = 0;
5883       int nr_need_stop = 0;
5884
5885       for (insnp = ready; insnp < e_ready; insnp++)
5886         if (safe_group_barrier_needed_p (*insnp))
5887           nr_need_stop++;
5888       
5889       if (reorder_type == 1 && n_ready == nr_need_stop)
5890         return 0;
5891       if (reorder_type == 0)
5892         return 1;
5893       insnp = e_ready;
5894       /* Move down everything that needs a stop bit, preserving
5895          relative order.  */
5896       while (insnp-- > ready + deleted)
5897         while (insnp >= ready + deleted)
5898           {
5899             rtx insn = *insnp;
5900             if (! safe_group_barrier_needed_p (insn))
5901               break;
5902             memmove (ready + 1, ready, (insnp - ready) * sizeof (rtx));
5903             *ready = insn;
5904             deleted++;
5905           }
5906       n_ready -= deleted;
5907       ready += deleted;
5908     }
5909
5910   return 1;
5911 }
5912
5913 /* We are about to being issuing insns for this clock cycle.  Override
5914    the default sort algorithm to better slot instructions.  */
5915
5916 static int
5917 ia64_sched_reorder (dump, sched_verbose, ready, pn_ready, clock_var)
5918      FILE *dump;
5919      int sched_verbose;
5920      rtx *ready;
5921      int *pn_ready;
5922      int clock_var;
5923 {
5924   return ia64_dfa_sched_reorder (dump, sched_verbose, ready,
5925                                  pn_ready, clock_var, 0);
5926 }
5927
5928 /* Like ia64_sched_reorder, but called after issuing each insn.
5929    Override the default sort algorithm to better slot instructions.  */
5930
5931 static int
5932 ia64_sched_reorder2 (dump, sched_verbose, ready, pn_ready, clock_var)
5933      FILE *dump ATTRIBUTE_UNUSED;
5934      int sched_verbose ATTRIBUTE_UNUSED;
5935      rtx *ready;
5936      int *pn_ready;
5937      int clock_var;
5938 {
5939   if (ia64_tune == PROCESSOR_ITANIUM && reload_completed && last_scheduled_insn)
5940     clocks [INSN_UID (last_scheduled_insn)] = clock_var;
5941   return ia64_dfa_sched_reorder (dump, sched_verbose, ready, pn_ready,
5942                                  clock_var, 1);
5943 }
5944
5945 /* We are about to issue INSN.  Return the number of insns left on the
5946    ready queue that can be issued this cycle.  */
5947
5948 static int
5949 ia64_variable_issue (dump, sched_verbose, insn, can_issue_more)
5950      FILE *dump ATTRIBUTE_UNUSED;
5951      int sched_verbose ATTRIBUTE_UNUSED;
5952      rtx insn ATTRIBUTE_UNUSED;
5953      int can_issue_more ATTRIBUTE_UNUSED;
5954 {
5955   last_scheduled_insn = insn;
5956   memcpy (prev_cycle_state, curr_state, dfa_state_size);
5957   if (reload_completed)
5958     {
5959       if (group_barrier_needed_p (insn))
5960         abort ();
5961       if (GET_CODE (insn) == CALL_INSN)
5962         init_insn_group_barriers ();
5963       stops_p [INSN_UID (insn)] = stop_before_p;
5964       stop_before_p = 0;
5965     }
5966   return 1;
5967 }
5968
5969 /* We are choosing insn from the ready queue.  Return nonzero if INSN
5970    can be chosen.  */
5971
5972 static int
5973 ia64_first_cycle_multipass_dfa_lookahead_guard (insn)
5974      rtx insn;
5975 {
5976   if (insn == NULL_RTX || !INSN_P (insn))
5977     abort ();
5978   return (!reload_completed
5979           || !safe_group_barrier_needed_p (insn));
5980 }
5981
5982 /* The following variable value is pseudo-insn used by the DFA insn
5983    scheduler to change the DFA state when the simulated clock is
5984    increased.  */
5985
5986 static rtx dfa_pre_cycle_insn;
5987
5988 /* We are about to being issuing INSN.  Return nonzero if we can not
5989    issue it on given cycle CLOCK and return zero if we should not sort
5990    the ready queue on the next clock start.  */
5991
5992 static int
5993 ia64_dfa_new_cycle (dump, verbose, insn, last_clock, clock, sort_p)
5994      FILE *dump;
5995      int verbose;
5996      rtx insn;
5997      int last_clock, clock;
5998      int *sort_p;
5999 {
6000   int setup_clocks_p = FALSE;
6001
6002   if (insn == NULL_RTX || !INSN_P (insn))
6003     abort ();
6004   if ((reload_completed && safe_group_barrier_needed_p (insn))
6005       || (last_scheduled_insn
6006           && (GET_CODE (last_scheduled_insn) == CALL_INSN
6007               || GET_CODE (PATTERN (last_scheduled_insn)) == ASM_INPUT
6008               || asm_noperands (PATTERN (last_scheduled_insn)) >= 0)))
6009     {
6010       init_insn_group_barriers ();
6011       if (verbose && dump)
6012         fprintf (dump, "//    Stop should be before %d%s\n", INSN_UID (insn),
6013                  last_clock == clock ? " + cycle advance" : "");
6014       stop_before_p = 1;
6015       if (last_clock == clock)
6016         {
6017           state_transition (curr_state, dfa_stop_insn);
6018           if (TARGET_EARLY_STOP_BITS)
6019             *sort_p = (last_scheduled_insn == NULL_RTX
6020                        || GET_CODE (last_scheduled_insn) != CALL_INSN);
6021           else
6022             *sort_p = 0;
6023           return 1;
6024         }
6025       else if (reload_completed)
6026         setup_clocks_p = TRUE;
6027       memcpy (curr_state, prev_cycle_state, dfa_state_size);
6028       state_transition (curr_state, dfa_stop_insn);
6029       state_transition (curr_state, dfa_pre_cycle_insn);
6030       state_transition (curr_state, NULL);
6031     }
6032   else if (reload_completed)
6033     setup_clocks_p = TRUE;
6034   if (setup_clocks_p && ia64_tune == PROCESSOR_ITANIUM)
6035     {
6036       enum attr_itanium_class c = ia64_safe_itanium_class (insn);
6037       
6038       if (c != ITANIUM_CLASS_MMMUL && c != ITANIUM_CLASS_MMSHF)
6039         {
6040           rtx link;
6041           int d = -1;
6042           
6043           for (link = LOG_LINKS (insn); link; link = XEXP (link, 1))
6044             if (REG_NOTE_KIND (link) == 0)
6045               {
6046                 enum attr_itanium_class dep_class;
6047                 rtx dep_insn = XEXP (link, 0);
6048                 
6049                 dep_class = ia64_safe_itanium_class (dep_insn);
6050                 if ((dep_class == ITANIUM_CLASS_MMMUL
6051                      || dep_class == ITANIUM_CLASS_MMSHF)
6052                     && last_clock - clocks [INSN_UID (dep_insn)] < 4
6053                     && (d < 0
6054                         || last_clock - clocks [INSN_UID (dep_insn)] < d))
6055                   d = last_clock - clocks [INSN_UID (dep_insn)];
6056               }
6057           if (d >= 0)
6058             add_cycles [INSN_UID (insn)] = 3 - d;
6059         }
6060     }
6061   return 0;
6062 }
6063
6064 \f
6065
6066 /* The following page contains abstract data `bundle states' which are
6067    used for bundling insns (inserting nops and template generation).  */
6068
6069 /* The following describes state of insn bundling.  */
6070
6071 struct bundle_state
6072 {
6073   /* Unique bundle state number to identify them in the debugging
6074      output  */
6075   int unique_num;
6076   rtx insn;     /* corresponding insn, NULL for the 1st and the last state  */
6077   /* number nops before and after the insn  */
6078   short before_nops_num, after_nops_num;
6079   int insn_num; /* insn number (0 - for initial state, 1 - for the 1st
6080                    insn */
6081   int cost;     /* cost of the state in cycles */
6082   int accumulated_insns_num; /* number of all previous insns including
6083                                 nops.  L is considered as 2 insns */
6084   int branch_deviation; /* deviation of previous branches from 3rd slots  */
6085   struct bundle_state *next;  /* next state with the same insn_num  */
6086   struct bundle_state *originator; /* originator (previous insn state)  */
6087   /* All bundle states are in the following chain.  */
6088   struct bundle_state *allocated_states_chain;
6089   /* The DFA State after issuing the insn and the nops.  */
6090   state_t dfa_state;
6091 };
6092
6093 /* The following is map insn number to the corresponding bundle state.  */
6094
6095 static struct bundle_state **index_to_bundle_states;
6096
6097 /* The unique number of next bundle state.  */
6098
6099 static int bundle_states_num;
6100
6101 /* All allocated bundle states are in the following chain.  */
6102
6103 static struct bundle_state *allocated_bundle_states_chain;
6104
6105 /* All allocated but not used bundle states are in the following
6106    chain.  */
6107
6108 static struct bundle_state *free_bundle_state_chain;
6109
6110
6111 /* The following function returns a free bundle state.  */
6112
6113 static struct bundle_state *
6114 get_free_bundle_state ()
6115 {
6116   struct bundle_state *result;
6117
6118   if (free_bundle_state_chain != NULL)
6119     {
6120       result = free_bundle_state_chain;
6121       free_bundle_state_chain = result->next;
6122     }
6123   else
6124     {
6125       result = xmalloc (sizeof (struct bundle_state));
6126       result->dfa_state = xmalloc (dfa_state_size);
6127       result->allocated_states_chain = allocated_bundle_states_chain;
6128       allocated_bundle_states_chain = result;
6129     }
6130   result->unique_num = bundle_states_num++;
6131   return result;
6132   
6133 }
6134
6135 /* The following function frees given bundle state.  */
6136
6137 static void
6138 free_bundle_state (state)
6139      struct bundle_state *state;
6140 {
6141   state->next = free_bundle_state_chain;
6142   free_bundle_state_chain = state;
6143 }
6144
6145 /* Start work with abstract data `bundle states'.  */
6146
6147 static void
6148 initiate_bundle_states ()
6149 {
6150   bundle_states_num = 0;
6151   free_bundle_state_chain = NULL;
6152   allocated_bundle_states_chain = NULL;
6153 }
6154
6155 /* Finish work with abstract data `bundle states'.  */
6156
6157 static void
6158 finish_bundle_states ()
6159 {
6160   struct bundle_state *curr_state, *next_state;
6161
6162   for (curr_state = allocated_bundle_states_chain;
6163        curr_state != NULL;
6164        curr_state = next_state)
6165     {
6166       next_state = curr_state->allocated_states_chain;
6167       free (curr_state->dfa_state);
6168       free (curr_state);
6169     }
6170 }
6171
6172 /* Hash table of the bundle states.  The key is dfa_state and insn_num
6173    of the bundle states.  */
6174
6175 static htab_t bundle_state_table;
6176
6177 /* The function returns hash of BUNDLE_STATE.  */
6178
6179 static unsigned
6180 bundle_state_hash (bundle_state)
6181      const void *bundle_state;
6182 {
6183   const struct bundle_state *state = (struct bundle_state *) bundle_state;
6184   unsigned result, i;
6185
6186   for (result = i = 0; i < dfa_state_size; i++)
6187     result += (((unsigned char *) state->dfa_state) [i]
6188                << ((i % CHAR_BIT) * 3 + CHAR_BIT));
6189   return result + state->insn_num;
6190 }
6191
6192 /* The function returns nonzero if the bundle state keys are equal.  */
6193
6194 static int
6195 bundle_state_eq_p (bundle_state_1, bundle_state_2)
6196      const void *bundle_state_1;
6197      const void *bundle_state_2;
6198 {
6199   const struct bundle_state * state1 = (struct bundle_state *) bundle_state_1;
6200   const struct bundle_state * state2 = (struct bundle_state *) bundle_state_2;
6201
6202   return (state1->insn_num == state2->insn_num
6203           && memcmp (state1->dfa_state, state2->dfa_state,
6204                      dfa_state_size) == 0);
6205 }
6206
6207 /* The function inserts the BUNDLE_STATE into the hash table.  The
6208    function returns nonzero if the bundle has been inserted into the
6209    table.  The table contains the best bundle state with given key.  */
6210
6211 static int
6212 insert_bundle_state (bundle_state)
6213      struct bundle_state *bundle_state;
6214 {
6215   void **entry_ptr;
6216
6217   entry_ptr = htab_find_slot (bundle_state_table, bundle_state, 1);
6218   if (*entry_ptr == NULL)
6219     {
6220       bundle_state->next = index_to_bundle_states [bundle_state->insn_num];
6221       index_to_bundle_states [bundle_state->insn_num] = bundle_state;
6222       *entry_ptr = (void *) bundle_state;
6223       return TRUE;
6224     }
6225   else if (bundle_state->cost < ((struct bundle_state *) *entry_ptr)->cost
6226            || (bundle_state->cost == ((struct bundle_state *) *entry_ptr)->cost
6227                && (((struct bundle_state *)*entry_ptr)->accumulated_insns_num
6228                    > bundle_state->accumulated_insns_num
6229                    || (((struct bundle_state *)
6230                         *entry_ptr)->accumulated_insns_num
6231                        == bundle_state->accumulated_insns_num
6232                        && ((struct bundle_state *)
6233                            *entry_ptr)->branch_deviation
6234                        > bundle_state->branch_deviation))))
6235                    
6236     {
6237       struct bundle_state temp;
6238
6239       temp = *(struct bundle_state *) *entry_ptr;
6240       *(struct bundle_state *) *entry_ptr = *bundle_state;
6241       ((struct bundle_state *) *entry_ptr)->next = temp.next;
6242       *bundle_state = temp;
6243     }
6244   return FALSE;
6245 }
6246
6247 /* Start work with the hash table.  */
6248
6249 static void
6250 initiate_bundle_state_table ()
6251 {
6252   bundle_state_table = htab_create (50, bundle_state_hash, bundle_state_eq_p,
6253                                     (htab_del) 0);
6254 }
6255
6256 /* Finish work with the hash table.  */
6257
6258 static void
6259 finish_bundle_state_table ()
6260 {
6261   htab_delete (bundle_state_table);
6262 }
6263
6264 \f
6265
6266 /* The following variable is a insn `nop' used to check bundle states
6267    with different number of inserted nops.  */
6268
6269 static rtx ia64_nop;
6270
6271 /* The following function tries to issue NOPS_NUM nops for the current
6272    state without advancing processor cycle.  If it failed, the
6273    function returns FALSE and frees the current state.  */
6274
6275 static int
6276 try_issue_nops (curr_state, nops_num)
6277      struct bundle_state *curr_state;
6278      int nops_num;
6279 {
6280   int i;
6281
6282   for (i = 0; i < nops_num; i++)
6283     if (state_transition (curr_state->dfa_state, ia64_nop) >= 0)
6284       {
6285         free_bundle_state (curr_state);
6286         return FALSE;
6287       }
6288   return TRUE;
6289 }
6290
6291 /* The following function tries to issue INSN for the current
6292    state without advancing processor cycle.  If it failed, the
6293    function returns FALSE and frees the current state.  */
6294
6295 static int
6296 try_issue_insn (curr_state, insn)
6297      struct bundle_state *curr_state;
6298      rtx insn;
6299 {
6300   if (insn && state_transition (curr_state->dfa_state, insn) >= 0)
6301     {
6302       free_bundle_state (curr_state);
6303       return FALSE;
6304     }
6305   return TRUE;
6306 }
6307
6308 /* The following function tries to issue BEFORE_NOPS_NUM nops and INSN
6309    starting with ORIGINATOR without advancing processor cycle.  If
6310    TRY_BUNDLE_END_P is TRUE, the function also/only (if
6311    ONLY_BUNDLE_END_P is TRUE) tries to issue nops to fill all bundle.
6312    If it was successful, the function creates new bundle state and
6313    insert into the hash table and into `index_to_bundle_states'.  */
6314
6315 static void
6316 issue_nops_and_insn (originator, before_nops_num, insn, try_bundle_end_p,
6317                      only_bundle_end_p)
6318      struct bundle_state *originator;
6319      int before_nops_num;
6320      rtx insn;
6321      int try_bundle_end_p, only_bundle_end_p;
6322 {
6323   struct bundle_state *curr_state;
6324
6325   curr_state = get_free_bundle_state ();
6326   memcpy (curr_state->dfa_state, originator->dfa_state, dfa_state_size);
6327   curr_state->insn = insn;
6328   curr_state->insn_num = originator->insn_num + 1;
6329   curr_state->cost = originator->cost;
6330   curr_state->originator = originator;
6331   curr_state->before_nops_num = before_nops_num;
6332   curr_state->after_nops_num = 0;
6333   curr_state->accumulated_insns_num
6334     = originator->accumulated_insns_num + before_nops_num;
6335   curr_state->branch_deviation = originator->branch_deviation;
6336   if (insn == NULL_RTX)
6337     abort ();
6338   else if (INSN_CODE (insn) == CODE_FOR_insn_group_barrier)
6339     {
6340       if (GET_MODE (insn) == TImode)
6341         abort ();
6342       if (!try_issue_nops (curr_state, before_nops_num))
6343         return;
6344       if (!try_issue_insn (curr_state, insn))
6345         return;
6346       memcpy (temp_dfa_state, curr_state->dfa_state, dfa_state_size);
6347       if (state_transition (temp_dfa_state, dfa_pre_cycle_insn) >= 0
6348           && curr_state->accumulated_insns_num % 3 != 0)
6349         {
6350           free_bundle_state (curr_state);
6351           return;
6352         }
6353     }
6354   else if (GET_MODE (insn) != TImode)
6355     {
6356       if (!try_issue_nops (curr_state, before_nops_num))
6357         return;
6358       if (!try_issue_insn (curr_state, insn))
6359         return;
6360       curr_state->accumulated_insns_num++;
6361       if (GET_CODE (PATTERN (insn)) == ASM_INPUT
6362           || asm_noperands (PATTERN (insn)) >= 0)
6363         abort ();
6364       if (ia64_safe_type (insn) == TYPE_L)
6365         curr_state->accumulated_insns_num++;
6366     }
6367   else
6368     {
6369       state_transition (curr_state->dfa_state, dfa_pre_cycle_insn);
6370       state_transition (curr_state->dfa_state, NULL);
6371       curr_state->cost++;
6372       if (!try_issue_nops (curr_state, before_nops_num))
6373         return;
6374       if (!try_issue_insn (curr_state, insn))
6375         return;
6376       curr_state->accumulated_insns_num++;
6377       if (GET_CODE (PATTERN (insn)) == ASM_INPUT
6378           || asm_noperands (PATTERN (insn)) >= 0)
6379         {
6380           /* Finish bundle containing asm insn.  */
6381           curr_state->after_nops_num
6382             = 3 - curr_state->accumulated_insns_num % 3;
6383           curr_state->accumulated_insns_num
6384             += 3 - curr_state->accumulated_insns_num % 3;
6385         }
6386       else if (ia64_safe_type (insn) == TYPE_L)
6387         curr_state->accumulated_insns_num++;
6388     }
6389   if (ia64_safe_type (insn) == TYPE_B)
6390     curr_state->branch_deviation
6391       += 2 - (curr_state->accumulated_insns_num - 1) % 3;
6392   if (try_bundle_end_p && curr_state->accumulated_insns_num % 3 != 0)
6393     {
6394       if (!only_bundle_end_p && insert_bundle_state (curr_state))
6395         {
6396           state_t dfa_state;
6397           struct bundle_state *curr_state1;
6398           struct bundle_state *allocated_states_chain;
6399
6400           curr_state1 = get_free_bundle_state ();
6401           dfa_state = curr_state1->dfa_state;
6402           allocated_states_chain = curr_state1->allocated_states_chain;
6403           *curr_state1 = *curr_state;
6404           curr_state1->dfa_state = dfa_state;
6405           curr_state1->allocated_states_chain = allocated_states_chain;
6406           memcpy (curr_state1->dfa_state, curr_state->dfa_state,
6407                   dfa_state_size);
6408           curr_state = curr_state1;
6409         }
6410       if (!try_issue_nops (curr_state,
6411                            3 - curr_state->accumulated_insns_num % 3))
6412         return;
6413       curr_state->after_nops_num
6414         = 3 - curr_state->accumulated_insns_num % 3;
6415       curr_state->accumulated_insns_num
6416         += 3 - curr_state->accumulated_insns_num % 3;
6417     }
6418   if (!insert_bundle_state (curr_state))
6419     free_bundle_state (curr_state);
6420   return;
6421 }
6422
6423 /* The following function returns position in the two window bundle
6424    for given STATE.  */
6425
6426 static int
6427 get_max_pos (state)
6428      state_t state;
6429 {
6430   if (cpu_unit_reservation_p (state, pos_6))
6431     return 6;
6432   else if (cpu_unit_reservation_p (state, pos_5))
6433     return 5;
6434   else if (cpu_unit_reservation_p (state, pos_4))
6435     return 4;
6436   else if (cpu_unit_reservation_p (state, pos_3))
6437     return 3;
6438   else if (cpu_unit_reservation_p (state, pos_2))
6439     return 2;
6440   else if (cpu_unit_reservation_p (state, pos_1))
6441     return 1;
6442   else
6443     return 0;
6444 }
6445
6446 /* The function returns code of a possible template for given position
6447    and state.  The function should be called only with 2 values of
6448    position equal to 3 or 6.  */
6449
6450 static int
6451 get_template (state, pos)
6452      state_t state;
6453      int pos;
6454 {
6455   switch (pos)
6456     {
6457     case 3:
6458       if (cpu_unit_reservation_p (state, _0mii_))
6459         return 0;
6460       else if (cpu_unit_reservation_p (state, _0mmi_))
6461         return 1;
6462       else if (cpu_unit_reservation_p (state, _0mfi_))
6463         return 2;
6464       else if (cpu_unit_reservation_p (state, _0mmf_))
6465         return 3;
6466       else if (cpu_unit_reservation_p (state, _0bbb_))
6467         return 4;
6468       else if (cpu_unit_reservation_p (state, _0mbb_))
6469         return 5;
6470       else if (cpu_unit_reservation_p (state, _0mib_))
6471         return 6;
6472       else if (cpu_unit_reservation_p (state, _0mmb_))
6473         return 7;
6474       else if (cpu_unit_reservation_p (state, _0mfb_))
6475         return 8;
6476       else if (cpu_unit_reservation_p (state, _0mlx_))
6477         return 9;
6478       else
6479         abort ();
6480     case 6:
6481       if (cpu_unit_reservation_p (state, _1mii_))
6482         return 0;
6483       else if (cpu_unit_reservation_p (state, _1mmi_))
6484         return 1;
6485       else if (cpu_unit_reservation_p (state, _1mfi_))
6486         return 2;
6487       else if (_1mmf_ >= 0 && cpu_unit_reservation_p (state, _1mmf_))
6488         return 3;
6489       else if (cpu_unit_reservation_p (state, _1bbb_))
6490         return 4;
6491       else if (cpu_unit_reservation_p (state, _1mbb_))
6492         return 5;
6493       else if (cpu_unit_reservation_p (state, _1mib_))
6494         return 6;
6495       else if (cpu_unit_reservation_p (state, _1mmb_))
6496         return 7;
6497       else if (cpu_unit_reservation_p (state, _1mfb_))
6498         return 8;
6499       else if (cpu_unit_reservation_p (state, _1mlx_))
6500         return 9;
6501       else
6502         abort ();
6503     default:
6504       abort ();
6505     }
6506 }
6507
6508 /* The following function returns an insn important for insn bundling
6509    followed by INSN and before TAIL.  */
6510
6511 static rtx
6512 get_next_important_insn (insn, tail)
6513      rtx insn, tail;
6514 {
6515   for (; insn && insn != tail; insn = NEXT_INSN (insn))
6516     if (INSN_P (insn)
6517         && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
6518         && GET_CODE (PATTERN (insn)) != USE
6519         && GET_CODE (PATTERN (insn)) != CLOBBER)
6520       return insn;
6521   return NULL_RTX;
6522 }
6523
6524 /* The following function does insn bundling.  Bundling algorithm is
6525    based on dynamic programming.  It tries to insert different number of
6526    nop insns before/after the real insns.  At the end of EBB, it chooses the
6527    best alternative and then, moving back in EBB, inserts templates for
6528    the best alternative.  The algorithm is directed by information
6529    (changes of simulated processor cycle) created by the 2nd insn
6530    scheduling.  */
6531
6532 static void
6533 bundling (dump, verbose, prev_head_insn, tail)
6534      FILE *dump;
6535      int verbose;
6536      rtx prev_head_insn, tail;
6537 {
6538   struct bundle_state *curr_state, *next_state, *best_state;
6539   rtx insn, next_insn;
6540   int insn_num;
6541   int i, bundle_end_p, only_bundle_end_p, asm_p;
6542   int pos, max_pos, template0, template1;
6543   rtx b;
6544   rtx nop;
6545   enum attr_type type;
6546
6547   insn_num = 0;
6548   for (insn = NEXT_INSN (prev_head_insn);
6549        insn && insn != tail;
6550        insn = NEXT_INSN (insn))
6551     if (INSN_P (insn))
6552       insn_num++;
6553   if (insn_num == 0)
6554     return;
6555   bundling_p = 1;
6556   dfa_clean_insn_cache ();
6557   initiate_bundle_state_table ();
6558   index_to_bundle_states = xmalloc ((insn_num + 2)
6559                                     * sizeof (struct bundle_state *));
6560   /* First (forward) pass -- generates states. */
6561   curr_state = get_free_bundle_state ();
6562   curr_state->insn = NULL;
6563   curr_state->before_nops_num = 0;
6564   curr_state->after_nops_num = 0;
6565   curr_state->insn_num = 0;
6566   curr_state->cost = 0;
6567   curr_state->accumulated_insns_num = 0;
6568   curr_state->branch_deviation = 0;
6569   curr_state->next = NULL;
6570   curr_state->originator = NULL;
6571   state_reset (curr_state->dfa_state);
6572   index_to_bundle_states [0] = curr_state;
6573   insn_num = 0;
6574   for (insn = NEXT_INSN (prev_head_insn);
6575        insn != tail;
6576        insn = NEXT_INSN (insn))
6577     if (INSN_P (insn)
6578         && (ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IGNORE
6579             || GET_CODE (PATTERN (insn)) == USE
6580             || GET_CODE (PATTERN (insn)) == CLOBBER)
6581         && GET_MODE (insn) == TImode)
6582       {
6583         PUT_MODE (insn, VOIDmode);
6584         for (next_insn = NEXT_INSN (insn);
6585              next_insn != tail;
6586              next_insn = NEXT_INSN (next_insn))
6587           if (INSN_P (next_insn)
6588               && ia64_safe_itanium_class (next_insn) != ITANIUM_CLASS_IGNORE
6589               && GET_CODE (PATTERN (next_insn)) != USE
6590               && GET_CODE (PATTERN (next_insn)) != CLOBBER)
6591             {
6592               PUT_MODE (next_insn, TImode);
6593               break;
6594             }
6595       }
6596   for (insn = get_next_important_insn (NEXT_INSN (prev_head_insn), tail);
6597        insn != NULL_RTX;
6598        insn = next_insn)
6599     {
6600       if (!INSN_P (insn)
6601           || ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IGNORE
6602           || GET_CODE (PATTERN (insn)) == USE
6603           || GET_CODE (PATTERN (insn)) == CLOBBER)
6604         abort ();
6605       type = ia64_safe_type (insn);
6606       next_insn = get_next_important_insn (NEXT_INSN (insn), tail);
6607       insn_num++;
6608       index_to_bundle_states [insn_num] = NULL;
6609       for (curr_state = index_to_bundle_states [insn_num - 1];
6610            curr_state != NULL;
6611            curr_state = next_state)
6612         {
6613           pos = curr_state->accumulated_insns_num % 3;
6614           next_state = curr_state->next;
6615           /* Finish the current bundle in order to start a subsequent
6616              asm insn in a new bundle.  */
6617           only_bundle_end_p
6618             = (next_insn != NULL_RTX
6619                && INSN_CODE (insn) == CODE_FOR_insn_group_barrier
6620                && ia64_safe_type (next_insn) == TYPE_UNKNOWN);
6621           bundle_end_p
6622             = (only_bundle_end_p || next_insn == NULL_RTX
6623                || (GET_MODE (next_insn) == TImode
6624                    && INSN_CODE (insn) != CODE_FOR_insn_group_barrier));
6625           if (type == TYPE_F || type == TYPE_B || type == TYPE_L
6626               || type == TYPE_S
6627               /* We need to insert 2 Nops for cases like M_MII.  */
6628               || (type == TYPE_M && ia64_tune == PROCESSOR_ITANIUM
6629                   && !bundle_end_p && pos == 1))
6630             issue_nops_and_insn (curr_state, 2, insn, bundle_end_p,
6631                                  only_bundle_end_p);
6632           issue_nops_and_insn (curr_state, 1, insn, bundle_end_p,
6633                                only_bundle_end_p);
6634           issue_nops_and_insn (curr_state, 0, insn, bundle_end_p,
6635                                only_bundle_end_p);
6636         }
6637       if (index_to_bundle_states [insn_num] == NULL)
6638         abort ();
6639       for (curr_state = index_to_bundle_states [insn_num];
6640            curr_state != NULL;
6641            curr_state = curr_state->next)
6642         if (verbose >= 2 && dump)
6643           {
6644             struct DFA_chip
6645             {
6646               unsigned short one_automaton_state;
6647               unsigned short oneb_automaton_state;
6648               unsigned short two_automaton_state;
6649               unsigned short twob_automaton_state;
6650             };
6651             
6652             fprintf
6653               (dump,
6654                "//    Bundle state %d (orig %d, cost %d, nops %d/%d, insns %d, branch %d, state %d) for %d\n",
6655                curr_state->unique_num,
6656                (curr_state->originator == NULL
6657                 ? -1 : curr_state->originator->unique_num),
6658                curr_state->cost,
6659                curr_state->before_nops_num, curr_state->after_nops_num,
6660                curr_state->accumulated_insns_num, curr_state->branch_deviation,
6661                (ia64_tune == PROCESSOR_ITANIUM
6662                 ? ((struct DFA_chip *) curr_state->dfa_state)->oneb_automaton_state
6663                 : ((struct DFA_chip *) curr_state->dfa_state)->twob_automaton_state),
6664                INSN_UID (insn));
6665           }
6666     }
6667   if (index_to_bundle_states [insn_num] == NULL)
6668     abort ();
6669   /* Finding state with a minimal cost:  */
6670   best_state = NULL;
6671   for (curr_state = index_to_bundle_states [insn_num];
6672        curr_state != NULL;
6673        curr_state = curr_state->next)
6674     if (curr_state->accumulated_insns_num % 3 == 0
6675         && (best_state == NULL || best_state->cost > curr_state->cost
6676             || (best_state->cost == curr_state->cost
6677                 && (curr_state->accumulated_insns_num
6678                     < best_state->accumulated_insns_num
6679                     || (curr_state->accumulated_insns_num
6680                         == best_state->accumulated_insns_num
6681                         && curr_state->branch_deviation
6682                         < best_state->branch_deviation)))))
6683       best_state = curr_state;
6684   /* Second (backward) pass: adding nops and templates:  */
6685   insn_num = best_state->before_nops_num;
6686   template0 = template1 = -1;
6687   for (curr_state = best_state;
6688        curr_state->originator != NULL;
6689        curr_state = curr_state->originator)
6690     {
6691       insn = curr_state->insn;
6692       asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
6693                || asm_noperands (PATTERN (insn)) >= 0);
6694       insn_num++;
6695       if (verbose >= 2 && dump)
6696         {
6697           struct DFA_chip
6698           {
6699             unsigned short one_automaton_state;
6700             unsigned short oneb_automaton_state;
6701             unsigned short two_automaton_state;
6702             unsigned short twob_automaton_state;
6703           };
6704           
6705           fprintf
6706             (dump,
6707              "//    Best %d (orig %d, cost %d, nops %d/%d, insns %d, branch %d, state %d) for %d\n",
6708              curr_state->unique_num,
6709              (curr_state->originator == NULL
6710               ? -1 : curr_state->originator->unique_num),
6711              curr_state->cost,
6712              curr_state->before_nops_num, curr_state->after_nops_num,
6713              curr_state->accumulated_insns_num, curr_state->branch_deviation,
6714              (ia64_tune == PROCESSOR_ITANIUM
6715               ? ((struct DFA_chip *) curr_state->dfa_state)->oneb_automaton_state
6716               : ((struct DFA_chip *) curr_state->dfa_state)->twob_automaton_state),
6717              INSN_UID (insn));
6718         }
6719       max_pos = get_max_pos (curr_state->dfa_state);
6720       if (max_pos == 6 || (max_pos == 3 && template0 < 0))
6721         {
6722           pos = max_pos;
6723           if (max_pos == 3)
6724             template0 = get_template (curr_state->dfa_state, 3);
6725           else
6726             {
6727               template1 = get_template (curr_state->dfa_state, 3);
6728               template0 = get_template (curr_state->dfa_state, 6);
6729             }
6730         }
6731       if (max_pos > 3 && template1 < 0)
6732         {
6733           if (pos > 3)
6734             abort ();
6735           template1 = get_template (curr_state->dfa_state, 3);
6736           pos += 3;
6737         }
6738       if (!asm_p)
6739         for (i = 0; i < curr_state->after_nops_num; i++)
6740           {
6741             nop = gen_nop ();
6742             emit_insn_after (nop, insn);
6743             pos--;
6744             if (pos < 0)
6745               abort ();
6746             if (pos % 3 == 0)
6747               {
6748                 if (template0 < 0)
6749                   abort ();
6750                 b = gen_bundle_selector (GEN_INT (template0));
6751                 ia64_emit_insn_before (b, nop);
6752                 template0 = template1;
6753                 template1 = -1;
6754               }
6755           }
6756       if (INSN_CODE (insn) != CODE_FOR_insn_group_barrier
6757           && GET_CODE (PATTERN (insn)) != ASM_INPUT
6758           && asm_noperands (PATTERN (insn)) < 0)
6759         pos--;
6760       if (ia64_safe_type (insn) == TYPE_L)
6761         pos--;
6762       if (pos < 0)
6763         abort ();
6764       if (pos % 3 == 0
6765           && INSN_CODE (insn) != CODE_FOR_insn_group_barrier
6766           && GET_CODE (PATTERN (insn)) != ASM_INPUT
6767           && asm_noperands (PATTERN (insn)) < 0)
6768         {
6769           if (template0 < 0)
6770             abort ();
6771           b = gen_bundle_selector (GEN_INT (template0));
6772           ia64_emit_insn_before (b, insn);
6773           b = PREV_INSN (insn);
6774           insn = b;
6775           template0 = template1;
6776           template1 = -1;
6777         }
6778       for (i = 0; i < curr_state->before_nops_num; i++)
6779         {
6780           nop = gen_nop ();
6781           ia64_emit_insn_before (nop, insn);
6782           nop = PREV_INSN (insn);
6783           insn = nop;
6784           pos--;
6785           if (pos < 0)
6786             abort ();
6787           if (pos % 3 == 0)
6788             {
6789               if (template0 < 0)
6790                 abort ();
6791               b = gen_bundle_selector (GEN_INT (template0));
6792               ia64_emit_insn_before (b, insn);
6793               b = PREV_INSN (insn);
6794               insn = b;
6795               template0 = template1;
6796               template1 = -1;
6797             }
6798         }
6799     }
6800   if (ia64_tune == PROCESSOR_ITANIUM)
6801     /* Insert additional cycles for MM-insns: */
6802     for (insn = get_next_important_insn (NEXT_INSN (prev_head_insn), tail);
6803          insn != NULL_RTX;
6804          insn = next_insn)
6805       {
6806         if (!INSN_P (insn)
6807             || ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IGNORE
6808             || GET_CODE (PATTERN (insn)) == USE
6809             || GET_CODE (PATTERN (insn)) == CLOBBER)
6810           abort ();
6811         next_insn = get_next_important_insn (NEXT_INSN (insn), tail);
6812         if (INSN_UID (insn) < clocks_length && add_cycles [INSN_UID (insn)])
6813           {
6814             rtx last;
6815             int i, j, n;
6816             int pred_stop_p;
6817             
6818             last = prev_active_insn (insn);
6819             pred_stop_p = recog_memoized (last) == CODE_FOR_insn_group_barrier;
6820             if (pred_stop_p)
6821               last = prev_active_insn (last);
6822             n = 0;
6823             for (;; last = prev_active_insn (last))
6824               if (recog_memoized (last) == CODE_FOR_bundle_selector)
6825                 {
6826                   template0 = XINT (XVECEXP (PATTERN (last), 0, 0), 0);
6827                   if (template0 == 9)
6828                     PATTERN (last)
6829                       = gen_bundle_selector (GEN_INT (2)); /* -> MFI */
6830                   break;
6831                 }
6832               else if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
6833                 n++;
6834             if ((pred_stop_p && n == 0) || n > 2
6835                 || (template0 == 9 && n != 0))
6836               abort ();
6837             for (j = 3 - n; j > 0; j --)
6838               ia64_emit_insn_before (gen_nop (), insn);
6839             add_cycles [INSN_UID (insn)]--;
6840             if (!pred_stop_p || add_cycles [INSN_UID (insn)])
6841               ia64_emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
6842                                      insn);
6843             if (pred_stop_p)
6844               add_cycles [INSN_UID (insn)]--;
6845             for (i = add_cycles [INSN_UID (insn)]; i > 0; i--)
6846               {
6847                 /* Insert .MII bundle.  */
6848                 ia64_emit_insn_before (gen_bundle_selector (GEN_INT (0)),
6849                                        insn);
6850                 ia64_emit_insn_before (gen_nop (), insn);
6851                 ia64_emit_insn_before (gen_nop (), insn);
6852                 if (i > 1)
6853                   {
6854                     ia64_emit_insn_before
6855                       (gen_insn_group_barrier (GEN_INT (3)), insn);
6856                     i--;
6857                   }
6858                 ia64_emit_insn_before (gen_nop (), insn);
6859                 ia64_emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
6860                                        insn);
6861               }
6862             ia64_emit_insn_before (gen_bundle_selector (GEN_INT (template0)),
6863                                    insn);
6864             for (j = n; j > 0; j --)
6865               ia64_emit_insn_before (gen_nop (), insn);
6866             if (pred_stop_p)
6867               ia64_emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
6868                                      insn);
6869           }
6870       }
6871   free (index_to_bundle_states);
6872   finish_bundle_state_table ();
6873   bundling_p = 0;
6874   dfa_clean_insn_cache ();
6875 }
6876
6877 /* The following function is called at the end of scheduling BB or
6878    EBB.  After reload, it inserts stop bits and does insn bundling.  */
6879
6880 static void
6881 ia64_sched_finish (dump, sched_verbose)
6882      FILE *dump;
6883      int sched_verbose;
6884 {
6885   if (sched_verbose)
6886     fprintf (dump, "// Finishing schedule.\n");
6887   if (!reload_completed)
6888     return;
6889   if (reload_completed)
6890     {
6891       final_emit_insn_group_barriers (dump);
6892       bundling (dump, sched_verbose, current_sched_info->prev_head,
6893                 current_sched_info->next_tail);
6894       if (sched_verbose && dump)
6895         fprintf (dump, "//    finishing %d-%d\n",
6896                  INSN_UID (NEXT_INSN (current_sched_info->prev_head)),
6897                  INSN_UID (PREV_INSN (current_sched_info->next_tail)));
6898       
6899       return;
6900     }
6901 }
6902
6903 /* The following function inserts stop bits in scheduled BB or EBB.  */
6904
6905 static void
6906 final_emit_insn_group_barriers (dump)
6907      FILE *dump ATTRIBUTE_UNUSED;
6908 {
6909   rtx insn;
6910   int need_barrier_p = 0;
6911   rtx prev_insn = NULL_RTX;
6912
6913   init_insn_group_barriers ();
6914
6915   for (insn = NEXT_INSN (current_sched_info->prev_head);
6916        insn != current_sched_info->next_tail;
6917        insn = NEXT_INSN (insn))
6918     {
6919       if (GET_CODE (insn) == BARRIER)
6920         {
6921           rtx last = prev_active_insn (insn);
6922
6923           if (! last)
6924             continue;
6925           if (GET_CODE (last) == JUMP_INSN
6926               && GET_CODE (PATTERN (last)) == ADDR_DIFF_VEC)
6927             last = prev_active_insn (last);
6928           if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
6929             emit_insn_after (gen_insn_group_barrier (GEN_INT (3)), last);
6930
6931           init_insn_group_barriers ();
6932           need_barrier_p = 0;
6933           prev_insn = NULL_RTX;
6934         }
6935       else if (INSN_P (insn))
6936         {
6937           if (recog_memoized (insn) == CODE_FOR_insn_group_barrier)
6938             {
6939               init_insn_group_barriers ();
6940               need_barrier_p = 0;
6941               prev_insn = NULL_RTX;
6942             }
6943           else if (need_barrier_p || group_barrier_needed_p (insn))
6944             {
6945               if (TARGET_EARLY_STOP_BITS)
6946                 {
6947                   rtx last;
6948                   
6949                   for (last = insn;
6950                        last != current_sched_info->prev_head;
6951                        last = PREV_INSN (last))
6952                     if (INSN_P (last) && GET_MODE (last) == TImode
6953                         && stops_p [INSN_UID (last)])
6954                       break;
6955                   if (last == current_sched_info->prev_head)
6956                     last = insn;
6957                   last = prev_active_insn (last);
6958                   if (last
6959                       && recog_memoized (last) != CODE_FOR_insn_group_barrier)
6960                     emit_insn_after (gen_insn_group_barrier (GEN_INT (3)),
6961                                      last);
6962                   init_insn_group_barriers ();
6963                   for (last = NEXT_INSN (last);
6964                        last != insn;
6965                        last = NEXT_INSN (last))
6966                     if (INSN_P (last))
6967                       group_barrier_needed_p (last);
6968                 }
6969               else
6970                 {
6971                   emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
6972                                     insn);
6973                   init_insn_group_barriers ();
6974                 }
6975               group_barrier_needed_p (insn);
6976               prev_insn = NULL_RTX;
6977             }
6978           else if (recog_memoized (insn) >= 0)
6979             prev_insn = insn;
6980           need_barrier_p = (GET_CODE (insn) == CALL_INSN
6981                             || GET_CODE (PATTERN (insn)) == ASM_INPUT
6982                             || asm_noperands (PATTERN (insn)) >= 0);
6983         }
6984     }
6985 }
6986
6987 \f
6988
6989 /* If the following function returns TRUE, we will use the the DFA
6990    insn scheduler.  */
6991
6992 static int
6993 ia64_use_dfa_pipeline_interface ()
6994 {
6995   return 1;
6996 }
6997
6998 /* If the following function returns TRUE, we will use the the DFA
6999    insn scheduler.  */
7000
7001 static int
7002 ia64_first_cycle_multipass_dfa_lookahead ()
7003 {
7004   return (reload_completed ? 6 : 4);
7005 }
7006
7007 /* The following function initiates variable `dfa_pre_cycle_insn'.  */
7008
7009 static void
7010 ia64_init_dfa_pre_cycle_insn ()
7011 {
7012   if (temp_dfa_state == NULL)
7013     {
7014       dfa_state_size = state_size ();
7015       temp_dfa_state = xmalloc (dfa_state_size);
7016       prev_cycle_state = xmalloc (dfa_state_size);
7017     }
7018   dfa_pre_cycle_insn = make_insn_raw (gen_pre_cycle ());
7019   PREV_INSN (dfa_pre_cycle_insn) = NEXT_INSN (dfa_pre_cycle_insn) = NULL_RTX;
7020   recog_memoized (dfa_pre_cycle_insn);
7021   dfa_stop_insn = make_insn_raw (gen_insn_group_barrier (GEN_INT (3)));
7022   PREV_INSN (dfa_stop_insn) = NEXT_INSN (dfa_stop_insn) = NULL_RTX;
7023   recog_memoized (dfa_stop_insn);
7024 }
7025
7026 /* The following function returns the pseudo insn DFA_PRE_CYCLE_INSN
7027    used by the DFA insn scheduler.  */
7028
7029 static rtx
7030 ia64_dfa_pre_cycle_insn ()
7031 {
7032   return dfa_pre_cycle_insn;
7033 }
7034
7035 /* The following function returns TRUE if PRODUCER (of type ilog or
7036    ld) produces address for CONSUMER (of type st or stf). */
7037
7038 int
7039 ia64_st_address_bypass_p (producer, consumer)
7040      rtx producer;
7041      rtx consumer;
7042 {
7043   rtx dest, reg, mem;
7044
7045   if (producer == NULL_RTX || consumer == NULL_RTX)
7046     abort ();
7047   dest = ia64_single_set (producer);
7048   if (dest == NULL_RTX || (reg = SET_DEST (dest)) == NULL_RTX
7049       || (GET_CODE (reg) != REG && GET_CODE (reg) != SUBREG))
7050     abort ();
7051   if (GET_CODE (reg) == SUBREG)
7052     reg = SUBREG_REG (reg);
7053   dest = ia64_single_set (consumer);
7054   if (dest == NULL_RTX || (mem = SET_DEST (dest)) == NULL_RTX
7055       || GET_CODE (mem) != MEM)
7056     abort ();
7057   return reg_mentioned_p (reg, mem);
7058 }
7059
7060 /* The following function returns TRUE if PRODUCER (of type ilog or
7061    ld) produces address for CONSUMER (of type ld or fld). */
7062
7063 int
7064 ia64_ld_address_bypass_p (producer, consumer)
7065      rtx producer;
7066      rtx consumer;
7067 {
7068   rtx dest, src, reg, mem;
7069
7070   if (producer == NULL_RTX || consumer == NULL_RTX)
7071     abort ();
7072   dest = ia64_single_set (producer);
7073   if (dest == NULL_RTX || (reg = SET_DEST (dest)) == NULL_RTX
7074       || (GET_CODE (reg) != REG && GET_CODE (reg) != SUBREG))
7075     abort ();
7076   if (GET_CODE (reg) == SUBREG)
7077     reg = SUBREG_REG (reg);
7078   src = ia64_single_set (consumer);
7079   if (src == NULL_RTX || (mem = SET_SRC (src)) == NULL_RTX)
7080     abort ();
7081   if (GET_CODE (mem) == UNSPEC && XVECLEN (mem, 0) > 0)
7082     mem = XVECEXP (mem, 0, 0);
7083   while (GET_CODE (mem) == SUBREG || GET_CODE (mem) == ZERO_EXTEND)
7084     mem = XEXP (mem, 0);
7085
7086   /* Note that LO_SUM is used for GOT loads.  */
7087   if (GET_CODE (mem) != LO_SUM && GET_CODE (mem) != MEM)
7088     abort ();
7089
7090   return reg_mentioned_p (reg, mem);
7091 }
7092
7093 /* The following function returns TRUE if INSN produces address for a
7094    load/store insn.  We will place such insns into M slot because it
7095    decreases its latency time. */
7096
7097 int
7098 ia64_produce_address_p (insn)
7099      rtx insn;
7100 {
7101   return insn->call;
7102 }
7103
7104 \f
7105 /* Emit pseudo-ops for the assembler to describe predicate relations.
7106    At present this assumes that we only consider predicate pairs to
7107    be mutex, and that the assembler can deduce proper values from
7108    straight-line code.  */
7109
7110 static void
7111 emit_predicate_relation_info ()
7112 {
7113   basic_block bb;
7114
7115   FOR_EACH_BB_REVERSE (bb)
7116     {
7117       int r;
7118       rtx head = bb->head;
7119
7120       /* We only need such notes at code labels.  */
7121       if (GET_CODE (head) != CODE_LABEL)
7122         continue;
7123       if (GET_CODE (NEXT_INSN (head)) == NOTE
7124           && NOTE_LINE_NUMBER (NEXT_INSN (head)) == NOTE_INSN_BASIC_BLOCK)
7125         head = NEXT_INSN (head);
7126
7127       for (r = PR_REG (0); r < PR_REG (64); r += 2)
7128         if (REGNO_REG_SET_P (bb->global_live_at_start, r))
7129           {
7130             rtx p = gen_rtx_REG (BImode, r);
7131             rtx n = emit_insn_after (gen_pred_rel_mutex (p), head);
7132             if (head == bb->end)
7133               bb->end = n;
7134             head = n;
7135           }
7136     }
7137
7138   /* Look for conditional calls that do not return, and protect predicate
7139      relations around them.  Otherwise the assembler will assume the call
7140      returns, and complain about uses of call-clobbered predicates after
7141      the call.  */
7142   FOR_EACH_BB_REVERSE (bb)
7143     {
7144       rtx insn = bb->head;
7145       
7146       while (1)
7147         {
7148           if (GET_CODE (insn) == CALL_INSN
7149               && GET_CODE (PATTERN (insn)) == COND_EXEC
7150               && find_reg_note (insn, REG_NORETURN, NULL_RTX))
7151             {
7152               rtx b = emit_insn_before (gen_safe_across_calls_all (), insn);
7153               rtx a = emit_insn_after (gen_safe_across_calls_normal (), insn);
7154               if (bb->head == insn)
7155                 bb->head = b;
7156               if (bb->end == insn)
7157                 bb->end = a;
7158             }
7159           
7160           if (insn == bb->end)
7161             break;
7162           insn = NEXT_INSN (insn);
7163         }
7164     }
7165 }
7166
7167 /* Perform machine dependent operations on the rtl chain INSNS.  */
7168
7169 void
7170 ia64_reorg (insns)
7171      rtx insns;
7172 {
7173   /* We are freeing block_for_insn in the toplev to keep compatibility
7174      with old MDEP_REORGS that are not CFG based.  Recompute it now.  */
7175   compute_bb_for_insn ();
7176
7177   /* If optimizing, we'll have split before scheduling.  */
7178   if (optimize == 0)
7179     split_all_insns (0);
7180
7181   /* ??? update_life_info_in_dirty_blocks fails to terminate during
7182      non-optimizing bootstrap.  */
7183   update_life_info (NULL, UPDATE_LIFE_GLOBAL_RM_NOTES, PROP_DEATH_NOTES);
7184
7185   if (ia64_flag_schedule_insns2)
7186     {
7187       timevar_push (TV_SCHED2);
7188       ia64_final_schedule = 1;
7189
7190       initiate_bundle_states ();
7191       ia64_nop = make_insn_raw (gen_nop ());
7192       PREV_INSN (ia64_nop) = NEXT_INSN (ia64_nop) = NULL_RTX;
7193       recog_memoized (ia64_nop);
7194       clocks_length = get_max_uid () + 1;
7195       stops_p = (char *) xmalloc (clocks_length);
7196       memset (stops_p, 0, clocks_length);
7197       if (ia64_tune == PROCESSOR_ITANIUM)
7198         {
7199           clocks = (int *) xmalloc (clocks_length * sizeof (int));
7200           memset (clocks, 0, clocks_length * sizeof (int));
7201           add_cycles = (int *) xmalloc (clocks_length * sizeof (int));
7202           memset (add_cycles, 0, clocks_length * sizeof (int));
7203         }
7204       if (ia64_tune == PROCESSOR_ITANIUM2)
7205         {
7206           pos_1 = get_cpu_unit_code ("2_1");
7207           pos_2 = get_cpu_unit_code ("2_2");
7208           pos_3 = get_cpu_unit_code ("2_3");
7209           pos_4 = get_cpu_unit_code ("2_4");
7210           pos_5 = get_cpu_unit_code ("2_5");
7211           pos_6 = get_cpu_unit_code ("2_6");
7212           _0mii_ = get_cpu_unit_code ("2b_0mii.");
7213           _0mmi_ = get_cpu_unit_code ("2b_0mmi.");
7214           _0mfi_ = get_cpu_unit_code ("2b_0mfi.");
7215           _0mmf_ = get_cpu_unit_code ("2b_0mmf.");
7216           _0bbb_ = get_cpu_unit_code ("2b_0bbb.");
7217           _0mbb_ = get_cpu_unit_code ("2b_0mbb.");
7218           _0mib_ = get_cpu_unit_code ("2b_0mib.");
7219           _0mmb_ = get_cpu_unit_code ("2b_0mmb.");
7220           _0mfb_ = get_cpu_unit_code ("2b_0mfb.");
7221           _0mlx_ = get_cpu_unit_code ("2b_0mlx.");
7222           _1mii_ = get_cpu_unit_code ("2b_1mii.");
7223           _1mmi_ = get_cpu_unit_code ("2b_1mmi.");
7224           _1mfi_ = get_cpu_unit_code ("2b_1mfi.");
7225           _1mmf_ = get_cpu_unit_code ("2b_1mmf.");
7226           _1bbb_ = get_cpu_unit_code ("2b_1bbb.");
7227           _1mbb_ = get_cpu_unit_code ("2b_1mbb.");
7228           _1mib_ = get_cpu_unit_code ("2b_1mib.");
7229           _1mmb_ = get_cpu_unit_code ("2b_1mmb.");
7230           _1mfb_ = get_cpu_unit_code ("2b_1mfb.");
7231           _1mlx_ = get_cpu_unit_code ("2b_1mlx.");
7232         }
7233       else
7234         {
7235           pos_1 = get_cpu_unit_code ("1_1");
7236           pos_2 = get_cpu_unit_code ("1_2");
7237           pos_3 = get_cpu_unit_code ("1_3");
7238           pos_4 = get_cpu_unit_code ("1_4");
7239           pos_5 = get_cpu_unit_code ("1_5");
7240           pos_6 = get_cpu_unit_code ("1_6");
7241           _0mii_ = get_cpu_unit_code ("1b_0mii.");
7242           _0mmi_ = get_cpu_unit_code ("1b_0mmi.");
7243           _0mfi_ = get_cpu_unit_code ("1b_0mfi.");
7244           _0mmf_ = get_cpu_unit_code ("1b_0mmf.");
7245           _0bbb_ = get_cpu_unit_code ("1b_0bbb.");
7246           _0mbb_ = get_cpu_unit_code ("1b_0mbb.");
7247           _0mib_ = get_cpu_unit_code ("1b_0mib.");
7248           _0mmb_ = get_cpu_unit_code ("1b_0mmb.");
7249           _0mfb_ = get_cpu_unit_code ("1b_0mfb.");
7250           _0mlx_ = get_cpu_unit_code ("1b_0mlx.");
7251           _1mii_ = get_cpu_unit_code ("1b_1mii.");
7252           _1mmi_ = get_cpu_unit_code ("1b_1mmi.");
7253           _1mfi_ = get_cpu_unit_code ("1b_1mfi.");
7254           _1mmf_ = get_cpu_unit_code ("1b_1mmf.");
7255           _1bbb_ = get_cpu_unit_code ("1b_1bbb.");
7256           _1mbb_ = get_cpu_unit_code ("1b_1mbb.");
7257           _1mib_ = get_cpu_unit_code ("1b_1mib.");
7258           _1mmb_ = get_cpu_unit_code ("1b_1mmb.");
7259           _1mfb_ = get_cpu_unit_code ("1b_1mfb.");
7260           _1mlx_ = get_cpu_unit_code ("1b_1mlx.");
7261         }
7262       schedule_ebbs (rtl_dump_file);
7263       finish_bundle_states ();
7264       if (ia64_tune == PROCESSOR_ITANIUM)
7265         {
7266           free (add_cycles);
7267           free (clocks);
7268         }
7269       free (stops_p);
7270       emit_insn_group_barriers (rtl_dump_file, insns);
7271
7272       ia64_final_schedule = 0;
7273       timevar_pop (TV_SCHED2);
7274     }
7275   else
7276     emit_all_insn_group_barriers (rtl_dump_file, insns);
7277
7278   /* A call must not be the last instruction in a function, so that the
7279      return address is still within the function, so that unwinding works
7280      properly.  Note that IA-64 differs from dwarf2 on this point.  */
7281   if (flag_unwind_tables || (flag_exceptions && !USING_SJLJ_EXCEPTIONS))
7282     {
7283       rtx insn;
7284       int saw_stop = 0;
7285
7286       insn = get_last_insn ();
7287       if (! INSN_P (insn))
7288         insn = prev_active_insn (insn);
7289       if (GET_CODE (insn) == INSN
7290           && GET_CODE (PATTERN (insn)) == UNSPEC_VOLATILE
7291           && XINT (PATTERN (insn), 1) == UNSPECV_INSN_GROUP_BARRIER)
7292         {
7293           saw_stop = 1;
7294           insn = prev_active_insn (insn);
7295         }
7296       if (GET_CODE (insn) == CALL_INSN)
7297         {
7298           if (! saw_stop)
7299             emit_insn (gen_insn_group_barrier (GEN_INT (3)));
7300           emit_insn (gen_break_f ());
7301           emit_insn (gen_insn_group_barrier (GEN_INT (3)));
7302         }
7303     }
7304
7305   fixup_errata ();
7306   emit_predicate_relation_info ();
7307 }
7308 \f
7309 /* Return true if REGNO is used by the epilogue.  */
7310
7311 int
7312 ia64_epilogue_uses (regno)
7313      int regno;
7314 {
7315   switch (regno)
7316     {
7317     case R_GR (1):
7318       /* When a function makes a call through a function descriptor, we
7319          will write a (potentially) new value to "gp".  After returning
7320          from such a call, we need to make sure the function restores the
7321          original gp-value, even if the function itself does not use the
7322          gp anymore.  */
7323       return (TARGET_CONST_GP && !(TARGET_AUTO_PIC || TARGET_NO_PIC));
7324
7325     case IN_REG (0): case IN_REG (1): case IN_REG (2): case IN_REG (3):
7326     case IN_REG (4): case IN_REG (5): case IN_REG (6): case IN_REG (7):
7327       /* For functions defined with the syscall_linkage attribute, all
7328          input registers are marked as live at all function exits.  This
7329          prevents the register allocator from using the input registers,
7330          which in turn makes it possible to restart a system call after
7331          an interrupt without having to save/restore the input registers.
7332          This also prevents kernel data from leaking to application code.  */
7333       return lookup_attribute ("syscall_linkage",
7334            TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))) != NULL;
7335
7336     case R_BR (0):
7337       /* Conditional return patterns can't represent the use of `b0' as
7338          the return address, so we force the value live this way.  */
7339       return 1;
7340
7341     case AR_PFS_REGNUM:
7342       /* Likewise for ar.pfs, which is used by br.ret.  */
7343       return 1;
7344
7345     default:
7346       return 0;
7347     }
7348 }
7349
7350 /* Return true if REGNO is used by the frame unwinder.  */
7351
7352 int
7353 ia64_eh_uses (regno)
7354      int regno;
7355 {
7356   if (! reload_completed)
7357     return 0;
7358
7359   if (current_frame_info.reg_save_b0
7360       && regno == current_frame_info.reg_save_b0)
7361     return 1;
7362   if (current_frame_info.reg_save_pr
7363       && regno == current_frame_info.reg_save_pr)
7364     return 1;
7365   if (current_frame_info.reg_save_ar_pfs
7366       && regno == current_frame_info.reg_save_ar_pfs)
7367     return 1;
7368   if (current_frame_info.reg_save_ar_unat
7369       && regno == current_frame_info.reg_save_ar_unat)
7370     return 1;
7371   if (current_frame_info.reg_save_ar_lc
7372       && regno == current_frame_info.reg_save_ar_lc)
7373     return 1;
7374
7375   return 0;
7376 }
7377 \f
7378 /* Return true if this goes in small data/bss.  */
7379
7380 /* ??? We could also support own long data here.  Generating movl/add/ld8
7381    instead of addl,ld8/ld8.  This makes the code bigger, but should make the
7382    code faster because there is one less load.  This also includes incomplete
7383    types which can't go in sdata/sbss.  */
7384
7385 static bool
7386 ia64_in_small_data_p (exp)
7387      tree exp;
7388 {
7389   if (TARGET_NO_SDATA)
7390     return false;
7391
7392   /* We want to merge strings, so we never consider them small data.  */
7393   if (TREE_CODE (exp) == STRING_CST)
7394     return false;
7395
7396   if (TREE_CODE (exp) == VAR_DECL && DECL_SECTION_NAME (exp))
7397     {
7398       const char *section = TREE_STRING_POINTER (DECL_SECTION_NAME (exp));
7399       if (strcmp (section, ".sdata") == 0
7400           || strcmp (section, ".sbss") == 0)
7401         return true;
7402     }
7403   else
7404     {
7405       HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (exp));
7406
7407       /* If this is an incomplete type with size 0, then we can't put it
7408          in sdata because it might be too big when completed.  */
7409       if (size > 0 && size <= ia64_section_threshold)
7410         return true;
7411     }
7412
7413   return false;
7414 }
7415 \f
7416 /* Output assembly directives for prologue regions.  */
7417
7418 /* The current basic block number.  */
7419
7420 static bool last_block;
7421
7422 /* True if we need a copy_state command at the start of the next block.  */
7423
7424 static bool need_copy_state;
7425
7426 /* The function emits unwind directives for the start of an epilogue.  */
7427
7428 static void
7429 process_epilogue ()
7430 {
7431   /* If this isn't the last block of the function, then we need to label the
7432      current state, and copy it back in at the start of the next block.  */
7433
7434   if (!last_block)
7435     {
7436       fprintf (asm_out_file, "\t.label_state 1\n");
7437       need_copy_state = true;
7438     }
7439
7440   fprintf (asm_out_file, "\t.restore sp\n");
7441 }
7442
7443 /* This function processes a SET pattern looking for specific patterns
7444    which result in emitting an assembly directive required for unwinding.  */
7445
7446 static int
7447 process_set (asm_out_file, pat)
7448      FILE *asm_out_file;
7449      rtx pat;
7450 {
7451   rtx src = SET_SRC (pat);
7452   rtx dest = SET_DEST (pat);
7453   int src_regno, dest_regno;
7454
7455   /* Look for the ALLOC insn.  */
7456   if (GET_CODE (src) == UNSPEC_VOLATILE
7457       && XINT (src, 1) == UNSPECV_ALLOC
7458       && GET_CODE (dest) == REG)
7459     {
7460       dest_regno = REGNO (dest);
7461
7462       /* If this isn't the final destination for ar.pfs, the alloc
7463          shouldn't have been marked frame related.  */
7464       if (dest_regno != current_frame_info.reg_save_ar_pfs)
7465         abort ();
7466
7467       fprintf (asm_out_file, "\t.save ar.pfs, r%d\n",
7468                ia64_dbx_register_number (dest_regno));
7469       return 1;
7470     }
7471
7472   /* Look for SP = ....  */
7473   if (GET_CODE (dest) == REG && REGNO (dest) == STACK_POINTER_REGNUM)
7474     {
7475       if (GET_CODE (src) == PLUS)
7476         {
7477           rtx op0 = XEXP (src, 0);
7478           rtx op1 = XEXP (src, 1);
7479           if (op0 == dest && GET_CODE (op1) == CONST_INT)
7480             {
7481               if (INTVAL (op1) < 0)
7482                 {
7483                   fputs ("\t.fframe ", asm_out_file);
7484                   fprintf (asm_out_file, HOST_WIDE_INT_PRINT_DEC,
7485                            -INTVAL (op1));
7486                   fputc ('\n', asm_out_file);
7487                 }
7488               else
7489                 process_epilogue ();
7490             }
7491           else
7492             abort ();
7493         }
7494       else if (GET_CODE (src) == REG
7495                && REGNO (src) == HARD_FRAME_POINTER_REGNUM)
7496         process_epilogue ();
7497       else
7498         abort ();
7499
7500       return 1;
7501     }
7502
7503   /* Register move we need to look at.  */
7504   if (GET_CODE (dest) == REG && GET_CODE (src) == REG)
7505     {
7506       src_regno = REGNO (src);
7507       dest_regno = REGNO (dest);
7508
7509       switch (src_regno)
7510         {
7511         case BR_REG (0):
7512           /* Saving return address pointer.  */
7513           if (dest_regno != current_frame_info.reg_save_b0)
7514             abort ();
7515           fprintf (asm_out_file, "\t.save rp, r%d\n",
7516                    ia64_dbx_register_number (dest_regno));
7517           return 1;
7518
7519         case PR_REG (0):
7520           if (dest_regno != current_frame_info.reg_save_pr)
7521             abort ();
7522           fprintf (asm_out_file, "\t.save pr, r%d\n",
7523                    ia64_dbx_register_number (dest_regno));
7524           return 1;
7525
7526         case AR_UNAT_REGNUM:
7527           if (dest_regno != current_frame_info.reg_save_ar_unat)
7528             abort ();
7529           fprintf (asm_out_file, "\t.save ar.unat, r%d\n",
7530                    ia64_dbx_register_number (dest_regno));
7531           return 1;
7532
7533         case AR_LC_REGNUM:
7534           if (dest_regno != current_frame_info.reg_save_ar_lc)
7535             abort ();
7536           fprintf (asm_out_file, "\t.save ar.lc, r%d\n",
7537                    ia64_dbx_register_number (dest_regno));
7538           return 1;
7539
7540         case STACK_POINTER_REGNUM:
7541           if (dest_regno != HARD_FRAME_POINTER_REGNUM
7542               || ! frame_pointer_needed)
7543             abort ();
7544           fprintf (asm_out_file, "\t.vframe r%d\n",
7545                    ia64_dbx_register_number (dest_regno));
7546           return 1;
7547
7548         default:
7549           /* Everything else should indicate being stored to memory.  */
7550           abort ();
7551         }
7552     }
7553
7554   /* Memory store we need to look at.  */
7555   if (GET_CODE (dest) == MEM && GET_CODE (src) == REG)
7556     {
7557       long off;
7558       rtx base;
7559       const char *saveop;
7560
7561       if (GET_CODE (XEXP (dest, 0)) == REG)
7562         {
7563           base = XEXP (dest, 0);
7564           off = 0;
7565         }
7566       else if (GET_CODE (XEXP (dest, 0)) == PLUS
7567                && GET_CODE (XEXP (XEXP (dest, 0), 1)) == CONST_INT)
7568         {
7569           base = XEXP (XEXP (dest, 0), 0);
7570           off = INTVAL (XEXP (XEXP (dest, 0), 1));
7571         }
7572       else
7573         abort ();
7574
7575       if (base == hard_frame_pointer_rtx)
7576         {
7577           saveop = ".savepsp";
7578           off = - off;
7579         }
7580       else if (base == stack_pointer_rtx)
7581         saveop = ".savesp";
7582       else
7583         abort ();
7584
7585       src_regno = REGNO (src);
7586       switch (src_regno)
7587         {
7588         case BR_REG (0):
7589           if (current_frame_info.reg_save_b0 != 0)
7590             abort ();
7591           fprintf (asm_out_file, "\t%s rp, %ld\n", saveop, off);
7592           return 1;
7593
7594         case PR_REG (0):
7595           if (current_frame_info.reg_save_pr != 0)
7596             abort ();
7597           fprintf (asm_out_file, "\t%s pr, %ld\n", saveop, off);
7598           return 1;
7599
7600         case AR_LC_REGNUM:
7601           if (current_frame_info.reg_save_ar_lc != 0)
7602             abort ();
7603           fprintf (asm_out_file, "\t%s ar.lc, %ld\n", saveop, off);
7604           return 1;
7605
7606         case AR_PFS_REGNUM:
7607           if (current_frame_info.reg_save_ar_pfs != 0)
7608             abort ();
7609           fprintf (asm_out_file, "\t%s ar.pfs, %ld\n", saveop, off);
7610           return 1;
7611
7612         case AR_UNAT_REGNUM:
7613           if (current_frame_info.reg_save_ar_unat != 0)
7614             abort ();
7615           fprintf (asm_out_file, "\t%s ar.unat, %ld\n", saveop, off);
7616           return 1;
7617
7618         case GR_REG (4):
7619         case GR_REG (5):
7620         case GR_REG (6):
7621         case GR_REG (7):
7622           fprintf (asm_out_file, "\t.save.g 0x%x\n",
7623                    1 << (src_regno - GR_REG (4)));
7624           return 1;
7625
7626         case BR_REG (1):
7627         case BR_REG (2):
7628         case BR_REG (3):
7629         case BR_REG (4):
7630         case BR_REG (5):
7631           fprintf (asm_out_file, "\t.save.b 0x%x\n",
7632                    1 << (src_regno - BR_REG (1)));
7633           return 1;
7634
7635         case FR_REG (2):
7636         case FR_REG (3):
7637         case FR_REG (4):
7638         case FR_REG (5):
7639           fprintf (asm_out_file, "\t.save.f 0x%x\n",
7640                    1 << (src_regno - FR_REG (2)));
7641           return 1;
7642
7643         case FR_REG (16): case FR_REG (17): case FR_REG (18): case FR_REG (19):
7644         case FR_REG (20): case FR_REG (21): case FR_REG (22): case FR_REG (23):
7645         case FR_REG (24): case FR_REG (25): case FR_REG (26): case FR_REG (27):
7646         case FR_REG (28): case FR_REG (29): case FR_REG (30): case FR_REG (31):
7647           fprintf (asm_out_file, "\t.save.gf 0x0, 0x%x\n",
7648                    1 << (src_regno - FR_REG (12)));
7649           return 1;
7650
7651         default:
7652           return 0;
7653         }
7654     }
7655
7656   return 0;
7657 }
7658
7659
7660 /* This function looks at a single insn and emits any directives
7661    required to unwind this insn.  */
7662 void
7663 process_for_unwind_directive (asm_out_file, insn)
7664      FILE *asm_out_file;
7665      rtx insn;
7666 {
7667   if (flag_unwind_tables
7668       || (flag_exceptions && !USING_SJLJ_EXCEPTIONS))
7669     {
7670       rtx pat;
7671
7672       if (GET_CODE (insn) == NOTE
7673           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_BASIC_BLOCK)
7674         {
7675           last_block = NOTE_BASIC_BLOCK (insn)->next_bb == EXIT_BLOCK_PTR;
7676
7677           /* Restore unwind state from immediately before the epilogue.  */
7678           if (need_copy_state)
7679             {
7680               fprintf (asm_out_file, "\t.body\n");
7681               fprintf (asm_out_file, "\t.copy_state 1\n");
7682               need_copy_state = false;
7683             }
7684         }
7685
7686       if (GET_CODE (insn) == NOTE || ! RTX_FRAME_RELATED_P (insn))
7687         return;
7688
7689       pat = find_reg_note (insn, REG_FRAME_RELATED_EXPR, NULL_RTX);
7690       if (pat)
7691         pat = XEXP (pat, 0);
7692       else
7693         pat = PATTERN (insn);
7694
7695       switch (GET_CODE (pat))
7696         {
7697         case SET:
7698           process_set (asm_out_file, pat);
7699           break;
7700
7701         case PARALLEL:
7702           {
7703             int par_index;
7704             int limit = XVECLEN (pat, 0);
7705             for (par_index = 0; par_index < limit; par_index++)
7706               {
7707                 rtx x = XVECEXP (pat, 0, par_index);
7708                 if (GET_CODE (x) == SET)
7709                   process_set (asm_out_file, x);
7710               }
7711             break;
7712           }
7713
7714         default:
7715           abort ();
7716         }
7717     }
7718 }
7719
7720 \f
7721 void
7722 ia64_init_builtins ()
7723 {
7724   tree psi_type_node = build_pointer_type (integer_type_node);
7725   tree pdi_type_node = build_pointer_type (long_integer_type_node);
7726
7727   /* __sync_val_compare_and_swap_si, __sync_bool_compare_and_swap_si */
7728   tree si_ftype_psi_si_si
7729     = build_function_type_list (integer_type_node,
7730                                 psi_type_node, integer_type_node,
7731                                 integer_type_node, NULL_TREE);
7732
7733   /* __sync_val_compare_and_swap_di */
7734   tree di_ftype_pdi_di_di
7735     = build_function_type_list (long_integer_type_node,
7736                                 pdi_type_node, long_integer_type_node,
7737                                 long_integer_type_node, NULL_TREE);
7738   /* __sync_bool_compare_and_swap_di */
7739   tree si_ftype_pdi_di_di
7740     = build_function_type_list (integer_type_node,
7741                                 pdi_type_node, long_integer_type_node,
7742                                 long_integer_type_node, NULL_TREE);
7743   /* __sync_synchronize */
7744   tree void_ftype_void
7745     = build_function_type (void_type_node, void_list_node);
7746
7747   /* __sync_lock_test_and_set_si */
7748   tree si_ftype_psi_si
7749     = build_function_type_list (integer_type_node,
7750                                 psi_type_node, integer_type_node, NULL_TREE);
7751
7752   /* __sync_lock_test_and_set_di */
7753   tree di_ftype_pdi_di
7754     = build_function_type_list (long_integer_type_node,
7755                                 pdi_type_node, long_integer_type_node,
7756                                 NULL_TREE);
7757
7758   /* __sync_lock_release_si */
7759   tree void_ftype_psi
7760     = build_function_type_list (void_type_node, psi_type_node, NULL_TREE);
7761
7762   /* __sync_lock_release_di */
7763   tree void_ftype_pdi
7764     = build_function_type_list (void_type_node, pdi_type_node, NULL_TREE);
7765
7766 #define def_builtin(name, type, code) \
7767   builtin_function ((name), (type), (code), BUILT_IN_MD, NULL, NULL_TREE)
7768
7769   def_builtin ("__sync_val_compare_and_swap_si", si_ftype_psi_si_si,
7770                IA64_BUILTIN_VAL_COMPARE_AND_SWAP_SI);
7771   def_builtin ("__sync_val_compare_and_swap_di", di_ftype_pdi_di_di,
7772                IA64_BUILTIN_VAL_COMPARE_AND_SWAP_DI);
7773   def_builtin ("__sync_bool_compare_and_swap_si", si_ftype_psi_si_si,
7774                IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_SI);
7775   def_builtin ("__sync_bool_compare_and_swap_di", si_ftype_pdi_di_di,
7776                IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_DI);
7777
7778   def_builtin ("__sync_synchronize", void_ftype_void,
7779                IA64_BUILTIN_SYNCHRONIZE);
7780
7781   def_builtin ("__sync_lock_test_and_set_si", si_ftype_psi_si,
7782                IA64_BUILTIN_LOCK_TEST_AND_SET_SI);
7783   def_builtin ("__sync_lock_test_and_set_di", di_ftype_pdi_di,
7784                IA64_BUILTIN_LOCK_TEST_AND_SET_DI);
7785   def_builtin ("__sync_lock_release_si", void_ftype_psi,
7786                IA64_BUILTIN_LOCK_RELEASE_SI);
7787   def_builtin ("__sync_lock_release_di", void_ftype_pdi,
7788                IA64_BUILTIN_LOCK_RELEASE_DI);
7789
7790   def_builtin ("__builtin_ia64_bsp",
7791                build_function_type (ptr_type_node, void_list_node),
7792                IA64_BUILTIN_BSP);
7793
7794   def_builtin ("__builtin_ia64_flushrs", 
7795                build_function_type (void_type_node, void_list_node), 
7796                IA64_BUILTIN_FLUSHRS);
7797
7798   def_builtin ("__sync_fetch_and_add_si", si_ftype_psi_si,
7799                IA64_BUILTIN_FETCH_AND_ADD_SI);
7800   def_builtin ("__sync_fetch_and_sub_si", si_ftype_psi_si,
7801                IA64_BUILTIN_FETCH_AND_SUB_SI);
7802   def_builtin ("__sync_fetch_and_or_si", si_ftype_psi_si,
7803                IA64_BUILTIN_FETCH_AND_OR_SI);
7804   def_builtin ("__sync_fetch_and_and_si", si_ftype_psi_si,
7805                IA64_BUILTIN_FETCH_AND_AND_SI);
7806   def_builtin ("__sync_fetch_and_xor_si", si_ftype_psi_si,
7807                IA64_BUILTIN_FETCH_AND_XOR_SI);
7808   def_builtin ("__sync_fetch_and_nand_si", si_ftype_psi_si,
7809                IA64_BUILTIN_FETCH_AND_NAND_SI);
7810
7811   def_builtin ("__sync_add_and_fetch_si", si_ftype_psi_si,
7812                IA64_BUILTIN_ADD_AND_FETCH_SI);
7813   def_builtin ("__sync_sub_and_fetch_si", si_ftype_psi_si,
7814                IA64_BUILTIN_SUB_AND_FETCH_SI);
7815   def_builtin ("__sync_or_and_fetch_si", si_ftype_psi_si,
7816                IA64_BUILTIN_OR_AND_FETCH_SI);
7817   def_builtin ("__sync_and_and_fetch_si", si_ftype_psi_si,
7818                IA64_BUILTIN_AND_AND_FETCH_SI);
7819   def_builtin ("__sync_xor_and_fetch_si", si_ftype_psi_si,
7820                IA64_BUILTIN_XOR_AND_FETCH_SI);
7821   def_builtin ("__sync_nand_and_fetch_si", si_ftype_psi_si,
7822                IA64_BUILTIN_NAND_AND_FETCH_SI);
7823
7824   def_builtin ("__sync_fetch_and_add_di", di_ftype_pdi_di,
7825                IA64_BUILTIN_FETCH_AND_ADD_DI);
7826   def_builtin ("__sync_fetch_and_sub_di", di_ftype_pdi_di,
7827                IA64_BUILTIN_FETCH_AND_SUB_DI);
7828   def_builtin ("__sync_fetch_and_or_di", di_ftype_pdi_di,
7829                IA64_BUILTIN_FETCH_AND_OR_DI);
7830   def_builtin ("__sync_fetch_and_and_di", di_ftype_pdi_di,
7831                IA64_BUILTIN_FETCH_AND_AND_DI);
7832   def_builtin ("__sync_fetch_and_xor_di", di_ftype_pdi_di,
7833                IA64_BUILTIN_FETCH_AND_XOR_DI);
7834   def_builtin ("__sync_fetch_and_nand_di", di_ftype_pdi_di,
7835                IA64_BUILTIN_FETCH_AND_NAND_DI);
7836
7837   def_builtin ("__sync_add_and_fetch_di", di_ftype_pdi_di,
7838                IA64_BUILTIN_ADD_AND_FETCH_DI);
7839   def_builtin ("__sync_sub_and_fetch_di", di_ftype_pdi_di,
7840                IA64_BUILTIN_SUB_AND_FETCH_DI);
7841   def_builtin ("__sync_or_and_fetch_di", di_ftype_pdi_di,
7842                IA64_BUILTIN_OR_AND_FETCH_DI);
7843   def_builtin ("__sync_and_and_fetch_di", di_ftype_pdi_di,
7844                IA64_BUILTIN_AND_AND_FETCH_DI);
7845   def_builtin ("__sync_xor_and_fetch_di", di_ftype_pdi_di,
7846                IA64_BUILTIN_XOR_AND_FETCH_DI);
7847   def_builtin ("__sync_nand_and_fetch_di", di_ftype_pdi_di,
7848                IA64_BUILTIN_NAND_AND_FETCH_DI);
7849
7850 #undef def_builtin
7851 }
7852
7853 /* Expand fetch_and_op intrinsics.  The basic code sequence is:
7854
7855      mf
7856      tmp = [ptr];
7857      do {
7858        ret = tmp;
7859        ar.ccv = tmp;
7860        tmp <op>= value;
7861        cmpxchgsz.acq tmp = [ptr], tmp
7862      } while (tmp != ret)
7863 */
7864
7865 static rtx
7866 ia64_expand_fetch_and_op (binoptab, mode, arglist, target)
7867      optab binoptab;
7868      enum machine_mode mode;
7869      tree arglist;
7870      rtx target;
7871 {
7872   rtx ret, label, tmp, ccv, insn, mem, value;
7873   tree arg0, arg1;
7874
7875   arg0 = TREE_VALUE (arglist);
7876   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
7877   mem = expand_expr (arg0, NULL_RTX, Pmode, 0);
7878 #ifdef POINTERS_EXTEND_UNSIGNED
7879   if (GET_MODE(mem) != Pmode)
7880     mem = convert_memory_address (Pmode, mem);
7881 #endif
7882   value = expand_expr (arg1, NULL_RTX, mode, 0);
7883
7884   mem = gen_rtx_MEM (mode, force_reg (Pmode, mem));
7885   MEM_VOLATILE_P (mem) = 1;
7886
7887   if (target && register_operand (target, mode))
7888     ret = target;
7889   else
7890     ret = gen_reg_rtx (mode);
7891
7892   emit_insn (gen_mf ());
7893
7894   /* Special case for fetchadd instructions.  */
7895   if (binoptab == add_optab && fetchadd_operand (value, VOIDmode))
7896     {
7897       if (mode == SImode)
7898         insn = gen_fetchadd_acq_si (ret, mem, value);
7899       else
7900         insn = gen_fetchadd_acq_di (ret, mem, value);
7901       emit_insn (insn);
7902       return ret;
7903     }
7904
7905   tmp = gen_reg_rtx (mode);
7906   ccv = gen_rtx_REG (mode, AR_CCV_REGNUM);
7907   emit_move_insn (tmp, mem);
7908
7909   label = gen_label_rtx ();
7910   emit_label (label);
7911   emit_move_insn (ret, tmp);
7912   emit_move_insn (ccv, tmp);
7913
7914   /* Perform the specific operation.  Special case NAND by noticing
7915      one_cmpl_optab instead.  */
7916   if (binoptab == one_cmpl_optab)
7917     {
7918       tmp = expand_unop (mode, binoptab, tmp, NULL, OPTAB_WIDEN);
7919       binoptab = and_optab;
7920     }
7921   tmp = expand_binop (mode, binoptab, tmp, value, tmp, 1, OPTAB_WIDEN);
7922
7923   if (mode == SImode)
7924     insn = gen_cmpxchg_acq_si (tmp, mem, tmp, ccv);
7925   else
7926     insn = gen_cmpxchg_acq_di (tmp, mem, tmp, ccv);
7927   emit_insn (insn);
7928
7929   emit_cmp_and_jump_insns (tmp, ret, NE, 0, mode, 1, label);
7930
7931   return ret;
7932 }
7933
7934 /* Expand op_and_fetch intrinsics.  The basic code sequence is:
7935
7936      mf
7937      tmp = [ptr];
7938      do {
7939        old = tmp;
7940        ar.ccv = tmp;
7941        ret = tmp <op> value;
7942        cmpxchgsz.acq tmp = [ptr], ret
7943      } while (tmp != old)
7944 */
7945
7946 static rtx
7947 ia64_expand_op_and_fetch (binoptab, mode, arglist, target)
7948      optab binoptab;
7949      enum machine_mode mode;
7950      tree arglist;
7951      rtx target;
7952 {
7953   rtx old, label, tmp, ret, ccv, insn, mem, value;
7954   tree arg0, arg1;
7955
7956   arg0 = TREE_VALUE (arglist);
7957   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
7958   mem = expand_expr (arg0, NULL_RTX, Pmode, 0);
7959 #ifdef POINTERS_EXTEND_UNSIGNED
7960   if (GET_MODE(mem) != Pmode)
7961     mem = convert_memory_address (Pmode, mem);
7962 #endif
7963
7964   value = expand_expr (arg1, NULL_RTX, mode, 0);
7965
7966   mem = gen_rtx_MEM (mode, force_reg (Pmode, mem));
7967   MEM_VOLATILE_P (mem) = 1;
7968
7969   if (target && ! register_operand (target, mode))
7970     target = NULL_RTX;
7971
7972   emit_insn (gen_mf ());
7973   tmp = gen_reg_rtx (mode);
7974   old = gen_reg_rtx (mode);
7975   ccv = gen_rtx_REG (mode, AR_CCV_REGNUM);
7976
7977   emit_move_insn (tmp, mem);
7978
7979   label = gen_label_rtx ();
7980   emit_label (label);
7981   emit_move_insn (old, tmp);
7982   emit_move_insn (ccv, tmp);
7983
7984   /* Perform the specific operation.  Special case NAND by noticing
7985      one_cmpl_optab instead.  */
7986   if (binoptab == one_cmpl_optab)
7987     {
7988       tmp = expand_unop (mode, binoptab, tmp, NULL, OPTAB_WIDEN);
7989       binoptab = and_optab;
7990     }
7991   ret = expand_binop (mode, binoptab, tmp, value, target, 1, OPTAB_WIDEN);
7992
7993   if (mode == SImode)
7994     insn = gen_cmpxchg_acq_si (tmp, mem, ret, ccv);
7995   else
7996     insn = gen_cmpxchg_acq_di (tmp, mem, ret, ccv);
7997   emit_insn (insn);
7998
7999   emit_cmp_and_jump_insns (tmp, old, NE, 0, mode, 1, label);
8000
8001   return ret;
8002 }
8003
8004 /* Expand val_ and bool_compare_and_swap.  For val_ we want:
8005
8006      ar.ccv = oldval
8007      mf
8008      cmpxchgsz.acq ret = [ptr], newval, ar.ccv
8009      return ret
8010
8011    For bool_ it's the same except return ret == oldval.
8012 */
8013
8014 static rtx
8015 ia64_expand_compare_and_swap (mode, boolp, arglist, target)
8016      enum machine_mode mode;
8017      int boolp;
8018      tree arglist;
8019      rtx target;
8020 {
8021   tree arg0, arg1, arg2;
8022   rtx mem, old, new, ccv, tmp, insn;
8023
8024   arg0 = TREE_VALUE (arglist);
8025   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
8026   arg2 = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
8027   mem = expand_expr (arg0, NULL_RTX, ptr_mode, 0);
8028   old = expand_expr (arg1, NULL_RTX, mode, 0);
8029   new = expand_expr (arg2, NULL_RTX, mode, 0);
8030
8031   mem = gen_rtx_MEM (mode, force_reg (ptr_mode, mem));
8032   MEM_VOLATILE_P (mem) = 1;
8033
8034   if (! register_operand (old, mode))
8035     old = copy_to_mode_reg (mode, old);
8036   if (! register_operand (new, mode))
8037     new = copy_to_mode_reg (mode, new);
8038
8039   if (! boolp && target && register_operand (target, mode))
8040     tmp = target;
8041   else
8042     tmp = gen_reg_rtx (mode);
8043
8044   ccv = gen_rtx_REG (DImode, AR_CCV_REGNUM);
8045   if (mode == DImode)
8046     emit_move_insn (ccv, old);
8047   else
8048     {
8049       rtx ccvtmp = gen_reg_rtx (DImode);
8050       emit_insn (gen_zero_extendsidi2 (ccvtmp, old));
8051       emit_move_insn (ccv, ccvtmp);
8052     }
8053   emit_insn (gen_mf ());
8054   if (mode == SImode)
8055     insn = gen_cmpxchg_acq_si (tmp, mem, new, ccv);
8056   else
8057     insn = gen_cmpxchg_acq_di (tmp, mem, new, ccv);
8058   emit_insn (insn);
8059
8060   if (boolp)
8061     {
8062       if (! target)
8063         target = gen_reg_rtx (mode);
8064       return emit_store_flag_force (target, EQ, tmp, old, mode, 1, 1);
8065     }
8066   else
8067     return tmp;
8068 }
8069
8070 /* Expand lock_test_and_set.  I.e. `xchgsz ret = [ptr], new'.  */
8071
8072 static rtx
8073 ia64_expand_lock_test_and_set (mode, arglist, target)
8074      enum machine_mode mode;
8075      tree arglist;
8076      rtx target;
8077 {
8078   tree arg0, arg1;
8079   rtx mem, new, ret, insn;
8080
8081   arg0 = TREE_VALUE (arglist);
8082   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
8083   mem = expand_expr (arg0, NULL_RTX, ptr_mode, 0);
8084   new = expand_expr (arg1, NULL_RTX, mode, 0);
8085
8086   mem = gen_rtx_MEM (mode, force_reg (ptr_mode, mem));
8087   MEM_VOLATILE_P (mem) = 1;
8088   if (! register_operand (new, mode))
8089     new = copy_to_mode_reg (mode, new);
8090
8091   if (target && register_operand (target, mode))
8092     ret = target;
8093   else
8094     ret = gen_reg_rtx (mode);
8095
8096   if (mode == SImode)
8097     insn = gen_xchgsi (ret, mem, new);
8098   else
8099     insn = gen_xchgdi (ret, mem, new);
8100   emit_insn (insn);
8101
8102   return ret;
8103 }
8104
8105 /* Expand lock_release.  I.e. `stsz.rel [ptr] = r0'.  */
8106
8107 static rtx
8108 ia64_expand_lock_release (mode, arglist, target)
8109      enum machine_mode mode;
8110      tree arglist;
8111      rtx target ATTRIBUTE_UNUSED;
8112 {
8113   tree arg0;
8114   rtx mem;
8115
8116   arg0 = TREE_VALUE (arglist);
8117   mem = expand_expr (arg0, NULL_RTX, ptr_mode, 0);
8118
8119   mem = gen_rtx_MEM (mode, force_reg (ptr_mode, mem));
8120   MEM_VOLATILE_P (mem) = 1;
8121
8122   emit_move_insn (mem, const0_rtx);
8123
8124   return const0_rtx;
8125 }
8126
8127 rtx
8128 ia64_expand_builtin (exp, target, subtarget, mode, ignore)
8129      tree exp;
8130      rtx target;
8131      rtx subtarget ATTRIBUTE_UNUSED;
8132      enum machine_mode mode ATTRIBUTE_UNUSED;
8133      int ignore ATTRIBUTE_UNUSED;
8134 {
8135   tree fndecl = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
8136   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
8137   tree arglist = TREE_OPERAND (exp, 1);
8138
8139   switch (fcode)
8140     {
8141     case IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_SI:
8142     case IA64_BUILTIN_VAL_COMPARE_AND_SWAP_SI:
8143     case IA64_BUILTIN_LOCK_TEST_AND_SET_SI:
8144     case IA64_BUILTIN_LOCK_RELEASE_SI:
8145     case IA64_BUILTIN_FETCH_AND_ADD_SI:
8146     case IA64_BUILTIN_FETCH_AND_SUB_SI:
8147     case IA64_BUILTIN_FETCH_AND_OR_SI:
8148     case IA64_BUILTIN_FETCH_AND_AND_SI:
8149     case IA64_BUILTIN_FETCH_AND_XOR_SI:
8150     case IA64_BUILTIN_FETCH_AND_NAND_SI:
8151     case IA64_BUILTIN_ADD_AND_FETCH_SI:
8152     case IA64_BUILTIN_SUB_AND_FETCH_SI:
8153     case IA64_BUILTIN_OR_AND_FETCH_SI:
8154     case IA64_BUILTIN_AND_AND_FETCH_SI:
8155     case IA64_BUILTIN_XOR_AND_FETCH_SI:
8156     case IA64_BUILTIN_NAND_AND_FETCH_SI:
8157       mode = SImode;
8158       break;
8159
8160     case IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_DI:
8161     case IA64_BUILTIN_VAL_COMPARE_AND_SWAP_DI:
8162     case IA64_BUILTIN_LOCK_TEST_AND_SET_DI:
8163     case IA64_BUILTIN_LOCK_RELEASE_DI:
8164     case IA64_BUILTIN_FETCH_AND_ADD_DI:
8165     case IA64_BUILTIN_FETCH_AND_SUB_DI:
8166     case IA64_BUILTIN_FETCH_AND_OR_DI:
8167     case IA64_BUILTIN_FETCH_AND_AND_DI:
8168     case IA64_BUILTIN_FETCH_AND_XOR_DI:
8169     case IA64_BUILTIN_FETCH_AND_NAND_DI:
8170     case IA64_BUILTIN_ADD_AND_FETCH_DI:
8171     case IA64_BUILTIN_SUB_AND_FETCH_DI:
8172     case IA64_BUILTIN_OR_AND_FETCH_DI:
8173     case IA64_BUILTIN_AND_AND_FETCH_DI:
8174     case IA64_BUILTIN_XOR_AND_FETCH_DI:
8175     case IA64_BUILTIN_NAND_AND_FETCH_DI:
8176       mode = DImode;
8177       break;
8178
8179     default:
8180       break;
8181     }
8182
8183   switch (fcode)
8184     {
8185     case IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_SI:
8186     case IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_DI:
8187       return ia64_expand_compare_and_swap (mode, 1, arglist, target);
8188
8189     case IA64_BUILTIN_VAL_COMPARE_AND_SWAP_SI:
8190     case IA64_BUILTIN_VAL_COMPARE_AND_SWAP_DI:
8191       return ia64_expand_compare_and_swap (mode, 0, arglist, target);
8192
8193     case IA64_BUILTIN_SYNCHRONIZE:
8194       emit_insn (gen_mf ());
8195       return const0_rtx;
8196
8197     case IA64_BUILTIN_LOCK_TEST_AND_SET_SI:
8198     case IA64_BUILTIN_LOCK_TEST_AND_SET_DI:
8199       return ia64_expand_lock_test_and_set (mode, arglist, target);
8200
8201     case IA64_BUILTIN_LOCK_RELEASE_SI:
8202     case IA64_BUILTIN_LOCK_RELEASE_DI:
8203       return ia64_expand_lock_release (mode, arglist, target);
8204
8205     case IA64_BUILTIN_BSP:
8206       if (! target || ! register_operand (target, DImode))
8207         target = gen_reg_rtx (DImode);
8208       emit_insn (gen_bsp_value (target));
8209       return target;
8210
8211     case IA64_BUILTIN_FLUSHRS:
8212       emit_insn (gen_flushrs ());
8213       return const0_rtx;
8214
8215     case IA64_BUILTIN_FETCH_AND_ADD_SI:
8216     case IA64_BUILTIN_FETCH_AND_ADD_DI:
8217       return ia64_expand_fetch_and_op (add_optab, mode, arglist, target);
8218
8219     case IA64_BUILTIN_FETCH_AND_SUB_SI:
8220     case IA64_BUILTIN_FETCH_AND_SUB_DI:
8221       return ia64_expand_fetch_and_op (sub_optab, mode, arglist, target);
8222
8223     case IA64_BUILTIN_FETCH_AND_OR_SI:
8224     case IA64_BUILTIN_FETCH_AND_OR_DI:
8225       return ia64_expand_fetch_and_op (ior_optab, mode, arglist, target);
8226
8227     case IA64_BUILTIN_FETCH_AND_AND_SI:
8228     case IA64_BUILTIN_FETCH_AND_AND_DI:
8229       return ia64_expand_fetch_and_op (and_optab, mode, arglist, target);
8230
8231     case IA64_BUILTIN_FETCH_AND_XOR_SI:
8232     case IA64_BUILTIN_FETCH_AND_XOR_DI:
8233       return ia64_expand_fetch_and_op (xor_optab, mode, arglist, target);
8234
8235     case IA64_BUILTIN_FETCH_AND_NAND_SI:
8236     case IA64_BUILTIN_FETCH_AND_NAND_DI:
8237       return ia64_expand_fetch_and_op (one_cmpl_optab, mode, arglist, target);
8238
8239     case IA64_BUILTIN_ADD_AND_FETCH_SI:
8240     case IA64_BUILTIN_ADD_AND_FETCH_DI:
8241       return ia64_expand_op_and_fetch (add_optab, mode, arglist, target);
8242
8243     case IA64_BUILTIN_SUB_AND_FETCH_SI:
8244     case IA64_BUILTIN_SUB_AND_FETCH_DI:
8245       return ia64_expand_op_and_fetch (sub_optab, mode, arglist, target);
8246
8247     case IA64_BUILTIN_OR_AND_FETCH_SI:
8248     case IA64_BUILTIN_OR_AND_FETCH_DI:
8249       return ia64_expand_op_and_fetch (ior_optab, mode, arglist, target);
8250
8251     case IA64_BUILTIN_AND_AND_FETCH_SI:
8252     case IA64_BUILTIN_AND_AND_FETCH_DI:
8253       return ia64_expand_op_and_fetch (and_optab, mode, arglist, target);
8254
8255     case IA64_BUILTIN_XOR_AND_FETCH_SI:
8256     case IA64_BUILTIN_XOR_AND_FETCH_DI:
8257       return ia64_expand_op_and_fetch (xor_optab, mode, arglist, target);
8258
8259     case IA64_BUILTIN_NAND_AND_FETCH_SI:
8260     case IA64_BUILTIN_NAND_AND_FETCH_DI:
8261       return ia64_expand_op_and_fetch (one_cmpl_optab, mode, arglist, target);
8262
8263     default:
8264       break;
8265     }
8266
8267   return NULL_RTX;
8268 }
8269
8270 /* For the HP-UX IA64 aggregate parameters are passed stored in the
8271    most significant bits of the stack slot.  */
8272
8273 enum direction
8274 ia64_hpux_function_arg_padding (mode, type)
8275      enum machine_mode mode;
8276      tree type;
8277 {
8278    /* Exception to normal case for structures/unions/etc.  */
8279
8280    if (type && AGGREGATE_TYPE_P (type)
8281        && int_size_in_bytes (type) < UNITS_PER_WORD)
8282      return upward;
8283
8284    /* This is the standard FUNCTION_ARG_PADDING with !BYTES_BIG_ENDIAN
8285       hardwired to be true.  */
8286
8287    return((mode == BLKmode
8288        ? (type && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
8289           && int_size_in_bytes (type) < (PARM_BOUNDARY / BITS_PER_UNIT))
8290        : GET_MODE_BITSIZE (mode) < PARM_BOUNDARY)
8291       ? downward : upward);
8292 }
8293
8294 /* Linked list of all external functions that are to be emitted by GCC.
8295    We output the name if and only if TREE_SYMBOL_REFERENCED is set in
8296    order to avoid putting out names that are never really used.  */
8297
8298 struct extern_func_list
8299 {
8300   struct extern_func_list *next; /* next external */
8301   char *name;                    /* name of the external */
8302 } *extern_func_head = 0;
8303
8304 static void
8305 ia64_hpux_add_extern_decl (name)
8306         const char *name;
8307 {
8308   struct extern_func_list *p;
8309
8310   p = (struct extern_func_list *) xmalloc (sizeof (struct extern_func_list));
8311   p->name = xmalloc (strlen (name) + 1);
8312   strcpy(p->name, name);
8313   p->next = extern_func_head;
8314   extern_func_head = p;
8315 }
8316
8317 /* Print out the list of used global functions.  */
8318
8319 void
8320 ia64_hpux_asm_file_end (file)
8321         FILE *file;
8322 {
8323   while (extern_func_head)
8324     {
8325       const char *real_name;
8326       tree decl;
8327
8328       real_name = (* targetm.strip_name_encoding) (extern_func_head->name);
8329       decl = maybe_get_identifier (real_name);
8330
8331       if (!decl
8332           || (! TREE_ASM_WRITTEN (decl) && TREE_SYMBOL_REFERENCED (decl)))
8333         {
8334           if (decl)
8335             TREE_ASM_WRITTEN (decl) = 1;
8336           (*targetm.asm_out.globalize_label) (file, extern_func_head->name);
8337           fprintf (file, "%s", TYPE_ASM_OP);
8338           assemble_name (file, extern_func_head->name);
8339           putc (',', file);
8340           fprintf (file, TYPE_OPERAND_FMT, "function");
8341           putc ('\n', file);
8342         }
8343       extern_func_head = extern_func_head->next;
8344     }
8345 }
8346
8347 \f
8348 /* Switch to the section to which we should output X.  The only thing
8349    special we do here is to honor small data.  */
8350
8351 static void
8352 ia64_select_rtx_section (mode, x, align)
8353      enum machine_mode mode;
8354      rtx x;
8355      unsigned HOST_WIDE_INT align;
8356 {
8357   if (GET_MODE_SIZE (mode) > 0
8358       && GET_MODE_SIZE (mode) <= ia64_section_threshold)
8359     sdata_section ();
8360   else
8361     default_elf_select_rtx_section (mode, x, align);
8362 }
8363
8364 /* It is illegal to have relocations in shared segments on AIX and HPUX.
8365    Pretend flag_pic is always set.  */
8366
8367 static void
8368 ia64_rwreloc_select_section (exp, reloc, align)
8369      tree exp;
8370      int reloc;
8371      unsigned HOST_WIDE_INT align;
8372 {
8373   default_elf_select_section_1 (exp, reloc, align, true);
8374 }
8375
8376 static void
8377 ia64_rwreloc_unique_section (decl, reloc)
8378      tree decl;
8379      int reloc;
8380 {
8381   default_unique_section_1 (decl, reloc, true);
8382 }
8383
8384 static void
8385 ia64_rwreloc_select_rtx_section (mode, x, align)
8386      enum machine_mode mode;
8387      rtx x;
8388      unsigned HOST_WIDE_INT align;
8389 {
8390   int save_pic = flag_pic;
8391   flag_pic = 1;
8392   ia64_select_rtx_section (mode, x, align);
8393   flag_pic = save_pic;
8394 }
8395
8396 static unsigned int
8397 ia64_rwreloc_section_type_flags (decl, name, reloc)
8398      tree decl;
8399      const char *name;
8400      int reloc;
8401 {
8402   return default_section_type_flags_1 (decl, name, reloc, true);
8403 }
8404
8405
8406 /* Output the assembler code for a thunk function.  THUNK_DECL is the
8407    declaration for the thunk function itself, FUNCTION is the decl for
8408    the target function.  DELTA is an immediate constant offset to be
8409    added to THIS.  If VCALL_OFFSET is nonzero, the word at
8410    *(*this + vcall_offset) should be added to THIS.  */
8411
8412 static void
8413 ia64_output_mi_thunk (file, thunk, delta, vcall_offset, function)
8414      FILE *file;
8415      tree thunk ATTRIBUTE_UNUSED;
8416      HOST_WIDE_INT delta;
8417      HOST_WIDE_INT vcall_offset;
8418      tree function;
8419 {
8420   rtx this, insn, funexp;
8421
8422   reload_completed = 1;
8423   no_new_pseudos = 1;
8424
8425   /* Set things up as ia64_expand_prologue might.  */
8426   last_scratch_gr_reg = 15;
8427
8428   memset (&current_frame_info, 0, sizeof (current_frame_info));
8429   current_frame_info.spill_cfa_off = -16;
8430   current_frame_info.n_input_regs = 1;
8431   current_frame_info.need_regstk = (TARGET_REG_NAMES != 0);
8432
8433   if (!TARGET_REG_NAMES)
8434     reg_names[IN_REG (0)] = ia64_reg_numbers[0];
8435
8436   /* Mark the end of the (empty) prologue.  */
8437   emit_note (NULL, NOTE_INSN_PROLOGUE_END);
8438
8439   this = gen_rtx_REG (Pmode, IN_REG (0));
8440
8441   /* Apply the constant offset, if required.  */
8442   if (delta)
8443     {
8444       rtx delta_rtx = GEN_INT (delta);
8445
8446       if (!CONST_OK_FOR_I (delta))
8447         {
8448           rtx tmp = gen_rtx_REG (Pmode, 2);
8449           emit_move_insn (tmp, delta_rtx);
8450           delta_rtx = tmp;
8451         }
8452       emit_insn (gen_adddi3 (this, this, delta_rtx));
8453     }
8454
8455   /* Apply the offset from the vtable, if required.  */
8456   if (vcall_offset)
8457     {
8458       rtx vcall_offset_rtx = GEN_INT (vcall_offset);
8459       rtx tmp = gen_rtx_REG (Pmode, 2);
8460
8461       emit_move_insn (tmp, gen_rtx_MEM (Pmode, this));
8462
8463       if (!CONST_OK_FOR_J (vcall_offset))
8464         {
8465           rtx tmp2 = gen_rtx_REG (Pmode, next_scratch_gr_reg ());
8466           emit_move_insn (tmp2, vcall_offset_rtx);
8467           vcall_offset_rtx = tmp2;
8468         }
8469       emit_insn (gen_adddi3 (tmp, tmp, vcall_offset_rtx));
8470
8471       emit_move_insn (tmp, gen_rtx_MEM (Pmode, tmp));
8472
8473       emit_insn (gen_adddi3 (this, this, tmp));
8474     }
8475
8476   /* Generate a tail call to the target function.  */
8477   if (! TREE_USED (function))
8478     {
8479       assemble_external (function);
8480       TREE_USED (function) = 1;
8481     }
8482   funexp = XEXP (DECL_RTL (function), 0);
8483   funexp = gen_rtx_MEM (FUNCTION_MODE, funexp);
8484   ia64_expand_call (NULL_RTX, funexp, NULL_RTX, 1);
8485   insn = get_last_insn ();
8486   SIBLING_CALL_P (insn) = 1;
8487
8488   /* Code generation for calls relies on splitting.  */
8489   reload_completed = 1;
8490   try_split (PATTERN (insn), insn, 0);
8491
8492   emit_barrier ();
8493
8494   /* Run just enough of rest_of_compilation to get the insns emitted.
8495      There's not really enough bulk here to make other passes such as
8496      instruction scheduling worth while.  Note that use_thunk calls
8497      assemble_start_function and assemble_end_function.  */
8498
8499   insn = get_insns ();
8500   emit_all_insn_group_barriers (NULL, insn);
8501   shorten_branches (insn);
8502   final_start_function (insn, file, 1);
8503   final (insn, file, 1, 0);
8504   final_end_function ();
8505
8506   reload_completed = 0;
8507   no_new_pseudos = 0;
8508 }
8509
8510 #include "gt-ia64.h"