OSDN Git Service

4a738095c6e60970d3e2558b7e8b83eb0e771abc
[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, 2004, 2005, 2006, 2007, 2008,
3    2009, 2010
4    Free Software Foundation, Inc.
5    Contributed by James E. Wilson <wilson@cygnus.com> and
6                   David Mosberger <davidm@hpl.hp.com>.
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "rtl.h"
29 #include "tree.h"
30 #include "regs.h"
31 #include "hard-reg-set.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 "libfuncs.h"
45 #include "diagnostic-core.h"
46 #include "toplev.h"
47 #include "sched-int.h"
48 #include "timevar.h"
49 #include "target.h"
50 #include "target-def.h"
51 #include "tm_p.h"
52 #include "hashtab.h"
53 #include "langhooks.h"
54 #include "cfglayout.h"
55 #include "gimple.h"
56 #include "intl.h"
57 #include "df.h"
58 #include "debug.h"
59 #include "params.h"
60 #include "dbgcnt.h"
61 #include "tm-constrs.h"
62 #include "sel-sched.h"
63 #include "reload.h"
64
65 /* This is used for communication between ASM_OUTPUT_LABEL and
66    ASM_OUTPUT_LABELREF.  */
67 int ia64_asm_output_label = 0;
68
69 /* Register names for ia64_expand_prologue.  */
70 static const char * const ia64_reg_numbers[96] =
71 { "r32", "r33", "r34", "r35", "r36", "r37", "r38", "r39",
72   "r40", "r41", "r42", "r43", "r44", "r45", "r46", "r47",
73   "r48", "r49", "r50", "r51", "r52", "r53", "r54", "r55",
74   "r56", "r57", "r58", "r59", "r60", "r61", "r62", "r63",
75   "r64", "r65", "r66", "r67", "r68", "r69", "r70", "r71",
76   "r72", "r73", "r74", "r75", "r76", "r77", "r78", "r79",
77   "r80", "r81", "r82", "r83", "r84", "r85", "r86", "r87",
78   "r88", "r89", "r90", "r91", "r92", "r93", "r94", "r95",
79   "r96", "r97", "r98", "r99", "r100","r101","r102","r103",
80   "r104","r105","r106","r107","r108","r109","r110","r111",
81   "r112","r113","r114","r115","r116","r117","r118","r119",
82   "r120","r121","r122","r123","r124","r125","r126","r127"};
83
84 /* ??? These strings could be shared with REGISTER_NAMES.  */
85 static const char * const ia64_input_reg_names[8] =
86 { "in0",  "in1",  "in2",  "in3",  "in4",  "in5",  "in6",  "in7" };
87
88 /* ??? These strings could be shared with REGISTER_NAMES.  */
89 static const char * const ia64_local_reg_names[80] =
90 { "loc0", "loc1", "loc2", "loc3", "loc4", "loc5", "loc6", "loc7",
91   "loc8", "loc9", "loc10","loc11","loc12","loc13","loc14","loc15",
92   "loc16","loc17","loc18","loc19","loc20","loc21","loc22","loc23",
93   "loc24","loc25","loc26","loc27","loc28","loc29","loc30","loc31",
94   "loc32","loc33","loc34","loc35","loc36","loc37","loc38","loc39",
95   "loc40","loc41","loc42","loc43","loc44","loc45","loc46","loc47",
96   "loc48","loc49","loc50","loc51","loc52","loc53","loc54","loc55",
97   "loc56","loc57","loc58","loc59","loc60","loc61","loc62","loc63",
98   "loc64","loc65","loc66","loc67","loc68","loc69","loc70","loc71",
99   "loc72","loc73","loc74","loc75","loc76","loc77","loc78","loc79" };
100
101 /* ??? These strings could be shared with REGISTER_NAMES.  */
102 static const char * const ia64_output_reg_names[8] =
103 { "out0", "out1", "out2", "out3", "out4", "out5", "out6", "out7" };
104
105 /* Which cpu are we scheduling for.  */
106 enum processor_type ia64_tune = PROCESSOR_ITANIUM2;
107
108 /* Determines whether we run our final scheduling pass or not.  We always
109    avoid the normal second scheduling pass.  */
110 static int ia64_flag_schedule_insns2;
111
112 /* Determines whether we run variable tracking in machine dependent
113    reorganization.  */
114 static int ia64_flag_var_tracking;
115
116 /* Variables which are this size or smaller are put in the sdata/sbss
117    sections.  */
118
119 unsigned int ia64_section_threshold;
120
121 /* The following variable is used by the DFA insn scheduler.  The value is
122    TRUE if we do insn bundling instead of insn scheduling.  */
123 int bundling_p = 0;
124
125 enum ia64_frame_regs
126 {
127    reg_fp,
128    reg_save_b0,
129    reg_save_pr,
130    reg_save_ar_pfs,
131    reg_save_ar_unat,
132    reg_save_ar_lc,
133    reg_save_gp,
134    number_of_ia64_frame_regs
135 };
136
137 /* Structure to be filled in by ia64_compute_frame_size with register
138    save masks and offsets for the current function.  */
139
140 struct ia64_frame_info
141 {
142   HOST_WIDE_INT total_size;     /* size of the stack frame, not including
143                                    the caller's scratch area.  */
144   HOST_WIDE_INT spill_cfa_off;  /* top of the reg spill area from the cfa.  */
145   HOST_WIDE_INT spill_size;     /* size of the gr/br/fr spill area.  */
146   HOST_WIDE_INT extra_spill_size;  /* size of spill area for others.  */
147   HARD_REG_SET mask;            /* mask of saved registers.  */
148   unsigned int gr_used_mask;    /* mask of registers in use as gr spill
149                                    registers or long-term scratches.  */
150   int n_spilled;                /* number of spilled registers.  */
151   int r[number_of_ia64_frame_regs];  /* Frame related registers.  */
152   int n_input_regs;             /* number of input registers used.  */
153   int n_local_regs;             /* number of local registers used.  */
154   int n_output_regs;            /* number of output registers used.  */
155   int n_rotate_regs;            /* number of rotating registers used.  */
156
157   char need_regstk;             /* true if a .regstk directive needed.  */
158   char initialized;             /* true if the data is finalized.  */
159 };
160
161 /* Current frame information calculated by ia64_compute_frame_size.  */
162 static struct ia64_frame_info current_frame_info;
163 /* The actual registers that are emitted.  */
164 static int emitted_frame_related_regs[number_of_ia64_frame_regs];
165 \f
166 static int ia64_first_cycle_multipass_dfa_lookahead (void);
167 static void ia64_dependencies_evaluation_hook (rtx, rtx);
168 static void ia64_init_dfa_pre_cycle_insn (void);
169 static rtx ia64_dfa_pre_cycle_insn (void);
170 static int ia64_first_cycle_multipass_dfa_lookahead_guard (rtx);
171 static bool ia64_first_cycle_multipass_dfa_lookahead_guard_spec (const_rtx);
172 static int ia64_dfa_new_cycle (FILE *, int, rtx, int, int, int *);
173 static void ia64_h_i_d_extended (void);
174 static void * ia64_alloc_sched_context (void);
175 static void ia64_init_sched_context (void *, bool);
176 static void ia64_set_sched_context (void *);
177 static void ia64_clear_sched_context (void *);
178 static void ia64_free_sched_context (void *);
179 static int ia64_mode_to_int (enum machine_mode);
180 static void ia64_set_sched_flags (spec_info_t);
181 static ds_t ia64_get_insn_spec_ds (rtx);
182 static ds_t ia64_get_insn_checked_ds (rtx);
183 static bool ia64_skip_rtx_p (const_rtx);
184 static int ia64_speculate_insn (rtx, ds_t, rtx *);
185 static bool ia64_needs_block_p (int);
186 static rtx ia64_gen_spec_check (rtx, rtx, ds_t);
187 static int ia64_spec_check_p (rtx);
188 static int ia64_spec_check_src_p (rtx);
189 static rtx gen_tls_get_addr (void);
190 static rtx gen_thread_pointer (void);
191 static int find_gr_spill (enum ia64_frame_regs, int);
192 static int next_scratch_gr_reg (void);
193 static void mark_reg_gr_used_mask (rtx, void *);
194 static void ia64_compute_frame_size (HOST_WIDE_INT);
195 static void setup_spill_pointers (int, rtx, HOST_WIDE_INT);
196 static void finish_spill_pointers (void);
197 static rtx spill_restore_mem (rtx, HOST_WIDE_INT);
198 static void do_spill (rtx (*)(rtx, rtx, rtx), rtx, HOST_WIDE_INT, rtx);
199 static void do_restore (rtx (*)(rtx, rtx, rtx), rtx, HOST_WIDE_INT);
200 static rtx gen_movdi_x (rtx, rtx, rtx);
201 static rtx gen_fr_spill_x (rtx, rtx, rtx);
202 static rtx gen_fr_restore_x (rtx, rtx, rtx);
203
204 static void ia64_option_override (void);
205 static void ia64_option_default_params (void);
206 static bool ia64_can_eliminate (const int, const int);
207 static enum machine_mode hfa_element_mode (const_tree, bool);
208 static void ia64_setup_incoming_varargs (CUMULATIVE_ARGS *, enum machine_mode,
209                                          tree, int *, int);
210 static int ia64_arg_partial_bytes (CUMULATIVE_ARGS *, enum machine_mode,
211                                    tree, bool);
212 static rtx ia64_function_arg_1 (const CUMULATIVE_ARGS *, enum machine_mode,
213                                 const_tree, bool, bool);
214 static rtx ia64_function_arg (CUMULATIVE_ARGS *, enum machine_mode,
215                               const_tree, bool);
216 static rtx ia64_function_incoming_arg (CUMULATIVE_ARGS *,
217                                        enum machine_mode, const_tree, bool);
218 static void ia64_function_arg_advance (CUMULATIVE_ARGS *, enum machine_mode,
219                                        const_tree, bool);
220 static bool ia64_function_ok_for_sibcall (tree, tree);
221 static bool ia64_return_in_memory (const_tree, const_tree);
222 static rtx ia64_function_value (const_tree, const_tree, bool);
223 static rtx ia64_libcall_value (enum machine_mode, const_rtx);
224 static bool ia64_function_value_regno_p (const unsigned int);
225 static int ia64_register_move_cost (enum machine_mode, reg_class_t,
226                                     reg_class_t);
227 static int ia64_memory_move_cost (enum machine_mode mode, reg_class_t,
228                                   bool);
229 static bool ia64_rtx_costs (rtx, int, int, int *, bool);
230 static int ia64_unspec_may_trap_p (const_rtx, unsigned);
231 static void fix_range (const char *);
232 static bool ia64_handle_option (size_t, const char *, int);
233 static struct machine_function * ia64_init_machine_status (void);
234 static void emit_insn_group_barriers (FILE *);
235 static void emit_all_insn_group_barriers (FILE *);
236 static void final_emit_insn_group_barriers (FILE *);
237 static void emit_predicate_relation_info (void);
238 static void ia64_reorg (void);
239 static bool ia64_in_small_data_p (const_tree);
240 static void process_epilogue (FILE *, rtx, bool, bool);
241
242 static bool ia64_assemble_integer (rtx, unsigned int, int);
243 static void ia64_output_function_prologue (FILE *, HOST_WIDE_INT);
244 static void ia64_output_function_epilogue (FILE *, HOST_WIDE_INT);
245 static void ia64_output_function_end_prologue (FILE *);
246
247 static int ia64_issue_rate (void);
248 static int ia64_adjust_cost_2 (rtx, int, rtx, int, dw_t);
249 static void ia64_sched_init (FILE *, int, int);
250 static void ia64_sched_init_global (FILE *, int, int);
251 static void ia64_sched_finish_global (FILE *, int);
252 static void ia64_sched_finish (FILE *, int);
253 static int ia64_dfa_sched_reorder (FILE *, int, rtx *, int *, int, int);
254 static int ia64_sched_reorder (FILE *, int, rtx *, int *, int);
255 static int ia64_sched_reorder2 (FILE *, int, rtx *, int *, int);
256 static int ia64_variable_issue (FILE *, int, rtx, int);
257
258 static void ia64_asm_unwind_emit (FILE *, rtx);
259 static void ia64_asm_emit_except_personality (rtx);
260 static void ia64_asm_init_sections (void);
261
262 static enum unwind_info_type ia64_debug_unwind_info (void);
263 static enum unwind_info_type ia64_except_unwind_info (void);
264
265 static struct bundle_state *get_free_bundle_state (void);
266 static void free_bundle_state (struct bundle_state *);
267 static void initiate_bundle_states (void);
268 static void finish_bundle_states (void);
269 static unsigned bundle_state_hash (const void *);
270 static int bundle_state_eq_p (const void *, const void *);
271 static int insert_bundle_state (struct bundle_state *);
272 static void initiate_bundle_state_table (void);
273 static void finish_bundle_state_table (void);
274 static int try_issue_nops (struct bundle_state *, int);
275 static int try_issue_insn (struct bundle_state *, rtx);
276 static void issue_nops_and_insn (struct bundle_state *, int, rtx, int, int);
277 static int get_max_pos (state_t);
278 static int get_template (state_t, int);
279
280 static rtx get_next_important_insn (rtx, rtx);
281 static bool important_for_bundling_p (rtx);
282 static void bundling (FILE *, int, rtx, rtx);
283
284 static void ia64_output_mi_thunk (FILE *, tree, HOST_WIDE_INT,
285                                   HOST_WIDE_INT, tree);
286 static void ia64_file_start (void);
287 static void ia64_globalize_decl_name (FILE *, tree);
288
289 static int ia64_hpux_reloc_rw_mask (void) ATTRIBUTE_UNUSED;
290 static int ia64_reloc_rw_mask (void) ATTRIBUTE_UNUSED;
291 static section *ia64_select_rtx_section (enum machine_mode, rtx,
292                                          unsigned HOST_WIDE_INT);
293 static void ia64_output_dwarf_dtprel (FILE *, int, rtx)
294      ATTRIBUTE_UNUSED;
295 static unsigned int ia64_section_type_flags (tree, const char *, int);
296 static void ia64_init_libfuncs (void)
297      ATTRIBUTE_UNUSED;
298 static void ia64_hpux_init_libfuncs (void)
299      ATTRIBUTE_UNUSED;
300 static void ia64_sysv4_init_libfuncs (void)
301      ATTRIBUTE_UNUSED;
302 static void ia64_vms_init_libfuncs (void)
303      ATTRIBUTE_UNUSED;
304 static void ia64_soft_fp_init_libfuncs (void)
305      ATTRIBUTE_UNUSED;
306 static bool ia64_vms_valid_pointer_mode (enum machine_mode mode)
307      ATTRIBUTE_UNUSED;
308 static tree ia64_vms_common_object_attribute (tree *, tree, tree, int, bool *)
309      ATTRIBUTE_UNUSED;
310
311 static tree ia64_handle_model_attribute (tree *, tree, tree, int, bool *);
312 static tree ia64_handle_version_id_attribute (tree *, tree, tree, int, bool *);
313 static void ia64_encode_section_info (tree, rtx, int);
314 static rtx ia64_struct_value_rtx (tree, int);
315 static tree ia64_gimplify_va_arg (tree, tree, gimple_seq *, gimple_seq *);
316 static bool ia64_scalar_mode_supported_p (enum machine_mode mode);
317 static bool ia64_vector_mode_supported_p (enum machine_mode mode);
318 static bool ia64_cannot_force_const_mem (rtx);
319 static const char *ia64_mangle_type (const_tree);
320 static const char *ia64_invalid_conversion (const_tree, const_tree);
321 static const char *ia64_invalid_unary_op (int, const_tree);
322 static const char *ia64_invalid_binary_op (int, const_tree, const_tree);
323 static enum machine_mode ia64_c_mode_for_suffix (char);
324 static enum machine_mode ia64_promote_function_mode (const_tree,
325                                                      enum machine_mode,
326                                                      int *,
327                                                      const_tree,
328                                                      int);
329 static void ia64_trampoline_init (rtx, tree, rtx);
330 static void ia64_override_options_after_change (void);
331
332 static void ia64_dwarf_handle_frame_unspec (const char *, rtx, int);
333 static tree ia64_builtin_decl (unsigned, bool);
334
335 static reg_class_t ia64_preferred_reload_class (rtx, reg_class_t);
336 static enum machine_mode ia64_get_reg_raw_mode (int regno);
337 \f
338 /* Table of valid machine attributes.  */
339 static const struct attribute_spec ia64_attribute_table[] =
340 {
341   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
342   { "syscall_linkage", 0, 0, false, true,  true,  NULL },
343   { "model",           1, 1, true, false, false, ia64_handle_model_attribute },
344 #if TARGET_ABI_OPEN_VMS
345   { "common_object",   1, 1, true, false, false, ia64_vms_common_object_attribute},
346 #endif
347   { "version_id",      1, 1, true, false, false,
348     ia64_handle_version_id_attribute },
349   { NULL,              0, 0, false, false, false, NULL }
350 };
351
352 /* Implement overriding of the optimization options.  */
353 static const struct default_options ia64_option_optimization_table[] =
354   {
355     { OPT_LEVELS_1_PLUS, OPT_fomit_frame_pointer, NULL, 1 },
356 #ifdef SUBTARGET_OPTIMIZATION_OPTIONS
357     SUBTARGET_OPTIMIZATION_OPTIONS,
358 #endif
359     { OPT_LEVELS_NONE, 0, NULL, 0 }
360   };
361
362 /* Initialize the GCC target structure.  */
363 #undef TARGET_ATTRIBUTE_TABLE
364 #define TARGET_ATTRIBUTE_TABLE ia64_attribute_table
365
366 #undef TARGET_INIT_BUILTINS
367 #define TARGET_INIT_BUILTINS ia64_init_builtins
368
369 #undef TARGET_EXPAND_BUILTIN
370 #define TARGET_EXPAND_BUILTIN ia64_expand_builtin
371
372 #undef TARGET_BUILTIN_DECL
373 #define TARGET_BUILTIN_DECL ia64_builtin_decl
374
375 #undef TARGET_ASM_BYTE_OP
376 #define TARGET_ASM_BYTE_OP "\tdata1\t"
377 #undef TARGET_ASM_ALIGNED_HI_OP
378 #define TARGET_ASM_ALIGNED_HI_OP "\tdata2\t"
379 #undef TARGET_ASM_ALIGNED_SI_OP
380 #define TARGET_ASM_ALIGNED_SI_OP "\tdata4\t"
381 #undef TARGET_ASM_ALIGNED_DI_OP
382 #define TARGET_ASM_ALIGNED_DI_OP "\tdata8\t"
383 #undef TARGET_ASM_UNALIGNED_HI_OP
384 #define TARGET_ASM_UNALIGNED_HI_OP "\tdata2.ua\t"
385 #undef TARGET_ASM_UNALIGNED_SI_OP
386 #define TARGET_ASM_UNALIGNED_SI_OP "\tdata4.ua\t"
387 #undef TARGET_ASM_UNALIGNED_DI_OP
388 #define TARGET_ASM_UNALIGNED_DI_OP "\tdata8.ua\t"
389 #undef TARGET_ASM_INTEGER
390 #define TARGET_ASM_INTEGER ia64_assemble_integer
391
392 #undef TARGET_OPTION_OVERRIDE
393 #define TARGET_OPTION_OVERRIDE ia64_option_override
394 #undef TARGET_OPTION_OPTIMIZATION_TABLE
395 #define TARGET_OPTION_OPTIMIZATION_TABLE ia64_option_optimization_table
396 #undef TARGET_OPTION_DEFAULT_PARAMS
397 #define TARGET_OPTION_DEFAULT_PARAMS ia64_option_default_params
398
399 #undef TARGET_ASM_FUNCTION_PROLOGUE
400 #define TARGET_ASM_FUNCTION_PROLOGUE ia64_output_function_prologue
401 #undef TARGET_ASM_FUNCTION_END_PROLOGUE
402 #define TARGET_ASM_FUNCTION_END_PROLOGUE ia64_output_function_end_prologue
403 #undef TARGET_ASM_FUNCTION_EPILOGUE
404 #define TARGET_ASM_FUNCTION_EPILOGUE ia64_output_function_epilogue
405
406 #undef TARGET_IN_SMALL_DATA_P
407 #define TARGET_IN_SMALL_DATA_P  ia64_in_small_data_p
408
409 #undef TARGET_SCHED_ADJUST_COST_2
410 #define TARGET_SCHED_ADJUST_COST_2 ia64_adjust_cost_2
411 #undef TARGET_SCHED_ISSUE_RATE
412 #define TARGET_SCHED_ISSUE_RATE ia64_issue_rate
413 #undef TARGET_SCHED_VARIABLE_ISSUE
414 #define TARGET_SCHED_VARIABLE_ISSUE ia64_variable_issue
415 #undef TARGET_SCHED_INIT
416 #define TARGET_SCHED_INIT ia64_sched_init
417 #undef TARGET_SCHED_FINISH
418 #define TARGET_SCHED_FINISH ia64_sched_finish
419 #undef TARGET_SCHED_INIT_GLOBAL
420 #define TARGET_SCHED_INIT_GLOBAL ia64_sched_init_global
421 #undef TARGET_SCHED_FINISH_GLOBAL
422 #define TARGET_SCHED_FINISH_GLOBAL ia64_sched_finish_global
423 #undef TARGET_SCHED_REORDER
424 #define TARGET_SCHED_REORDER ia64_sched_reorder
425 #undef TARGET_SCHED_REORDER2
426 #define TARGET_SCHED_REORDER2 ia64_sched_reorder2
427
428 #undef TARGET_SCHED_DEPENDENCIES_EVALUATION_HOOK
429 #define TARGET_SCHED_DEPENDENCIES_EVALUATION_HOOK ia64_dependencies_evaluation_hook
430
431 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
432 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD ia64_first_cycle_multipass_dfa_lookahead
433
434 #undef TARGET_SCHED_INIT_DFA_PRE_CYCLE_INSN
435 #define TARGET_SCHED_INIT_DFA_PRE_CYCLE_INSN ia64_init_dfa_pre_cycle_insn
436 #undef TARGET_SCHED_DFA_PRE_CYCLE_INSN
437 #define TARGET_SCHED_DFA_PRE_CYCLE_INSN ia64_dfa_pre_cycle_insn
438
439 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD
440 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD\
441   ia64_first_cycle_multipass_dfa_lookahead_guard
442
443 #undef TARGET_SCHED_DFA_NEW_CYCLE
444 #define TARGET_SCHED_DFA_NEW_CYCLE ia64_dfa_new_cycle
445
446 #undef TARGET_SCHED_H_I_D_EXTENDED
447 #define TARGET_SCHED_H_I_D_EXTENDED ia64_h_i_d_extended
448
449 #undef TARGET_SCHED_ALLOC_SCHED_CONTEXT
450 #define TARGET_SCHED_ALLOC_SCHED_CONTEXT ia64_alloc_sched_context
451
452 #undef TARGET_SCHED_INIT_SCHED_CONTEXT
453 #define TARGET_SCHED_INIT_SCHED_CONTEXT ia64_init_sched_context
454
455 #undef TARGET_SCHED_SET_SCHED_CONTEXT
456 #define TARGET_SCHED_SET_SCHED_CONTEXT ia64_set_sched_context
457
458 #undef TARGET_SCHED_CLEAR_SCHED_CONTEXT
459 #define TARGET_SCHED_CLEAR_SCHED_CONTEXT ia64_clear_sched_context
460
461 #undef TARGET_SCHED_FREE_SCHED_CONTEXT
462 #define TARGET_SCHED_FREE_SCHED_CONTEXT ia64_free_sched_context
463
464 #undef TARGET_SCHED_SET_SCHED_FLAGS
465 #define TARGET_SCHED_SET_SCHED_FLAGS ia64_set_sched_flags
466
467 #undef TARGET_SCHED_GET_INSN_SPEC_DS
468 #define TARGET_SCHED_GET_INSN_SPEC_DS ia64_get_insn_spec_ds
469
470 #undef TARGET_SCHED_GET_INSN_CHECKED_DS
471 #define TARGET_SCHED_GET_INSN_CHECKED_DS ia64_get_insn_checked_ds
472
473 #undef TARGET_SCHED_SPECULATE_INSN
474 #define TARGET_SCHED_SPECULATE_INSN ia64_speculate_insn
475
476 #undef TARGET_SCHED_NEEDS_BLOCK_P
477 #define TARGET_SCHED_NEEDS_BLOCK_P ia64_needs_block_p
478
479 #undef TARGET_SCHED_GEN_SPEC_CHECK
480 #define TARGET_SCHED_GEN_SPEC_CHECK ia64_gen_spec_check
481
482 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD_SPEC
483 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD_SPEC\
484   ia64_first_cycle_multipass_dfa_lookahead_guard_spec
485
486 #undef TARGET_SCHED_SKIP_RTX_P
487 #define TARGET_SCHED_SKIP_RTX_P ia64_skip_rtx_p
488
489 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
490 #define TARGET_FUNCTION_OK_FOR_SIBCALL ia64_function_ok_for_sibcall
491 #undef TARGET_ARG_PARTIAL_BYTES
492 #define TARGET_ARG_PARTIAL_BYTES ia64_arg_partial_bytes
493 #undef TARGET_FUNCTION_ARG
494 #define TARGET_FUNCTION_ARG ia64_function_arg
495 #undef TARGET_FUNCTION_INCOMING_ARG
496 #define TARGET_FUNCTION_INCOMING_ARG ia64_function_incoming_arg
497 #undef TARGET_FUNCTION_ARG_ADVANCE
498 #define TARGET_FUNCTION_ARG_ADVANCE ia64_function_arg_advance
499
500 #undef TARGET_ASM_OUTPUT_MI_THUNK
501 #define TARGET_ASM_OUTPUT_MI_THUNK ia64_output_mi_thunk
502 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
503 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
504
505 #undef TARGET_ASM_FILE_START
506 #define TARGET_ASM_FILE_START ia64_file_start
507
508 #undef TARGET_ASM_GLOBALIZE_DECL_NAME
509 #define TARGET_ASM_GLOBALIZE_DECL_NAME ia64_globalize_decl_name
510
511 #undef TARGET_REGISTER_MOVE_COST
512 #define TARGET_REGISTER_MOVE_COST ia64_register_move_cost
513 #undef TARGET_MEMORY_MOVE_COST
514 #define TARGET_MEMORY_MOVE_COST ia64_memory_move_cost
515 #undef TARGET_RTX_COSTS
516 #define TARGET_RTX_COSTS ia64_rtx_costs
517 #undef TARGET_ADDRESS_COST
518 #define TARGET_ADDRESS_COST hook_int_rtx_bool_0
519
520 #undef TARGET_UNSPEC_MAY_TRAP_P
521 #define TARGET_UNSPEC_MAY_TRAP_P ia64_unspec_may_trap_p
522
523 #undef TARGET_MACHINE_DEPENDENT_REORG
524 #define TARGET_MACHINE_DEPENDENT_REORG ia64_reorg
525
526 #undef TARGET_ENCODE_SECTION_INFO
527 #define TARGET_ENCODE_SECTION_INFO ia64_encode_section_info
528
529 #undef  TARGET_SECTION_TYPE_FLAGS
530 #define TARGET_SECTION_TYPE_FLAGS  ia64_section_type_flags
531
532 #ifdef HAVE_AS_TLS
533 #undef TARGET_ASM_OUTPUT_DWARF_DTPREL
534 #define TARGET_ASM_OUTPUT_DWARF_DTPREL ia64_output_dwarf_dtprel
535 #endif
536
537 #undef TARGET_PROMOTE_FUNCTION_MODE
538 #define TARGET_PROMOTE_FUNCTION_MODE ia64_promote_function_mode
539
540 /* ??? Investigate.  */
541 #if 0
542 #undef TARGET_PROMOTE_PROTOTYPES
543 #define TARGET_PROMOTE_PROTOTYPES hook_bool_tree_true
544 #endif
545
546 #undef TARGET_FUNCTION_VALUE
547 #define TARGET_FUNCTION_VALUE ia64_function_value
548 #undef TARGET_LIBCALL_VALUE
549 #define TARGET_LIBCALL_VALUE ia64_libcall_value
550 #undef TARGET_FUNCTION_VALUE_REGNO_P
551 #define TARGET_FUNCTION_VALUE_REGNO_P ia64_function_value_regno_p
552
553 #undef TARGET_STRUCT_VALUE_RTX
554 #define TARGET_STRUCT_VALUE_RTX ia64_struct_value_rtx
555 #undef TARGET_RETURN_IN_MEMORY
556 #define TARGET_RETURN_IN_MEMORY ia64_return_in_memory
557 #undef TARGET_SETUP_INCOMING_VARARGS
558 #define TARGET_SETUP_INCOMING_VARARGS ia64_setup_incoming_varargs
559 #undef TARGET_STRICT_ARGUMENT_NAMING
560 #define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true
561 #undef TARGET_MUST_PASS_IN_STACK
562 #define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
563 #undef TARGET_GET_RAW_RESULT_MODE
564 #define TARGET_GET_RAW_RESULT_MODE ia64_get_reg_raw_mode
565 #undef TARGET_GET_RAW_ARG_MODE
566 #define TARGET_GET_RAW_ARG_MODE ia64_get_reg_raw_mode
567
568 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
569 #define TARGET_GIMPLIFY_VA_ARG_EXPR ia64_gimplify_va_arg
570
571 #undef TARGET_DWARF_HANDLE_FRAME_UNSPEC
572 #define TARGET_DWARF_HANDLE_FRAME_UNSPEC  ia64_dwarf_handle_frame_unspec
573 #undef TARGET_ASM_UNWIND_EMIT
574 #define TARGET_ASM_UNWIND_EMIT ia64_asm_unwind_emit
575 #undef TARGET_ASM_EMIT_EXCEPT_PERSONALITY
576 #define TARGET_ASM_EMIT_EXCEPT_PERSONALITY  ia64_asm_emit_except_personality
577 #undef TARGET_ASM_INIT_SECTIONS
578 #define TARGET_ASM_INIT_SECTIONS  ia64_asm_init_sections
579
580 #undef TARGET_DEBUG_UNWIND_INFO
581 #define TARGET_DEBUG_UNWIND_INFO  ia64_debug_unwind_info
582 #undef TARGET_EXCEPT_UNWIND_INFO
583 #define TARGET_EXCEPT_UNWIND_INFO  ia64_except_unwind_info
584
585 #undef TARGET_SCALAR_MODE_SUPPORTED_P
586 #define TARGET_SCALAR_MODE_SUPPORTED_P ia64_scalar_mode_supported_p
587 #undef TARGET_VECTOR_MODE_SUPPORTED_P
588 #define TARGET_VECTOR_MODE_SUPPORTED_P ia64_vector_mode_supported_p
589
590 /* ia64 architecture manual 4.4.7: ... reads, writes, and flushes may occur
591    in an order different from the specified program order.  */
592 #undef TARGET_RELAXED_ORDERING
593 #define TARGET_RELAXED_ORDERING true
594
595 #undef TARGET_DEFAULT_TARGET_FLAGS
596 #define TARGET_DEFAULT_TARGET_FLAGS (TARGET_DEFAULT | TARGET_CPU_DEFAULT)
597 #undef TARGET_HANDLE_OPTION
598 #define TARGET_HANDLE_OPTION ia64_handle_option
599
600 #undef TARGET_CANNOT_FORCE_CONST_MEM
601 #define TARGET_CANNOT_FORCE_CONST_MEM ia64_cannot_force_const_mem
602
603 #undef TARGET_MANGLE_TYPE
604 #define TARGET_MANGLE_TYPE ia64_mangle_type
605
606 #undef TARGET_INVALID_CONVERSION
607 #define TARGET_INVALID_CONVERSION ia64_invalid_conversion
608 #undef TARGET_INVALID_UNARY_OP
609 #define TARGET_INVALID_UNARY_OP ia64_invalid_unary_op
610 #undef TARGET_INVALID_BINARY_OP
611 #define TARGET_INVALID_BINARY_OP ia64_invalid_binary_op
612
613 #undef TARGET_C_MODE_FOR_SUFFIX
614 #define TARGET_C_MODE_FOR_SUFFIX ia64_c_mode_for_suffix
615
616 #undef TARGET_CAN_ELIMINATE
617 #define TARGET_CAN_ELIMINATE ia64_can_eliminate
618
619 #undef TARGET_TRAMPOLINE_INIT
620 #define TARGET_TRAMPOLINE_INIT ia64_trampoline_init
621
622 #undef TARGET_INVALID_WITHIN_DOLOOP
623 #define TARGET_INVALID_WITHIN_DOLOOP hook_constcharptr_const_rtx_null
624
625 #undef TARGET_OVERRIDE_OPTIONS_AFTER_CHANGE
626 #define TARGET_OVERRIDE_OPTIONS_AFTER_CHANGE ia64_override_options_after_change
627
628 #undef TARGET_PREFERRED_RELOAD_CLASS
629 #define TARGET_PREFERRED_RELOAD_CLASS ia64_preferred_reload_class
630
631 struct gcc_target targetm = TARGET_INITIALIZER;
632 \f
633 typedef enum
634   {
635     ADDR_AREA_NORMAL,   /* normal address area */
636     ADDR_AREA_SMALL     /* addressable by "addl" (-2MB < addr < 2MB) */
637   }
638 ia64_addr_area;
639
640 static GTY(()) tree small_ident1;
641 static GTY(()) tree small_ident2;
642
643 static void
644 init_idents (void)
645 {
646   if (small_ident1 == 0)
647     {
648       small_ident1 = get_identifier ("small");
649       small_ident2 = get_identifier ("__small__");
650     }
651 }
652
653 /* Retrieve the address area that has been chosen for the given decl.  */
654
655 static ia64_addr_area
656 ia64_get_addr_area (tree decl)
657 {
658   tree model_attr;
659
660   model_attr = lookup_attribute ("model", DECL_ATTRIBUTES (decl));
661   if (model_attr)
662     {
663       tree id;
664
665       init_idents ();
666       id = TREE_VALUE (TREE_VALUE (model_attr));
667       if (id == small_ident1 || id == small_ident2)
668         return ADDR_AREA_SMALL;
669     }
670   return ADDR_AREA_NORMAL;
671 }
672
673 static tree
674 ia64_handle_model_attribute (tree *node, tree name, tree args,
675                              int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
676 {
677   ia64_addr_area addr_area = ADDR_AREA_NORMAL;
678   ia64_addr_area area;
679   tree arg, decl = *node;
680
681   init_idents ();
682   arg = TREE_VALUE (args);
683   if (arg == small_ident1 || arg == small_ident2)
684     {
685       addr_area = ADDR_AREA_SMALL;
686     }
687   else
688     {
689       warning (OPT_Wattributes, "invalid argument of %qE attribute",
690                name);
691       *no_add_attrs = true;
692     }
693
694   switch (TREE_CODE (decl))
695     {
696     case VAR_DECL:
697       if ((DECL_CONTEXT (decl) && TREE_CODE (DECL_CONTEXT (decl))
698            == FUNCTION_DECL)
699           && !TREE_STATIC (decl))
700         {
701           error_at (DECL_SOURCE_LOCATION (decl),
702                     "an address area attribute cannot be specified for "
703                     "local variables");
704           *no_add_attrs = true;
705         }
706       area = ia64_get_addr_area (decl);
707       if (area != ADDR_AREA_NORMAL && addr_area != area)
708         {
709           error ("address area of %q+D conflicts with previous "
710                  "declaration", decl);
711           *no_add_attrs = true;
712         }
713       break;
714
715     case FUNCTION_DECL:
716       error_at (DECL_SOURCE_LOCATION (decl),
717                 "address area attribute cannot be specified for "
718                 "functions");
719       *no_add_attrs = true;
720       break;
721
722     default:
723       warning (OPT_Wattributes, "%qE attribute ignored",
724                name);
725       *no_add_attrs = true;
726       break;
727     }
728
729   return NULL_TREE;
730 }
731
732 /* The section must have global and overlaid attributes.  */
733 #define SECTION_VMS_OVERLAY SECTION_MACH_DEP
734
735 /* Part of the low level implementation of DEC Ada pragma Common_Object which
736    enables the shared use of variables stored in overlaid linker areas
737    corresponding to the use of Fortran COMMON.  */
738
739 static tree
740 ia64_vms_common_object_attribute (tree *node, tree name, tree args,
741                                   int flags ATTRIBUTE_UNUSED,
742                                   bool *no_add_attrs)
743 {
744     tree decl = *node;
745     tree id, val;
746     if (! DECL_P (decl))
747       abort ();
748   
749     DECL_COMMON (decl) = 1;
750     id = TREE_VALUE (args);
751     if (TREE_CODE (id) == IDENTIFIER_NODE)
752       val = build_string (IDENTIFIER_LENGTH (id), IDENTIFIER_POINTER (id));
753     else if (TREE_CODE (id) == STRING_CST)
754       val = id;
755     else
756       {
757         warning (OPT_Wattributes,
758                  "%qE attribute requires a string constant argument", name);
759         *no_add_attrs = true;
760         return NULL_TREE;
761       }
762     DECL_SECTION_NAME (decl) = val;
763     return NULL_TREE;
764 }
765
766 /* Part of the low level implementation of DEC Ada pragma Common_Object.  */
767
768 void
769 ia64_vms_output_aligned_decl_common (FILE *file, tree decl, const char *name,
770                                      unsigned HOST_WIDE_INT size,
771                                      unsigned int align)
772 {
773   tree attr = DECL_ATTRIBUTES (decl);
774
775   /* As common_object attribute set DECL_SECTION_NAME check it before
776      looking up the attribute.  */
777   if (DECL_SECTION_NAME (decl) && attr)
778     attr = lookup_attribute ("common_object", attr);
779   else
780     attr = NULL_TREE;
781
782   if (!attr)
783     {
784       /*  Code from elfos.h.  */
785       fprintf (file, "%s", COMMON_ASM_OP);
786       assemble_name (file, name);
787       fprintf (file, ","HOST_WIDE_INT_PRINT_UNSIGNED",%u\n",
788                size, align / BITS_PER_UNIT);
789     }
790   else
791     {
792       ASM_OUTPUT_ALIGN (file, floor_log2 (align / BITS_PER_UNIT));
793       ASM_OUTPUT_LABEL (file, name);
794       ASM_OUTPUT_SKIP (file, size ? size : 1);
795     }
796 }
797
798 /* Definition of TARGET_ASM_NAMED_SECTION for VMS.  */
799
800 void
801 ia64_vms_elf_asm_named_section (const char *name, unsigned int flags,
802                                 tree decl)
803 {
804   if (!(flags & SECTION_VMS_OVERLAY))
805     {
806       default_elf_asm_named_section (name, flags, decl);
807       return;
808     }
809   if (flags != (SECTION_VMS_OVERLAY | SECTION_WRITE))
810     abort ();
811
812   if (flags & SECTION_DECLARED)
813     {
814       fprintf (asm_out_file, "\t.section\t%s\n", name);
815       return;
816     }
817
818   fprintf (asm_out_file, "\t.section\t%s,\"awgO\"\n", name);
819 }
820
821 static void
822 ia64_encode_addr_area (tree decl, rtx symbol)
823 {
824   int flags;
825
826   flags = SYMBOL_REF_FLAGS (symbol);
827   switch (ia64_get_addr_area (decl))
828     {
829     case ADDR_AREA_NORMAL: break;
830     case ADDR_AREA_SMALL: flags |= SYMBOL_FLAG_SMALL_ADDR; break;
831     default: gcc_unreachable ();
832     }
833   SYMBOL_REF_FLAGS (symbol) = flags;
834 }
835
836 static void
837 ia64_encode_section_info (tree decl, rtx rtl, int first)
838 {
839   default_encode_section_info (decl, rtl, first);
840
841   /* Careful not to prod global register variables.  */
842   if (TREE_CODE (decl) == VAR_DECL
843       && GET_CODE (DECL_RTL (decl)) == MEM
844       && GET_CODE (XEXP (DECL_RTL (decl), 0)) == SYMBOL_REF
845       && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)))
846     ia64_encode_addr_area (decl, XEXP (rtl, 0));
847 }
848 \f
849 /* Return 1 if the operands of a move are ok.  */
850
851 int
852 ia64_move_ok (rtx dst, rtx src)
853 {
854   /* If we're under init_recog_no_volatile, we'll not be able to use
855      memory_operand.  So check the code directly and don't worry about
856      the validity of the underlying address, which should have been
857      checked elsewhere anyway.  */
858   if (GET_CODE (dst) != MEM)
859     return 1;
860   if (GET_CODE (src) == MEM)
861     return 0;
862   if (register_operand (src, VOIDmode))
863     return 1;
864
865   /* Otherwise, this must be a constant, and that either 0 or 0.0 or 1.0.  */
866   if (INTEGRAL_MODE_P (GET_MODE (dst)))
867     return src == const0_rtx;
868   else
869     return satisfies_constraint_G (src);
870 }
871
872 /* Return 1 if the operands are ok for a floating point load pair.  */
873
874 int
875 ia64_load_pair_ok (rtx dst, rtx src)
876 {
877   if (GET_CODE (dst) != REG || !FP_REGNO_P (REGNO (dst)))
878     return 0;
879   if (GET_CODE (src) != MEM || MEM_VOLATILE_P (src))
880     return 0;
881   switch (GET_CODE (XEXP (src, 0)))
882     {
883     case REG:
884     case POST_INC:
885       break;
886     case POST_DEC:
887       return 0;
888     case POST_MODIFY:
889       {
890         rtx adjust = XEXP (XEXP (XEXP (src, 0), 1), 1);
891
892         if (GET_CODE (adjust) != CONST_INT
893             || INTVAL (adjust) != GET_MODE_SIZE (GET_MODE (src)))
894           return 0;
895       }
896       break;
897     default:
898       abort ();
899     }
900   return 1;
901 }
902
903 int
904 addp4_optimize_ok (rtx op1, rtx op2)
905 {
906   return (basereg_operand (op1, GET_MODE(op1)) !=
907           basereg_operand (op2, GET_MODE(op2)));
908 }
909
910 /* Check if OP is a mask suitable for use with SHIFT in a dep.z instruction.
911    Return the length of the field, or <= 0 on failure.  */
912
913 int
914 ia64_depz_field_mask (rtx rop, rtx rshift)
915 {
916   unsigned HOST_WIDE_INT op = INTVAL (rop);
917   unsigned HOST_WIDE_INT shift = INTVAL (rshift);
918
919   /* Get rid of the zero bits we're shifting in.  */
920   op >>= shift;
921
922   /* We must now have a solid block of 1's at bit 0.  */
923   return exact_log2 (op + 1);
924 }
925
926 /* Return the TLS model to use for ADDR.  */
927
928 static enum tls_model
929 tls_symbolic_operand_type (rtx addr)
930 {
931   enum tls_model tls_kind = TLS_MODEL_NONE;
932
933   if (GET_CODE (addr) == CONST)
934     {
935       if (GET_CODE (XEXP (addr, 0)) == PLUS
936           && GET_CODE (XEXP (XEXP (addr, 0), 0)) == SYMBOL_REF)
937         tls_kind = SYMBOL_REF_TLS_MODEL (XEXP (XEXP (addr, 0), 0));
938     }
939   else if (GET_CODE (addr) == SYMBOL_REF)
940     tls_kind = SYMBOL_REF_TLS_MODEL (addr);
941
942   return tls_kind;
943 }
944
945 /* Return true if X is a constant that is valid for some immediate
946    field in an instruction.  */
947
948 bool
949 ia64_legitimate_constant_p (rtx x)
950 {
951   switch (GET_CODE (x))
952     {
953     case CONST_INT:
954     case LABEL_REF:
955       return true;
956
957     case CONST_DOUBLE:
958       if (GET_MODE (x) == VOIDmode || GET_MODE (x) == SFmode
959           || GET_MODE (x) == DFmode)
960         return true;
961       return satisfies_constraint_G (x);
962
963     case CONST:
964     case SYMBOL_REF:
965       /* ??? Short term workaround for PR 28490.  We must make the code here
966          match the code in ia64_expand_move and move_operand, even though they
967          are both technically wrong.  */
968       if (tls_symbolic_operand_type (x) == 0)
969         {
970           HOST_WIDE_INT addend = 0;
971           rtx op = x;
972
973           if (GET_CODE (op) == CONST
974               && GET_CODE (XEXP (op, 0)) == PLUS
975               && GET_CODE (XEXP (XEXP (op, 0), 1)) == CONST_INT)
976             {
977               addend = INTVAL (XEXP (XEXP (op, 0), 1));
978               op = XEXP (XEXP (op, 0), 0);
979             }
980
981           if (any_offset_symbol_operand (op, GET_MODE (op))
982               || function_operand (op, GET_MODE (op)))
983             return true;
984           if (aligned_offset_symbol_operand (op, GET_MODE (op)))
985             return (addend & 0x3fff) == 0;
986           return false;
987         }
988       return false;
989
990     case CONST_VECTOR:
991       {
992         enum machine_mode mode = GET_MODE (x);
993
994         if (mode == V2SFmode)
995           return satisfies_constraint_Y (x);
996
997         return (GET_MODE_CLASS (mode) == MODE_VECTOR_INT
998                 && GET_MODE_SIZE (mode) <= 8);
999       }
1000
1001     default:
1002       return false;
1003     }
1004 }
1005
1006 /* Don't allow TLS addresses to get spilled to memory.  */
1007
1008 static bool
1009 ia64_cannot_force_const_mem (rtx x)
1010 {
1011   if (GET_MODE (x) == RFmode)
1012     return true;
1013   return tls_symbolic_operand_type (x) != 0;
1014 }
1015
1016 /* Expand a symbolic constant load.  */
1017
1018 bool
1019 ia64_expand_load_address (rtx dest, rtx src)
1020 {
1021   gcc_assert (GET_CODE (dest) == REG);
1022
1023   /* ILP32 mode still loads 64-bits of data from the GOT.  This avoids
1024      having to pointer-extend the value afterward.  Other forms of address
1025      computation below are also more natural to compute as 64-bit quantities.
1026      If we've been given an SImode destination register, change it.  */
1027   if (GET_MODE (dest) != Pmode)
1028     dest = gen_rtx_REG_offset (dest, Pmode, REGNO (dest),
1029                                byte_lowpart_offset (Pmode, GET_MODE (dest)));
1030
1031   if (TARGET_NO_PIC)
1032     return false;
1033   if (small_addr_symbolic_operand (src, VOIDmode))
1034     return false;
1035
1036   if (TARGET_AUTO_PIC)
1037     emit_insn (gen_load_gprel64 (dest, src));
1038   else if (GET_CODE (src) == SYMBOL_REF && SYMBOL_REF_FUNCTION_P (src))
1039     emit_insn (gen_load_fptr (dest, src));
1040   else if (sdata_symbolic_operand (src, VOIDmode))
1041     emit_insn (gen_load_gprel (dest, src));
1042   else
1043     {
1044       HOST_WIDE_INT addend = 0;
1045       rtx tmp;
1046
1047       /* We did split constant offsets in ia64_expand_move, and we did try
1048          to keep them split in move_operand, but we also allowed reload to
1049          rematerialize arbitrary constants rather than spill the value to
1050          the stack and reload it.  So we have to be prepared here to split
1051          them apart again.  */
1052       if (GET_CODE (src) == CONST)
1053         {
1054           HOST_WIDE_INT hi, lo;
1055
1056           hi = INTVAL (XEXP (XEXP (src, 0), 1));
1057           lo = ((hi & 0x3fff) ^ 0x2000) - 0x2000;
1058           hi = hi - lo;
1059
1060           if (lo != 0)
1061             {
1062               addend = lo;
1063               src = plus_constant (XEXP (XEXP (src, 0), 0), hi);
1064             }
1065         }
1066
1067       tmp = gen_rtx_HIGH (Pmode, src);
1068       tmp = gen_rtx_PLUS (Pmode, tmp, pic_offset_table_rtx);
1069       emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
1070
1071       tmp = gen_rtx_LO_SUM (Pmode, dest, src);
1072       emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
1073
1074       if (addend)
1075         {
1076           tmp = gen_rtx_PLUS (Pmode, dest, GEN_INT (addend));
1077           emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
1078         }
1079     }
1080
1081   return true;
1082 }
1083
1084 static GTY(()) rtx gen_tls_tga;
1085 static rtx
1086 gen_tls_get_addr (void)
1087 {
1088   if (!gen_tls_tga)
1089     gen_tls_tga = init_one_libfunc ("__tls_get_addr");
1090   return gen_tls_tga;
1091 }
1092
1093 static GTY(()) rtx thread_pointer_rtx;
1094 static rtx
1095 gen_thread_pointer (void)
1096 {
1097   if (!thread_pointer_rtx)
1098     thread_pointer_rtx = gen_rtx_REG (Pmode, 13);
1099   return thread_pointer_rtx;
1100 }
1101
1102 static rtx
1103 ia64_expand_tls_address (enum tls_model tls_kind, rtx op0, rtx op1,
1104                          rtx orig_op1, HOST_WIDE_INT addend)
1105 {
1106   rtx tga_op1, tga_op2, tga_ret, tga_eqv, tmp, insns;
1107   rtx orig_op0 = op0;
1108   HOST_WIDE_INT addend_lo, addend_hi;
1109
1110   switch (tls_kind)
1111     {
1112     case TLS_MODEL_GLOBAL_DYNAMIC:
1113       start_sequence ();
1114
1115       tga_op1 = gen_reg_rtx (Pmode);
1116       emit_insn (gen_load_dtpmod (tga_op1, op1));
1117
1118       tga_op2 = gen_reg_rtx (Pmode);
1119       emit_insn (gen_load_dtprel (tga_op2, op1));
1120
1121       tga_ret = emit_library_call_value (gen_tls_get_addr (), NULL_RTX,
1122                                          LCT_CONST, Pmode, 2, tga_op1,
1123                                          Pmode, tga_op2, Pmode);
1124
1125       insns = get_insns ();
1126       end_sequence ();
1127
1128       if (GET_MODE (op0) != Pmode)
1129         op0 = tga_ret;
1130       emit_libcall_block (insns, op0, tga_ret, op1);
1131       break;
1132
1133     case TLS_MODEL_LOCAL_DYNAMIC:
1134       /* ??? This isn't the completely proper way to do local-dynamic
1135          If the call to __tls_get_addr is used only by a single symbol,
1136          then we should (somehow) move the dtprel to the second arg
1137          to avoid the extra add.  */
1138       start_sequence ();
1139
1140       tga_op1 = gen_reg_rtx (Pmode);
1141       emit_insn (gen_load_dtpmod (tga_op1, op1));
1142
1143       tga_op2 = const0_rtx;
1144
1145       tga_ret = emit_library_call_value (gen_tls_get_addr (), NULL_RTX,
1146                                          LCT_CONST, Pmode, 2, tga_op1,
1147                                          Pmode, tga_op2, Pmode);
1148
1149       insns = get_insns ();
1150       end_sequence ();
1151
1152       tga_eqv = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx),
1153                                 UNSPEC_LD_BASE);
1154       tmp = gen_reg_rtx (Pmode);
1155       emit_libcall_block (insns, tmp, tga_ret, tga_eqv);
1156
1157       if (!register_operand (op0, Pmode))
1158         op0 = gen_reg_rtx (Pmode);
1159       if (TARGET_TLS64)
1160         {
1161           emit_insn (gen_load_dtprel (op0, op1));
1162           emit_insn (gen_adddi3 (op0, tmp, op0));
1163         }
1164       else
1165         emit_insn (gen_add_dtprel (op0, op1, tmp));
1166       break;
1167
1168     case TLS_MODEL_INITIAL_EXEC:
1169       addend_lo = ((addend & 0x3fff) ^ 0x2000) - 0x2000;
1170       addend_hi = addend - addend_lo;
1171
1172       op1 = plus_constant (op1, addend_hi);
1173       addend = addend_lo;
1174
1175       tmp = gen_reg_rtx (Pmode);
1176       emit_insn (gen_load_tprel (tmp, op1));
1177
1178       if (!register_operand (op0, Pmode))
1179         op0 = gen_reg_rtx (Pmode);
1180       emit_insn (gen_adddi3 (op0, tmp, gen_thread_pointer ()));
1181       break;
1182
1183     case TLS_MODEL_LOCAL_EXEC:
1184       if (!register_operand (op0, Pmode))
1185         op0 = gen_reg_rtx (Pmode);
1186
1187       op1 = orig_op1;
1188       addend = 0;
1189       if (TARGET_TLS64)
1190         {
1191           emit_insn (gen_load_tprel (op0, op1));
1192           emit_insn (gen_adddi3 (op0, op0, gen_thread_pointer ()));
1193         }
1194       else
1195         emit_insn (gen_add_tprel (op0, op1, gen_thread_pointer ()));
1196       break;
1197
1198     default:
1199       gcc_unreachable ();
1200     }
1201
1202   if (addend)
1203     op0 = expand_simple_binop (Pmode, PLUS, op0, GEN_INT (addend),
1204                                orig_op0, 1, OPTAB_DIRECT);
1205   if (orig_op0 == op0)
1206     return NULL_RTX;
1207   if (GET_MODE (orig_op0) == Pmode)
1208     return op0;
1209   return gen_lowpart (GET_MODE (orig_op0), op0);
1210 }
1211
1212 rtx
1213 ia64_expand_move (rtx op0, rtx op1)
1214 {
1215   enum machine_mode mode = GET_MODE (op0);
1216
1217   if (!reload_in_progress && !reload_completed && !ia64_move_ok (op0, op1))
1218     op1 = force_reg (mode, op1);
1219
1220   if ((mode == Pmode || mode == ptr_mode) && symbolic_operand (op1, VOIDmode))
1221     {
1222       HOST_WIDE_INT addend = 0;
1223       enum tls_model tls_kind;
1224       rtx sym = op1;
1225
1226       if (GET_CODE (op1) == CONST
1227           && GET_CODE (XEXP (op1, 0)) == PLUS
1228           && GET_CODE (XEXP (XEXP (op1, 0), 1)) == CONST_INT)
1229         {
1230           addend = INTVAL (XEXP (XEXP (op1, 0), 1));
1231           sym = XEXP (XEXP (op1, 0), 0);
1232         }
1233
1234       tls_kind = tls_symbolic_operand_type (sym);
1235       if (tls_kind)
1236         return ia64_expand_tls_address (tls_kind, op0, sym, op1, addend);
1237
1238       if (any_offset_symbol_operand (sym, mode))
1239         addend = 0;
1240       else if (aligned_offset_symbol_operand (sym, mode))
1241         {
1242           HOST_WIDE_INT addend_lo, addend_hi;
1243               
1244           addend_lo = ((addend & 0x3fff) ^ 0x2000) - 0x2000;
1245           addend_hi = addend - addend_lo;
1246
1247           if (addend_lo != 0)
1248             {
1249               op1 = plus_constant (sym, addend_hi);
1250               addend = addend_lo;
1251             }
1252           else
1253             addend = 0;
1254         }
1255       else
1256         op1 = sym;
1257
1258       if (reload_completed)
1259         {
1260           /* We really should have taken care of this offset earlier.  */
1261           gcc_assert (addend == 0);
1262           if (ia64_expand_load_address (op0, op1))
1263             return NULL_RTX;
1264         }
1265
1266       if (addend)
1267         {
1268           rtx subtarget = !can_create_pseudo_p () ? op0 : gen_reg_rtx (mode);
1269
1270           emit_insn (gen_rtx_SET (VOIDmode, subtarget, op1));
1271
1272           op1 = expand_simple_binop (mode, PLUS, subtarget,
1273                                      GEN_INT (addend), op0, 1, OPTAB_DIRECT);
1274           if (op0 == op1)
1275             return NULL_RTX;
1276         }
1277     }
1278
1279   return op1;
1280 }
1281
1282 /* Split a move from OP1 to OP0 conditional on COND.  */
1283
1284 void
1285 ia64_emit_cond_move (rtx op0, rtx op1, rtx cond)
1286 {
1287   rtx insn, first = get_last_insn ();
1288
1289   emit_move_insn (op0, op1);
1290
1291   for (insn = get_last_insn (); insn != first; insn = PREV_INSN (insn))
1292     if (INSN_P (insn))
1293       PATTERN (insn) = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (cond),
1294                                           PATTERN (insn));
1295 }
1296
1297 /* Split a post-reload TImode or TFmode reference into two DImode
1298    components.  This is made extra difficult by the fact that we do
1299    not get any scratch registers to work with, because reload cannot
1300    be prevented from giving us a scratch that overlaps the register
1301    pair involved.  So instead, when addressing memory, we tweak the
1302    pointer register up and back down with POST_INCs.  Or up and not
1303    back down when we can get away with it.
1304
1305    REVERSED is true when the loads must be done in reversed order
1306    (high word first) for correctness.  DEAD is true when the pointer
1307    dies with the second insn we generate and therefore the second
1308    address must not carry a postmodify.
1309
1310    May return an insn which is to be emitted after the moves.  */
1311
1312 static rtx
1313 ia64_split_tmode (rtx out[2], rtx in, bool reversed, bool dead)
1314 {
1315   rtx fixup = 0;
1316
1317   switch (GET_CODE (in))
1318     {
1319     case REG:
1320       out[reversed] = gen_rtx_REG (DImode, REGNO (in));
1321       out[!reversed] = gen_rtx_REG (DImode, REGNO (in) + 1);
1322       break;
1323
1324     case CONST_INT:
1325     case CONST_DOUBLE:
1326       /* Cannot occur reversed.  */
1327       gcc_assert (!reversed);
1328       
1329       if (GET_MODE (in) != TFmode)
1330         split_double (in, &out[0], &out[1]);
1331       else
1332         /* split_double does not understand how to split a TFmode
1333            quantity into a pair of DImode constants.  */
1334         {
1335           REAL_VALUE_TYPE r;
1336           unsigned HOST_WIDE_INT p[2];
1337           long l[4];  /* TFmode is 128 bits */
1338
1339           REAL_VALUE_FROM_CONST_DOUBLE (r, in);
1340           real_to_target (l, &r, TFmode);
1341
1342           if (FLOAT_WORDS_BIG_ENDIAN)
1343             {
1344               p[0] = (((unsigned HOST_WIDE_INT) l[0]) << 32) + l[1];
1345               p[1] = (((unsigned HOST_WIDE_INT) l[2]) << 32) + l[3];
1346             }
1347           else
1348             {
1349               p[0] = (((unsigned HOST_WIDE_INT) l[1]) << 32) + l[0];
1350               p[1] = (((unsigned HOST_WIDE_INT) l[3]) << 32) + l[2];
1351             }
1352           out[0] = GEN_INT (p[0]);
1353           out[1] = GEN_INT (p[1]);
1354         }
1355       break;
1356
1357     case MEM:
1358       {
1359         rtx base = XEXP (in, 0);
1360         rtx offset;
1361
1362         switch (GET_CODE (base))
1363           {
1364           case REG:
1365             if (!reversed)
1366               {
1367                 out[0] = adjust_automodify_address
1368                   (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1369                 out[1] = adjust_automodify_address
1370                   (in, DImode, dead ? 0 : gen_rtx_POST_DEC (Pmode, base), 8);
1371               }
1372             else
1373               {
1374                 /* Reversal requires a pre-increment, which can only
1375                    be done as a separate insn.  */
1376                 emit_insn (gen_adddi3 (base, base, GEN_INT (8)));
1377                 out[0] = adjust_automodify_address
1378                   (in, DImode, gen_rtx_POST_DEC (Pmode, base), 8);
1379                 out[1] = adjust_address (in, DImode, 0);
1380               }
1381             break;
1382
1383           case POST_INC:
1384             gcc_assert (!reversed && !dead);
1385             
1386             /* Just do the increment in two steps.  */
1387             out[0] = adjust_automodify_address (in, DImode, 0, 0);
1388             out[1] = adjust_automodify_address (in, DImode, 0, 8);
1389             break;
1390
1391           case POST_DEC:
1392             gcc_assert (!reversed && !dead);
1393             
1394             /* Add 8, subtract 24.  */
1395             base = XEXP (base, 0);
1396             out[0] = adjust_automodify_address
1397               (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1398             out[1] = adjust_automodify_address
1399               (in, DImode,
1400                gen_rtx_POST_MODIFY (Pmode, base, plus_constant (base, -24)),
1401                8);
1402             break;
1403
1404           case POST_MODIFY:
1405             gcc_assert (!reversed && !dead);
1406
1407             /* Extract and adjust the modification.  This case is
1408                trickier than the others, because we might have an
1409                index register, or we might have a combined offset that
1410                doesn't fit a signed 9-bit displacement field.  We can
1411                assume the incoming expression is already legitimate.  */
1412             offset = XEXP (base, 1);
1413             base = XEXP (base, 0);
1414
1415             out[0] = adjust_automodify_address
1416               (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1417
1418             if (GET_CODE (XEXP (offset, 1)) == REG)
1419               {
1420                 /* Can't adjust the postmodify to match.  Emit the
1421                    original, then a separate addition insn.  */
1422                 out[1] = adjust_automodify_address (in, DImode, 0, 8);
1423                 fixup = gen_adddi3 (base, base, GEN_INT (-8));
1424               }
1425             else
1426               {
1427                 gcc_assert (GET_CODE (XEXP (offset, 1)) == CONST_INT);
1428                 if (INTVAL (XEXP (offset, 1)) < -256 + 8)
1429                   {
1430                     /* Again the postmodify cannot be made to match,
1431                        but in this case it's more efficient to get rid
1432                        of the postmodify entirely and fix up with an
1433                        add insn.  */
1434                     out[1] = adjust_automodify_address (in, DImode, base, 8);
1435                     fixup = gen_adddi3
1436                       (base, base, GEN_INT (INTVAL (XEXP (offset, 1)) - 8));
1437                   }
1438                 else
1439                   {
1440                     /* Combined offset still fits in the displacement field.
1441                        (We cannot overflow it at the high end.)  */
1442                     out[1] = adjust_automodify_address
1443                       (in, DImode, gen_rtx_POST_MODIFY
1444                        (Pmode, base, gen_rtx_PLUS
1445                         (Pmode, base,
1446                          GEN_INT (INTVAL (XEXP (offset, 1)) - 8))),
1447                        8);
1448                   }
1449               }
1450             break;
1451
1452           default:
1453             gcc_unreachable ();
1454           }
1455         break;
1456       }
1457
1458     default:
1459       gcc_unreachable ();
1460     }
1461
1462   return fixup;
1463 }
1464
1465 /* Split a TImode or TFmode move instruction after reload.
1466    This is used by *movtf_internal and *movti_internal.  */
1467 void
1468 ia64_split_tmode_move (rtx operands[])
1469 {
1470   rtx in[2], out[2], insn;
1471   rtx fixup[2];
1472   bool dead = false;
1473   bool reversed = false;
1474
1475   /* It is possible for reload to decide to overwrite a pointer with
1476      the value it points to.  In that case we have to do the loads in
1477      the appropriate order so that the pointer is not destroyed too
1478      early.  Also we must not generate a postmodify for that second
1479      load, or rws_access_regno will die.  */
1480   if (GET_CODE (operands[1]) == MEM
1481       && reg_overlap_mentioned_p (operands[0], operands[1]))
1482     {
1483       rtx base = XEXP (operands[1], 0);
1484       while (GET_CODE (base) != REG)
1485         base = XEXP (base, 0);
1486
1487       if (REGNO (base) == REGNO (operands[0]))
1488         reversed = true;
1489       dead = true;
1490     }
1491   /* Another reason to do the moves in reversed order is if the first
1492      element of the target register pair is also the second element of
1493      the source register pair.  */
1494   if (GET_CODE (operands[0]) == REG && GET_CODE (operands[1]) == REG
1495       && REGNO (operands[0]) == REGNO (operands[1]) + 1)
1496     reversed = true;
1497
1498   fixup[0] = ia64_split_tmode (in, operands[1], reversed, dead);
1499   fixup[1] = ia64_split_tmode (out, operands[0], reversed, dead);
1500
1501 #define MAYBE_ADD_REG_INC_NOTE(INSN, EXP)                               \
1502   if (GET_CODE (EXP) == MEM                                             \
1503       && (GET_CODE (XEXP (EXP, 0)) == POST_MODIFY                       \
1504           || GET_CODE (XEXP (EXP, 0)) == POST_INC                       \
1505           || GET_CODE (XEXP (EXP, 0)) == POST_DEC))                     \
1506     add_reg_note (insn, REG_INC, XEXP (XEXP (EXP, 0), 0))
1507
1508   insn = emit_insn (gen_rtx_SET (VOIDmode, out[0], in[0]));
1509   MAYBE_ADD_REG_INC_NOTE (insn, in[0]);
1510   MAYBE_ADD_REG_INC_NOTE (insn, out[0]);
1511
1512   insn = emit_insn (gen_rtx_SET (VOIDmode, out[1], in[1]));
1513   MAYBE_ADD_REG_INC_NOTE (insn, in[1]);
1514   MAYBE_ADD_REG_INC_NOTE (insn, out[1]);
1515
1516   if (fixup[0])
1517     emit_insn (fixup[0]);
1518   if (fixup[1])
1519     emit_insn (fixup[1]);
1520
1521 #undef MAYBE_ADD_REG_INC_NOTE
1522 }
1523
1524 /* ??? Fixing GR->FR XFmode moves during reload is hard.  You need to go
1525    through memory plus an extra GR scratch register.  Except that you can
1526    either get the first from SECONDARY_MEMORY_NEEDED or the second from
1527    SECONDARY_RELOAD_CLASS, but not both.
1528
1529    We got into problems in the first place by allowing a construct like
1530    (subreg:XF (reg:TI)), which we got from a union containing a long double.
1531    This solution attempts to prevent this situation from occurring.  When
1532    we see something like the above, we spill the inner register to memory.  */
1533
1534 static rtx
1535 spill_xfmode_rfmode_operand (rtx in, int force, enum machine_mode mode)
1536 {
1537   if (GET_CODE (in) == SUBREG
1538       && GET_MODE (SUBREG_REG (in)) == TImode
1539       && GET_CODE (SUBREG_REG (in)) == REG)
1540     {
1541       rtx memt = assign_stack_temp (TImode, 16, 0);
1542       emit_move_insn (memt, SUBREG_REG (in));
1543       return adjust_address (memt, mode, 0);
1544     }
1545   else if (force && GET_CODE (in) == REG)
1546     {
1547       rtx memx = assign_stack_temp (mode, 16, 0);
1548       emit_move_insn (memx, in);
1549       return memx;
1550     }
1551   else
1552     return in;
1553 }
1554
1555 /* Expand the movxf or movrf pattern (MODE says which) with the given
1556    OPERANDS, returning true if the pattern should then invoke
1557    DONE.  */
1558
1559 bool
1560 ia64_expand_movxf_movrf (enum machine_mode mode, rtx operands[])
1561 {
1562   rtx op0 = operands[0];
1563
1564   if (GET_CODE (op0) == SUBREG)
1565     op0 = SUBREG_REG (op0);
1566
1567   /* We must support XFmode loads into general registers for stdarg/vararg,
1568      unprototyped calls, and a rare case where a long double is passed as
1569      an argument after a float HFA fills the FP registers.  We split them into
1570      DImode loads for convenience.  We also need to support XFmode stores
1571      for the last case.  This case does not happen for stdarg/vararg routines,
1572      because we do a block store to memory of unnamed arguments.  */
1573
1574   if (GET_CODE (op0) == REG && GR_REGNO_P (REGNO (op0)))
1575     {
1576       rtx out[2];
1577
1578       /* We're hoping to transform everything that deals with XFmode
1579          quantities and GR registers early in the compiler.  */
1580       gcc_assert (can_create_pseudo_p ());
1581
1582       /* Struct to register can just use TImode instead.  */
1583       if ((GET_CODE (operands[1]) == SUBREG
1584            && GET_MODE (SUBREG_REG (operands[1])) == TImode)
1585           || (GET_CODE (operands[1]) == REG
1586               && GR_REGNO_P (REGNO (operands[1]))))
1587         {
1588           rtx op1 = operands[1];
1589
1590           if (GET_CODE (op1) == SUBREG)
1591             op1 = SUBREG_REG (op1);
1592           else
1593             op1 = gen_rtx_REG (TImode, REGNO (op1));
1594
1595           emit_move_insn (gen_rtx_REG (TImode, REGNO (op0)), op1);
1596           return true;
1597         }
1598
1599       if (GET_CODE (operands[1]) == CONST_DOUBLE)
1600         {
1601           /* Don't word-swap when reading in the constant.  */
1602           emit_move_insn (gen_rtx_REG (DImode, REGNO (op0)),
1603                           operand_subword (operands[1], WORDS_BIG_ENDIAN,
1604                                            0, mode));
1605           emit_move_insn (gen_rtx_REG (DImode, REGNO (op0) + 1),
1606                           operand_subword (operands[1], !WORDS_BIG_ENDIAN,
1607                                            0, mode));
1608           return true;
1609         }
1610
1611       /* If the quantity is in a register not known to be GR, spill it.  */
1612       if (register_operand (operands[1], mode))
1613         operands[1] = spill_xfmode_rfmode_operand (operands[1], 1, mode);
1614
1615       gcc_assert (GET_CODE (operands[1]) == MEM);
1616
1617       /* Don't word-swap when reading in the value.  */
1618       out[0] = gen_rtx_REG (DImode, REGNO (op0));
1619       out[1] = gen_rtx_REG (DImode, REGNO (op0) + 1);
1620
1621       emit_move_insn (out[0], adjust_address (operands[1], DImode, 0));
1622       emit_move_insn (out[1], adjust_address (operands[1], DImode, 8));
1623       return true;
1624     }
1625
1626   if (GET_CODE (operands[1]) == REG && GR_REGNO_P (REGNO (operands[1])))
1627     {
1628       /* We're hoping to transform everything that deals with XFmode
1629          quantities and GR registers early in the compiler.  */
1630       gcc_assert (can_create_pseudo_p ());
1631
1632       /* Op0 can't be a GR_REG here, as that case is handled above.
1633          If op0 is a register, then we spill op1, so that we now have a
1634          MEM operand.  This requires creating an XFmode subreg of a TImode reg
1635          to force the spill.  */
1636       if (register_operand (operands[0], mode))
1637         {
1638           rtx op1 = gen_rtx_REG (TImode, REGNO (operands[1]));
1639           op1 = gen_rtx_SUBREG (mode, op1, 0);
1640           operands[1] = spill_xfmode_rfmode_operand (op1, 0, mode);
1641         }
1642
1643       else
1644         {
1645           rtx in[2];
1646
1647           gcc_assert (GET_CODE (operands[0]) == MEM);
1648
1649           /* Don't word-swap when writing out the value.  */
1650           in[0] = gen_rtx_REG (DImode, REGNO (operands[1]));
1651           in[1] = gen_rtx_REG (DImode, REGNO (operands[1]) + 1);
1652
1653           emit_move_insn (adjust_address (operands[0], DImode, 0), in[0]);
1654           emit_move_insn (adjust_address (operands[0], DImode, 8), in[1]);
1655           return true;
1656         }
1657     }
1658
1659   if (!reload_in_progress && !reload_completed)
1660     {
1661       operands[1] = spill_xfmode_rfmode_operand (operands[1], 0, mode);
1662
1663       if (GET_MODE (op0) == TImode && GET_CODE (op0) == REG)
1664         {
1665           rtx memt, memx, in = operands[1];
1666           if (CONSTANT_P (in))
1667             in = validize_mem (force_const_mem (mode, in));
1668           if (GET_CODE (in) == MEM)
1669             memt = adjust_address (in, TImode, 0);
1670           else
1671             {
1672               memt = assign_stack_temp (TImode, 16, 0);
1673               memx = adjust_address (memt, mode, 0);
1674               emit_move_insn (memx, in);
1675             }
1676           emit_move_insn (op0, memt);
1677           return true;
1678         }
1679
1680       if (!ia64_move_ok (operands[0], operands[1]))
1681         operands[1] = force_reg (mode, operands[1]);
1682     }
1683
1684   return false;
1685 }
1686
1687 /* Emit comparison instruction if necessary, replacing *EXPR, *OP0, *OP1
1688    with the expression that holds the compare result (in VOIDmode).  */
1689
1690 static GTY(()) rtx cmptf_libfunc;
1691
1692 void
1693 ia64_expand_compare (rtx *expr, rtx *op0, rtx *op1)
1694 {
1695   enum rtx_code code = GET_CODE (*expr);
1696   rtx cmp;
1697
1698   /* If we have a BImode input, then we already have a compare result, and
1699      do not need to emit another comparison.  */
1700   if (GET_MODE (*op0) == BImode)
1701     {
1702       gcc_assert ((code == NE || code == EQ) && *op1 == const0_rtx);
1703       cmp = *op0;
1704     }
1705   /* HPUX TFmode compare requires a library call to _U_Qfcmp, which takes a
1706      magic number as its third argument, that indicates what to do.
1707      The return value is an integer to be compared against zero.  */
1708   else if (TARGET_HPUX && GET_MODE (*op0) == TFmode)
1709     {
1710       enum qfcmp_magic {
1711         QCMP_INV = 1,   /* Raise FP_INVALID on SNaN as a side effect.  */
1712         QCMP_UNORD = 2,
1713         QCMP_EQ = 4,
1714         QCMP_LT = 8,
1715         QCMP_GT = 16
1716       };
1717       int magic;
1718       enum rtx_code ncode;
1719       rtx ret, insns;
1720       
1721       gcc_assert (cmptf_libfunc && GET_MODE (*op1) == TFmode);
1722       switch (code)
1723         {
1724           /* 1 = equal, 0 = not equal.  Equality operators do
1725              not raise FP_INVALID when given an SNaN operand.  */
1726         case EQ:        magic = QCMP_EQ;                  ncode = NE; break;
1727         case NE:        magic = QCMP_EQ;                  ncode = EQ; break;
1728           /* isunordered() from C99.  */
1729         case UNORDERED: magic = QCMP_UNORD;               ncode = NE; break;
1730         case ORDERED:   magic = QCMP_UNORD;               ncode = EQ; break;
1731           /* Relational operators raise FP_INVALID when given
1732              an SNaN operand.  */
1733         case LT:        magic = QCMP_LT        |QCMP_INV; ncode = NE; break;
1734         case LE:        magic = QCMP_LT|QCMP_EQ|QCMP_INV; ncode = NE; break;
1735         case GT:        magic = QCMP_GT        |QCMP_INV; ncode = NE; break;
1736         case GE:        magic = QCMP_GT|QCMP_EQ|QCMP_INV; ncode = NE; break;
1737           /* FUTURE: Implement UNEQ, UNLT, UNLE, UNGT, UNGE, LTGT.
1738              Expanders for buneq etc. weuld have to be added to ia64.md
1739              for this to be useful.  */
1740         default: gcc_unreachable ();
1741         }
1742
1743       start_sequence ();
1744
1745       ret = emit_library_call_value (cmptf_libfunc, 0, LCT_CONST, DImode, 3,
1746                                      *op0, TFmode, *op1, TFmode,
1747                                      GEN_INT (magic), DImode);
1748       cmp = gen_reg_rtx (BImode);
1749       emit_insn (gen_rtx_SET (VOIDmode, cmp,
1750                               gen_rtx_fmt_ee (ncode, BImode,
1751                                               ret, const0_rtx)));
1752
1753       insns = get_insns ();
1754       end_sequence ();
1755
1756       emit_libcall_block (insns, cmp, cmp,
1757                           gen_rtx_fmt_ee (code, BImode, *op0, *op1));
1758       code = NE;
1759     }
1760   else
1761     {
1762       cmp = gen_reg_rtx (BImode);
1763       emit_insn (gen_rtx_SET (VOIDmode, cmp,
1764                               gen_rtx_fmt_ee (code, BImode, *op0, *op1)));
1765       code = NE;
1766     }
1767
1768   *expr = gen_rtx_fmt_ee (code, VOIDmode, cmp, const0_rtx);
1769   *op0 = cmp;
1770   *op1 = const0_rtx;
1771 }
1772
1773 /* Generate an integral vector comparison.  Return true if the condition has
1774    been reversed, and so the sense of the comparison should be inverted.  */
1775
1776 static bool
1777 ia64_expand_vecint_compare (enum rtx_code code, enum machine_mode mode,
1778                             rtx dest, rtx op0, rtx op1)
1779 {
1780   bool negate = false;
1781   rtx x;
1782
1783   /* Canonicalize the comparison to EQ, GT, GTU.  */
1784   switch (code)
1785     {
1786     case EQ:
1787     case GT:
1788     case GTU:
1789       break;
1790
1791     case NE:
1792     case LE:
1793     case LEU:
1794       code = reverse_condition (code);
1795       negate = true;
1796       break;
1797
1798     case GE:
1799     case GEU:
1800       code = reverse_condition (code);
1801       negate = true;
1802       /* FALLTHRU */
1803
1804     case LT:
1805     case LTU:
1806       code = swap_condition (code);
1807       x = op0, op0 = op1, op1 = x;
1808       break;
1809
1810     default:
1811       gcc_unreachable ();
1812     }
1813
1814   /* Unsigned parallel compare is not supported by the hardware.  Play some
1815      tricks to turn this into a signed comparison against 0.  */
1816   if (code == GTU)
1817     {
1818       switch (mode)
1819         {
1820         case V2SImode:
1821           {
1822             rtx t1, t2, mask;
1823
1824             /* Subtract (-(INT MAX) - 1) from both operands to make
1825                them signed.  */
1826             mask = GEN_INT (0x80000000);
1827             mask = gen_rtx_CONST_VECTOR (V2SImode, gen_rtvec (2, mask, mask));
1828             mask = force_reg (mode, mask);
1829             t1 = gen_reg_rtx (mode);
1830             emit_insn (gen_subv2si3 (t1, op0, mask));
1831             t2 = gen_reg_rtx (mode);
1832             emit_insn (gen_subv2si3 (t2, op1, mask));
1833             op0 = t1;
1834             op1 = t2;
1835             code = GT;
1836           }
1837           break;
1838
1839         case V8QImode:
1840         case V4HImode:
1841           /* Perform a parallel unsigned saturating subtraction.  */
1842           x = gen_reg_rtx (mode);
1843           emit_insn (gen_rtx_SET (VOIDmode, x,
1844                                   gen_rtx_US_MINUS (mode, op0, op1)));
1845
1846           code = EQ;
1847           op0 = x;
1848           op1 = CONST0_RTX (mode);
1849           negate = !negate;
1850           break;
1851
1852         default:
1853           gcc_unreachable ();
1854         }
1855     }
1856
1857   x = gen_rtx_fmt_ee (code, mode, op0, op1);
1858   emit_insn (gen_rtx_SET (VOIDmode, dest, x));
1859
1860   return negate;
1861 }
1862
1863 /* Emit an integral vector conditional move.  */
1864
1865 void
1866 ia64_expand_vecint_cmov (rtx operands[])
1867 {
1868   enum machine_mode mode = GET_MODE (operands[0]);
1869   enum rtx_code code = GET_CODE (operands[3]);
1870   bool negate;
1871   rtx cmp, x, ot, of;
1872
1873   cmp = gen_reg_rtx (mode);
1874   negate = ia64_expand_vecint_compare (code, mode, cmp,
1875                                        operands[4], operands[5]);
1876
1877   ot = operands[1+negate];
1878   of = operands[2-negate];
1879
1880   if (ot == CONST0_RTX (mode))
1881     {
1882       if (of == CONST0_RTX (mode))
1883         {
1884           emit_move_insn (operands[0], ot);
1885           return;
1886         }
1887
1888       x = gen_rtx_NOT (mode, cmp);
1889       x = gen_rtx_AND (mode, x, of);
1890       emit_insn (gen_rtx_SET (VOIDmode, operands[0], x));
1891     }
1892   else if (of == CONST0_RTX (mode))
1893     {
1894       x = gen_rtx_AND (mode, cmp, ot);
1895       emit_insn (gen_rtx_SET (VOIDmode, operands[0], x));
1896     }
1897   else
1898     {
1899       rtx t, f;
1900
1901       t = gen_reg_rtx (mode);
1902       x = gen_rtx_AND (mode, cmp, operands[1+negate]);
1903       emit_insn (gen_rtx_SET (VOIDmode, t, x));
1904
1905       f = gen_reg_rtx (mode);
1906       x = gen_rtx_NOT (mode, cmp);
1907       x = gen_rtx_AND (mode, x, operands[2-negate]);
1908       emit_insn (gen_rtx_SET (VOIDmode, f, x));
1909
1910       x = gen_rtx_IOR (mode, t, f);
1911       emit_insn (gen_rtx_SET (VOIDmode, operands[0], x));
1912     }
1913 }
1914
1915 /* Emit an integral vector min or max operation.  Return true if all done.  */
1916
1917 bool
1918 ia64_expand_vecint_minmax (enum rtx_code code, enum machine_mode mode,
1919                            rtx operands[])
1920 {
1921   rtx xops[6];
1922
1923   /* These four combinations are supported directly.  */
1924   if (mode == V8QImode && (code == UMIN || code == UMAX))
1925     return false;
1926   if (mode == V4HImode && (code == SMIN || code == SMAX))
1927     return false;
1928
1929   /* This combination can be implemented with only saturating subtraction.  */
1930   if (mode == V4HImode && code == UMAX)
1931     {
1932       rtx x, tmp = gen_reg_rtx (mode);
1933
1934       x = gen_rtx_US_MINUS (mode, operands[1], operands[2]);
1935       emit_insn (gen_rtx_SET (VOIDmode, tmp, x));
1936
1937       emit_insn (gen_addv4hi3 (operands[0], tmp, operands[2]));
1938       return true;
1939     }
1940
1941   /* Everything else implemented via vector comparisons.  */
1942   xops[0] = operands[0];
1943   xops[4] = xops[1] = operands[1];
1944   xops[5] = xops[2] = operands[2];
1945
1946   switch (code)
1947     {
1948     case UMIN:
1949       code = LTU;
1950       break;
1951     case UMAX:
1952       code = GTU;
1953       break;
1954     case SMIN:
1955       code = LT;
1956       break;
1957     case SMAX:
1958       code = GT;
1959       break;
1960     default:
1961       gcc_unreachable ();
1962     }
1963   xops[3] = gen_rtx_fmt_ee (code, VOIDmode, operands[1], operands[2]);
1964
1965   ia64_expand_vecint_cmov (xops);
1966   return true;
1967 }
1968
1969 /* Emit an integral vector widening sum operations.  */
1970
1971 void
1972 ia64_expand_widen_sum (rtx operands[3], bool unsignedp)
1973 {
1974   rtx l, h, x, s;
1975   enum machine_mode wmode, mode;
1976   rtx (*unpack_l) (rtx, rtx, rtx);
1977   rtx (*unpack_h) (rtx, rtx, rtx);
1978   rtx (*plus) (rtx, rtx, rtx);
1979
1980   wmode = GET_MODE (operands[0]);
1981   mode = GET_MODE (operands[1]);
1982
1983   switch (mode)
1984     {
1985     case V8QImode:
1986       unpack_l = gen_unpack1_l;
1987       unpack_h = gen_unpack1_h;
1988       plus = gen_addv4hi3;
1989       break;
1990     case V4HImode:
1991       unpack_l = gen_unpack2_l;
1992       unpack_h = gen_unpack2_h;
1993       plus = gen_addv2si3;
1994       break;
1995     default:
1996       gcc_unreachable ();
1997     }
1998
1999   /* Fill in x with the sign extension of each element in op1.  */
2000   if (unsignedp)
2001     x = CONST0_RTX (mode);
2002   else
2003     {
2004       bool neg;
2005
2006       x = gen_reg_rtx (mode);
2007
2008       neg = ia64_expand_vecint_compare (LT, mode, x, operands[1],
2009                                         CONST0_RTX (mode));
2010       gcc_assert (!neg);
2011     }
2012
2013   l = gen_reg_rtx (wmode);
2014   h = gen_reg_rtx (wmode);
2015   s = gen_reg_rtx (wmode);
2016
2017   emit_insn (unpack_l (gen_lowpart (mode, l), operands[1], x));
2018   emit_insn (unpack_h (gen_lowpart (mode, h), operands[1], x));
2019   emit_insn (plus (s, l, operands[2]));
2020   emit_insn (plus (operands[0], h, s));
2021 }
2022
2023 /* Emit a signed or unsigned V8QI dot product operation.  */
2024
2025 void
2026 ia64_expand_dot_prod_v8qi (rtx operands[4], bool unsignedp)
2027 {
2028   rtx l1, l2, h1, h2, x1, x2, p1, p2, p3, p4, s1, s2, s3;
2029
2030   /* Fill in x1 and x2 with the sign extension of each element.  */
2031   if (unsignedp)
2032     x1 = x2 = CONST0_RTX (V8QImode);
2033   else
2034     {
2035       bool neg;
2036
2037       x1 = gen_reg_rtx (V8QImode);
2038       x2 = gen_reg_rtx (V8QImode);
2039
2040       neg = ia64_expand_vecint_compare (LT, V8QImode, x1, operands[1],
2041                                         CONST0_RTX (V8QImode));
2042       gcc_assert (!neg);
2043       neg = ia64_expand_vecint_compare (LT, V8QImode, x2, operands[2],
2044                                         CONST0_RTX (V8QImode));
2045       gcc_assert (!neg);
2046     }
2047
2048   l1 = gen_reg_rtx (V4HImode);
2049   l2 = gen_reg_rtx (V4HImode);
2050   h1 = gen_reg_rtx (V4HImode);
2051   h2 = gen_reg_rtx (V4HImode);
2052
2053   emit_insn (gen_unpack1_l (gen_lowpart (V8QImode, l1), operands[1], x1));
2054   emit_insn (gen_unpack1_l (gen_lowpart (V8QImode, l2), operands[2], x2));
2055   emit_insn (gen_unpack1_h (gen_lowpart (V8QImode, h1), operands[1], x1));
2056   emit_insn (gen_unpack1_h (gen_lowpart (V8QImode, h2), operands[2], x2));
2057
2058   p1 = gen_reg_rtx (V2SImode);
2059   p2 = gen_reg_rtx (V2SImode);
2060   p3 = gen_reg_rtx (V2SImode);
2061   p4 = gen_reg_rtx (V2SImode);
2062   emit_insn (gen_pmpy2_r (p1, l1, l2));
2063   emit_insn (gen_pmpy2_l (p2, l1, l2));
2064   emit_insn (gen_pmpy2_r (p3, h1, h2));
2065   emit_insn (gen_pmpy2_l (p4, h1, h2));
2066
2067   s1 = gen_reg_rtx (V2SImode);
2068   s2 = gen_reg_rtx (V2SImode);
2069   s3 = gen_reg_rtx (V2SImode);
2070   emit_insn (gen_addv2si3 (s1, p1, p2));
2071   emit_insn (gen_addv2si3 (s2, p3, p4));
2072   emit_insn (gen_addv2si3 (s3, s1, operands[3]));
2073   emit_insn (gen_addv2si3 (operands[0], s2, s3));
2074 }
2075
2076 /* Emit the appropriate sequence for a call.  */
2077
2078 void
2079 ia64_expand_call (rtx retval, rtx addr, rtx nextarg ATTRIBUTE_UNUSED,
2080                   int sibcall_p)
2081 {
2082   rtx insn, b0;
2083
2084   addr = XEXP (addr, 0);
2085   addr = convert_memory_address (DImode, addr);
2086   b0 = gen_rtx_REG (DImode, R_BR (0));
2087
2088   /* ??? Should do this for functions known to bind local too.  */
2089   if (TARGET_NO_PIC || TARGET_AUTO_PIC)
2090     {
2091       if (sibcall_p)
2092         insn = gen_sibcall_nogp (addr);
2093       else if (! retval)
2094         insn = gen_call_nogp (addr, b0);
2095       else
2096         insn = gen_call_value_nogp (retval, addr, b0);
2097       insn = emit_call_insn (insn);
2098     }
2099   else
2100     {
2101       if (sibcall_p)
2102         insn = gen_sibcall_gp (addr);
2103       else if (! retval)
2104         insn = gen_call_gp (addr, b0);
2105       else
2106         insn = gen_call_value_gp (retval, addr, b0);
2107       insn = emit_call_insn (insn);
2108
2109       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
2110     }
2111
2112   if (sibcall_p)
2113     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), b0);
2114
2115   if (TARGET_ABI_OPEN_VMS)
2116     use_reg (&CALL_INSN_FUNCTION_USAGE (insn),
2117              gen_rtx_REG (DImode, GR_REG (25)));
2118 }
2119
2120 static void
2121 reg_emitted (enum ia64_frame_regs r)
2122 {
2123   if (emitted_frame_related_regs[r] == 0)
2124     emitted_frame_related_regs[r] = current_frame_info.r[r];
2125   else
2126     gcc_assert (emitted_frame_related_regs[r] == current_frame_info.r[r]);
2127 }
2128
2129 static int
2130 get_reg (enum ia64_frame_regs r)
2131 {
2132   reg_emitted (r);
2133   return current_frame_info.r[r];
2134 }
2135
2136 static bool
2137 is_emitted (int regno)
2138 {
2139   unsigned int r;
2140
2141   for (r = reg_fp; r < number_of_ia64_frame_regs; r++)
2142     if (emitted_frame_related_regs[r] == regno)
2143       return true;
2144   return false;
2145 }
2146
2147 void
2148 ia64_reload_gp (void)
2149 {
2150   rtx tmp;
2151
2152   if (current_frame_info.r[reg_save_gp])
2153     {
2154       tmp = gen_rtx_REG (DImode, get_reg (reg_save_gp));
2155     }
2156   else
2157     {
2158       HOST_WIDE_INT offset;
2159       rtx offset_r;
2160
2161       offset = (current_frame_info.spill_cfa_off
2162                 + current_frame_info.spill_size);
2163       if (frame_pointer_needed)
2164         {
2165           tmp = hard_frame_pointer_rtx;
2166           offset = -offset;
2167         }
2168       else
2169         {
2170           tmp = stack_pointer_rtx;
2171           offset = current_frame_info.total_size - offset;
2172         }
2173
2174       offset_r = GEN_INT (offset);
2175       if (satisfies_constraint_I (offset_r))
2176         emit_insn (gen_adddi3 (pic_offset_table_rtx, tmp, offset_r));
2177       else
2178         {
2179           emit_move_insn (pic_offset_table_rtx, offset_r);
2180           emit_insn (gen_adddi3 (pic_offset_table_rtx,
2181                                  pic_offset_table_rtx, tmp));
2182         }
2183
2184       tmp = gen_rtx_MEM (DImode, pic_offset_table_rtx);
2185     }
2186
2187   emit_move_insn (pic_offset_table_rtx, tmp);
2188 }
2189
2190 void
2191 ia64_split_call (rtx retval, rtx addr, rtx retaddr, rtx scratch_r,
2192                  rtx scratch_b, int noreturn_p, int sibcall_p)
2193 {
2194   rtx insn;
2195   bool is_desc = false;
2196
2197   /* If we find we're calling through a register, then we're actually
2198      calling through a descriptor, so load up the values.  */
2199   if (REG_P (addr) && GR_REGNO_P (REGNO (addr)))
2200     {
2201       rtx tmp;
2202       bool addr_dead_p;
2203
2204       /* ??? We are currently constrained to *not* use peep2, because
2205          we can legitimately change the global lifetime of the GP
2206          (in the form of killing where previously live).  This is
2207          because a call through a descriptor doesn't use the previous
2208          value of the GP, while a direct call does, and we do not
2209          commit to either form until the split here.
2210
2211          That said, this means that we lack precise life info for
2212          whether ADDR is dead after this call.  This is not terribly
2213          important, since we can fix things up essentially for free
2214          with the POST_DEC below, but it's nice to not use it when we
2215          can immediately tell it's not necessary.  */
2216       addr_dead_p = ((noreturn_p || sibcall_p
2217                       || TEST_HARD_REG_BIT (regs_invalidated_by_call,
2218                                             REGNO (addr)))
2219                      && !FUNCTION_ARG_REGNO_P (REGNO (addr)));
2220
2221       /* Load the code address into scratch_b.  */
2222       tmp = gen_rtx_POST_INC (Pmode, addr);
2223       tmp = gen_rtx_MEM (Pmode, tmp);
2224       emit_move_insn (scratch_r, tmp);
2225       emit_move_insn (scratch_b, scratch_r);
2226
2227       /* Load the GP address.  If ADDR is not dead here, then we must
2228          revert the change made above via the POST_INCREMENT.  */
2229       if (!addr_dead_p)
2230         tmp = gen_rtx_POST_DEC (Pmode, addr);
2231       else
2232         tmp = addr;
2233       tmp = gen_rtx_MEM (Pmode, tmp);
2234       emit_move_insn (pic_offset_table_rtx, tmp);
2235
2236       is_desc = true;
2237       addr = scratch_b;
2238     }
2239
2240   if (sibcall_p)
2241     insn = gen_sibcall_nogp (addr);
2242   else if (retval)
2243     insn = gen_call_value_nogp (retval, addr, retaddr);
2244   else
2245     insn = gen_call_nogp (addr, retaddr);
2246   emit_call_insn (insn);
2247
2248   if ((!TARGET_CONST_GP || is_desc) && !noreturn_p && !sibcall_p)
2249     ia64_reload_gp ();
2250 }
2251
2252 /* Expand an atomic operation.  We want to perform MEM <CODE>= VAL atomically.
2253
2254    This differs from the generic code in that we know about the zero-extending
2255    properties of cmpxchg, and the zero-extending requirements of ar.ccv.  We
2256    also know that ld.acq+cmpxchg.rel equals a full barrier.
2257
2258    The loop we want to generate looks like
2259
2260         cmp_reg = mem;
2261       label:
2262         old_reg = cmp_reg;
2263         new_reg = cmp_reg op val;
2264         cmp_reg = compare-and-swap(mem, old_reg, new_reg)
2265         if (cmp_reg != old_reg)
2266           goto label;
2267
2268    Note that we only do the plain load from memory once.  Subsequent
2269    iterations use the value loaded by the compare-and-swap pattern.  */
2270
2271 void
2272 ia64_expand_atomic_op (enum rtx_code code, rtx mem, rtx val,
2273                        rtx old_dst, rtx new_dst)
2274 {
2275   enum machine_mode mode = GET_MODE (mem);
2276   rtx old_reg, new_reg, cmp_reg, ar_ccv, label;
2277   enum insn_code icode;
2278
2279   /* Special case for using fetchadd.  */
2280   if ((mode == SImode || mode == DImode)
2281       && (code == PLUS || code == MINUS)
2282       && fetchadd_operand (val, mode))
2283     {
2284       if (code == MINUS)
2285         val = GEN_INT (-INTVAL (val));
2286
2287       if (!old_dst)
2288         old_dst = gen_reg_rtx (mode);
2289
2290       emit_insn (gen_memory_barrier ());
2291
2292       if (mode == SImode)
2293         icode = CODE_FOR_fetchadd_acq_si;
2294       else
2295         icode = CODE_FOR_fetchadd_acq_di;
2296       emit_insn (GEN_FCN (icode) (old_dst, mem, val));
2297
2298       if (new_dst)
2299         {
2300           new_reg = expand_simple_binop (mode, PLUS, old_dst, val, new_dst,
2301                                          true, OPTAB_WIDEN);
2302           if (new_reg != new_dst)
2303             emit_move_insn (new_dst, new_reg);
2304         }
2305       return;
2306     }
2307
2308   /* Because of the volatile mem read, we get an ld.acq, which is the
2309      front half of the full barrier.  The end half is the cmpxchg.rel.  */
2310   gcc_assert (MEM_VOLATILE_P (mem));
2311
2312   old_reg = gen_reg_rtx (DImode);
2313   cmp_reg = gen_reg_rtx (DImode);
2314   label = gen_label_rtx ();
2315
2316   if (mode != DImode)
2317     {
2318       val = simplify_gen_subreg (DImode, val, mode, 0);
2319       emit_insn (gen_extend_insn (cmp_reg, mem, DImode, mode, 1));
2320     }
2321   else
2322     emit_move_insn (cmp_reg, mem);
2323
2324   emit_label (label);
2325
2326   ar_ccv = gen_rtx_REG (DImode, AR_CCV_REGNUM);
2327   emit_move_insn (old_reg, cmp_reg);
2328   emit_move_insn (ar_ccv, cmp_reg);
2329
2330   if (old_dst)
2331     emit_move_insn (old_dst, gen_lowpart (mode, cmp_reg));
2332
2333   new_reg = cmp_reg;
2334   if (code == NOT)
2335     {
2336       new_reg = expand_simple_binop (DImode, AND, new_reg, val, NULL_RTX,
2337                                      true, OPTAB_DIRECT);
2338       new_reg = expand_simple_unop (DImode, code, new_reg, NULL_RTX, true);
2339     }
2340   else
2341     new_reg = expand_simple_binop (DImode, code, new_reg, val, NULL_RTX,
2342                                    true, OPTAB_DIRECT);
2343
2344   if (mode != DImode)
2345     new_reg = gen_lowpart (mode, new_reg);
2346   if (new_dst)
2347     emit_move_insn (new_dst, new_reg);
2348
2349   switch (mode)
2350     {
2351     case QImode:  icode = CODE_FOR_cmpxchg_rel_qi;  break;
2352     case HImode:  icode = CODE_FOR_cmpxchg_rel_hi;  break;
2353     case SImode:  icode = CODE_FOR_cmpxchg_rel_si;  break;
2354     case DImode:  icode = CODE_FOR_cmpxchg_rel_di;  break;
2355     default:
2356       gcc_unreachable ();
2357     }
2358
2359   emit_insn (GEN_FCN (icode) (cmp_reg, mem, ar_ccv, new_reg));
2360
2361   emit_cmp_and_jump_insns (cmp_reg, old_reg, NE, NULL, DImode, true, label);
2362 }
2363 \f
2364 /* Begin the assembly file.  */
2365
2366 static void
2367 ia64_file_start (void)
2368 {
2369   /* Variable tracking should be run after all optimizations which change order
2370      of insns.  It also needs a valid CFG.  This can't be done in
2371      ia64_option_override, because flag_var_tracking is finalized after
2372      that.  */
2373   ia64_flag_var_tracking = flag_var_tracking;
2374   flag_var_tracking = 0;
2375
2376   default_file_start ();
2377   emit_safe_across_calls ();
2378 }
2379
2380 void
2381 emit_safe_across_calls (void)
2382 {
2383   unsigned int rs, re;
2384   int out_state;
2385
2386   rs = 1;
2387   out_state = 0;
2388   while (1)
2389     {
2390       while (rs < 64 && call_used_regs[PR_REG (rs)])
2391         rs++;
2392       if (rs >= 64)
2393         break;
2394       for (re = rs + 1; re < 64 && ! call_used_regs[PR_REG (re)]; re++)
2395         continue;
2396       if (out_state == 0)
2397         {
2398           fputs ("\t.pred.safe_across_calls ", asm_out_file);
2399           out_state = 1;
2400         }
2401       else
2402         fputc (',', asm_out_file);
2403       if (re == rs + 1)
2404         fprintf (asm_out_file, "p%u", rs);
2405       else
2406         fprintf (asm_out_file, "p%u-p%u", rs, re - 1);
2407       rs = re + 1;
2408     }
2409   if (out_state)
2410     fputc ('\n', asm_out_file);
2411 }
2412
2413 /* Globalize a declaration.  */
2414
2415 static void
2416 ia64_globalize_decl_name (FILE * stream, tree decl)
2417 {
2418   const char *name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
2419   tree version_attr = lookup_attribute ("version_id", DECL_ATTRIBUTES (decl));
2420   if (version_attr)
2421     {
2422       tree v = TREE_VALUE (TREE_VALUE (version_attr));
2423       const char *p = TREE_STRING_POINTER (v);
2424       fprintf (stream, "\t.alias %s#, \"%s{%s}\"\n", name, name, p);
2425     }
2426   targetm.asm_out.globalize_label (stream, name);
2427   if (TREE_CODE (decl) == FUNCTION_DECL)
2428     ASM_OUTPUT_TYPE_DIRECTIVE (stream, name, "function");
2429 }
2430
2431 /* Helper function for ia64_compute_frame_size: find an appropriate general
2432    register to spill some special register to.  SPECIAL_SPILL_MASK contains
2433    bits in GR0 to GR31 that have already been allocated by this routine.
2434    TRY_LOCALS is true if we should attempt to locate a local regnum.  */
2435
2436 static int
2437 find_gr_spill (enum ia64_frame_regs r, int try_locals)
2438 {
2439   int regno;
2440
2441   if (emitted_frame_related_regs[r] != 0)
2442     {
2443       regno = emitted_frame_related_regs[r];
2444       if (regno >= LOC_REG (0) && regno < LOC_REG (80 - frame_pointer_needed)
2445           && current_frame_info.n_local_regs < regno - LOC_REG (0) + 1)
2446         current_frame_info.n_local_regs = regno - LOC_REG (0) + 1;
2447       else if (current_function_is_leaf 
2448                && regno >= GR_REG (1) && regno <= GR_REG (31))
2449         current_frame_info.gr_used_mask |= 1 << regno;
2450
2451       return regno;
2452     }
2453
2454   /* If this is a leaf function, first try an otherwise unused
2455      call-clobbered register.  */
2456   if (current_function_is_leaf)
2457     {
2458       for (regno = GR_REG (1); regno <= GR_REG (31); regno++)
2459         if (! df_regs_ever_live_p (regno)
2460             && call_used_regs[regno]
2461             && ! fixed_regs[regno]
2462             && ! global_regs[regno]
2463             && ((current_frame_info.gr_used_mask >> regno) & 1) == 0
2464             && ! is_emitted (regno))
2465           {
2466             current_frame_info.gr_used_mask |= 1 << regno;
2467             return regno;
2468           }
2469     }
2470
2471   if (try_locals)
2472     {
2473       regno = current_frame_info.n_local_regs;
2474       /* If there is a frame pointer, then we can't use loc79, because
2475          that is HARD_FRAME_POINTER_REGNUM.  In particular, see the
2476          reg_name switching code in ia64_expand_prologue.  */
2477       while (regno < (80 - frame_pointer_needed))
2478         if (! is_emitted (LOC_REG (regno++)))
2479           {
2480             current_frame_info.n_local_regs = regno;
2481             return LOC_REG (regno - 1);
2482           }
2483     }
2484
2485   /* Failed to find a general register to spill to.  Must use stack.  */
2486   return 0;
2487 }
2488
2489 /* In order to make for nice schedules, we try to allocate every temporary
2490    to a different register.  We must of course stay away from call-saved,
2491    fixed, and global registers.  We must also stay away from registers
2492    allocated in current_frame_info.gr_used_mask, since those include regs
2493    used all through the prologue.
2494
2495    Any register allocated here must be used immediately.  The idea is to
2496    aid scheduling, not to solve data flow problems.  */
2497
2498 static int last_scratch_gr_reg;
2499
2500 static int
2501 next_scratch_gr_reg (void)
2502 {
2503   int i, regno;
2504
2505   for (i = 0; i < 32; ++i)
2506     {
2507       regno = (last_scratch_gr_reg + i + 1) & 31;
2508       if (call_used_regs[regno]
2509           && ! fixed_regs[regno]
2510           && ! global_regs[regno]
2511           && ((current_frame_info.gr_used_mask >> regno) & 1) == 0)
2512         {
2513           last_scratch_gr_reg = regno;
2514           return regno;
2515         }
2516     }
2517
2518   /* There must be _something_ available.  */
2519   gcc_unreachable ();
2520 }
2521
2522 /* Helper function for ia64_compute_frame_size, called through
2523    diddle_return_value.  Mark REG in current_frame_info.gr_used_mask.  */
2524
2525 static void
2526 mark_reg_gr_used_mask (rtx reg, void *data ATTRIBUTE_UNUSED)
2527 {
2528   unsigned int regno = REGNO (reg);
2529   if (regno < 32)
2530     {
2531       unsigned int i, n = hard_regno_nregs[regno][GET_MODE (reg)];
2532       for (i = 0; i < n; ++i)
2533         current_frame_info.gr_used_mask |= 1 << (regno + i);
2534     }
2535 }
2536
2537
2538 /* Returns the number of bytes offset between the frame pointer and the stack
2539    pointer for the current function.  SIZE is the number of bytes of space
2540    needed for local variables.  */
2541
2542 static void
2543 ia64_compute_frame_size (HOST_WIDE_INT size)
2544 {
2545   HOST_WIDE_INT total_size;
2546   HOST_WIDE_INT spill_size = 0;
2547   HOST_WIDE_INT extra_spill_size = 0;
2548   HOST_WIDE_INT pretend_args_size;
2549   HARD_REG_SET mask;
2550   int n_spilled = 0;
2551   int spilled_gr_p = 0;
2552   int spilled_fr_p = 0;
2553   unsigned int regno;
2554   int min_regno;
2555   int max_regno;
2556   int i;
2557
2558   if (current_frame_info.initialized)
2559     return;
2560
2561   memset (&current_frame_info, 0, sizeof current_frame_info);
2562   CLEAR_HARD_REG_SET (mask);
2563
2564   /* Don't allocate scratches to the return register.  */
2565   diddle_return_value (mark_reg_gr_used_mask, NULL);
2566
2567   /* Don't allocate scratches to the EH scratch registers.  */
2568   if (cfun->machine->ia64_eh_epilogue_sp)
2569     mark_reg_gr_used_mask (cfun->machine->ia64_eh_epilogue_sp, NULL);
2570   if (cfun->machine->ia64_eh_epilogue_bsp)
2571     mark_reg_gr_used_mask (cfun->machine->ia64_eh_epilogue_bsp, NULL);
2572
2573   /* Find the size of the register stack frame.  We have only 80 local
2574      registers, because we reserve 8 for the inputs and 8 for the
2575      outputs.  */
2576
2577   /* Skip HARD_FRAME_POINTER_REGNUM (loc79) when frame_pointer_needed,
2578      since we'll be adjusting that down later.  */
2579   regno = LOC_REG (78) + ! frame_pointer_needed;
2580   for (; regno >= LOC_REG (0); regno--)
2581     if (df_regs_ever_live_p (regno) && !is_emitted (regno))
2582       break;
2583   current_frame_info.n_local_regs = regno - LOC_REG (0) + 1;
2584
2585   /* For functions marked with the syscall_linkage attribute, we must mark
2586      all eight input registers as in use, so that locals aren't visible to
2587      the caller.  */
2588
2589   if (cfun->machine->n_varargs > 0
2590       || lookup_attribute ("syscall_linkage",
2591                            TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))))
2592     current_frame_info.n_input_regs = 8;
2593   else
2594     {
2595       for (regno = IN_REG (7); regno >= IN_REG (0); regno--)
2596         if (df_regs_ever_live_p (regno))
2597           break;
2598       current_frame_info.n_input_regs = regno - IN_REG (0) + 1;
2599     }
2600
2601   for (regno = OUT_REG (7); regno >= OUT_REG (0); regno--)
2602     if (df_regs_ever_live_p (regno))
2603       break;
2604   i = regno - OUT_REG (0) + 1;
2605
2606 #ifndef PROFILE_HOOK
2607   /* When -p profiling, we need one output register for the mcount argument.
2608      Likewise for -a profiling for the bb_init_func argument.  For -ax
2609      profiling, we need two output registers for the two bb_init_trace_func
2610      arguments.  */
2611   if (crtl->profile)
2612     i = MAX (i, 1);
2613 #endif
2614   current_frame_info.n_output_regs = i;
2615
2616   /* ??? No rotating register support yet.  */
2617   current_frame_info.n_rotate_regs = 0;
2618
2619   /* Discover which registers need spilling, and how much room that
2620      will take.  Begin with floating point and general registers,
2621      which will always wind up on the stack.  */
2622
2623   for (regno = FR_REG (2); regno <= FR_REG (127); regno++)
2624     if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
2625       {
2626         SET_HARD_REG_BIT (mask, regno);
2627         spill_size += 16;
2628         n_spilled += 1;
2629         spilled_fr_p = 1;
2630       }
2631
2632   for (regno = GR_REG (1); regno <= GR_REG (31); regno++)
2633     if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
2634       {
2635         SET_HARD_REG_BIT (mask, regno);
2636         spill_size += 8;
2637         n_spilled += 1;
2638         spilled_gr_p = 1;
2639       }
2640
2641   for (regno = BR_REG (1); regno <= BR_REG (7); regno++)
2642     if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
2643       {
2644         SET_HARD_REG_BIT (mask, regno);
2645         spill_size += 8;
2646         n_spilled += 1;
2647       }
2648
2649   /* Now come all special registers that might get saved in other
2650      general registers.  */
2651
2652   if (frame_pointer_needed)
2653     {
2654       current_frame_info.r[reg_fp] = find_gr_spill (reg_fp, 1);
2655       /* If we did not get a register, then we take LOC79.  This is guaranteed
2656          to be free, even if regs_ever_live is already set, because this is
2657          HARD_FRAME_POINTER_REGNUM.  This requires incrementing n_local_regs,
2658          as we don't count loc79 above.  */
2659       if (current_frame_info.r[reg_fp] == 0)
2660         {
2661           current_frame_info.r[reg_fp] = LOC_REG (79);
2662           current_frame_info.n_local_regs = LOC_REG (79) - LOC_REG (0) + 1;
2663         }
2664     }
2665
2666   if (! current_function_is_leaf)
2667     {
2668       /* Emit a save of BR0 if we call other functions.  Do this even
2669          if this function doesn't return, as EH depends on this to be
2670          able to unwind the stack.  */
2671       SET_HARD_REG_BIT (mask, BR_REG (0));
2672
2673       current_frame_info.r[reg_save_b0] = find_gr_spill (reg_save_b0, 1);
2674       if (current_frame_info.r[reg_save_b0] == 0)
2675         {
2676           extra_spill_size += 8;
2677           n_spilled += 1;
2678         }
2679
2680       /* Similarly for ar.pfs.  */
2681       SET_HARD_REG_BIT (mask, AR_PFS_REGNUM);
2682       current_frame_info.r[reg_save_ar_pfs] = find_gr_spill (reg_save_ar_pfs, 1);
2683       if (current_frame_info.r[reg_save_ar_pfs] == 0)
2684         {
2685           extra_spill_size += 8;
2686           n_spilled += 1;
2687         }
2688
2689       /* Similarly for gp.  Note that if we're calling setjmp, the stacked
2690          registers are clobbered, so we fall back to the stack.  */
2691       current_frame_info.r[reg_save_gp]
2692         = (cfun->calls_setjmp ? 0 : find_gr_spill (reg_save_gp, 1));
2693       if (current_frame_info.r[reg_save_gp] == 0)
2694         {
2695           SET_HARD_REG_BIT (mask, GR_REG (1));
2696           spill_size += 8;
2697           n_spilled += 1;
2698         }
2699     }
2700   else
2701     {
2702       if (df_regs_ever_live_p (BR_REG (0)) && ! call_used_regs[BR_REG (0)])
2703         {
2704           SET_HARD_REG_BIT (mask, BR_REG (0));
2705           extra_spill_size += 8;
2706           n_spilled += 1;
2707         }
2708
2709       if (df_regs_ever_live_p (AR_PFS_REGNUM))
2710         {
2711           SET_HARD_REG_BIT (mask, AR_PFS_REGNUM);
2712           current_frame_info.r[reg_save_ar_pfs] 
2713             = find_gr_spill (reg_save_ar_pfs, 1);
2714           if (current_frame_info.r[reg_save_ar_pfs] == 0)
2715             {
2716               extra_spill_size += 8;
2717               n_spilled += 1;
2718             }
2719         }
2720     }
2721
2722   /* Unwind descriptor hackery: things are most efficient if we allocate
2723      consecutive GR save registers for RP, PFS, FP in that order. However,
2724      it is absolutely critical that FP get the only hard register that's
2725      guaranteed to be free, so we allocated it first.  If all three did
2726      happen to be allocated hard regs, and are consecutive, rearrange them
2727      into the preferred order now.  
2728      
2729      If we have already emitted code for any of those registers,
2730      then it's already too late to change.  */
2731   min_regno = MIN (current_frame_info.r[reg_fp],
2732                    MIN (current_frame_info.r[reg_save_b0],
2733                         current_frame_info.r[reg_save_ar_pfs]));
2734   max_regno = MAX (current_frame_info.r[reg_fp],
2735                    MAX (current_frame_info.r[reg_save_b0],
2736                         current_frame_info.r[reg_save_ar_pfs]));
2737   if (min_regno > 0
2738       && min_regno + 2 == max_regno
2739       && (current_frame_info.r[reg_fp] == min_regno + 1
2740           || current_frame_info.r[reg_save_b0] == min_regno + 1
2741           || current_frame_info.r[reg_save_ar_pfs] == min_regno + 1)
2742       && (emitted_frame_related_regs[reg_save_b0] == 0
2743           || emitted_frame_related_regs[reg_save_b0] == min_regno)
2744       && (emitted_frame_related_regs[reg_save_ar_pfs] == 0
2745           || emitted_frame_related_regs[reg_save_ar_pfs] == min_regno + 1)
2746       && (emitted_frame_related_regs[reg_fp] == 0
2747           || emitted_frame_related_regs[reg_fp] == min_regno + 2))
2748     {
2749       current_frame_info.r[reg_save_b0] = min_regno;
2750       current_frame_info.r[reg_save_ar_pfs] = min_regno + 1;
2751       current_frame_info.r[reg_fp] = min_regno + 2;
2752     }
2753
2754   /* See if we need to store the predicate register block.  */
2755   for (regno = PR_REG (0); regno <= PR_REG (63); regno++)
2756     if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
2757       break;
2758   if (regno <= PR_REG (63))
2759     {
2760       SET_HARD_REG_BIT (mask, PR_REG (0));
2761       current_frame_info.r[reg_save_pr] = find_gr_spill (reg_save_pr, 1);
2762       if (current_frame_info.r[reg_save_pr] == 0)
2763         {
2764           extra_spill_size += 8;
2765           n_spilled += 1;
2766         }
2767
2768       /* ??? Mark them all as used so that register renaming and such
2769          are free to use them.  */
2770       for (regno = PR_REG (0); regno <= PR_REG (63); regno++)
2771         df_set_regs_ever_live (regno, true);
2772     }
2773
2774   /* If we're forced to use st8.spill, we're forced to save and restore
2775      ar.unat as well.  The check for existing liveness allows inline asm
2776      to touch ar.unat.  */
2777   if (spilled_gr_p || cfun->machine->n_varargs
2778       || df_regs_ever_live_p (AR_UNAT_REGNUM))
2779     {
2780       df_set_regs_ever_live (AR_UNAT_REGNUM, true);
2781       SET_HARD_REG_BIT (mask, AR_UNAT_REGNUM);
2782       current_frame_info.r[reg_save_ar_unat] 
2783         = find_gr_spill (reg_save_ar_unat, spill_size == 0);
2784       if (current_frame_info.r[reg_save_ar_unat] == 0)
2785         {
2786           extra_spill_size += 8;
2787           n_spilled += 1;
2788         }
2789     }
2790
2791   if (df_regs_ever_live_p (AR_LC_REGNUM))
2792     {
2793       SET_HARD_REG_BIT (mask, AR_LC_REGNUM);
2794       current_frame_info.r[reg_save_ar_lc] 
2795         = find_gr_spill (reg_save_ar_lc, spill_size == 0);
2796       if (current_frame_info.r[reg_save_ar_lc] == 0)
2797         {
2798           extra_spill_size += 8;
2799           n_spilled += 1;
2800         }
2801     }
2802
2803   /* If we have an odd number of words of pretend arguments written to
2804      the stack, then the FR save area will be unaligned.  We round the
2805      size of this area up to keep things 16 byte aligned.  */
2806   if (spilled_fr_p)
2807     pretend_args_size = IA64_STACK_ALIGN (crtl->args.pretend_args_size);
2808   else
2809     pretend_args_size = crtl->args.pretend_args_size;
2810
2811   total_size = (spill_size + extra_spill_size + size + pretend_args_size
2812                 + crtl->outgoing_args_size);
2813   total_size = IA64_STACK_ALIGN (total_size);
2814
2815   /* We always use the 16-byte scratch area provided by the caller, but
2816      if we are a leaf function, there's no one to which we need to provide
2817      a scratch area.  */
2818   if (current_function_is_leaf)
2819     total_size = MAX (0, total_size - 16);
2820
2821   current_frame_info.total_size = total_size;
2822   current_frame_info.spill_cfa_off = pretend_args_size - 16;
2823   current_frame_info.spill_size = spill_size;
2824   current_frame_info.extra_spill_size = extra_spill_size;
2825   COPY_HARD_REG_SET (current_frame_info.mask, mask);
2826   current_frame_info.n_spilled = n_spilled;
2827   current_frame_info.initialized = reload_completed;
2828 }
2829
2830 /* Worker function for TARGET_CAN_ELIMINATE.  */
2831
2832 bool
2833 ia64_can_eliminate (const int from ATTRIBUTE_UNUSED, const int to)
2834 {
2835   return (to == BR_REG (0) ? current_function_is_leaf : true);
2836 }
2837
2838 /* Compute the initial difference between the specified pair of registers.  */
2839
2840 HOST_WIDE_INT
2841 ia64_initial_elimination_offset (int from, int to)
2842 {
2843   HOST_WIDE_INT offset;
2844
2845   ia64_compute_frame_size (get_frame_size ());
2846   switch (from)
2847     {
2848     case FRAME_POINTER_REGNUM:
2849       switch (to)
2850         {
2851         case HARD_FRAME_POINTER_REGNUM:
2852           if (current_function_is_leaf)
2853             offset = -current_frame_info.total_size;
2854           else
2855             offset = -(current_frame_info.total_size
2856                        - crtl->outgoing_args_size - 16);
2857           break;
2858
2859         case STACK_POINTER_REGNUM:
2860           if (current_function_is_leaf)
2861             offset = 0;
2862           else
2863             offset = 16 + crtl->outgoing_args_size;
2864           break;
2865
2866         default:
2867           gcc_unreachable ();
2868         }
2869       break;
2870
2871     case ARG_POINTER_REGNUM:
2872       /* Arguments start above the 16 byte save area, unless stdarg
2873          in which case we store through the 16 byte save area.  */
2874       switch (to)
2875         {
2876         case HARD_FRAME_POINTER_REGNUM:
2877           offset = 16 - crtl->args.pretend_args_size;
2878           break;
2879
2880         case STACK_POINTER_REGNUM:
2881           offset = (current_frame_info.total_size
2882                     + 16 - crtl->args.pretend_args_size);
2883           break;
2884
2885         default:
2886           gcc_unreachable ();
2887         }
2888       break;
2889
2890     default:
2891       gcc_unreachable ();
2892     }
2893
2894   return offset;
2895 }
2896
2897 /* If there are more than a trivial number of register spills, we use
2898    two interleaved iterators so that we can get two memory references
2899    per insn group.
2900
2901    In order to simplify things in the prologue and epilogue expanders,
2902    we use helper functions to fix up the memory references after the
2903    fact with the appropriate offsets to a POST_MODIFY memory mode.
2904    The following data structure tracks the state of the two iterators
2905    while insns are being emitted.  */
2906
2907 struct spill_fill_data
2908 {
2909   rtx init_after;               /* point at which to emit initializations */
2910   rtx init_reg[2];              /* initial base register */
2911   rtx iter_reg[2];              /* the iterator registers */
2912   rtx *prev_addr[2];            /* address of last memory use */
2913   rtx prev_insn[2];             /* the insn corresponding to prev_addr */
2914   HOST_WIDE_INT prev_off[2];    /* last offset */
2915   int n_iter;                   /* number of iterators in use */
2916   int next_iter;                /* next iterator to use */
2917   unsigned int save_gr_used_mask;
2918 };
2919
2920 static struct spill_fill_data spill_fill_data;
2921
2922 static void
2923 setup_spill_pointers (int n_spills, rtx init_reg, HOST_WIDE_INT cfa_off)
2924 {
2925   int i;
2926
2927   spill_fill_data.init_after = get_last_insn ();
2928   spill_fill_data.init_reg[0] = init_reg;
2929   spill_fill_data.init_reg[1] = init_reg;
2930   spill_fill_data.prev_addr[0] = NULL;
2931   spill_fill_data.prev_addr[1] = NULL;
2932   spill_fill_data.prev_insn[0] = NULL;
2933   spill_fill_data.prev_insn[1] = NULL;
2934   spill_fill_data.prev_off[0] = cfa_off;
2935   spill_fill_data.prev_off[1] = cfa_off;
2936   spill_fill_data.next_iter = 0;
2937   spill_fill_data.save_gr_used_mask = current_frame_info.gr_used_mask;
2938
2939   spill_fill_data.n_iter = 1 + (n_spills > 2);
2940   for (i = 0; i < spill_fill_data.n_iter; ++i)
2941     {
2942       int regno = next_scratch_gr_reg ();
2943       spill_fill_data.iter_reg[i] = gen_rtx_REG (DImode, regno);
2944       current_frame_info.gr_used_mask |= 1 << regno;
2945     }
2946 }
2947
2948 static void
2949 finish_spill_pointers (void)
2950 {
2951   current_frame_info.gr_used_mask = spill_fill_data.save_gr_used_mask;
2952 }
2953
2954 static rtx
2955 spill_restore_mem (rtx reg, HOST_WIDE_INT cfa_off)
2956 {
2957   int iter = spill_fill_data.next_iter;
2958   HOST_WIDE_INT disp = spill_fill_data.prev_off[iter] - cfa_off;
2959   rtx disp_rtx = GEN_INT (disp);
2960   rtx mem;
2961
2962   if (spill_fill_data.prev_addr[iter])
2963     {
2964       if (satisfies_constraint_N (disp_rtx))
2965         {
2966           *spill_fill_data.prev_addr[iter]
2967             = gen_rtx_POST_MODIFY (DImode, spill_fill_data.iter_reg[iter],
2968                                    gen_rtx_PLUS (DImode,
2969                                                  spill_fill_data.iter_reg[iter],
2970                                                  disp_rtx));
2971           add_reg_note (spill_fill_data.prev_insn[iter],
2972                         REG_INC, spill_fill_data.iter_reg[iter]);
2973         }
2974       else
2975         {
2976           /* ??? Could use register post_modify for loads.  */
2977           if (!satisfies_constraint_I (disp_rtx))
2978             {
2979               rtx tmp = gen_rtx_REG (DImode, next_scratch_gr_reg ());
2980               emit_move_insn (tmp, disp_rtx);
2981               disp_rtx = tmp;
2982             }
2983           emit_insn (gen_adddi3 (spill_fill_data.iter_reg[iter],
2984                                  spill_fill_data.iter_reg[iter], disp_rtx));
2985         }
2986     }
2987   /* Micro-optimization: if we've created a frame pointer, it's at
2988      CFA 0, which may allow the real iterator to be initialized lower,
2989      slightly increasing parallelism.  Also, if there are few saves
2990      it may eliminate the iterator entirely.  */
2991   else if (disp == 0
2992            && spill_fill_data.init_reg[iter] == stack_pointer_rtx
2993            && frame_pointer_needed)
2994     {
2995       mem = gen_rtx_MEM (GET_MODE (reg), hard_frame_pointer_rtx);
2996       set_mem_alias_set (mem, get_varargs_alias_set ());
2997       return mem;
2998     }
2999   else
3000     {
3001       rtx seq, insn;
3002
3003       if (disp == 0)
3004         seq = gen_movdi (spill_fill_data.iter_reg[iter],
3005                          spill_fill_data.init_reg[iter]);
3006       else
3007         {
3008           start_sequence ();
3009
3010           if (!satisfies_constraint_I (disp_rtx))
3011             {
3012               rtx tmp = gen_rtx_REG (DImode, next_scratch_gr_reg ());
3013               emit_move_insn (tmp, disp_rtx);
3014               disp_rtx = tmp;
3015             }
3016
3017           emit_insn (gen_adddi3 (spill_fill_data.iter_reg[iter],
3018                                  spill_fill_data.init_reg[iter],
3019                                  disp_rtx));
3020
3021           seq = get_insns ();
3022           end_sequence ();
3023         }
3024
3025       /* Careful for being the first insn in a sequence.  */
3026       if (spill_fill_data.init_after)
3027         insn = emit_insn_after (seq, spill_fill_data.init_after);
3028       else
3029         {
3030           rtx first = get_insns ();
3031           if (first)
3032             insn = emit_insn_before (seq, first);
3033           else
3034             insn = emit_insn (seq);
3035         }
3036       spill_fill_data.init_after = insn;
3037     }
3038
3039   mem = gen_rtx_MEM (GET_MODE (reg), spill_fill_data.iter_reg[iter]);
3040
3041   /* ??? Not all of the spills are for varargs, but some of them are.
3042      The rest of the spills belong in an alias set of their own.  But
3043      it doesn't actually hurt to include them here.  */
3044   set_mem_alias_set (mem, get_varargs_alias_set ());
3045
3046   spill_fill_data.prev_addr[iter] = &XEXP (mem, 0);
3047   spill_fill_data.prev_off[iter] = cfa_off;
3048
3049   if (++iter >= spill_fill_data.n_iter)
3050     iter = 0;
3051   spill_fill_data.next_iter = iter;
3052
3053   return mem;
3054 }
3055
3056 static void
3057 do_spill (rtx (*move_fn) (rtx, rtx, rtx), rtx reg, HOST_WIDE_INT cfa_off,
3058           rtx frame_reg)
3059 {
3060   int iter = spill_fill_data.next_iter;
3061   rtx mem, insn;
3062
3063   mem = spill_restore_mem (reg, cfa_off);
3064   insn = emit_insn ((*move_fn) (mem, reg, GEN_INT (cfa_off)));
3065   spill_fill_data.prev_insn[iter] = insn;
3066
3067   if (frame_reg)
3068     {
3069       rtx base;
3070       HOST_WIDE_INT off;
3071
3072       RTX_FRAME_RELATED_P (insn) = 1;
3073
3074       /* Don't even pretend that the unwind code can intuit its way
3075          through a pair of interleaved post_modify iterators.  Just
3076          provide the correct answer.  */
3077
3078       if (frame_pointer_needed)
3079         {
3080           base = hard_frame_pointer_rtx;
3081           off = - cfa_off;
3082         }
3083       else
3084         {
3085           base = stack_pointer_rtx;
3086           off = current_frame_info.total_size - cfa_off;
3087         }
3088
3089       add_reg_note (insn, REG_CFA_OFFSET,
3090                     gen_rtx_SET (VOIDmode,
3091                                  gen_rtx_MEM (GET_MODE (reg),
3092                                               plus_constant (base, off)),
3093                                  frame_reg));
3094     }
3095 }
3096
3097 static void
3098 do_restore (rtx (*move_fn) (rtx, rtx, rtx), rtx reg, HOST_WIDE_INT cfa_off)
3099 {
3100   int iter = spill_fill_data.next_iter;
3101   rtx insn;
3102
3103   insn = emit_insn ((*move_fn) (reg, spill_restore_mem (reg, cfa_off),
3104                                 GEN_INT (cfa_off)));
3105   spill_fill_data.prev_insn[iter] = insn;
3106 }
3107
3108 /* Wrapper functions that discards the CONST_INT spill offset.  These
3109    exist so that we can give gr_spill/gr_fill the offset they need and
3110    use a consistent function interface.  */
3111
3112 static rtx
3113 gen_movdi_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
3114 {
3115   return gen_movdi (dest, src);
3116 }
3117
3118 static rtx
3119 gen_fr_spill_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
3120 {
3121   return gen_fr_spill (dest, src);
3122 }
3123
3124 static rtx
3125 gen_fr_restore_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
3126 {
3127   return gen_fr_restore (dest, src);
3128 }
3129
3130 /* Called after register allocation to add any instructions needed for the
3131    prologue.  Using a prologue insn is favored compared to putting all of the
3132    instructions in output_function_prologue(), since it allows the scheduler
3133    to intermix instructions with the saves of the caller saved registers.  In
3134    some cases, it might be necessary to emit a barrier instruction as the last
3135    insn to prevent such scheduling.
3136
3137    Also any insns generated here should have RTX_FRAME_RELATED_P(insn) = 1
3138    so that the debug info generation code can handle them properly.
3139
3140    The register save area is layed out like so:
3141    cfa+16
3142         [ varargs spill area ]
3143         [ fr register spill area ]
3144         [ br register spill area ]
3145         [ ar register spill area ]
3146         [ pr register spill area ]
3147         [ gr register spill area ] */
3148
3149 /* ??? Get inefficient code when the frame size is larger than can fit in an
3150    adds instruction.  */
3151
3152 void
3153 ia64_expand_prologue (void)
3154 {
3155   rtx insn, ar_pfs_save_reg, ar_unat_save_reg;
3156   int i, epilogue_p, regno, alt_regno, cfa_off, n_varargs;
3157   rtx reg, alt_reg;
3158
3159   ia64_compute_frame_size (get_frame_size ());
3160   last_scratch_gr_reg = 15;
3161
3162   if (flag_stack_usage)
3163     current_function_static_stack_size = current_frame_info.total_size;
3164
3165   if (dump_file) 
3166     {
3167       fprintf (dump_file, "ia64 frame related registers "
3168                "recorded in current_frame_info.r[]:\n");
3169 #define PRINTREG(a) if (current_frame_info.r[a]) \
3170         fprintf(dump_file, "%s = %d\n", #a, current_frame_info.r[a])
3171       PRINTREG(reg_fp);
3172       PRINTREG(reg_save_b0);
3173       PRINTREG(reg_save_pr);
3174       PRINTREG(reg_save_ar_pfs);
3175       PRINTREG(reg_save_ar_unat);
3176       PRINTREG(reg_save_ar_lc);
3177       PRINTREG(reg_save_gp);
3178 #undef PRINTREG
3179     }
3180
3181   /* If there is no epilogue, then we don't need some prologue insns.
3182      We need to avoid emitting the dead prologue insns, because flow
3183      will complain about them.  */
3184   if (optimize)
3185     {
3186       edge e;
3187       edge_iterator ei;
3188
3189       FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
3190         if ((e->flags & EDGE_FAKE) == 0
3191             && (e->flags & EDGE_FALLTHRU) != 0)
3192           break;
3193       epilogue_p = (e != NULL);
3194     }
3195   else
3196     epilogue_p = 1;
3197
3198   /* Set the local, input, and output register names.  We need to do this
3199      for GNU libc, which creates crti.S/crtn.S by splitting initfini.c in
3200      half.  If we use in/loc/out register names, then we get assembler errors
3201      in crtn.S because there is no alloc insn or regstk directive in there.  */
3202   if (! TARGET_REG_NAMES)
3203     {
3204       int inputs = current_frame_info.n_input_regs;
3205       int locals = current_frame_info.n_local_regs;
3206       int outputs = current_frame_info.n_output_regs;
3207
3208       for (i = 0; i < inputs; i++)
3209         reg_names[IN_REG (i)] = ia64_reg_numbers[i];
3210       for (i = 0; i < locals; i++)
3211         reg_names[LOC_REG (i)] = ia64_reg_numbers[inputs + i];
3212       for (i = 0; i < outputs; i++)
3213         reg_names[OUT_REG (i)] = ia64_reg_numbers[inputs + locals + i];
3214     }
3215
3216   /* Set the frame pointer register name.  The regnum is logically loc79,
3217      but of course we'll not have allocated that many locals.  Rather than
3218      worrying about renumbering the existing rtxs, we adjust the name.  */
3219   /* ??? This code means that we can never use one local register when
3220      there is a frame pointer.  loc79 gets wasted in this case, as it is
3221      renamed to a register that will never be used.  See also the try_locals
3222      code in find_gr_spill.  */
3223   if (current_frame_info.r[reg_fp])
3224     {
3225       const char *tmp = reg_names[HARD_FRAME_POINTER_REGNUM];
3226       reg_names[HARD_FRAME_POINTER_REGNUM]
3227         = reg_names[current_frame_info.r[reg_fp]];
3228       reg_names[current_frame_info.r[reg_fp]] = tmp;
3229     }
3230
3231   /* We don't need an alloc instruction if we've used no outputs or locals.  */
3232   if (current_frame_info.n_local_regs == 0
3233       && current_frame_info.n_output_regs == 0
3234       && current_frame_info.n_input_regs <= crtl->args.info.int_regs
3235       && !TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM))
3236     {
3237       /* If there is no alloc, but there are input registers used, then we
3238          need a .regstk directive.  */
3239       current_frame_info.need_regstk = (TARGET_REG_NAMES != 0);
3240       ar_pfs_save_reg = NULL_RTX;
3241     }
3242   else
3243     {
3244       current_frame_info.need_regstk = 0;
3245
3246       if (current_frame_info.r[reg_save_ar_pfs])
3247         {
3248           regno = current_frame_info.r[reg_save_ar_pfs];
3249           reg_emitted (reg_save_ar_pfs);
3250         }
3251       else
3252         regno = next_scratch_gr_reg ();
3253       ar_pfs_save_reg = gen_rtx_REG (DImode, regno);
3254
3255       insn = emit_insn (gen_alloc (ar_pfs_save_reg,
3256                                    GEN_INT (current_frame_info.n_input_regs),
3257                                    GEN_INT (current_frame_info.n_local_regs),
3258                                    GEN_INT (current_frame_info.n_output_regs),
3259                                    GEN_INT (current_frame_info.n_rotate_regs)));
3260       RTX_FRAME_RELATED_P (insn) = (current_frame_info.r[reg_save_ar_pfs] != 0);
3261     }
3262
3263   /* Set up frame pointer, stack pointer, and spill iterators.  */
3264
3265   n_varargs = cfun->machine->n_varargs;
3266   setup_spill_pointers (current_frame_info.n_spilled + n_varargs,
3267                         stack_pointer_rtx, 0);
3268
3269   if (frame_pointer_needed)
3270     {
3271       insn = emit_move_insn (hard_frame_pointer_rtx, stack_pointer_rtx);
3272       RTX_FRAME_RELATED_P (insn) = 1;
3273
3274       /* Force the unwind info to recognize this as defining a new CFA,
3275          rather than some temp register setup.  */
3276       add_reg_note (insn, REG_CFA_ADJUST_CFA, NULL_RTX);
3277     }
3278
3279   if (current_frame_info.total_size != 0)
3280     {
3281       rtx frame_size_rtx = GEN_INT (- current_frame_info.total_size);
3282       rtx offset;
3283
3284       if (satisfies_constraint_I (frame_size_rtx))
3285         offset = frame_size_rtx;
3286       else
3287         {
3288           regno = next_scratch_gr_reg ();
3289           offset = gen_rtx_REG (DImode, regno);
3290           emit_move_insn (offset, frame_size_rtx);
3291         }
3292
3293       insn = emit_insn (gen_adddi3 (stack_pointer_rtx,
3294                                     stack_pointer_rtx, offset));
3295
3296       if (! frame_pointer_needed)
3297         {
3298           RTX_FRAME_RELATED_P (insn) = 1;
3299           add_reg_note (insn, REG_CFA_ADJUST_CFA,
3300                         gen_rtx_SET (VOIDmode,
3301                                      stack_pointer_rtx,
3302                                      gen_rtx_PLUS (DImode,
3303                                                    stack_pointer_rtx,
3304                                                    frame_size_rtx)));
3305         }
3306
3307       /* ??? At this point we must generate a magic insn that appears to
3308          modify the stack pointer, the frame pointer, and all spill
3309          iterators.  This would allow the most scheduling freedom.  For
3310          now, just hard stop.  */
3311       emit_insn (gen_blockage ());
3312     }
3313
3314   /* Must copy out ar.unat before doing any integer spills.  */
3315   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
3316     {
3317       if (current_frame_info.r[reg_save_ar_unat])
3318         {
3319           ar_unat_save_reg
3320             = gen_rtx_REG (DImode, current_frame_info.r[reg_save_ar_unat]);
3321           reg_emitted (reg_save_ar_unat);
3322         }
3323       else
3324         {
3325           alt_regno = next_scratch_gr_reg ();
3326           ar_unat_save_reg = gen_rtx_REG (DImode, alt_regno);
3327           current_frame_info.gr_used_mask |= 1 << alt_regno;
3328         }
3329
3330       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
3331       insn = emit_move_insn (ar_unat_save_reg, reg);
3332       if (current_frame_info.r[reg_save_ar_unat])
3333         {
3334           RTX_FRAME_RELATED_P (insn) = 1;
3335           add_reg_note (insn, REG_CFA_REGISTER, NULL_RTX);
3336         }
3337
3338       /* Even if we're not going to generate an epilogue, we still
3339          need to save the register so that EH works.  */
3340       if (! epilogue_p && current_frame_info.r[reg_save_ar_unat])
3341         emit_insn (gen_prologue_use (ar_unat_save_reg));
3342     }
3343   else
3344     ar_unat_save_reg = NULL_RTX;
3345
3346   /* Spill all varargs registers.  Do this before spilling any GR registers,
3347      since we want the UNAT bits for the GR registers to override the UNAT
3348      bits from varargs, which we don't care about.  */
3349
3350   cfa_off = -16;
3351   for (regno = GR_ARG_FIRST + 7; n_varargs > 0; --n_varargs, --regno)
3352     {
3353       reg = gen_rtx_REG (DImode, regno);
3354       do_spill (gen_gr_spill, reg, cfa_off += 8, NULL_RTX);
3355     }
3356
3357   /* Locate the bottom of the register save area.  */
3358   cfa_off = (current_frame_info.spill_cfa_off
3359              + current_frame_info.spill_size
3360              + current_frame_info.extra_spill_size);
3361
3362   /* Save the predicate register block either in a register or in memory.  */
3363   if (TEST_HARD_REG_BIT (current_frame_info.mask, PR_REG (0)))
3364     {
3365       reg = gen_rtx_REG (DImode, PR_REG (0));
3366       if (current_frame_info.r[reg_save_pr] != 0)
3367         {
3368           alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_pr]);
3369           reg_emitted (reg_save_pr);
3370           insn = emit_move_insn (alt_reg, reg);
3371
3372           /* ??? Denote pr spill/fill by a DImode move that modifies all
3373              64 hard registers.  */
3374           RTX_FRAME_RELATED_P (insn) = 1;
3375           add_reg_note (insn, REG_CFA_REGISTER, NULL_RTX);
3376
3377           /* Even if we're not going to generate an epilogue, we still
3378              need to save the register so that EH works.  */
3379           if (! epilogue_p)
3380             emit_insn (gen_prologue_use (alt_reg));
3381         }
3382       else
3383         {
3384           alt_regno = next_scratch_gr_reg ();
3385           alt_reg = gen_rtx_REG (DImode, alt_regno);
3386           insn = emit_move_insn (alt_reg, reg);
3387           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
3388           cfa_off -= 8;
3389         }
3390     }
3391
3392   /* Handle AR regs in numerical order.  All of them get special handling.  */
3393   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM)
3394       && current_frame_info.r[reg_save_ar_unat] == 0)
3395     {
3396       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
3397       do_spill (gen_movdi_x, ar_unat_save_reg, cfa_off, reg);
3398       cfa_off -= 8;
3399     }
3400
3401   /* The alloc insn already copied ar.pfs into a general register.  The
3402      only thing we have to do now is copy that register to a stack slot
3403      if we'd not allocated a local register for the job.  */
3404   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM)
3405       && current_frame_info.r[reg_save_ar_pfs] == 0)
3406     {
3407       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
3408       do_spill (gen_movdi_x, ar_pfs_save_reg, cfa_off, reg);
3409       cfa_off -= 8;
3410     }
3411
3412   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_LC_REGNUM))
3413     {
3414       reg = gen_rtx_REG (DImode, AR_LC_REGNUM);
3415       if (current_frame_info.r[reg_save_ar_lc] != 0)
3416         {
3417           alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_ar_lc]);
3418           reg_emitted (reg_save_ar_lc);
3419           insn = emit_move_insn (alt_reg, reg);
3420           RTX_FRAME_RELATED_P (insn) = 1;
3421           add_reg_note (insn, REG_CFA_REGISTER, NULL_RTX);
3422
3423           /* Even if we're not going to generate an epilogue, we still
3424              need to save the register so that EH works.  */
3425           if (! epilogue_p)
3426             emit_insn (gen_prologue_use (alt_reg));
3427         }
3428       else
3429         {
3430           alt_regno = next_scratch_gr_reg ();
3431           alt_reg = gen_rtx_REG (DImode, alt_regno);
3432           emit_move_insn (alt_reg, reg);
3433           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
3434           cfa_off -= 8;
3435         }
3436     }
3437
3438   /* Save the return pointer.  */
3439   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3440     {
3441       reg = gen_rtx_REG (DImode, BR_REG (0));
3442       if (current_frame_info.r[reg_save_b0] != 0)
3443         {
3444           alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_b0]);
3445           reg_emitted (reg_save_b0);
3446           insn = emit_move_insn (alt_reg, reg);
3447           RTX_FRAME_RELATED_P (insn) = 1;
3448           add_reg_note (insn, REG_CFA_REGISTER, NULL_RTX);
3449
3450           /* Even if we're not going to generate an epilogue, we still
3451              need to save the register so that EH works.  */
3452           if (! epilogue_p)
3453             emit_insn (gen_prologue_use (alt_reg));
3454         }
3455       else
3456         {
3457           alt_regno = next_scratch_gr_reg ();
3458           alt_reg = gen_rtx_REG (DImode, alt_regno);
3459           emit_move_insn (alt_reg, reg);
3460           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
3461           cfa_off -= 8;
3462         }
3463     }
3464
3465   if (current_frame_info.r[reg_save_gp])
3466     {
3467       reg_emitted (reg_save_gp);
3468       insn = emit_move_insn (gen_rtx_REG (DImode,
3469                                           current_frame_info.r[reg_save_gp]),
3470                              pic_offset_table_rtx);
3471     }
3472
3473   /* We should now be at the base of the gr/br/fr spill area.  */
3474   gcc_assert (cfa_off == (current_frame_info.spill_cfa_off
3475                           + current_frame_info.spill_size));
3476
3477   /* Spill all general registers.  */
3478   for (regno = GR_REG (1); regno <= GR_REG (31); ++regno)
3479     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3480       {
3481         reg = gen_rtx_REG (DImode, regno);
3482         do_spill (gen_gr_spill, reg, cfa_off, reg);
3483         cfa_off -= 8;
3484       }
3485
3486   /* Spill the rest of the BR registers.  */
3487   for (regno = BR_REG (1); regno <= BR_REG (7); ++regno)
3488     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3489       {
3490         alt_regno = next_scratch_gr_reg ();
3491         alt_reg = gen_rtx_REG (DImode, alt_regno);
3492         reg = gen_rtx_REG (DImode, regno);
3493         emit_move_insn (alt_reg, reg);
3494         do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
3495         cfa_off -= 8;
3496       }
3497
3498   /* Align the frame and spill all FR registers.  */
3499   for (regno = FR_REG (2); regno <= FR_REG (127); ++regno)
3500     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3501       {
3502         gcc_assert (!(cfa_off & 15));
3503         reg = gen_rtx_REG (XFmode, regno);
3504         do_spill (gen_fr_spill_x, reg, cfa_off, reg);
3505         cfa_off -= 16;
3506       }
3507
3508   gcc_assert (cfa_off == current_frame_info.spill_cfa_off);
3509
3510   finish_spill_pointers ();
3511 }
3512
3513 /* Output the textual info surrounding the prologue.  */
3514
3515 void
3516 ia64_start_function (FILE *file, const char *fnname,
3517                      tree decl ATTRIBUTE_UNUSED)
3518 {
3519 #if VMS_DEBUGGING_INFO
3520   if (vms_debug_main
3521       && strncmp (vms_debug_main, fnname, strlen (vms_debug_main)) == 0)
3522     {
3523       targetm.asm_out.globalize_label (asm_out_file, VMS_DEBUG_MAIN_POINTER);
3524       ASM_OUTPUT_DEF (asm_out_file, VMS_DEBUG_MAIN_POINTER, fnname);
3525       dwarf2out_vms_debug_main_pointer ();
3526       vms_debug_main = 0;
3527     }
3528 #endif
3529
3530   fputs ("\t.proc ", file);
3531   assemble_name (file, fnname);
3532   fputc ('\n', file);
3533   ASM_OUTPUT_LABEL (file, fnname);
3534 }
3535
3536 /* Called after register allocation to add any instructions needed for the
3537    epilogue.  Using an epilogue insn is favored compared to putting all of the
3538    instructions in output_function_prologue(), since it allows the scheduler
3539    to intermix instructions with the saves of the caller saved registers.  In
3540    some cases, it might be necessary to emit a barrier instruction as the last
3541    insn to prevent such scheduling.  */
3542
3543 void
3544 ia64_expand_epilogue (int sibcall_p)
3545 {
3546   rtx insn, reg, alt_reg, ar_unat_save_reg;
3547   int regno, alt_regno, cfa_off;
3548
3549   ia64_compute_frame_size (get_frame_size ());
3550
3551   /* If there is a frame pointer, then we use it instead of the stack
3552      pointer, so that the stack pointer does not need to be valid when
3553      the epilogue starts.  See EXIT_IGNORE_STACK.  */
3554   if (frame_pointer_needed)
3555     setup_spill_pointers (current_frame_info.n_spilled,
3556                           hard_frame_pointer_rtx, 0);
3557   else
3558     setup_spill_pointers (current_frame_info.n_spilled, stack_pointer_rtx,
3559                           current_frame_info.total_size);
3560
3561   if (current_frame_info.total_size != 0)
3562     {
3563       /* ??? At this point we must generate a magic insn that appears to
3564          modify the spill iterators and the frame pointer.  This would
3565          allow the most scheduling freedom.  For now, just hard stop.  */
3566       emit_insn (gen_blockage ());
3567     }
3568
3569   /* Locate the bottom of the register save area.  */
3570   cfa_off = (current_frame_info.spill_cfa_off
3571              + current_frame_info.spill_size
3572              + current_frame_info.extra_spill_size);
3573
3574   /* Restore the predicate registers.  */
3575   if (TEST_HARD_REG_BIT (current_frame_info.mask, PR_REG (0)))
3576     {
3577       if (current_frame_info.r[reg_save_pr] != 0)
3578         {
3579           alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_pr]);
3580           reg_emitted (reg_save_pr);
3581         }
3582       else
3583         {
3584           alt_regno = next_scratch_gr_reg ();
3585           alt_reg = gen_rtx_REG (DImode, alt_regno);
3586           do_restore (gen_movdi_x, alt_reg, cfa_off);
3587           cfa_off -= 8;
3588         }
3589       reg = gen_rtx_REG (DImode, PR_REG (0));
3590       emit_move_insn (reg, alt_reg);
3591     }
3592
3593   /* Restore the application registers.  */
3594
3595   /* Load the saved unat from the stack, but do not restore it until
3596      after the GRs have been restored.  */
3597   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
3598     {
3599       if (current_frame_info.r[reg_save_ar_unat] != 0)
3600         {
3601           ar_unat_save_reg
3602             = gen_rtx_REG (DImode, current_frame_info.r[reg_save_ar_unat]);
3603           reg_emitted (reg_save_ar_unat);
3604         }
3605       else
3606         {
3607           alt_regno = next_scratch_gr_reg ();
3608           ar_unat_save_reg = gen_rtx_REG (DImode, alt_regno);
3609           current_frame_info.gr_used_mask |= 1 << alt_regno;
3610           do_restore (gen_movdi_x, ar_unat_save_reg, cfa_off);
3611           cfa_off -= 8;
3612         }
3613     }
3614   else
3615     ar_unat_save_reg = NULL_RTX;
3616
3617   if (current_frame_info.r[reg_save_ar_pfs] != 0)
3618     {
3619       reg_emitted (reg_save_ar_pfs);
3620       alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_ar_pfs]);
3621       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
3622       emit_move_insn (reg, alt_reg);
3623     }
3624   else if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM))
3625     {
3626       alt_regno = next_scratch_gr_reg ();
3627       alt_reg = gen_rtx_REG (DImode, alt_regno);
3628       do_restore (gen_movdi_x, alt_reg, cfa_off);
3629       cfa_off -= 8;
3630       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
3631       emit_move_insn (reg, alt_reg);
3632     }
3633
3634   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_LC_REGNUM))
3635     {
3636       if (current_frame_info.r[reg_save_ar_lc] != 0)
3637         {
3638           alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_ar_lc]);
3639           reg_emitted (reg_save_ar_lc);
3640         }
3641       else
3642         {
3643           alt_regno = next_scratch_gr_reg ();
3644           alt_reg = gen_rtx_REG (DImode, alt_regno);
3645           do_restore (gen_movdi_x, alt_reg, cfa_off);
3646           cfa_off -= 8;
3647         }
3648       reg = gen_rtx_REG (DImode, AR_LC_REGNUM);
3649       emit_move_insn (reg, alt_reg);
3650     }
3651
3652   /* Restore the return pointer.  */
3653   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3654     {
3655       if (current_frame_info.r[reg_save_b0] != 0)
3656         {
3657          alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_b0]);
3658          reg_emitted (reg_save_b0);
3659         }
3660       else
3661         {
3662           alt_regno = next_scratch_gr_reg ();
3663           alt_reg = gen_rtx_REG (DImode, alt_regno);
3664           do_restore (gen_movdi_x, alt_reg, cfa_off);
3665           cfa_off -= 8;
3666         }
3667       reg = gen_rtx_REG (DImode, BR_REG (0));
3668       emit_move_insn (reg, alt_reg);
3669     }
3670
3671   /* We should now be at the base of the gr/br/fr spill area.  */
3672   gcc_assert (cfa_off == (current_frame_info.spill_cfa_off
3673                           + current_frame_info.spill_size));
3674
3675   /* The GP may be stored on the stack in the prologue, but it's
3676      never restored in the epilogue.  Skip the stack slot.  */
3677   if (TEST_HARD_REG_BIT (current_frame_info.mask, GR_REG (1)))
3678     cfa_off -= 8;
3679
3680   /* Restore all general registers.  */
3681   for (regno = GR_REG (2); regno <= GR_REG (31); ++regno)
3682     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3683       {
3684         reg = gen_rtx_REG (DImode, regno);
3685         do_restore (gen_gr_restore, reg, cfa_off);
3686         cfa_off -= 8;
3687       }
3688
3689   /* Restore the branch registers.  */
3690   for (regno = BR_REG (1); regno <= BR_REG (7); ++regno)
3691     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3692       {
3693         alt_regno = next_scratch_gr_reg ();
3694         alt_reg = gen_rtx_REG (DImode, alt_regno);
3695         do_restore (gen_movdi_x, alt_reg, cfa_off);
3696         cfa_off -= 8;
3697         reg = gen_rtx_REG (DImode, regno);
3698         emit_move_insn (reg, alt_reg);
3699       }
3700
3701   /* Restore floating point registers.  */
3702   for (regno = FR_REG (2); regno <= FR_REG (127); ++regno)
3703     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3704       {
3705         gcc_assert (!(cfa_off & 15));
3706         reg = gen_rtx_REG (XFmode, regno);
3707         do_restore (gen_fr_restore_x, reg, cfa_off);
3708         cfa_off -= 16;
3709       }
3710
3711   /* Restore ar.unat for real.  */
3712   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
3713     {
3714       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
3715       emit_move_insn (reg, ar_unat_save_reg);
3716     }
3717
3718   gcc_assert (cfa_off == current_frame_info.spill_cfa_off);
3719
3720   finish_spill_pointers ();
3721
3722   if (current_frame_info.total_size
3723       || cfun->machine->ia64_eh_epilogue_sp
3724       || frame_pointer_needed)
3725     {
3726       /* ??? At this point we must generate a magic insn that appears to
3727          modify the spill iterators, the stack pointer, and the frame
3728          pointer.  This would allow the most scheduling freedom.  For now,
3729          just hard stop.  */
3730       emit_insn (gen_blockage ());
3731     }
3732
3733   if (cfun->machine->ia64_eh_epilogue_sp)
3734     emit_move_insn (stack_pointer_rtx, cfun->machine->ia64_eh_epilogue_sp);
3735   else if (frame_pointer_needed)
3736     {
3737       insn = emit_move_insn (stack_pointer_rtx, hard_frame_pointer_rtx);
3738       RTX_FRAME_RELATED_P (insn) = 1;
3739       add_reg_note (insn, REG_CFA_ADJUST_CFA, NULL);
3740     }
3741   else if (current_frame_info.total_size)
3742     {
3743       rtx offset, frame_size_rtx;
3744
3745       frame_size_rtx = GEN_INT (current_frame_info.total_size);
3746       if (satisfies_constraint_I (frame_size_rtx))
3747         offset = frame_size_rtx;
3748       else
3749         {
3750           regno = next_scratch_gr_reg ();
3751           offset = gen_rtx_REG (DImode, regno);
3752           emit_move_insn (offset, frame_size_rtx);
3753         }
3754
3755       insn = emit_insn (gen_adddi3 (stack_pointer_rtx, stack_pointer_rtx,
3756                                     offset));
3757
3758       RTX_FRAME_RELATED_P (insn) = 1;
3759       add_reg_note (insn, REG_CFA_ADJUST_CFA,
3760                     gen_rtx_SET (VOIDmode,
3761                                  stack_pointer_rtx,
3762                                  gen_rtx_PLUS (DImode,
3763                                                stack_pointer_rtx,
3764                                                frame_size_rtx)));
3765     }
3766
3767   if (cfun->machine->ia64_eh_epilogue_bsp)
3768     emit_insn (gen_set_bsp (cfun->machine->ia64_eh_epilogue_bsp));
3769
3770   if (! sibcall_p)
3771     emit_jump_insn (gen_return_internal (gen_rtx_REG (DImode, BR_REG (0))));
3772   else
3773     {
3774       int fp = GR_REG (2);
3775       /* We need a throw away register here, r0 and r1 are reserved,
3776          so r2 is the first available call clobbered register.  If
3777          there was a frame_pointer register, we may have swapped the
3778          names of r2 and HARD_FRAME_POINTER_REGNUM, so we have to make
3779          sure we're using the string "r2" when emitting the register
3780          name for the assembler.  */
3781       if (current_frame_info.r[reg_fp] 
3782           && current_frame_info.r[reg_fp] == GR_REG (2))
3783         fp = HARD_FRAME_POINTER_REGNUM;
3784
3785       /* We must emit an alloc to force the input registers to become output
3786          registers.  Otherwise, if the callee tries to pass its parameters
3787          through to another call without an intervening alloc, then these
3788          values get lost.  */
3789       /* ??? We don't need to preserve all input registers.  We only need to
3790          preserve those input registers used as arguments to the sibling call.
3791          It is unclear how to compute that number here.  */
3792       if (current_frame_info.n_input_regs != 0)
3793         {
3794           rtx n_inputs = GEN_INT (current_frame_info.n_input_regs);
3795           insn = emit_insn (gen_alloc (gen_rtx_REG (DImode, fp),
3796                                 const0_rtx, const0_rtx,
3797                                 n_inputs, const0_rtx));
3798           RTX_FRAME_RELATED_P (insn) = 1;
3799         }
3800     }
3801 }
3802
3803 /* Return 1 if br.ret can do all the work required to return from a
3804    function.  */
3805
3806 int
3807 ia64_direct_return (void)
3808 {
3809   if (reload_completed && ! frame_pointer_needed)
3810     {
3811       ia64_compute_frame_size (get_frame_size ());
3812
3813       return (current_frame_info.total_size == 0
3814               && current_frame_info.n_spilled == 0
3815               && current_frame_info.r[reg_save_b0] == 0
3816               && current_frame_info.r[reg_save_pr] == 0
3817               && current_frame_info.r[reg_save_ar_pfs] == 0
3818               && current_frame_info.r[reg_save_ar_unat] == 0
3819               && current_frame_info.r[reg_save_ar_lc] == 0);
3820     }
3821   return 0;
3822 }
3823
3824 /* Return the magic cookie that we use to hold the return address
3825    during early compilation.  */
3826
3827 rtx
3828 ia64_return_addr_rtx (HOST_WIDE_INT count, rtx frame ATTRIBUTE_UNUSED)
3829 {
3830   if (count != 0)
3831     return NULL;
3832   return gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx), UNSPEC_RET_ADDR);
3833 }
3834
3835 /* Split this value after reload, now that we know where the return
3836    address is saved.  */
3837
3838 void
3839 ia64_split_return_addr_rtx (rtx dest)
3840 {
3841   rtx src;
3842
3843   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3844     {
3845       if (current_frame_info.r[reg_save_b0] != 0)
3846         {
3847           src = gen_rtx_REG (DImode, current_frame_info.r[reg_save_b0]);
3848           reg_emitted (reg_save_b0);
3849         }
3850       else
3851         {
3852           HOST_WIDE_INT off;
3853           unsigned int regno;
3854           rtx off_r;
3855
3856           /* Compute offset from CFA for BR0.  */
3857           /* ??? Must be kept in sync with ia64_expand_prologue.  */
3858           off = (current_frame_info.spill_cfa_off
3859                  + current_frame_info.spill_size);
3860           for (regno = GR_REG (1); regno <= GR_REG (31); ++regno)
3861             if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3862               off -= 8;
3863
3864           /* Convert CFA offset to a register based offset.  */
3865           if (frame_pointer_needed)
3866             src = hard_frame_pointer_rtx;
3867           else
3868             {
3869               src = stack_pointer_rtx;
3870               off += current_frame_info.total_size;
3871             }
3872
3873           /* Load address into scratch register.  */
3874           off_r = GEN_INT (off);
3875           if (satisfies_constraint_I (off_r))
3876             emit_insn (gen_adddi3 (dest, src, off_r));
3877           else
3878             {
3879               emit_move_insn (dest, off_r);
3880               emit_insn (gen_adddi3 (dest, src, dest));
3881             }
3882
3883           src = gen_rtx_MEM (Pmode, dest);
3884         }
3885     }
3886   else
3887     src = gen_rtx_REG (DImode, BR_REG (0));
3888
3889   emit_move_insn (dest, src);
3890 }
3891
3892 int
3893 ia64_hard_regno_rename_ok (int from, int to)
3894 {
3895   /* Don't clobber any of the registers we reserved for the prologue.  */
3896   unsigned int r;
3897
3898   for (r = reg_fp; r <= reg_save_ar_lc; r++)
3899     if (to == current_frame_info.r[r] 
3900         || from == current_frame_info.r[r]
3901         || to == emitted_frame_related_regs[r]
3902         || from == emitted_frame_related_regs[r])
3903       return 0;
3904
3905   /* Don't use output registers outside the register frame.  */
3906   if (OUT_REGNO_P (to) && to >= OUT_REG (current_frame_info.n_output_regs))
3907     return 0;
3908
3909   /* Retain even/oddness on predicate register pairs.  */
3910   if (PR_REGNO_P (from) && PR_REGNO_P (to))
3911     return (from & 1) == (to & 1);
3912
3913   return 1;
3914 }
3915
3916 /* Target hook for assembling integer objects.  Handle word-sized
3917    aligned objects and detect the cases when @fptr is needed.  */
3918
3919 static bool
3920 ia64_assemble_integer (rtx x, unsigned int size, int aligned_p)
3921 {
3922   if (size == POINTER_SIZE / BITS_PER_UNIT
3923       && !(TARGET_NO_PIC || TARGET_AUTO_PIC)
3924       && GET_CODE (x) == SYMBOL_REF
3925       && SYMBOL_REF_FUNCTION_P (x))
3926     {
3927       static const char * const directive[2][2] = {
3928           /* 64-bit pointer */  /* 32-bit pointer */
3929         { "\tdata8.ua\t@fptr(", "\tdata4.ua\t@fptr("},  /* unaligned */
3930         { "\tdata8\t@fptr(",    "\tdata4\t@fptr("}      /* aligned */
3931       };
3932       fputs (directive[(aligned_p != 0)][POINTER_SIZE == 32], asm_out_file);
3933       output_addr_const (asm_out_file, x);
3934       fputs (")\n", asm_out_file);
3935       return true;
3936     }
3937   return default_assemble_integer (x, size, aligned_p);
3938 }
3939
3940 /* Emit the function prologue.  */
3941
3942 static void
3943 ia64_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
3944 {
3945   int mask, grsave, grsave_prev;
3946
3947   if (current_frame_info.need_regstk)
3948     fprintf (file, "\t.regstk %d, %d, %d, %d\n",
3949              current_frame_info.n_input_regs,
3950              current_frame_info.n_local_regs,
3951              current_frame_info.n_output_regs,
3952              current_frame_info.n_rotate_regs);
3953
3954   if (ia64_except_unwind_info () != UI_TARGET)
3955     return;
3956
3957   /* Emit the .prologue directive.  */
3958
3959   mask = 0;
3960   grsave = grsave_prev = 0;
3961   if (current_frame_info.r[reg_save_b0] != 0)
3962     {
3963       mask |= 8;
3964       grsave = grsave_prev = current_frame_info.r[reg_save_b0];
3965     }
3966   if (current_frame_info.r[reg_save_ar_pfs] != 0
3967       && (grsave_prev == 0
3968           || current_frame_info.r[reg_save_ar_pfs] == grsave_prev + 1))
3969     {
3970       mask |= 4;
3971       if (grsave_prev == 0)
3972         grsave = current_frame_info.r[reg_save_ar_pfs];
3973       grsave_prev = current_frame_info.r[reg_save_ar_pfs];
3974     }
3975   if (current_frame_info.r[reg_fp] != 0
3976       && (grsave_prev == 0
3977           || current_frame_info.r[reg_fp] == grsave_prev + 1))
3978     {
3979       mask |= 2;
3980       if (grsave_prev == 0)
3981         grsave = HARD_FRAME_POINTER_REGNUM;
3982       grsave_prev = current_frame_info.r[reg_fp];
3983     }
3984   if (current_frame_info.r[reg_save_pr] != 0
3985       && (grsave_prev == 0
3986           || current_frame_info.r[reg_save_pr] == grsave_prev + 1))
3987     {
3988       mask |= 1;
3989       if (grsave_prev == 0)
3990         grsave = current_frame_info.r[reg_save_pr];
3991     }
3992
3993   if (mask && TARGET_GNU_AS)
3994     fprintf (file, "\t.prologue %d, %d\n", mask,
3995              ia64_dbx_register_number (grsave));
3996   else
3997     fputs ("\t.prologue\n", file);
3998
3999   /* Emit a .spill directive, if necessary, to relocate the base of
4000      the register spill area.  */
4001   if (current_frame_info.spill_cfa_off != -16)
4002     fprintf (file, "\t.spill %ld\n",
4003              (long) (current_frame_info.spill_cfa_off
4004                      + current_frame_info.spill_size));
4005 }
4006
4007 /* Emit the .body directive at the scheduled end of the prologue.  */
4008
4009 static void
4010 ia64_output_function_end_prologue (FILE *file)
4011 {
4012   if (ia64_except_unwind_info () != UI_TARGET)
4013     return;
4014
4015   fputs ("\t.body\n", file);
4016 }
4017
4018 /* Emit the function epilogue.  */
4019
4020 static void
4021 ia64_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
4022                                HOST_WIDE_INT size ATTRIBUTE_UNUSED)
4023 {
4024   int i;
4025
4026   if (current_frame_info.r[reg_fp])
4027     {
4028       const char *tmp = reg_names[HARD_FRAME_POINTER_REGNUM];
4029       reg_names[HARD_FRAME_POINTER_REGNUM]
4030         = reg_names[current_frame_info.r[reg_fp]];
4031       reg_names[current_frame_info.r[reg_fp]] = tmp;
4032       reg_emitted (reg_fp);
4033     }
4034   if (! TARGET_REG_NAMES)
4035     {
4036       for (i = 0; i < current_frame_info.n_input_regs; i++)
4037         reg_names[IN_REG (i)] = ia64_input_reg_names[i];
4038       for (i = 0; i < current_frame_info.n_local_regs; i++)
4039         reg_names[LOC_REG (i)] = ia64_local_reg_names[i];
4040       for (i = 0; i < current_frame_info.n_output_regs; i++)
4041         reg_names[OUT_REG (i)] = ia64_output_reg_names[i];
4042     }
4043
4044   current_frame_info.initialized = 0;
4045 }
4046
4047 int
4048 ia64_dbx_register_number (int regno)
4049 {
4050   /* In ia64_expand_prologue we quite literally renamed the frame pointer
4051      from its home at loc79 to something inside the register frame.  We
4052      must perform the same renumbering here for the debug info.  */
4053   if (current_frame_info.r[reg_fp])
4054     {
4055       if (regno == HARD_FRAME_POINTER_REGNUM)
4056         regno = current_frame_info.r[reg_fp];
4057       else if (regno == current_frame_info.r[reg_fp])
4058         regno = HARD_FRAME_POINTER_REGNUM;
4059     }
4060
4061   if (IN_REGNO_P (regno))
4062     return 32 + regno - IN_REG (0);
4063   else if (LOC_REGNO_P (regno))
4064     return 32 + current_frame_info.n_input_regs + regno - LOC_REG (0);
4065   else if (OUT_REGNO_P (regno))
4066     return (32 + current_frame_info.n_input_regs
4067             + current_frame_info.n_local_regs + regno - OUT_REG (0));
4068   else
4069     return regno;
4070 }
4071
4072 /* Implement TARGET_TRAMPOLINE_INIT.
4073
4074    The trampoline should set the static chain pointer to value placed
4075    into the trampoline and should branch to the specified routine.
4076    To make the normal indirect-subroutine calling convention work,
4077    the trampoline must look like a function descriptor; the first
4078    word being the target address and the second being the target's
4079    global pointer.
4080
4081    We abuse the concept of a global pointer by arranging for it
4082    to point to the data we need to load.  The complete trampoline
4083    has the following form:
4084
4085                 +-------------------+ \
4086         TRAMP:  | __ia64_trampoline | |
4087                 +-------------------+  > fake function descriptor
4088                 | TRAMP+16          | |
4089                 +-------------------+ /
4090                 | target descriptor |
4091                 +-------------------+
4092                 | static link       |
4093                 +-------------------+
4094 */
4095
4096 static void
4097 ia64_trampoline_init (rtx m_tramp, tree fndecl, rtx static_chain)
4098 {
4099   rtx fnaddr = XEXP (DECL_RTL (fndecl), 0);
4100   rtx addr, addr_reg, tramp, eight = GEN_INT (8);
4101
4102   /* The Intel assembler requires that the global __ia64_trampoline symbol
4103      be declared explicitly */
4104   if (!TARGET_GNU_AS)
4105     {
4106       static bool declared_ia64_trampoline = false;
4107
4108       if (!declared_ia64_trampoline)
4109         {
4110           declared_ia64_trampoline = true;
4111           (*targetm.asm_out.globalize_label) (asm_out_file,
4112                                               "__ia64_trampoline");
4113         }
4114     }
4115
4116   /* Make sure addresses are Pmode even if we are in ILP32 mode. */
4117   addr = convert_memory_address (Pmode, XEXP (m_tramp, 0));
4118   fnaddr = convert_memory_address (Pmode, fnaddr);
4119   static_chain = convert_memory_address (Pmode, static_chain);
4120
4121   /* Load up our iterator.  */
4122   addr_reg = copy_to_reg (addr);
4123   m_tramp = adjust_automodify_address (m_tramp, Pmode, addr_reg, 0);
4124
4125   /* The first two words are the fake descriptor:
4126      __ia64_trampoline, ADDR+16.  */
4127   tramp = gen_rtx_SYMBOL_REF (Pmode, "__ia64_trampoline");
4128   if (TARGET_ABI_OPEN_VMS)
4129     {
4130       /* HP decided to break the ELF ABI on VMS (to deal with an ambiguity
4131          in the Macro-32 compiler) and changed the semantics of the LTOFF22
4132          relocation against function symbols to make it identical to the
4133          LTOFF_FPTR22 relocation.  Emit the latter directly to stay within
4134          strict ELF and dereference to get the bare code address.  */
4135       rtx reg = gen_reg_rtx (Pmode);
4136       SYMBOL_REF_FLAGS (tramp) |= SYMBOL_FLAG_FUNCTION;
4137       emit_move_insn (reg, tramp);
4138       emit_move_insn (reg, gen_rtx_MEM (Pmode, reg));
4139       tramp = reg;
4140    }
4141   emit_move_insn (m_tramp, tramp);
4142   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
4143   m_tramp = adjust_automodify_address (m_tramp, VOIDmode, NULL, 8);
4144
4145   emit_move_insn (m_tramp, force_reg (Pmode, plus_constant (addr, 16)));
4146   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
4147   m_tramp = adjust_automodify_address (m_tramp, VOIDmode, NULL, 8);
4148
4149   /* The third word is the target descriptor.  */
4150   emit_move_insn (m_tramp, force_reg (Pmode, fnaddr));
4151   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
4152   m_tramp = adjust_automodify_address (m_tramp, VOIDmode, NULL, 8);
4153
4154   /* The fourth word is the static chain.  */
4155   emit_move_insn (m_tramp, static_chain);
4156 }
4157 \f
4158 /* Do any needed setup for a variadic function.  CUM has not been updated
4159    for the last named argument which has type TYPE and mode MODE.
4160
4161    We generate the actual spill instructions during prologue generation.  */
4162
4163 static void
4164 ia64_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4165                              tree type, int * pretend_size,
4166                              int second_time ATTRIBUTE_UNUSED)
4167 {
4168   CUMULATIVE_ARGS next_cum = *cum;
4169
4170   /* Skip the current argument.  */
4171   ia64_function_arg_advance (&next_cum, mode, type, 1);
4172
4173   if (next_cum.words < MAX_ARGUMENT_SLOTS)
4174     {
4175       int n = MAX_ARGUMENT_SLOTS - next_cum.words;
4176       *pretend_size = n * UNITS_PER_WORD;
4177       cfun->machine->n_varargs = n;
4178     }
4179 }
4180
4181 /* Check whether TYPE is a homogeneous floating point aggregate.  If
4182    it is, return the mode of the floating point type that appears
4183    in all leafs.  If it is not, return VOIDmode.
4184
4185    An aggregate is a homogeneous floating point aggregate is if all
4186    fields/elements in it have the same floating point type (e.g,
4187    SFmode).  128-bit quad-precision floats are excluded.
4188
4189    Variable sized aggregates should never arrive here, since we should
4190    have already decided to pass them by reference.  Top-level zero-sized
4191    aggregates are excluded because our parallels crash the middle-end.  */
4192
4193 static enum machine_mode
4194 hfa_element_mode (const_tree type, bool nested)
4195 {
4196   enum machine_mode element_mode = VOIDmode;
4197   enum machine_mode mode;
4198   enum tree_code code = TREE_CODE (type);
4199   int know_element_mode = 0;
4200   tree t;
4201
4202   if (!nested && (!TYPE_SIZE (type) || integer_zerop (TYPE_SIZE (type))))
4203     return VOIDmode;
4204
4205   switch (code)
4206     {
4207     case VOID_TYPE:     case INTEGER_TYPE:      case ENUMERAL_TYPE:
4208     case BOOLEAN_TYPE:  case POINTER_TYPE:
4209     case OFFSET_TYPE:   case REFERENCE_TYPE:    case METHOD_TYPE:
4210     case LANG_TYPE:             case FUNCTION_TYPE:
4211       return VOIDmode;
4212
4213       /* Fortran complex types are supposed to be HFAs, so we need to handle
4214          gcc's COMPLEX_TYPEs as HFAs.  We need to exclude the integral complex
4215          types though.  */
4216     case COMPLEX_TYPE:
4217       if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_COMPLEX_FLOAT
4218           && TYPE_MODE (type) != TCmode)
4219         return GET_MODE_INNER (TYPE_MODE (type));
4220       else
4221         return VOIDmode;
4222
4223     case REAL_TYPE:
4224       /* We want to return VOIDmode for raw REAL_TYPEs, but the actual
4225          mode if this is contained within an aggregate.  */
4226       if (nested && TYPE_MODE (type) != TFmode)
4227         return TYPE_MODE (type);
4228       else
4229         return VOIDmode;
4230
4231     case ARRAY_TYPE:
4232       return hfa_element_mode (TREE_TYPE (type), 1);
4233
4234     case RECORD_TYPE:
4235     case UNION_TYPE:
4236     case QUAL_UNION_TYPE:
4237       for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
4238         {
4239           if (TREE_CODE (t) != FIELD_DECL)
4240             continue;
4241
4242           mode = hfa_element_mode (TREE_TYPE (t), 1);
4243           if (know_element_mode)
4244             {
4245               if (mode != element_mode)
4246                 return VOIDmode;
4247             }
4248           else if (GET_MODE_CLASS (mode) != MODE_FLOAT)
4249             return VOIDmode;
4250           else
4251             {
4252               know_element_mode = 1;
4253               element_mode = mode;
4254             }
4255         }
4256       return element_mode;
4257
4258     default:
4259       /* If we reach here, we probably have some front-end specific type
4260          that the backend doesn't know about.  This can happen via the
4261          aggregate_value_p call in init_function_start.  All we can do is
4262          ignore unknown tree types.  */
4263       return VOIDmode;
4264     }
4265
4266   return VOIDmode;
4267 }
4268
4269 /* Return the number of words required to hold a quantity of TYPE and MODE
4270    when passed as an argument.  */
4271 static int
4272 ia64_function_arg_words (const_tree type, enum machine_mode mode)
4273 {
4274   int words;
4275
4276   if (mode == BLKmode)
4277     words = int_size_in_bytes (type);
4278   else
4279     words = GET_MODE_SIZE (mode);
4280
4281   return (words + UNITS_PER_WORD - 1) / UNITS_PER_WORD;  /* round up */
4282 }
4283
4284 /* Return the number of registers that should be skipped so the current
4285    argument (described by TYPE and WORDS) will be properly aligned.
4286
4287    Integer and float arguments larger than 8 bytes start at the next
4288    even boundary.  Aggregates larger than 8 bytes start at the next
4289    even boundary if the aggregate has 16 byte alignment.  Note that
4290    in the 32-bit ABI, TImode and TFmode have only 8-byte alignment
4291    but are still to be aligned in registers.
4292
4293    ??? The ABI does not specify how to handle aggregates with
4294    alignment from 9 to 15 bytes, or greater than 16.  We handle them
4295    all as if they had 16 byte alignment.  Such aggregates can occur
4296    only if gcc extensions are used.  */
4297 static int
4298 ia64_function_arg_offset (const CUMULATIVE_ARGS *cum,
4299                           const_tree type, int words)
4300 {
4301   /* No registers are skipped on VMS.  */
4302   if (TARGET_ABI_OPEN_VMS || (cum->words & 1) == 0)
4303     return 0;
4304
4305   if (type
4306       && TREE_CODE (type) != INTEGER_TYPE
4307       && TREE_CODE (type) != REAL_TYPE)
4308     return TYPE_ALIGN (type) > 8 * BITS_PER_UNIT;
4309   else
4310     return words > 1;
4311 }
4312
4313 /* Return rtx for register where argument is passed, or zero if it is passed
4314    on the stack.  */
4315 /* ??? 128-bit quad-precision floats are always passed in general
4316    registers.  */
4317
4318 static rtx
4319 ia64_function_arg_1 (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
4320                      const_tree type, bool named, bool incoming)
4321 {
4322   int basereg = (incoming ? GR_ARG_FIRST : AR_ARG_FIRST);
4323   int words = ia64_function_arg_words (type, mode);
4324   int offset = ia64_function_arg_offset (cum, type, words);
4325   enum machine_mode hfa_mode = VOIDmode;
4326
4327   /* For OPEN VMS, emit the instruction setting up the argument register here,
4328      when we know this will be together with the other arguments setup related
4329      insns.  This is not the conceptually best place to do this, but this is
4330      the easiest as we have convenient access to cumulative args info.  */
4331
4332   if (TARGET_ABI_OPEN_VMS && mode == VOIDmode && type == void_type_node
4333       && named == 1)
4334     {
4335       unsigned HOST_WIDE_INT regval = cum->words;
4336       int i;
4337
4338       for (i = 0; i < 8; i++)
4339         regval |= ((int) cum->atypes[i]) << (i * 3 + 8);
4340
4341       emit_move_insn (gen_rtx_REG (DImode, GR_REG (25)),
4342                       GEN_INT (regval));
4343     }
4344
4345   /* If all argument slots are used, then it must go on the stack.  */
4346   if (cum->words + offset >= MAX_ARGUMENT_SLOTS)
4347     return 0;
4348
4349   /* Check for and handle homogeneous FP aggregates.  */
4350   if (type)
4351     hfa_mode = hfa_element_mode (type, 0);
4352
4353   /* Unnamed prototyped hfas are passed as usual.  Named prototyped hfas
4354      and unprototyped hfas are passed specially.  */
4355   if (hfa_mode != VOIDmode && (! cum->prototype || named))
4356     {
4357       rtx loc[16];
4358       int i = 0;
4359       int fp_regs = cum->fp_regs;
4360       int int_regs = cum->words + offset;
4361       int hfa_size = GET_MODE_SIZE (hfa_mode);
4362       int byte_size;
4363       int args_byte_size;
4364
4365       /* If prototyped, pass it in FR regs then GR regs.
4366          If not prototyped, pass it in both FR and GR regs.
4367
4368          If this is an SFmode aggregate, then it is possible to run out of
4369          FR regs while GR regs are still left.  In that case, we pass the
4370          remaining part in the GR regs.  */
4371
4372       /* Fill the FP regs.  We do this always.  We stop if we reach the end
4373          of the argument, the last FP register, or the last argument slot.  */
4374
4375       byte_size = ((mode == BLKmode)
4376                    ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
4377       args_byte_size = int_regs * UNITS_PER_WORD;
4378       offset = 0;
4379       for (; (offset < byte_size && fp_regs < MAX_ARGUMENT_SLOTS
4380               && args_byte_size < (MAX_ARGUMENT_SLOTS * UNITS_PER_WORD)); i++)
4381         {
4382           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4383                                       gen_rtx_REG (hfa_mode, (FR_ARG_FIRST
4384                                                               + fp_regs)),
4385                                       GEN_INT (offset));
4386           offset += hfa_size;
4387           args_byte_size += hfa_size;
4388           fp_regs++;
4389         }
4390
4391       /* If no prototype, then the whole thing must go in GR regs.  */
4392       if (! cum->prototype)
4393         offset = 0;
4394       /* If this is an SFmode aggregate, then we might have some left over
4395          that needs to go in GR regs.  */
4396       else if (byte_size != offset)
4397         int_regs += offset / UNITS_PER_WORD;
4398
4399       /* Fill in the GR regs.  We must use DImode here, not the hfa mode.  */
4400
4401       for (; offset < byte_size && int_regs < MAX_ARGUMENT_SLOTS; i++)
4402         {
4403           enum machine_mode gr_mode = DImode;
4404           unsigned int gr_size;
4405
4406           /* If we have an odd 4 byte hunk because we ran out of FR regs,
4407              then this goes in a GR reg left adjusted/little endian, right
4408              adjusted/big endian.  */
4409           /* ??? Currently this is handled wrong, because 4-byte hunks are
4410              always right adjusted/little endian.  */
4411           if (offset & 0x4)
4412             gr_mode = SImode;
4413           /* If we have an even 4 byte hunk because the aggregate is a
4414              multiple of 4 bytes in size, then this goes in a GR reg right
4415              adjusted/little endian.  */
4416           else if (byte_size - offset == 4)
4417             gr_mode = SImode;
4418
4419           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4420                                       gen_rtx_REG (gr_mode, (basereg
4421                                                              + int_regs)),
4422                                       GEN_INT (offset));
4423
4424           gr_size = GET_MODE_SIZE (gr_mode);
4425           offset += gr_size;
4426           if (gr_size == UNITS_PER_WORD
4427               || (gr_size < UNITS_PER_WORD && offset % UNITS_PER_WORD == 0))
4428             int_regs++;
4429           else if (gr_size > UNITS_PER_WORD)
4430             int_regs += gr_size / UNITS_PER_WORD;
4431         }
4432       return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
4433     }
4434   
4435   /* On OpenVMS variable argument is either in Rn or Fn.  */
4436   else if (TARGET_ABI_OPEN_VMS && named == 0)
4437     {
4438       if (FLOAT_MODE_P (mode))
4439         return gen_rtx_REG (mode, FR_ARG_FIRST + cum->words);
4440       else
4441         return gen_rtx_REG (mode, basereg + cum->words);
4442     }
4443
4444   /* Integral and aggregates go in general registers.  If we have run out of
4445      FR registers, then FP values must also go in general registers.  This can
4446      happen when we have a SFmode HFA.  */
4447   else if (mode == TFmode || mode == TCmode
4448            || (! FLOAT_MODE_P (mode) || cum->fp_regs == MAX_ARGUMENT_SLOTS))
4449     {
4450       int byte_size = ((mode == BLKmode)
4451                        ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
4452       if (BYTES_BIG_ENDIAN
4453         && (mode == BLKmode || (type && AGGREGATE_TYPE_P (type)))
4454         && byte_size < UNITS_PER_WORD
4455         && byte_size > 0)
4456         {
4457           rtx gr_reg = gen_rtx_EXPR_LIST (VOIDmode,
4458                                           gen_rtx_REG (DImode,
4459                                                        (basereg + cum->words
4460                                                         + offset)),
4461                                           const0_rtx);
4462           return gen_rtx_PARALLEL (mode, gen_rtvec (1, gr_reg));
4463         }
4464       else
4465         return gen_rtx_REG (mode, basereg + cum->words + offset);
4466
4467     }
4468
4469   /* If there is a prototype, then FP values go in a FR register when
4470      named, and in a GR register when unnamed.  */
4471   else if (cum->prototype)
4472     {
4473       if (named)
4474         return gen_rtx_REG (mode, FR_ARG_FIRST + cum->fp_regs);
4475       /* In big-endian mode, an anonymous SFmode value must be represented
4476          as (parallel:SF [(expr_list (reg:DI n) (const_int 0))]) to force
4477          the value into the high half of the general register.  */
4478       else if (BYTES_BIG_ENDIAN && mode == SFmode)
4479         return gen_rtx_PARALLEL (mode,
4480                  gen_rtvec (1,
4481                    gen_rtx_EXPR_LIST (VOIDmode,
4482                      gen_rtx_REG (DImode, basereg + cum->words + offset),
4483                                       const0_rtx)));
4484       else
4485         return gen_rtx_REG (mode, basereg + cum->words + offset);
4486     }
4487   /* If there is no prototype, then FP values go in both FR and GR
4488      registers.  */
4489   else
4490     {
4491       /* See comment above.  */
4492       enum machine_mode inner_mode =
4493         (BYTES_BIG_ENDIAN && mode == SFmode) ? DImode : mode;
4494
4495       rtx fp_reg = gen_rtx_EXPR_LIST (VOIDmode,
4496                                       gen_rtx_REG (mode, (FR_ARG_FIRST
4497                                                           + cum->fp_regs)),
4498                                       const0_rtx);
4499       rtx gr_reg = gen_rtx_EXPR_LIST (VOIDmode,
4500                                       gen_rtx_REG (inner_mode,
4501                                                    (basereg + cum->words
4502                                                     + offset)),
4503                                       const0_rtx);
4504
4505       return gen_rtx_PARALLEL (mode, gen_rtvec (2, fp_reg, gr_reg));
4506     }
4507 }
4508
4509 /* Implement TARGET_FUNCION_ARG target hook.  */
4510
4511 static rtx
4512 ia64_function_arg (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4513                    const_tree type, bool named)
4514 {
4515   return ia64_function_arg_1 (cum, mode, type, named, false);
4516 }
4517
4518 /* Implement TARGET_FUNCION_INCOMING_ARG target hook.  */
4519
4520 static rtx
4521 ia64_function_incoming_arg (CUMULATIVE_ARGS *cum,
4522                             enum machine_mode mode,
4523                             const_tree type, bool named)
4524 {
4525   return ia64_function_arg_1 (cum, mode, type, named, true);
4526 }
4527
4528 /* Return number of bytes, at the beginning of the argument, that must be
4529    put in registers.  0 is the argument is entirely in registers or entirely
4530    in memory.  */
4531
4532 static int
4533 ia64_arg_partial_bytes (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4534                         tree type, bool named ATTRIBUTE_UNUSED)
4535 {
4536   int words = ia64_function_arg_words (type, mode);
4537   int offset = ia64_function_arg_offset (cum, type, words);
4538
4539   /* If all argument slots are used, then it must go on the stack.  */
4540   if (cum->words + offset >= MAX_ARGUMENT_SLOTS)
4541     return 0;
4542
4543   /* It doesn't matter whether the argument goes in FR or GR regs.  If
4544      it fits within the 8 argument slots, then it goes entirely in
4545      registers.  If it extends past the last argument slot, then the rest
4546      goes on the stack.  */
4547
4548   if (words + cum->words + offset <= MAX_ARGUMENT_SLOTS)
4549     return 0;
4550
4551   return (MAX_ARGUMENT_SLOTS - cum->words - offset) * UNITS_PER_WORD;
4552 }
4553
4554 /* Return ivms_arg_type based on machine_mode.  */
4555
4556 static enum ivms_arg_type
4557 ia64_arg_type (enum machine_mode mode)
4558 {
4559   switch (mode)
4560     {
4561     case SFmode:
4562       return FS;
4563     case DFmode:
4564       return FT;
4565     default:
4566       return I64;
4567     }
4568 }
4569
4570 /* Update CUM to point after this argument.  This is patterned after
4571    ia64_function_arg.  */
4572
4573 static void
4574 ia64_function_arg_advance (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4575                            const_tree type, bool named)
4576 {
4577   int words = ia64_function_arg_words (type, mode);
4578   int offset = ia64_function_arg_offset (cum, type, words);
4579   enum machine_mode hfa_mode = VOIDmode;
4580
4581   /* If all arg slots are already full, then there is nothing to do.  */
4582   if (cum->words >= MAX_ARGUMENT_SLOTS)
4583     {
4584       cum->words += words + offset;
4585       return;
4586     }
4587
4588   cum->atypes[cum->words] = ia64_arg_type (mode);
4589   cum->words += words + offset;
4590
4591   /* Check for and handle homogeneous FP aggregates.  */
4592   if (type)
4593     hfa_mode = hfa_element_mode (type, 0);
4594
4595   /* Unnamed prototyped hfas are passed as usual.  Named prototyped hfas
4596      and unprototyped hfas are passed specially.  */
4597   if (hfa_mode != VOIDmode && (! cum->prototype || named))
4598     {
4599       int fp_regs = cum->fp_regs;
4600       /* This is the original value of cum->words + offset.  */
4601       int int_regs = cum->words - words;
4602       int hfa_size = GET_MODE_SIZE (hfa_mode);
4603       int byte_size;
4604       int args_byte_size;
4605
4606       /* If prototyped, pass it in FR regs then GR regs.
4607          If not prototyped, pass it in both FR and GR regs.
4608
4609          If this is an SFmode aggregate, then it is possible to run out of
4610          FR regs while GR regs are still left.  In that case, we pass the
4611          remaining part in the GR regs.  */
4612
4613       /* Fill the FP regs.  We do this always.  We stop if we reach the end
4614          of the argument, the last FP register, or the last argument slot.  */
4615
4616       byte_size = ((mode == BLKmode)
4617                    ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
4618       args_byte_size = int_regs * UNITS_PER_WORD;
4619       offset = 0;
4620       for (; (offset < byte_size && fp_regs < MAX_ARGUMENT_SLOTS
4621               && args_byte_size < (MAX_ARGUMENT_SLOTS * UNITS_PER_WORD));)
4622         {
4623           offset += hfa_size;
4624           args_byte_size += hfa_size;
4625           fp_regs++;
4626         }
4627
4628       cum->fp_regs = fp_regs;
4629     }
4630
4631   /* On OpenVMS variable argument is either in Rn or Fn.  */
4632   else if (TARGET_ABI_OPEN_VMS && named == 0)
4633     {
4634       cum->int_regs = cum->words;
4635       cum->fp_regs = cum->words;
4636     }
4637
4638   /* Integral and aggregates go in general registers.  So do TFmode FP values.
4639      If we have run out of FR registers, then other FP values must also go in
4640      general registers.  This can happen when we have a SFmode HFA.  */
4641   else if (mode == TFmode || mode == TCmode
4642            || (! FLOAT_MODE_P (mode) || cum->fp_regs == MAX_ARGUMENT_SLOTS))
4643     cum->int_regs = cum->words;
4644
4645   /* If there is a prototype, then FP values go in a FR register when
4646      named, and in a GR register when unnamed.  */
4647   else if (cum->prototype)
4648     {
4649       if (! named)
4650         cum->int_regs = cum->words;
4651       else
4652         /* ??? Complex types should not reach here.  */
4653         cum->fp_regs += (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT ? 2 : 1);
4654     }
4655   /* If there is no prototype, then FP values go in both FR and GR
4656      registers.  */
4657   else
4658     {
4659       /* ??? Complex types should not reach here.  */
4660       cum->fp_regs += (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT ? 2 : 1);
4661       cum->int_regs = cum->words;
4662     }
4663 }
4664
4665 /* Arguments with alignment larger than 8 bytes start at the next even
4666    boundary.  On ILP32 HPUX, TFmode arguments start on next even boundary
4667    even though their normal alignment is 8 bytes.  See ia64_function_arg.  */
4668
4669 int
4670 ia64_function_arg_boundary (enum machine_mode mode, tree type)
4671 {
4672
4673   if (mode == TFmode && TARGET_HPUX && TARGET_ILP32)
4674     return PARM_BOUNDARY * 2;
4675
4676   if (type)
4677     {
4678       if (TYPE_ALIGN (type) > PARM_BOUNDARY)
4679         return PARM_BOUNDARY * 2;
4680       else
4681         return PARM_BOUNDARY;
4682     }
4683
4684   if (GET_MODE_BITSIZE (mode) > PARM_BOUNDARY)
4685     return PARM_BOUNDARY * 2;
4686   else
4687     return PARM_BOUNDARY;
4688 }
4689
4690 /* True if it is OK to do sibling call optimization for the specified
4691    call expression EXP.  DECL will be the called function, or NULL if
4692    this is an indirect call.  */
4693 static bool
4694 ia64_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
4695 {
4696   /* We can't perform a sibcall if the current function has the syscall_linkage
4697      attribute.  */
4698   if (lookup_attribute ("syscall_linkage",
4699                         TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))))
4700     return false;
4701
4702   /* We must always return with our current GP.  This means we can
4703      only sibcall to functions defined in the current module unless
4704      TARGET_CONST_GP is set to true.  */
4705   return (decl && (*targetm.binds_local_p) (decl)) || TARGET_CONST_GP;
4706 }
4707 \f
4708
4709 /* Implement va_arg.  */
4710
4711 static tree
4712 ia64_gimplify_va_arg (tree valist, tree type, gimple_seq *pre_p,
4713                       gimple_seq *post_p)
4714 {
4715   /* Variable sized types are passed by reference.  */
4716   if (pass_by_reference (NULL, TYPE_MODE (type), type, false))
4717     {
4718       tree ptrtype = build_pointer_type (type);
4719       tree addr = std_gimplify_va_arg_expr (valist, ptrtype, pre_p, post_p);
4720       return build_va_arg_indirect_ref (addr);
4721     }
4722
4723   /* Aggregate arguments with alignment larger than 8 bytes start at
4724      the next even boundary.  Integer and floating point arguments
4725      do so if they are larger than 8 bytes, whether or not they are
4726      also aligned larger than 8 bytes.  */
4727   if ((TREE_CODE (type) == REAL_TYPE || TREE_CODE (type) == INTEGER_TYPE)
4728       ? int_size_in_bytes (type) > 8 : TYPE_ALIGN (type) > 8 * BITS_PER_UNIT)
4729     {
4730       tree t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (valist), valist,
4731                        size_int (2 * UNITS_PER_WORD - 1));
4732       t = fold_convert (sizetype, t);
4733       t = build2 (BIT_AND_EXPR, TREE_TYPE (t), t,
4734                   size_int (-2 * UNITS_PER_WORD));
4735       t = fold_convert (TREE_TYPE (valist), t);
4736       gimplify_assign (unshare_expr (valist), t, pre_p);
4737     }
4738
4739   return std_gimplify_va_arg_expr (valist, type, pre_p, post_p);
4740 }
4741 \f
4742 /* Return 1 if function return value returned in memory.  Return 0 if it is
4743    in a register.  */
4744
4745 static bool
4746 ia64_return_in_memory (const_tree valtype, const_tree fntype ATTRIBUTE_UNUSED)
4747 {
4748   enum machine_mode mode;
4749   enum machine_mode hfa_mode;
4750   HOST_WIDE_INT byte_size;
4751
4752   mode = TYPE_MODE (valtype);
4753   byte_size = GET_MODE_SIZE (mode);
4754   if (mode == BLKmode)
4755     {
4756       byte_size = int_size_in_bytes (valtype);
4757       if (byte_size < 0)
4758         return true;
4759     }
4760
4761   /* Hfa's with up to 8 elements are returned in the FP argument registers.  */
4762
4763   hfa_mode = hfa_element_mode (valtype, 0);
4764   if (hfa_mode != VOIDmode)
4765     {
4766       int hfa_size = GET_MODE_SIZE (hfa_mode);
4767
4768       if (byte_size / hfa_size > MAX_ARGUMENT_SLOTS)
4769         return true;
4770       else
4771         return false;
4772     }
4773   else if (byte_size > UNITS_PER_WORD * MAX_INT_RETURN_SLOTS)
4774     return true;
4775   else
4776     return false;
4777 }
4778
4779 /* Return rtx for register that holds the function return value.  */
4780
4781 static rtx
4782 ia64_function_value (const_tree valtype,
4783                      const_tree fn_decl_or_type,
4784                      bool outgoing ATTRIBUTE_UNUSED)
4785 {
4786   enum machine_mode mode;
4787   enum machine_mode hfa_mode;
4788   int unsignedp;
4789   const_tree func = fn_decl_or_type;
4790
4791   if (fn_decl_or_type
4792       && !DECL_P (fn_decl_or_type))
4793     func = NULL;
4794   
4795   mode = TYPE_MODE (valtype);
4796   hfa_mode = hfa_element_mode (valtype, 0);
4797
4798   if (hfa_mode != VOIDmode)
4799     {
4800       rtx loc[8];
4801       int i;
4802       int hfa_size;
4803       int byte_size;
4804       int offset;
4805
4806       hfa_size = GET_MODE_SIZE (hfa_mode);
4807       byte_size = ((mode == BLKmode)
4808                    ? int_size_in_bytes (valtype) : GET_MODE_SIZE (mode));
4809       offset = 0;
4810       for (i = 0; offset < byte_size; i++)
4811         {
4812           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4813                                       gen_rtx_REG (hfa_mode, FR_ARG_FIRST + i),
4814                                       GEN_INT (offset));
4815           offset += hfa_size;
4816         }
4817       return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
4818     }
4819   else if (FLOAT_TYPE_P (valtype) && mode != TFmode && mode != TCmode)
4820     return gen_rtx_REG (mode, FR_ARG_FIRST);
4821   else
4822     {
4823       bool need_parallel = false;
4824
4825       /* In big-endian mode, we need to manage the layout of aggregates
4826          in the registers so that we get the bits properly aligned in
4827          the highpart of the registers.  */
4828       if (BYTES_BIG_ENDIAN
4829           && (mode == BLKmode || (valtype && AGGREGATE_TYPE_P (valtype))))
4830         need_parallel = true;
4831
4832       /* Something like struct S { long double x; char a[0] } is not an
4833          HFA structure, and therefore doesn't go in fp registers.  But
4834          the middle-end will give it XFmode anyway, and XFmode values
4835          don't normally fit in integer registers.  So we need to smuggle
4836          the value inside a parallel.  */
4837       else if (mode == XFmode || mode == XCmode || mode == RFmode)
4838         need_parallel = true;
4839
4840       if (need_parallel)
4841         {
4842           rtx loc[8];
4843           int offset;
4844           int bytesize;
4845           int i;
4846
4847           offset = 0;
4848           bytesize = int_size_in_bytes (valtype);
4849           /* An empty PARALLEL is invalid here, but the return value
4850              doesn't matter for empty structs.  */
4851           if (bytesize == 0)
4852             return gen_rtx_REG (mode, GR_RET_FIRST);
4853           for (i = 0; offset < bytesize; i++)
4854             {
4855               loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4856                                           gen_rtx_REG (DImode,
4857                                                        GR_RET_FIRST + i),
4858                                           GEN_INT (offset));
4859               offset += UNITS_PER_WORD;
4860             }
4861           return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
4862         }
4863
4864       mode = ia64_promote_function_mode (valtype, mode, &unsignedp,
4865                                          func ? TREE_TYPE (func) : NULL_TREE,
4866                                          true);
4867
4868       return gen_rtx_REG (mode, GR_RET_FIRST);
4869     }
4870 }
4871
4872 /* Worker function for TARGET_LIBCALL_VALUE.  */
4873
4874 static rtx
4875 ia64_libcall_value (enum machine_mode mode,
4876                     const_rtx fun ATTRIBUTE_UNUSED)
4877 {
4878   return gen_rtx_REG (mode,
4879                       (((GET_MODE_CLASS (mode) == MODE_FLOAT
4880                          || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
4881                         && (mode) != TFmode)
4882                        ? FR_RET_FIRST : GR_RET_FIRST));
4883 }
4884
4885 /* Worker function for FUNCTION_VALUE_REGNO_P.  */
4886
4887 static bool
4888 ia64_function_value_regno_p (const unsigned int regno)
4889 {
4890   return ((regno >= GR_RET_FIRST && regno <= GR_RET_LAST)
4891           || (regno >= FR_RET_FIRST && regno <= FR_RET_LAST));
4892 }
4893
4894 /* This is called from dwarf2out.c via TARGET_ASM_OUTPUT_DWARF_DTPREL.
4895    We need to emit DTP-relative relocations.  */
4896
4897 static void
4898 ia64_output_dwarf_dtprel (FILE *file, int size, rtx x)
4899 {
4900   gcc_assert (size == 4 || size == 8);
4901   if (size == 4)
4902     fputs ("\tdata4.ua\t@dtprel(", file);
4903   else
4904     fputs ("\tdata8.ua\t@dtprel(", file);
4905   output_addr_const (file, x);
4906   fputs (")", file);
4907 }
4908
4909 /* Print a memory address as an operand to reference that memory location.  */
4910
4911 /* ??? Do we need this?  It gets used only for 'a' operands.  We could perhaps
4912    also call this from ia64_print_operand for memory addresses.  */
4913
4914 void
4915 ia64_print_operand_address (FILE * stream ATTRIBUTE_UNUSED,
4916                             rtx address ATTRIBUTE_UNUSED)
4917 {
4918 }
4919
4920 /* Print an operand to an assembler instruction.
4921    C    Swap and print a comparison operator.
4922    D    Print an FP comparison operator.
4923    E    Print 32 - constant, for SImode shifts as extract.
4924    e    Print 64 - constant, for DImode rotates.
4925    F    A floating point constant 0.0 emitted as f0, or 1.0 emitted as f1, or
4926         a floating point register emitted normally.
4927    G    A floating point constant.
4928    I    Invert a predicate register by adding 1.
4929    J    Select the proper predicate register for a condition.
4930    j    Select the inverse predicate register for a condition.
4931    O    Append .acq for volatile load.
4932    P    Postincrement of a MEM.
4933    Q    Append .rel for volatile store.
4934    R    Print .s .d or nothing for a single, double or no truncation.
4935    S    Shift amount for shladd instruction.
4936    T    Print an 8-bit sign extended number (K) as a 32-bit unsigned number
4937         for Intel assembler.
4938    U    Print an 8-bit sign extended number (K) as a 64-bit unsigned number
4939         for Intel assembler.
4940    X    A pair of floating point registers.
4941    r    Print register name, or constant 0 as r0.  HP compatibility for
4942         Linux kernel.
4943    v    Print vector constant value as an 8-byte integer value.  */
4944
4945 void
4946 ia64_print_operand (FILE * file, rtx x, int code)
4947 {
4948   const char *str;
4949
4950   switch (code)
4951     {
4952     case 0:
4953       /* Handled below.  */
4954       break;
4955
4956     case 'C':
4957       {
4958         enum rtx_code c = swap_condition (GET_CODE (x));
4959         fputs (GET_RTX_NAME (c), file);
4960         return;
4961       }
4962
4963     case 'D':
4964       switch (GET_CODE (x))
4965         {
4966         case NE:
4967           str = "neq";
4968           break;
4969         case UNORDERED:
4970           str = "unord";
4971           break;
4972         case ORDERED:
4973           str = "ord";
4974           break;
4975         case UNLT:
4976           str = "nge";
4977           break;
4978         case UNLE:
4979           str = "ngt";
4980           break;
4981         case UNGT:
4982           str = "nle";
4983           break;
4984         case UNGE:
4985           str = "nlt";
4986           break;
4987         default:
4988           str = GET_RTX_NAME (GET_CODE (x));
4989           break;
4990         }
4991       fputs (str, file);
4992       return;
4993
4994     case 'E':
4995       fprintf (file, HOST_WIDE_INT_PRINT_DEC, 32 - INTVAL (x));
4996       return;
4997
4998     case 'e':
4999       fprintf (file, HOST_WIDE_INT_PRINT_DEC, 64 - INTVAL (x));
5000       return;
5001
5002     case 'F':
5003       if (x == CONST0_RTX (GET_MODE (x)))
5004         str = reg_names [FR_REG (0)];
5005       else if (x == CONST1_RTX (GET_MODE (x)))
5006         str = reg_names [FR_REG (1)];
5007       else
5008         {
5009           gcc_assert (GET_CODE (x) == REG);
5010           str = reg_names [REGNO (x)];
5011         }
5012       fputs (str, file);
5013       return;
5014
5015     case 'G':
5016       {
5017         long val[4];
5018         REAL_VALUE_TYPE rv;
5019         REAL_VALUE_FROM_CONST_DOUBLE (rv, x);
5020         real_to_target (val, &rv, GET_MODE (x));
5021         if (GET_MODE (x) == SFmode)
5022           fprintf (file, "0x%08lx", val[0] & 0xffffffff);
5023         else if (GET_MODE (x) == DFmode)
5024           fprintf (file, "0x%08lx%08lx", (WORDS_BIG_ENDIAN ? val[0] : val[1])
5025                                           & 0xffffffff,
5026                                          (WORDS_BIG_ENDIAN ? val[1] : val[0])
5027                                           & 0xffffffff);
5028         else
5029           output_operand_lossage ("invalid %%G mode");
5030       }
5031       return;
5032
5033     case 'I':
5034       fputs (reg_names [REGNO (x) + 1], file);
5035       return;
5036
5037     case 'J':
5038     case 'j':
5039       {
5040         unsigned int regno = REGNO (XEXP (x, 0));
5041         if (GET_CODE (x) == EQ)
5042           regno += 1;
5043         if (code == 'j')
5044           regno ^= 1;
5045         fputs (reg_names [regno], file);
5046       }
5047       return;
5048
5049     case 'O':
5050       if (MEM_VOLATILE_P (x))
5051         fputs(".acq", file);
5052       return;
5053
5054     case 'P':
5055       {
5056         HOST_WIDE_INT value;
5057
5058         switch (GET_CODE (XEXP (x, 0)))
5059           {
5060           default:
5061             return;
5062
5063           case POST_MODIFY:
5064             x = XEXP (XEXP (XEXP (x, 0), 1), 1);
5065             if (GET_CODE (x) == CONST_INT)
5066               value = INTVAL (x);
5067             else
5068               {
5069                 gcc_assert (GET_CODE (x) == REG);
5070                 fprintf (file, ", %s", reg_names[REGNO (x)]);
5071                 return;
5072               }
5073             break;
5074
5075           case POST_INC:
5076             value = GET_MODE_SIZE (GET_MODE (x));
5077             break;
5078
5079           case POST_DEC:
5080             value = - (HOST_WIDE_INT) GET_MODE_SIZE (GET_MODE (x));
5081             break;
5082           }
5083
5084         fprintf (file, ", " HOST_WIDE_INT_PRINT_DEC, value);
5085         return;
5086       }
5087
5088     case 'Q':
5089       if (MEM_VOLATILE_P (x))
5090         fputs(".rel", file);
5091       return;
5092
5093     case 'R':
5094       if (x == CONST0_RTX (GET_MODE (x)))
5095         fputs(".s", file);
5096       else if (x == CONST1_RTX (GET_MODE (x)))
5097         fputs(".d", file);
5098       else if (x == CONST2_RTX (GET_MODE (x)))
5099         ;
5100       else
5101         output_operand_lossage ("invalid %%R value");
5102       return;
5103
5104     case 'S':
5105       fprintf (file, "%d", exact_log2 (INTVAL (x)));
5106       return;
5107
5108     case 'T':
5109       if (! TARGET_GNU_AS && GET_CODE (x) == CONST_INT)
5110         {
5111           fprintf (file, "0x%x", (int) INTVAL (x) & 0xffffffff);
5112           return;
5113         }
5114       break;
5115
5116     case 'U':
5117       if (! TARGET_GNU_AS && GET_CODE (x) == CONST_INT)
5118         {
5119           const char *prefix = "0x";
5120           if (INTVAL (x) & 0x80000000)
5121             {
5122               fprintf (file, "0xffffffff");
5123               prefix = "";
5124             }
5125           fprintf (file, "%s%x", prefix, (int) INTVAL (x) & 0xffffffff);
5126           return;
5127         }
5128       break;
5129
5130     case 'X':
5131       {
5132         unsigned int regno = REGNO (x);
5133         fprintf (file, "%s, %s", reg_names [regno], reg_names [regno + 1]);
5134       }
5135       return;
5136
5137     case 'r':
5138       /* If this operand is the constant zero, write it as register zero.
5139          Any register, zero, or CONST_INT value is OK here.  */
5140       if (GET_CODE (x) == REG)
5141         fputs (reg_names[REGNO (x)], file);
5142       else if (x == CONST0_RTX (GET_MODE (x)))
5143         fputs ("r0", file);
5144       else if (GET_CODE (x) == CONST_INT)
5145         output_addr_const (file, x);
5146       else
5147         output_operand_lossage ("invalid %%r value");
5148       return;
5149
5150     case 'v':
5151       gcc_assert (GET_CODE (x) == CONST_VECTOR);
5152       x = simplify_subreg (DImode, x, GET_MODE (x), 0);
5153       break;
5154
5155     case '+':
5156       {
5157         const char *which;
5158
5159         /* For conditional branches, returns or calls, substitute
5160            sptk, dptk, dpnt, or spnt for %s.  */
5161         x = find_reg_note (current_output_insn, REG_BR_PROB, 0);
5162         if (x)
5163           {
5164             int pred_val = INTVAL (XEXP (x, 0));
5165
5166             /* Guess top and bottom 10% statically predicted.  */
5167             if (pred_val < REG_BR_PROB_BASE / 50
5168                 && br_prob_note_reliable_p (x))
5169               which = ".spnt";
5170             else if (pred_val < REG_BR_PROB_BASE / 2)
5171               which = ".dpnt";
5172             else if (pred_val < REG_BR_PROB_BASE / 100 * 98
5173                      || !br_prob_note_reliable_p (x))
5174               which = ".dptk";
5175             else
5176               which = ".sptk";
5177           }
5178         else if (GET_CODE (current_output_insn) == CALL_INSN)
5179           which = ".sptk";
5180         else
5181           which = ".dptk";
5182
5183         fputs (which, file);
5184         return;
5185       }
5186
5187     case ',':
5188       x = current_insn_predicate;
5189       if (x)
5190         {
5191           unsigned int regno = REGNO (XEXP (x, 0));
5192           if (GET_CODE (x) == EQ)
5193             regno += 1;
5194           fprintf (file, "(%s) ", reg_names [regno]);
5195         }
5196       return;
5197
5198     default:
5199       output_operand_lossage ("ia64_print_operand: unknown code");
5200       return;
5201     }
5202
5203   switch (GET_CODE (x))
5204     {
5205       /* This happens for the spill/restore instructions.  */
5206     case POST_INC:
5207     case POST_DEC:
5208     case POST_MODIFY:
5209       x = XEXP (x, 0);
5210       /* ... fall through ...  */
5211
5212     case REG:
5213       fputs (reg_names [REGNO (x)], file);
5214       break;
5215
5216     case MEM:
5217       {
5218         rtx addr = XEXP (x, 0);
5219         if (GET_RTX_CLASS (GET_CODE (addr)) == RTX_AUTOINC)
5220           addr = XEXP (addr, 0);
5221         fprintf (file, "[%s]", reg_names [REGNO (addr)]);
5222         break;
5223       }
5224
5225     default:
5226       output_addr_const (file, x);
5227       break;
5228     }
5229
5230   return;
5231 }
5232 \f
5233 /* Compute a (partial) cost for rtx X.  Return true if the complete
5234    cost has been computed, and false if subexpressions should be
5235    scanned.  In either case, *TOTAL contains the cost result.  */
5236 /* ??? This is incomplete.  */
5237
5238 static bool
5239 ia64_rtx_costs (rtx x, int code, int outer_code, int *total,
5240                 bool speed ATTRIBUTE_UNUSED)
5241 {
5242   switch (code)
5243     {
5244     case CONST_INT:
5245       switch (outer_code)
5246         {
5247         case SET:
5248           *total = satisfies_constraint_J (x) ? 0 : COSTS_N_INSNS (1);
5249           return true;
5250         case PLUS:
5251           if (satisfies_constraint_I (x))
5252             *total = 0;
5253           else if (satisfies_constraint_J (x))
5254             *total = 1;
5255           else
5256             *total = COSTS_N_INSNS (1);
5257           return true;
5258         default:
5259           if (satisfies_constraint_K (x) || satisfies_constraint_L (x))
5260             *total = 0;
5261           else
5262             *total = COSTS_N_INSNS (1);
5263           return true;
5264         }
5265
5266     case CONST_DOUBLE:
5267       *total = COSTS_N_INSNS (1);
5268       return true;
5269
5270     case CONST:
5271     case SYMBOL_REF:
5272     case LABEL_REF:
5273       *total = COSTS_N_INSNS (3);
5274       return true;
5275
5276     case MULT:
5277       /* For multiplies wider than HImode, we have to go to the FPU,
5278          which normally involves copies.  Plus there's the latency
5279          of the multiply itself, and the latency of the instructions to
5280          transfer integer regs to FP regs.  */
5281       /* ??? Check for FP mode.  */
5282       if (GET_MODE_SIZE (GET_MODE (x)) > 2)
5283         *total = COSTS_N_INSNS (10);
5284       else
5285         *total = COSTS_N_INSNS (2);
5286       return true;
5287
5288     case PLUS:
5289     case MINUS:
5290     case ASHIFT:
5291     case ASHIFTRT:
5292     case LSHIFTRT:
5293       *total = COSTS_N_INSNS (1);
5294       return true;
5295
5296     case DIV:
5297     case UDIV:
5298     case MOD:
5299     case UMOD:
5300       /* We make divide expensive, so that divide-by-constant will be
5301          optimized to a multiply.  */
5302       *total = COSTS_N_INSNS (60);
5303       return true;
5304
5305     default:
5306       return false;
5307     }
5308 }
5309
5310 /* Calculate the cost of moving data from a register in class FROM to
5311    one in class TO, using MODE.  */
5312
5313 static int
5314 ia64_register_move_cost (enum machine_mode mode, reg_class_t from_i,
5315                          reg_class_t to_i)
5316 {
5317   enum reg_class from = (enum reg_class) from_i;
5318   enum reg_class to = (enum reg_class) to_i;
5319
5320   /* ADDL_REGS is the same as GR_REGS for movement purposes.  */
5321   if (to == ADDL_REGS)
5322     to = GR_REGS;
5323   if (from == ADDL_REGS)
5324     from = GR_REGS;
5325
5326   /* All costs are symmetric, so reduce cases by putting the
5327      lower number class as the destination.  */
5328   if (from < to)
5329     {
5330       enum reg_class tmp = to;
5331       to = from, from = tmp;
5332     }
5333
5334   /* Moving from FR<->GR in XFmode must be more expensive than 2,
5335      so that we get secondary memory reloads.  Between FR_REGS,
5336      we have to make this at least as expensive as memory_move_cost
5337      to avoid spectacularly poor register class preferencing.  */
5338   if (mode == XFmode || mode == RFmode)
5339     {
5340       if (to != GR_REGS || from != GR_REGS)
5341         return memory_move_cost (mode, to, false);
5342       else
5343         return 3;
5344     }
5345
5346   switch (to)
5347     {
5348     case PR_REGS:
5349       /* Moving between PR registers takes two insns.  */
5350       if (from == PR_REGS)
5351         return 3;
5352       /* Moving between PR and anything but GR is impossible.  */
5353       if (from != GR_REGS)
5354         return memory_move_cost (mode, to, false);
5355       break;
5356
5357     case BR_REGS:
5358       /* Moving between BR and anything but GR is impossible.  */
5359       if (from != GR_REGS && from != GR_AND_BR_REGS)
5360         return memory_move_cost (mode, to, false);
5361       break;
5362
5363     case AR_I_REGS:
5364     case AR_M_REGS:
5365       /* Moving between AR and anything but GR is impossible.  */
5366       if (from != GR_REGS)
5367         return memory_move_cost (mode, to, false);
5368       break;
5369
5370     case GR_REGS:
5371     case FR_REGS:
5372     case FP_REGS:
5373     case GR_AND_FR_REGS:
5374     case GR_AND_BR_REGS:
5375     case ALL_REGS:
5376       break;
5377
5378     default:
5379       gcc_unreachable ();
5380     }
5381
5382   return 2;
5383 }
5384
5385 /* Calculate the cost of moving data of MODE from a register to or from
5386    memory.  */
5387
5388 static int
5389 ia64_memory_move_cost (enum machine_mode mode ATTRIBUTE_UNUSED,
5390                        reg_class_t rclass,
5391                        bool in ATTRIBUTE_UNUSED)
5392 {
5393   if (rclass == GENERAL_REGS
5394       || rclass == FR_REGS
5395       || rclass == FP_REGS
5396       || rclass == GR_AND_FR_REGS)
5397     return 4;
5398   else
5399     return 10;
5400 }
5401
5402 /* Implement TARGET_PREFERRED_RELOAD_CLASS.  Place additional restrictions
5403    on RCLASS to use when copying X into that class.  */
5404
5405 static reg_class_t
5406 ia64_preferred_reload_class (rtx x, reg_class_t rclass)
5407 {
5408   switch (rclass)
5409     {
5410     case FR_REGS:
5411     case FP_REGS:
5412       /* Don't allow volatile mem reloads into floating point registers.
5413          This is defined to force reload to choose the r/m case instead
5414          of the f/f case when reloading (set (reg fX) (mem/v)).  */
5415       if (MEM_P (x) && MEM_VOLATILE_P (x))
5416         return NO_REGS;
5417       
5418       /* Force all unrecognized constants into the constant pool.  */
5419       if (CONSTANT_P (x))
5420         return NO_REGS;
5421       break;
5422
5423     case AR_M_REGS:
5424     case AR_I_REGS:
5425       if (!OBJECT_P (x))
5426         return NO_REGS;
5427       break;
5428
5429     default:
5430       break;
5431     }
5432
5433   return rclass;
5434 }
5435
5436 /* This function returns the register class required for a secondary
5437    register when copying between one of the registers in RCLASS, and X,
5438    using MODE.  A return value of NO_REGS means that no secondary register
5439    is required.  */
5440
5441 enum reg_class
5442 ia64_secondary_reload_class (enum reg_class rclass,
5443                              enum machine_mode mode ATTRIBUTE_UNUSED, rtx x)
5444 {
5445   int regno = -1;
5446
5447   if (GET_CODE (x) == REG || GET_CODE (x) == SUBREG)
5448     regno = true_regnum (x);
5449
5450   switch (rclass)
5451     {
5452     case BR_REGS:
5453     case AR_M_REGS:
5454     case AR_I_REGS:
5455       /* ??? BR<->BR register copies can happen due to a bad gcse/cse/global
5456          interaction.  We end up with two pseudos with overlapping lifetimes
5457          both of which are equiv to the same constant, and both which need
5458          to be in BR_REGS.  This seems to be a cse bug.  cse_basic_block_end
5459          changes depending on the path length, which means the qty_first_reg
5460          check in make_regs_eqv can give different answers at different times.
5461          At some point I'll probably need a reload_indi pattern to handle
5462          this.
5463
5464          We can also get GR_AND_FR_REGS to BR_REGS/AR_REGS copies, where we
5465          wound up with a FP register from GR_AND_FR_REGS.  Extend that to all
5466          non-general registers for good measure.  */
5467       if (regno >= 0 && ! GENERAL_REGNO_P (regno))
5468         return GR_REGS;
5469
5470       /* This is needed if a pseudo used as a call_operand gets spilled to a
5471          stack slot.  */
5472       if (GET_CODE (x) == MEM)
5473         return GR_REGS;
5474       break;
5475
5476     case FR_REGS:
5477     case FP_REGS:
5478       /* Need to go through general registers to get to other class regs.  */
5479       if (regno >= 0 && ! (FR_REGNO_P (regno) || GENERAL_REGNO_P (regno)))
5480         return GR_REGS;
5481
5482       /* This can happen when a paradoxical subreg is an operand to the
5483          muldi3 pattern.  */
5484       /* ??? This shouldn't be necessary after instruction scheduling is
5485          enabled, because paradoxical subregs are not accepted by
5486          register_operand when INSN_SCHEDULING is defined.  Or alternatively,
5487          stop the paradoxical subreg stupidity in the *_operand functions
5488          in recog.c.  */
5489       if (GET_CODE (x) == MEM
5490           && (GET_MODE (x) == SImode || GET_MODE (x) == HImode
5491               || GET_MODE (x) == QImode))
5492         return GR_REGS;
5493
5494       /* This can happen because of the ior/and/etc patterns that accept FP
5495          registers as operands.  If the third operand is a constant, then it
5496          needs to be reloaded into a FP register.  */
5497       if (GET_CODE (x) == CONST_INT)
5498         return GR_REGS;
5499
5500       /* This can happen because of register elimination in a muldi3 insn.
5501          E.g. `26107 * (unsigned long)&u'.  */
5502       if (GET_CODE (x) == PLUS)
5503         return GR_REGS;
5504       break;
5505
5506     case PR_REGS:
5507       /* ??? This happens if we cse/gcse a BImode value across a call,
5508          and the function has a nonlocal goto.  This is because global
5509          does not allocate call crossing pseudos to hard registers when
5510          crtl->has_nonlocal_goto is true.  This is relatively
5511          common for C++ programs that use exceptions.  To reproduce,
5512          return NO_REGS and compile libstdc++.  */
5513       if (GET_CODE (x) == MEM)
5514         return GR_REGS;
5515
5516       /* This can happen when we take a BImode subreg of a DImode value,
5517          and that DImode value winds up in some non-GR register.  */
5518       if (regno >= 0 && ! GENERAL_REGNO_P (regno) && ! PR_REGNO_P (regno))
5519         return GR_REGS;
5520       break;
5521
5522     default:
5523       break;
5524     }
5525
5526   return NO_REGS;
5527 }
5528
5529 \f
5530 /* Implement targetm.unspec_may_trap_p hook.  */
5531 static int
5532 ia64_unspec_may_trap_p (const_rtx x, unsigned flags)
5533 {
5534   if (GET_CODE (x) == UNSPEC)
5535     {
5536       switch (XINT (x, 1))
5537         {
5538         case UNSPEC_LDA:
5539         case UNSPEC_LDS:
5540         case UNSPEC_LDSA:
5541         case UNSPEC_LDCCLR:
5542         case UNSPEC_CHKACLR:
5543         case UNSPEC_CHKS:
5544           /* These unspecs are just wrappers.  */
5545           return may_trap_p_1 (XVECEXP (x, 0, 0), flags);
5546         }
5547     }
5548
5549   return default_unspec_may_trap_p (x, flags);
5550 }
5551
5552 \f
5553 /* Parse the -mfixed-range= option string.  */
5554
5555 static void
5556 fix_range (const char *const_str)
5557 {
5558   int i, first, last;
5559   char *str, *dash, *comma;
5560
5561   /* str must be of the form REG1'-'REG2{,REG1'-'REG} where REG1 and
5562      REG2 are either register names or register numbers.  The effect
5563      of this option is to mark the registers in the range from REG1 to
5564      REG2 as ``fixed'' so they won't be used by the compiler.  This is
5565      used, e.g., to ensure that kernel mode code doesn't use f32-f127.  */
5566
5567   i = strlen (const_str);
5568   str = (char *) alloca (i + 1);
5569   memcpy (str, const_str, i + 1);
5570
5571   while (1)
5572     {
5573       dash = strchr (str, '-');
5574       if (!dash)
5575         {
5576           warning (0, "value of -mfixed-range must have form REG1-REG2");
5577           return;
5578         }
5579       *dash = '\0';
5580
5581       comma = strchr (dash + 1, ',');
5582       if (comma)
5583         *comma = '\0';
5584
5585       first = decode_reg_name (str);
5586       if (first < 0)
5587         {
5588           warning (0, "unknown register name: %s", str);
5589           return;
5590         }
5591
5592       last = decode_reg_name (dash + 1);
5593       if (last < 0)
5594         {
5595           warning (0, "unknown register name: %s", dash + 1);
5596           return;
5597         }
5598
5599       *dash = '-';
5600
5601       if (first > last)
5602         {
5603           warning (0, "%s-%s is an empty range", str, dash + 1);
5604           return;
5605         }
5606
5607       for (i = first; i <= last; ++i)
5608         fixed_regs[i] = call_used_regs[i] = 1;
5609
5610       if (!comma)
5611         break;
5612
5613       *comma = ',';
5614       str = comma + 1;
5615     }
5616 }
5617
5618 /* Implement TARGET_HANDLE_OPTION.  */
5619
5620 static bool
5621 ia64_handle_option (size_t code, const char *arg, int value)
5622 {
5623   switch (code)
5624     {
5625     case OPT_mfixed_range_:
5626       fix_range (arg);
5627       return true;
5628
5629     case OPT_mtls_size_:
5630       if (value != 14 && value != 22 && value != 64)
5631         error ("bad value %<%s%> for -mtls-size= switch", arg);
5632       return true;
5633
5634     case OPT_mtune_:
5635       {
5636         static struct pta
5637           {
5638             const char *name;           /* processor name or nickname.  */
5639             enum processor_type processor;
5640           }
5641         const processor_alias_table[] =
5642           {
5643             {"itanium2", PROCESSOR_ITANIUM2},
5644             {"mckinley", PROCESSOR_ITANIUM2},
5645           };
5646         int const pta_size = ARRAY_SIZE (processor_alias_table);
5647         int i;
5648
5649         for (i = 0; i < pta_size; i++)
5650           if (!strcmp (arg, processor_alias_table[i].name))
5651             {
5652               ia64_tune = processor_alias_table[i].processor;
5653               break;
5654             }
5655         if (i == pta_size)
5656           error ("bad value %<%s%> for -mtune= switch", arg);
5657         return true;
5658       }
5659
5660     default:
5661       return true;
5662     }
5663 }
5664
5665 /* Implement TARGET_OPTION_OVERRIDE.  */
5666
5667 static void
5668 ia64_option_override (void)
5669 {
5670   if (TARGET_AUTO_PIC)
5671     target_flags |= MASK_CONST_GP;
5672
5673   /* Numerous experiment shows that IRA based loop pressure
5674      calculation works better for RTL loop invariant motion on targets
5675      with enough (>= 32) registers.  It is an expensive optimization.
5676      So it is on only for peak performance.  */
5677   if (optimize >= 3)
5678     flag_ira_loop_pressure = 1;
5679
5680
5681   ia64_section_threshold = (global_options_set.x_g_switch_value
5682                             ? g_switch_value
5683                             : IA64_DEFAULT_GVALUE);
5684
5685   init_machine_status = ia64_init_machine_status;
5686
5687   if (align_functions <= 0)
5688     align_functions = 64;
5689   if (align_loops <= 0)
5690     align_loops = 32;
5691   if (TARGET_ABI_OPEN_VMS)
5692     flag_no_common = 1;
5693
5694   ia64_override_options_after_change();
5695 }
5696
5697 /* Implement targetm.override_options_after_change.  */
5698
5699 static void
5700 ia64_override_options_after_change (void)
5701 {
5702   ia64_flag_schedule_insns2 = flag_schedule_insns_after_reload;
5703   flag_schedule_insns_after_reload = 0;
5704
5705   if (optimize >= 3
5706       && !global_options_set.x_flag_selective_scheduling
5707       && !global_options_set.x_flag_selective_scheduling2)
5708     {
5709       flag_selective_scheduling2 = 1;
5710       flag_sel_sched_pipelining = 1;
5711     }
5712   if (mflag_sched_control_spec == 2)
5713     {
5714       /* Control speculation is on by default for the selective scheduler,
5715          but not for the Haifa scheduler.  */
5716       mflag_sched_control_spec = flag_selective_scheduling2 ? 1 : 0;
5717     }
5718   if (flag_sel_sched_pipelining && flag_auto_inc_dec)
5719     {
5720       /* FIXME: remove this when we'd implement breaking autoinsns as
5721          a transformation.  */
5722       flag_auto_inc_dec = 0;
5723     }
5724 }
5725
5726 /* Initialize the record of emitted frame related registers.  */
5727
5728 void ia64_init_expanders (void)
5729 {
5730   memset (&emitted_frame_related_regs, 0, sizeof (emitted_frame_related_regs));
5731 }
5732
5733 static struct machine_function *
5734 ia64_init_machine_status (void)
5735 {
5736   return ggc_alloc_cleared_machine_function ();
5737 }
5738 \f
5739 static enum attr_itanium_class ia64_safe_itanium_class (rtx);
5740 static enum attr_type ia64_safe_type (rtx);
5741
5742 static enum attr_itanium_class
5743 ia64_safe_itanium_class (rtx insn)
5744 {
5745   if (recog_memoized (insn) >= 0)
5746     return get_attr_itanium_class (insn);
5747   else if (DEBUG_INSN_P (insn))
5748     return ITANIUM_CLASS_IGNORE;
5749   else
5750     return ITANIUM_CLASS_UNKNOWN;
5751 }
5752
5753 static enum attr_type
5754 ia64_safe_type (rtx insn)
5755 {
5756   if (recog_memoized (insn) >= 0)
5757     return get_attr_type (insn);
5758   else
5759     return TYPE_UNKNOWN;
5760 }
5761 \f
5762 /* The following collection of routines emit instruction group stop bits as
5763    necessary to avoid dependencies.  */
5764
5765 /* Need to track some additional registers as far as serialization is
5766    concerned so we can properly handle br.call and br.ret.  We could
5767    make these registers visible to gcc, but since these registers are
5768    never explicitly used in gcc generated code, it seems wasteful to
5769    do so (plus it would make the call and return patterns needlessly
5770    complex).  */
5771 #define REG_RP          (BR_REG (0))
5772 #define REG_AR_CFM      (FIRST_PSEUDO_REGISTER + 1)
5773 /* This is used for volatile asms which may require a stop bit immediately
5774    before and after them.  */
5775 #define REG_VOLATILE    (FIRST_PSEUDO_REGISTER + 2)
5776 #define AR_UNAT_BIT_0   (FIRST_PSEUDO_REGISTER + 3)
5777 #define NUM_REGS        (AR_UNAT_BIT_0 + 64)
5778
5779 /* For each register, we keep track of how it has been written in the
5780    current instruction group.
5781
5782    If a register is written unconditionally (no qualifying predicate),
5783    WRITE_COUNT is set to 2 and FIRST_PRED is ignored.
5784
5785    If a register is written if its qualifying predicate P is true, we
5786    set WRITE_COUNT to 1 and FIRST_PRED to P.  Later on, the same register
5787    may be written again by the complement of P (P^1) and when this happens,
5788    WRITE_COUNT gets set to 2.
5789
5790    The result of this is that whenever an insn attempts to write a register
5791    whose WRITE_COUNT is two, we need to issue an insn group barrier first.
5792
5793    If a predicate register is written by a floating-point insn, we set
5794    WRITTEN_BY_FP to true.
5795
5796    If a predicate register is written by an AND.ORCM we set WRITTEN_BY_AND
5797    to true; if it was written by an OR.ANDCM we set WRITTEN_BY_OR to true.  */
5798
5799 #if GCC_VERSION >= 4000
5800 #define RWS_FIELD_TYPE __extension__ unsigned short
5801 #else
5802 #define RWS_FIELD_TYPE unsigned int
5803 #endif
5804 struct reg_write_state
5805 {
5806   RWS_FIELD_TYPE write_count : 2;
5807   RWS_FIELD_TYPE first_pred : 10;
5808   RWS_FIELD_TYPE written_by_fp : 1;
5809   RWS_FIELD_TYPE written_by_and : 1;
5810   RWS_FIELD_TYPE written_by_or : 1;
5811 };
5812
5813 /* Cumulative info for the current instruction group.  */
5814 struct reg_write_state rws_sum[NUM_REGS];
5815 #ifdef ENABLE_CHECKING
5816 /* Bitmap whether a register has been written in the current insn.  */
5817 HARD_REG_ELT_TYPE rws_insn[(NUM_REGS + HOST_BITS_PER_WIDEST_FAST_INT - 1)
5818                            / HOST_BITS_PER_WIDEST_FAST_INT];
5819
5820 static inline void
5821 rws_insn_set (int regno)
5822 {
5823   gcc_assert (!TEST_HARD_REG_BIT (rws_insn, regno));
5824   SET_HARD_REG_BIT (rws_insn, regno);
5825 }
5826
5827 static inline int
5828 rws_insn_test (int regno)
5829 {
5830   return TEST_HARD_REG_BIT (rws_insn, regno);
5831 }
5832 #else
5833 /* When not checking, track just REG_AR_CFM and REG_VOLATILE.  */
5834 unsigned char rws_insn[2];
5835
5836 static inline void
5837 rws_insn_set (int regno)
5838 {
5839   if (regno == REG_AR_CFM)
5840     rws_insn[0] = 1;
5841   else if (regno == REG_VOLATILE)
5842     rws_insn[1] = 1;
5843 }
5844
5845 static inline int
5846 rws_insn_test (int regno)
5847 {
5848   if (regno == REG_AR_CFM)
5849     return rws_insn[0];
5850   if (regno == REG_VOLATILE)
5851     return rws_insn[1];
5852   return 0;
5853 }
5854 #endif
5855
5856 /* Indicates whether this is the first instruction after a stop bit,
5857    in which case we don't need another stop bit.  Without this,
5858    ia64_variable_issue will die when scheduling an alloc.  */
5859 static int first_instruction;
5860
5861 /* Misc flags needed to compute RAW/WAW dependencies while we are traversing
5862    RTL for one instruction.  */
5863 struct reg_flags
5864 {
5865   unsigned int is_write : 1;    /* Is register being written?  */
5866   unsigned int is_fp : 1;       /* Is register used as part of an fp op?  */
5867   unsigned int is_branch : 1;   /* Is register used as part of a branch?  */
5868   unsigned int is_and : 1;      /* Is register used as part of and.orcm?  */
5869   unsigned int is_or : 1;       /* Is register used as part of or.andcm?  */
5870   unsigned int is_sibcall : 1;  /* Is this a sibling or normal call?  */
5871 };
5872
5873 static void rws_update (int, struct reg_flags, int);
5874 static int rws_access_regno (int, struct reg_flags, int);
5875 static int rws_access_reg (rtx, struct reg_flags, int);
5876 static void update_set_flags (rtx, struct reg_flags *);
5877 static int set_src_needs_barrier (rtx, struct reg_flags, int);
5878 static int rtx_needs_barrier (rtx, struct reg_flags, int);
5879 static void init_insn_group_barriers (void);
5880 static int group_barrier_needed (rtx);
5881 static int safe_group_barrier_needed (rtx);
5882 static int in_safe_group_barrier;
5883
5884 /* Update *RWS for REGNO, which is being written by the current instruction,
5885    with predicate PRED, and associated register flags in FLAGS.  */
5886
5887 static void
5888 rws_update (int regno, struct reg_flags flags, int pred)
5889 {
5890   if (pred)
5891     rws_sum[regno].write_count++;
5892   else
5893     rws_sum[regno].write_count = 2;
5894   rws_sum[regno].written_by_fp |= flags.is_fp;
5895   /* ??? Not tracking and/or across differing predicates.  */
5896   rws_sum[regno].written_by_and = flags.is_and;
5897   rws_sum[regno].written_by_or = flags.is_or;
5898   rws_sum[regno].first_pred = pred;
5899 }
5900
5901 /* Handle an access to register REGNO of type FLAGS using predicate register
5902    PRED.  Update rws_sum array.  Return 1 if this access creates
5903    a dependency with an earlier instruction in the same group.  */
5904
5905 static int
5906 rws_access_regno (int regno, struct reg_flags flags, int pred)
5907 {
5908   int need_barrier = 0;
5909
5910   gcc_assert (regno < NUM_REGS);
5911
5912   if (! PR_REGNO_P (regno))
5913     flags.is_and = flags.is_or = 0;
5914
5915   if (flags.is_write)
5916     {
5917       int write_count;
5918
5919       rws_insn_set (regno);
5920       write_count = rws_sum[regno].write_count;
5921
5922       switch (write_count)
5923         {
5924         case 0:
5925           /* The register has not been written yet.  */
5926           if (!in_safe_group_barrier)
5927             rws_update (regno, flags, pred);
5928           break;
5929
5930         case 1:
5931           /* The register has been written via a predicate.  Treat
5932              it like a unconditional write and do not try to check
5933              for complementary pred reg in earlier write.  */
5934           if (flags.is_and && rws_sum[regno].written_by_and)
5935             ;
5936           else if (flags.is_or && rws_sum[regno].written_by_or)
5937             ;
5938           else
5939             need_barrier = 1;
5940           if (!in_safe_group_barrier)
5941             rws_update (regno, flags, pred);
5942           break;
5943
5944         case 2:
5945           /* The register has been unconditionally written already.  We
5946              need a barrier.  */
5947           if (flags.is_and && rws_sum[regno].written_by_and)
5948             ;
5949           else if (flags.is_or && rws_sum[regno].written_by_or)
5950             ;
5951           else
5952             need_barrier = 1;
5953           if (!in_safe_group_barrier)
5954             {
5955               rws_sum[regno].written_by_and = flags.is_and;
5956               rws_sum[regno].written_by_or = flags.is_or;
5957             }
5958           break;
5959
5960         default:
5961           gcc_unreachable ();
5962         }
5963     }
5964   else
5965     {
5966       if (flags.is_branch)
5967         {
5968           /* Branches have several RAW exceptions that allow to avoid
5969              barriers.  */
5970
5971           if (REGNO_REG_CLASS (regno) == BR_REGS || regno == AR_PFS_REGNUM)
5972             /* RAW dependencies on branch regs are permissible as long
5973                as the writer is a non-branch instruction.  Since we
5974                never generate code that uses a branch register written
5975                by a branch instruction, handling this case is
5976                easy.  */
5977             return 0;
5978
5979           if (REGNO_REG_CLASS (regno) == PR_REGS
5980               && ! rws_sum[regno].written_by_fp)
5981             /* The predicates of a branch are available within the
5982                same insn group as long as the predicate was written by
5983                something other than a floating-point instruction.  */
5984             return 0;
5985         }
5986
5987       if (flags.is_and && rws_sum[regno].written_by_and)
5988         return 0;
5989       if (flags.is_or && rws_sum[regno].written_by_or)
5990         return 0;
5991
5992       switch (rws_sum[regno].write_count)
5993         {
5994         case 0:
5995           /* The register has not been written yet.  */
5996           break;
5997
5998         case 1:
5999           /* The register has been written via a predicate, assume we
6000              need a barrier (don't check for complementary regs).  */
6001           need_barrier = 1;
6002           break;
6003
6004         case 2:
6005           /* The register has been unconditionally written already.  We
6006              need a barrier.  */
6007           need_barrier = 1;
6008           break;
6009
6010         default:
6011           gcc_unreachable ();
6012         }
6013     }
6014
6015   return need_barrier;
6016 }
6017
6018 static int
6019 rws_access_reg (rtx reg, struct reg_flags flags, int pred)
6020 {
6021   int regno = REGNO (reg);
6022   int n = HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg));
6023
6024   if (n == 1)
6025     return rws_access_regno (regno, flags, pred);
6026   else
6027     {
6028       int need_barrier = 0;
6029       while (--n >= 0)
6030         need_barrier |= rws_access_regno (regno + n, flags, pred);
6031       return need_barrier;
6032     }
6033 }
6034
6035 /* Examine X, which is a SET rtx, and update the flags, the predicate, and
6036    the condition, stored in *PFLAGS, *PPRED and *PCOND.  */
6037
6038 static void
6039 update_set_flags (rtx x, struct reg_flags *pflags)
6040 {
6041   rtx src = SET_SRC (x);
6042
6043   switch (GET_CODE (src))
6044     {
6045     case CALL:
6046       return;
6047
6048     case IF_THEN_ELSE:
6049       /* There are four cases here:
6050          (1) The destination is (pc), in which case this is a branch,
6051          nothing here applies.
6052          (2) The destination is ar.lc, in which case this is a
6053          doloop_end_internal,
6054          (3) The destination is an fp register, in which case this is
6055          an fselect instruction.
6056          (4) The condition has (unspec [(reg)] UNSPEC_LDC), in which case 
6057          this is a check load.
6058          In all cases, nothing we do in this function applies.  */
6059       return;
6060
6061     default:
6062       if (COMPARISON_P (src)
6063           && SCALAR_FLOAT_MODE_P (GET_MODE (XEXP (src, 0))))
6064         /* Set pflags->is_fp to 1 so that we know we're dealing
6065            with a floating point comparison when processing the
6066            destination of the SET.  */
6067         pflags->is_fp = 1;
6068
6069       /* Discover if this is a parallel comparison.  We only handle
6070          and.orcm and or.andcm at present, since we must retain a
6071          strict inverse on the predicate pair.  */
6072       else if (GET_CODE (src) == AND)
6073         pflags->is_and = 1;
6074       else if (GET_CODE (src) == IOR)
6075         pflags->is_or = 1;
6076
6077       break;
6078     }
6079 }
6080
6081 /* Subroutine of rtx_needs_barrier; this function determines whether the
6082    source of a given SET rtx found in X needs a barrier.  FLAGS and PRED
6083    are as in rtx_needs_barrier.  COND is an rtx that holds the condition
6084    for this insn.  */
6085
6086 static int
6087 set_src_needs_barrier (rtx x, struct reg_flags flags, int pred)
6088 {
6089   int need_barrier = 0;
6090   rtx dst;
6091   rtx src = SET_SRC (x);
6092
6093   if (GET_CODE (src) == CALL)
6094     /* We don't need to worry about the result registers that
6095        get written by subroutine call.  */
6096     return rtx_needs_barrier (src, flags, pred);
6097   else if (SET_DEST (x) == pc_rtx)
6098     {
6099       /* X is a conditional branch.  */
6100       /* ??? This seems redundant, as the caller sets this bit for
6101          all JUMP_INSNs.  */
6102       if (!ia64_spec_check_src_p (src))
6103         flags.is_branch = 1;
6104       return rtx_needs_barrier (src, flags, pred);
6105     }
6106
6107   if (ia64_spec_check_src_p (src))
6108     /* Avoid checking one register twice (in condition 
6109        and in 'then' section) for ldc pattern.  */
6110     {
6111       gcc_assert (REG_P (XEXP (src, 2)));
6112       need_barrier = rtx_needs_barrier (XEXP (src, 2), flags, pred);
6113                   
6114       /* We process MEM below.  */
6115       src = XEXP (src, 1);
6116     }
6117
6118   need_barrier |= rtx_needs_barrier (src, flags, pred);
6119
6120   dst = SET_DEST (x);
6121   if (GET_CODE (dst) == ZERO_EXTRACT)
6122     {
6123       need_barrier |= rtx_needs_barrier (XEXP (dst, 1), flags, pred);
6124       need_barrier |= rtx_needs_barrier (XEXP (dst, 2), flags, pred);
6125     }
6126   return need_barrier;
6127 }
6128
6129 /* Handle an access to rtx X of type FLAGS using predicate register
6130    PRED.  Return 1 if this access creates a dependency with an earlier
6131    instruction in the same group.  */
6132
6133 static int
6134 rtx_needs_barrier (rtx x, struct reg_flags flags, int pred)
6135 {
6136   int i, j;
6137   int is_complemented = 0;
6138   int need_barrier = 0;
6139   const char *format_ptr;
6140   struct reg_flags new_flags;
6141   rtx cond;
6142
6143   if (! x)
6144     return 0;
6145
6146   new_flags = flags;
6147
6148   switch (GET_CODE (x))
6149     {
6150     case SET:
6151       update_set_flags (x, &new_flags);
6152       need_barrier = set_src_needs_barrier (x, new_flags, pred);
6153       if (GET_CODE (SET_SRC (x)) != CALL)
6154         {
6155           new_flags.is_write = 1;
6156           need_barrier |= rtx_needs_barrier (SET_DEST (x), new_flags, pred);
6157         }
6158       break;
6159
6160     case CALL:
6161       new_flags.is_write = 0;
6162       need_barrier |= rws_access_regno (AR_EC_REGNUM, new_flags, pred);
6163
6164       /* Avoid multiple register writes, in case this is a pattern with
6165          multiple CALL rtx.  This avoids a failure in rws_access_reg.  */
6166       if (! flags.is_sibcall && ! rws_insn_test (REG_AR_CFM))
6167         {
6168           new_flags.is_write = 1;
6169           need_barrier |= rws_access_regno (REG_RP, new_flags, pred);
6170           need_barrier |= rws_access_regno (AR_PFS_REGNUM, new_flags, pred);
6171           need_barrier |= rws_access_regno (REG_AR_CFM, new_flags, pred);
6172         }
6173       break;
6174
6175     case COND_EXEC:
6176       /* X is a predicated instruction.  */
6177
6178       cond = COND_EXEC_TEST (x);
6179       gcc_assert (!pred);
6180       need_barrier = rtx_needs_barrier (cond, flags, 0);
6181
6182       if (GET_CODE (cond) == EQ)
6183         is_complemented = 1;
6184       cond = XEXP (cond, 0);
6185       gcc_assert (GET_CODE (cond) == REG
6186                   && REGNO_REG_CLASS (REGNO (cond)) == PR_REGS);
6187       pred = REGNO (cond);
6188       if (is_complemented)
6189         ++pred;
6190
6191       need_barrier |= rtx_needs_barrier (COND_EXEC_CODE (x), flags, pred);
6192       return need_barrier;
6193
6194     case CLOBBER:
6195     case USE:
6196       /* Clobber & use are for earlier compiler-phases only.  */
6197       break;
6198
6199     case ASM_OPERANDS:
6200     case ASM_INPUT:
6201       /* We always emit stop bits for traditional asms.  We emit stop bits
6202          for volatile extended asms if TARGET_VOL_ASM_STOP is true.  */
6203       if (GET_CODE (x) != ASM_OPERANDS
6204           || (MEM_VOLATILE_P (x) && TARGET_VOL_ASM_STOP))
6205         {
6206           /* Avoid writing the register multiple times if we have multiple
6207              asm outputs.  This avoids a failure in rws_access_reg.  */
6208           if (! rws_insn_test (REG_VOLATILE))
6209             {
6210               new_flags.is_write = 1;
6211               rws_access_regno (REG_VOLATILE, new_flags, pred);
6212             }
6213           return 1;
6214         }
6215
6216       /* For all ASM_OPERANDS, we must traverse the vector of input operands.
6217          We cannot just fall through here since then we would be confused
6218          by the ASM_INPUT rtx inside ASM_OPERANDS, which do not indicate
6219          traditional asms unlike their normal usage.  */
6220
6221       for (i = ASM_OPERANDS_INPUT_LENGTH (x) - 1; i >= 0; --i)
6222         if (rtx_needs_barrier (ASM_OPERANDS_INPUT (x, i), flags, pred))
6223           need_barrier = 1;
6224       break;
6225
6226     case PARALLEL:
6227       for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
6228         {
6229           rtx pat = XVECEXP (x, 0, i);
6230           switch (GET_CODE (pat))
6231             {
6232             case SET:
6233               update_set_flags (pat, &new_flags);
6234               need_barrier |= set_src_needs_barrier (pat, new_flags, pred);
6235               break;
6236
6237             case USE:
6238             case CALL:
6239             case ASM_OPERANDS:
6240               need_barrier |= rtx_needs_barrier (pat, flags, pred);
6241               break;
6242
6243             case CLOBBER:
6244             case RETURN:
6245               break;
6246
6247             default:
6248               gcc_unreachable ();
6249             }
6250         }
6251       for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
6252         {
6253           rtx pat = XVECEXP (x, 0, i);
6254           if (GET_CODE (pat) == SET)
6255             {
6256               if (GET_CODE (SET_SRC (pat)) != CALL)
6257                 {
6258                   new_flags.is_write = 1;
6259                   need_barrier |= rtx_needs_barrier (SET_DEST (pat), new_flags,
6260                                                      pred);
6261                 }
6262             }
6263           else if (GET_CODE (pat) == CLOBBER || GET_CODE (pat) == RETURN)
6264             need_barrier |= rtx_needs_barrier (pat, flags, pred);
6265         }
6266       break;
6267
6268     case SUBREG:
6269       need_barrier |= rtx_needs_barrier (SUBREG_REG (x), flags, pred);
6270       break;
6271     case REG:
6272       if (REGNO (x) == AR_UNAT_REGNUM)
6273         {
6274           for (i = 0; i < 64; ++i)
6275             need_barrier |= rws_access_regno (AR_UNAT_BIT_0 + i, flags, pred);
6276         }
6277       else
6278         need_barrier = rws_access_reg (x, flags, pred);
6279       break;
6280
6281     case MEM:
6282       /* Find the regs used in memory address computation.  */
6283       new_flags.is_write = 0;
6284       need_barrier = rtx_needs_barrier (XEXP (x, 0), new_flags, pred);
6285       break;
6286
6287     case CONST_INT:   case CONST_DOUBLE:  case CONST_VECTOR:
6288     case SYMBOL_REF:  case LABEL_REF:     case CONST:
6289       break;
6290
6291       /* Operators with side-effects.  */
6292     case POST_INC:    case POST_DEC:
6293       gcc_assert (GET_CODE (XEXP (x, 0)) == REG);
6294
6295       new_flags.is_write = 0;
6296       need_barrier  = rws_access_reg (XEXP (x, 0), new_flags, pred);
6297       new_flags.is_write = 1;
6298       need_barrier |= rws_access_reg (XEXP (x, 0), new_flags, pred);
6299       break;
6300
6301     case POST_MODIFY:
6302       gcc_assert (GET_CODE (XEXP (x, 0)) == REG);
6303
6304       new_flags.is_write = 0;
6305       need_barrier  = rws_access_reg (XEXP (x, 0), new_flags, pred);
6306       need_barrier |= rtx_needs_barrier (XEXP (x, 1), new_flags, pred);
6307       new_flags.is_write = 1;
6308       need_barrier |= rws_access_reg (XEXP (x, 0), new_flags, pred);
6309       break;
6310
6311       /* Handle common unary and binary ops for efficiency.  */
6312     case COMPARE:  case PLUS:    case MINUS:   case MULT:      case DIV:
6313     case MOD:      case UDIV:    case UMOD:    case AND:       case IOR:
6314     case XOR:      case ASHIFT:  case ROTATE:  case ASHIFTRT:  case LSHIFTRT:
6315     case ROTATERT: case SMIN:    case SMAX:    case UMIN:      case UMAX:
6316     case NE:       case EQ:      case GE:      case GT:        case LE:
6317     case LT:       case GEU:     case GTU:     case LEU:       case LTU:
6318       need_barrier = rtx_needs_barrier (XEXP (x, 0), new_flags, pred);
6319       need_barrier |= rtx_needs_barrier (XEXP (x, 1), new_flags, pred);
6320       break;
6321
6322     case NEG:      case NOT:            case SIGN_EXTEND:     case ZERO_EXTEND:
6323     case TRUNCATE: case FLOAT_EXTEND:   case FLOAT_TRUNCATE:  case FLOAT:
6324     case FIX:      case UNSIGNED_FLOAT: case UNSIGNED_FIX:    case ABS:
6325     case SQRT:     case FFS:            case POPCOUNT:
6326       need_barrier = rtx_needs_barrier (XEXP (x, 0), flags, pred);
6327       break;
6328
6329     case VEC_SELECT:
6330       /* VEC_SELECT's second argument is a PARALLEL with integers that
6331          describe the elements selected.  On ia64, those integers are
6332          always constants.  Avoid walking the PARALLEL so that we don't
6333          get confused with "normal" parallels and then die.  */
6334       need_barrier = rtx_needs_barrier (XEXP (x, 0), flags, pred);
6335       break;
6336
6337     case UNSPEC:
6338       switch (XINT (x, 1))
6339         {
6340         case UNSPEC_LTOFF_DTPMOD:
6341         case UNSPEC_LTOFF_DTPREL:
6342         case UNSPEC_DTPREL:
6343         case UNSPEC_LTOFF_TPREL:
6344         case UNSPEC_TPREL:
6345         case UNSPEC_PRED_REL_MUTEX:
6346         case UNSPEC_PIC_CALL:
6347         case UNSPEC_MF:
6348         case UNSPEC_FETCHADD_ACQ:
6349         case UNSPEC_BSP_VALUE:
6350         case UNSPEC_FLUSHRS:
6351         case UNSPEC_BUNDLE_SELECTOR:
6352           break;
6353
6354         case UNSPEC_GR_SPILL:
6355         case UNSPEC_GR_RESTORE:
6356           {
6357             HOST_WIDE_INT offset = INTVAL (XVECEXP (x, 0, 1));
6358             HOST_WIDE_INT bit = (offset >> 3) & 63;
6359
6360             need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
6361             new_flags.is_write = (XINT (x, 1) == UNSPEC_GR_SPILL);
6362             need_barrier |= rws_access_regno (AR_UNAT_BIT_0 + bit,
6363                                               new_flags, pred);
6364             break;
6365           }
6366
6367         case UNSPEC_FR_SPILL:
6368         case UNSPEC_FR_RESTORE:
6369         case UNSPEC_GETF_EXP:
6370         case UNSPEC_SETF_EXP:
6371         case UNSPEC_ADDP4:
6372         case UNSPEC_FR_SQRT_RECIP_APPROX:
6373         case UNSPEC_FR_SQRT_RECIP_APPROX_RES:
6374         case UNSPEC_LDA:
6375         case UNSPEC_LDS:
6376         case UNSPEC_LDS_A:
6377         case UNSPEC_LDSA:
6378         case UNSPEC_CHKACLR:
6379         case UNSPEC_CHKS:
6380           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
6381           break;
6382
6383         case UNSPEC_FR_RECIP_APPROX:
6384         case UNSPEC_SHRP:
6385         case UNSPEC_COPYSIGN:
6386         case UNSPEC_FR_RECIP_APPROX_RES:
6387           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
6388           need_barrier |= rtx_needs_barrier (XVECEXP (x, 0, 1), flags, pred);
6389           break;
6390
6391         case UNSPEC_CMPXCHG_ACQ:
6392           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 1), flags, pred);
6393           need_barrier |= rtx_needs_barrier (XVECEXP (x, 0, 2), flags, pred);
6394           break;
6395
6396         default:
6397           gcc_unreachable ();
6398         }
6399       break;
6400
6401     case UNSPEC_VOLATILE:
6402       switch (XINT (x, 1))
6403         {
6404         case UNSPECV_ALLOC:
6405           /* Alloc must always be the first instruction of a group.
6406              We force this by always returning true.  */
6407           /* ??? We might get better scheduling if we explicitly check for
6408              input/local/output register dependencies, and modify the
6409              scheduler so that alloc is always reordered to the start of
6410              the current group.  We could then eliminate all of the
6411              first_instruction code.  */
6412           rws_access_regno (AR_PFS_REGNUM, flags, pred);
6413
6414           new_flags.is_write = 1;
6415           rws_access_regno (REG_AR_CFM, new_flags, pred);
6416           return 1;
6417
6418         case UNSPECV_SET_BSP:
6419           need_barrier = 1;
6420           break;
6421
6422         case UNSPECV_BLOCKAGE:
6423         case UNSPECV_INSN_GROUP_BARRIER:
6424         case UNSPECV_BREAK:
6425         case UNSPECV_PSAC_ALL:
6426         case UNSPECV_PSAC_NORMAL:
6427           return 0;
6428
6429         default:
6430           gcc_unreachable ();
6431         }
6432       break;
6433
6434     case RETURN:
6435       new_flags.is_write = 0;
6436       need_barrier  = rws_access_regno (REG_RP, flags, pred);
6437       need_barrier |= rws_access_regno (AR_PFS_REGNUM, flags, pred);
6438
6439       new_flags.is_write = 1;
6440       need_barrier |= rws_access_regno (AR_EC_REGNUM, new_flags, pred);
6441       need_barrier |= rws_access_regno (REG_AR_CFM, new_flags, pred);
6442       break;
6443
6444     default:
6445       format_ptr = GET_RTX_FORMAT (GET_CODE (x));
6446       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
6447         switch (format_ptr[i])
6448           {
6449           case '0':     /* unused field */
6450           case 'i':     /* integer */
6451           case 'n':     /* note */
6452           case 'w':     /* wide integer */
6453           case 's':     /* pointer to string */
6454           case 'S':     /* optional pointer to string */
6455             break;
6456
6457           case 'e':
6458             if (rtx_needs_barrier (XEXP (x, i), flags, pred))
6459               need_barrier = 1;
6460             break;
6461
6462           case 'E':
6463             for (j = XVECLEN (x, i) - 1; j >= 0; --j)
6464               if (rtx_needs_barrier (XVECEXP (x, i, j), flags, pred))
6465                 need_barrier = 1;
6466             break;
6467
6468           default:
6469             gcc_unreachable ();
6470           }
6471       break;
6472     }
6473   return need_barrier;
6474 }
6475
6476 /* Clear out the state for group_barrier_needed at the start of a
6477    sequence of insns.  */
6478
6479 static void
6480 init_insn_group_barriers (void)
6481 {
6482   memset (rws_sum, 0, sizeof (rws_sum));
6483   first_instruction = 1;
6484 }
6485
6486 /* Given the current state, determine whether a group barrier (a stop bit) is
6487    necessary before INSN.  Return nonzero if so.  This modifies the state to
6488    include the effects of INSN as a side-effect.  */
6489
6490 static int
6491 group_barrier_needed (rtx insn)
6492 {
6493   rtx pat;
6494   int need_barrier = 0;
6495   struct reg_flags flags;
6496
6497   memset (&flags, 0, sizeof (flags));
6498   switch (GET_CODE (insn))
6499     {
6500     case NOTE:
6501     case DEBUG_INSN:
6502       break;
6503
6504     case BARRIER:
6505       /* A barrier doesn't imply an instruction group boundary.  */
6506       break;
6507
6508     case CODE_LABEL:
6509       memset (rws_insn, 0, sizeof (rws_insn));
6510       return 1;
6511
6512     case CALL_INSN:
6513       flags.is_branch = 1;
6514       flags.is_sibcall = SIBLING_CALL_P (insn);
6515       memset (rws_insn, 0, sizeof (rws_insn));
6516
6517       /* Don't bundle a call following another call.  */
6518       if ((pat = prev_active_insn (insn))
6519           && GET_CODE (pat) == CALL_INSN)
6520         {
6521           need_barrier = 1;
6522           break;
6523         }
6524
6525       need_barrier = rtx_needs_barrier (PATTERN (insn), flags, 0);
6526       break;
6527
6528     case JUMP_INSN:
6529       if (!ia64_spec_check_p (insn))
6530         flags.is_branch = 1;
6531
6532       /* Don't bundle a jump following a call.  */
6533       if ((pat = prev_active_insn (insn))
6534           && GET_CODE (pat) == CALL_INSN)
6535         {
6536           need_barrier = 1;
6537           break;
6538         }
6539       /* FALLTHRU */
6540
6541     case INSN:
6542       if (GET_CODE (PATTERN (insn)) == USE
6543           || GET_CODE (PATTERN (insn)) == CLOBBER)
6544         /* Don't care about USE and CLOBBER "insns"---those are used to
6545            indicate to the optimizer that it shouldn't get rid of
6546            certain operations.  */
6547         break;
6548
6549       pat = PATTERN (insn);
6550
6551       /* Ug.  Hack hacks hacked elsewhere.  */
6552       switch (recog_memoized (insn))
6553         {
6554           /* We play dependency tricks with the epilogue in order
6555              to get proper schedules.  Undo this for dv analysis.  */
6556         case CODE_FOR_epilogue_deallocate_stack:
6557         case CODE_FOR_prologue_allocate_stack:
6558           pat = XVECEXP (pat, 0, 0);
6559           break;
6560
6561           /* The pattern we use for br.cloop confuses the code above.
6562              The second element of the vector is representative.  */
6563         case CODE_FOR_doloop_end_internal:
6564           pat = XVECEXP (pat, 0, 1);
6565           break;
6566
6567           /* Doesn't generate code.  */
6568         case CODE_FOR_pred_rel_mutex:
6569         case CODE_FOR_prologue_use:
6570           return 0;
6571
6572         default:
6573           break;
6574         }
6575
6576       memset (rws_insn, 0, sizeof (rws_insn));
6577       need_barrier = rtx_needs_barrier (pat, flags, 0);
6578
6579       /* Check to see if the previous instruction was a volatile
6580          asm.  */
6581       if (! need_barrier)
6582         need_barrier = rws_access_regno (REG_VOLATILE, flags, 0);
6583
6584       break;
6585
6586     default:
6587       gcc_unreachable ();
6588     }
6589
6590   if (first_instruction && INSN_P (insn)
6591       && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
6592       && GET_CODE (PATTERN (insn)) != USE
6593       && GET_CODE (PATTERN (insn)) != CLOBBER)
6594     {
6595       need_barrier = 0;
6596       first_instruction = 0;
6597     }
6598
6599   return need_barrier;
6600 }
6601
6602 /* Like group_barrier_needed, but do not clobber the current state.  */
6603
6604 static int
6605 safe_group_barrier_needed (rtx insn)
6606 {
6607   int saved_first_instruction;
6608   int t;
6609
6610   saved_first_instruction = first_instruction;
6611   in_safe_group_barrier = 1;
6612
6613   t = group_barrier_needed (insn);
6614
6615   first_instruction = saved_first_instruction;
6616   in_safe_group_barrier = 0;
6617
6618   return t;
6619 }
6620
6621 /* Scan the current function and insert stop bits as necessary to
6622    eliminate dependencies.  This function assumes that a final
6623    instruction scheduling pass has been run which has already
6624    inserted most of the necessary stop bits.  This function only
6625    inserts new ones at basic block boundaries, since these are
6626    invisible to the scheduler.  */
6627
6628 static void
6629 emit_insn_group_barriers (FILE *dump)
6630 {
6631   rtx insn;
6632   rtx last_label = 0;
6633   int insns_since_last_label = 0;
6634
6635   init_insn_group_barriers ();
6636
6637   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
6638     {
6639       if (GET_CODE (insn) == CODE_LABEL)
6640         {
6641           if (insns_since_last_label)
6642             last_label = insn;
6643           insns_since_last_label = 0;
6644         }
6645       else if (GET_CODE (insn) == NOTE
6646                && NOTE_KIND (insn) == NOTE_INSN_BASIC_BLOCK)
6647         {
6648           if (insns_since_last_label)
6649             last_label = insn;
6650           insns_since_last_label = 0;
6651         }
6652       else if (GET_CODE (insn) == INSN
6653                && GET_CODE (PATTERN (insn)) == UNSPEC_VOLATILE
6654                && XINT (PATTERN (insn), 1) == UNSPECV_INSN_GROUP_BARRIER)
6655         {
6656           init_insn_group_barriers ();
6657           last_label = 0;
6658         }
6659       else if (NONDEBUG_INSN_P (insn))
6660         {
6661           insns_since_last_label = 1;
6662
6663           if (group_barrier_needed (insn))
6664             {
6665               if (last_label)
6666                 {
6667                   if (dump)
6668                     fprintf (dump, "Emitting stop before label %d\n",
6669                              INSN_UID (last_label));
6670                   emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), last_label);
6671                   insn = last_label;
6672
6673                   init_insn_group_barriers ();
6674                   last_label = 0;
6675                 }
6676             }
6677         }
6678     }
6679 }
6680
6681 /* Like emit_insn_group_barriers, but run if no final scheduling pass was run.
6682    This function has to emit all necessary group barriers.  */
6683
6684 static void
6685 emit_all_insn_group_barriers (FILE *dump ATTRIBUTE_UNUSED)
6686 {
6687   rtx insn;
6688
6689   init_insn_group_barriers ();
6690
6691   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
6692     {
6693       if (GET_CODE (insn) == BARRIER)
6694         {
6695           rtx last = prev_active_insn (insn);
6696
6697           if (! last)
6698             continue;
6699           if (GET_CODE (last) == JUMP_INSN
6700               && GET_CODE (PATTERN (last)) == ADDR_DIFF_VEC)
6701             last = prev_active_insn (last);
6702           if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
6703             emit_insn_after (gen_insn_group_barrier (GEN_INT (3)), last);
6704
6705           init_insn_group_barriers ();
6706         }
6707       else if (NONDEBUG_INSN_P (insn))
6708         {
6709           if (recog_memoized (insn) == CODE_FOR_insn_group_barrier)
6710             init_insn_group_barriers ();
6711           else if (group_barrier_needed (insn))
6712             {
6713               emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), insn);
6714               init_insn_group_barriers ();
6715               group_barrier_needed (insn);
6716             }
6717         }
6718     }
6719 }
6720
6721 \f
6722
6723 /* Instruction scheduling support.  */
6724
6725 #define NR_BUNDLES 10
6726
6727 /* A list of names of all available bundles.  */
6728
6729 static const char *bundle_name [NR_BUNDLES] =
6730 {
6731   ".mii",
6732   ".mmi",
6733   ".mfi",
6734   ".mmf",
6735 #if NR_BUNDLES == 10
6736   ".bbb",
6737   ".mbb",
6738 #endif
6739   ".mib",
6740   ".mmb",
6741   ".mfb",
6742   ".mlx"
6743 };
6744
6745 /* Nonzero if we should insert stop bits into the schedule.  */
6746
6747 int ia64_final_schedule = 0;
6748
6749 /* Codes of the corresponding queried units: */
6750
6751 static int _0mii_, _0mmi_, _0mfi_, _0mmf_;
6752 static int _0bbb_, _0mbb_, _0mib_, _0mmb_, _0mfb_, _0mlx_;
6753
6754 static int _1mii_, _1mmi_, _1mfi_, _1mmf_;
6755 static int _1bbb_, _1mbb_, _1mib_, _1mmb_, _1mfb_, _1mlx_;
6756
6757 static int pos_1, pos_2, pos_3, pos_4, pos_5, pos_6;
6758
6759 /* The following variable value is an insn group barrier.  */
6760
6761 static rtx dfa_stop_insn;
6762
6763 /* The following variable value is the last issued insn.  */
6764
6765 static rtx last_scheduled_insn;
6766
6767 /* The following variable value is pointer to a DFA state used as
6768    temporary variable.  */
6769
6770 static state_t temp_dfa_state = NULL;
6771
6772 /* The following variable value is DFA state after issuing the last
6773    insn.  */
6774
6775 static state_t prev_cycle_state = NULL;
6776
6777 /* The following array element values are TRUE if the corresponding
6778    insn requires to add stop bits before it.  */
6779
6780 static char *stops_p = NULL;
6781
6782 /* The following variable is used to set up the mentioned above array.  */
6783
6784 static int stop_before_p = 0;
6785
6786 /* The following variable value is length of the arrays `clocks' and
6787    `add_cycles'. */
6788
6789 static int clocks_length;
6790
6791 /* The following variable value is number of data speculations in progress.  */
6792 static int pending_data_specs = 0;
6793
6794 /* Number of memory references on current and three future processor cycles.  */
6795 static char mem_ops_in_group[4];
6796
6797 /* Number of current processor cycle (from scheduler's point of view).  */
6798 static int current_cycle;
6799
6800 static rtx ia64_single_set (rtx);
6801 static void ia64_emit_insn_before (rtx, rtx);
6802
6803 /* Map a bundle number to its pseudo-op.  */
6804
6805 const char *
6806 get_bundle_name (int b)
6807 {
6808   return bundle_name[b];
6809 }
6810
6811
6812 /* Return the maximum number of instructions a cpu can issue.  */
6813
6814 static int
6815 ia64_issue_rate (void)
6816 {
6817   return 6;
6818 }
6819
6820 /* Helper function - like single_set, but look inside COND_EXEC.  */
6821
6822 static rtx
6823 ia64_single_set (rtx insn)
6824 {
6825   rtx x = PATTERN (insn), ret;
6826   if (GET_CODE (x) == COND_EXEC)
6827     x = COND_EXEC_CODE (x);
6828   if (GET_CODE (x) == SET)
6829     return x;
6830
6831   /* Special case here prologue_allocate_stack and epilogue_deallocate_stack.
6832      Although they are not classical single set, the second set is there just
6833      to protect it from moving past FP-relative stack accesses.  */
6834   switch (recog_memoized (insn))
6835     {
6836     case CODE_FOR_prologue_allocate_stack:
6837     case CODE_FOR_epilogue_deallocate_stack:
6838       ret = XVECEXP (x, 0, 0);
6839       break;
6840
6841     default:
6842       ret = single_set_2 (insn, x);
6843       break;
6844     }
6845
6846   return ret;
6847 }
6848
6849 /* Adjust the cost of a scheduling dependency.
6850    Return the new cost of a dependency of type DEP_TYPE or INSN on DEP_INSN.
6851    COST is the current cost, DW is dependency weakness.  */
6852 static int
6853 ia64_adjust_cost_2 (rtx insn, int dep_type1, rtx dep_insn, int cost, dw_t dw)
6854 {
6855   enum reg_note dep_type = (enum reg_note) dep_type1;
6856   enum attr_itanium_class dep_class;
6857   enum attr_itanium_class insn_class;
6858
6859   insn_class = ia64_safe_itanium_class (insn);
6860   dep_class = ia64_safe_itanium_class (dep_insn);
6861
6862   /* Treat true memory dependencies separately.  Ignore apparent true
6863      dependence between store and call (call has a MEM inside a SYMBOL_REF).  */
6864   if (dep_type == REG_DEP_TRUE
6865       && (dep_class == ITANIUM_CLASS_ST || dep_class == ITANIUM_CLASS_STF)
6866       && (insn_class == ITANIUM_CLASS_BR || insn_class == ITANIUM_CLASS_SCALL))
6867     return 0;
6868
6869   if (dw == MIN_DEP_WEAK)
6870     /* Store and load are likely to alias, use higher cost to avoid stall.  */
6871     return PARAM_VALUE (PARAM_SCHED_MEM_TRUE_DEP_COST);
6872   else if (dw > MIN_DEP_WEAK)
6873     {
6874       /* Store and load are less likely to alias.  */
6875       if (mflag_sched_fp_mem_deps_zero_cost && dep_class == ITANIUM_CLASS_STF)
6876         /* Assume there will be no cache conflict for floating-point data.
6877            For integer data, L1 conflict penalty is huge (17 cycles), so we
6878            never assume it will not cause a conflict.  */
6879         return 0;
6880       else
6881         return cost;
6882     }
6883
6884   if (dep_type != REG_DEP_OUTPUT)
6885     return cost;
6886
6887   if (dep_class == ITANIUM_CLASS_ST || dep_class == ITANIUM_CLASS_STF
6888       || insn_class == ITANIUM_CLASS_ST || insn_class == ITANIUM_CLASS_STF)
6889     return 0;
6890
6891   return cost;
6892 }
6893
6894 /* Like emit_insn_before, but skip cycle_display notes.
6895    ??? When cycle display notes are implemented, update this.  */
6896
6897 static void
6898 ia64_emit_insn_before (rtx insn, rtx before)
6899 {
6900   emit_insn_before (insn, before);
6901 }
6902
6903 /* The following function marks insns who produce addresses for load
6904    and store insns.  Such insns will be placed into M slots because it
6905    decrease latency time for Itanium1 (see function
6906    `ia64_produce_address_p' and the DFA descriptions).  */
6907
6908 static void
6909 ia64_dependencies_evaluation_hook (rtx head, rtx tail)
6910 {
6911   rtx insn, next, next_tail;
6912
6913   /* Before reload, which_alternative is not set, which means that
6914      ia64_safe_itanium_class will produce wrong results for (at least)
6915      move instructions.  */
6916   if (!reload_completed)
6917     return;
6918
6919   next_tail = NEXT_INSN (tail);
6920   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6921     if (INSN_P (insn))
6922       insn->call = 0;
6923   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6924     if (INSN_P (insn)
6925         && ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IALU)
6926       {
6927         sd_iterator_def sd_it;
6928         dep_t dep;
6929         bool has_mem_op_consumer_p = false;
6930
6931         FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
6932           {
6933             enum attr_itanium_class c;
6934
6935             if (DEP_TYPE (dep) != REG_DEP_TRUE)
6936               continue;
6937
6938             next = DEP_CON (dep);
6939             c = ia64_safe_itanium_class (next);
6940             if ((c == ITANIUM_CLASS_ST
6941                  || c == ITANIUM_CLASS_STF)
6942                 && ia64_st_address_bypass_p (insn, next))
6943               {
6944                 has_mem_op_consumer_p = true;
6945                 break;
6946               }
6947             else if ((c == ITANIUM_CLASS_LD
6948                       || c == ITANIUM_CLASS_FLD
6949                       || c == ITANIUM_CLASS_FLDP)
6950                      && ia64_ld_address_bypass_p (insn, next))
6951               {
6952                 has_mem_op_consumer_p = true;
6953                 break;
6954               }
6955           }
6956
6957         insn->call = has_mem_op_consumer_p;
6958       }
6959 }
6960
6961 /* We're beginning a new block.  Initialize data structures as necessary.  */
6962
6963 static void
6964 ia64_sched_init (FILE *dump ATTRIBUTE_UNUSED,
6965                  int sched_verbose ATTRIBUTE_UNUSED,
6966                  int max_ready ATTRIBUTE_UNUSED)
6967 {
6968 #ifdef ENABLE_CHECKING
6969   rtx insn;
6970
6971   if (!sel_sched_p () && reload_completed)
6972     for (insn = NEXT_INSN (current_sched_info->prev_head);
6973          insn != current_sched_info->next_tail;
6974          insn = NEXT_INSN (insn))
6975       gcc_assert (!SCHED_GROUP_P (insn));
6976 #endif
6977   last_scheduled_insn = NULL_RTX;
6978   init_insn_group_barriers ();
6979
6980   current_cycle = 0;
6981   memset (mem_ops_in_group, 0, sizeof (mem_ops_in_group));
6982 }
6983
6984 /* We're beginning a scheduling pass.  Check assertion.  */
6985
6986 static void
6987 ia64_sched_init_global (FILE *dump ATTRIBUTE_UNUSED,
6988                         int sched_verbose ATTRIBUTE_UNUSED,
6989                         int max_ready ATTRIBUTE_UNUSED)
6990 {  
6991   gcc_assert (pending_data_specs == 0);
6992 }
6993
6994 /* Scheduling pass is now finished.  Free/reset static variable.  */
6995 static void
6996 ia64_sched_finish_global (FILE *dump ATTRIBUTE_UNUSED,
6997                           int sched_verbose ATTRIBUTE_UNUSED)
6998 {
6999   gcc_assert (pending_data_specs == 0);
7000 }
7001
7002 /* Return TRUE if INSN is a load (either normal or speculative, but not a
7003    speculation check), FALSE otherwise.  */
7004 static bool
7005 is_load_p (rtx insn)
7006 {
7007   enum attr_itanium_class insn_class = ia64_safe_itanium_class (insn);
7008
7009   return
7010    ((insn_class == ITANIUM_CLASS_LD || insn_class == ITANIUM_CLASS_FLD)
7011     && get_attr_check_load (insn) == CHECK_LOAD_NO);
7012 }
7013
7014 /* If INSN is a memory reference, memoize it in MEM_OPS_IN_GROUP global array
7015    (taking account for 3-cycle cache reference postponing for stores: Intel
7016    Itanium 2 Reference Manual for Software Development and Optimization,
7017    6.7.3.1).  */
7018 static void
7019 record_memory_reference (rtx insn)
7020 {
7021   enum attr_itanium_class insn_class = ia64_safe_itanium_class (insn);
7022
7023   switch (insn_class) {
7024     case ITANIUM_CLASS_FLD:
7025     case ITANIUM_CLASS_LD:
7026       mem_ops_in_group[current_cycle % 4]++;
7027       break;
7028     case ITANIUM_CLASS_STF:
7029     case ITANIUM_CLASS_ST:
7030       mem_ops_in_group[(current_cycle + 3) % 4]++;
7031       break;
7032     default:;
7033   }
7034 }
7035
7036 /* We are about to being issuing insns for this clock cycle.
7037    Override the default sort algorithm to better slot instructions.  */
7038
7039 static int
7040 ia64_dfa_sched_reorder (FILE *dump, int sched_verbose, rtx *ready,
7041                         int *pn_ready, int clock_var,
7042                         int reorder_type)
7043 {
7044   int n_asms;
7045   int n_ready = *pn_ready;
7046   rtx *e_ready = ready + n_ready;
7047   rtx *insnp;
7048
7049   if (sched_verbose)
7050     fprintf (dump, "// ia64_dfa_sched_reorder (type %d):\n", reorder_type);
7051
7052   if (reorder_type == 0)
7053     {
7054       /* First, move all USEs, CLOBBERs and other crud out of the way.  */
7055       n_asms = 0;
7056       for (insnp = ready; insnp < e_ready; insnp++)
7057         if (insnp < e_ready)
7058           {
7059             rtx insn = *insnp;
7060             enum attr_type t = ia64_safe_type (insn);
7061             if (t == TYPE_UNKNOWN)
7062               {
7063                 if (GET_CODE (PATTERN (insn)) == ASM_INPUT
7064                     || asm_noperands (PATTERN (insn)) >= 0)
7065                   {
7066                     rtx lowest = ready[n_asms];
7067                     ready[n_asms] = insn;
7068                     *insnp = lowest;
7069                     n_asms++;
7070                   }
7071                 else
7072                   {
7073                     rtx highest = ready[n_ready - 1];
7074                     ready[n_ready - 1] = insn;
7075                     *insnp = highest;
7076                     return 1;
7077                   }
7078               }
7079           }
7080
7081       if (n_asms < n_ready)
7082         {
7083           /* Some normal insns to process.  Skip the asms.  */
7084           ready += n_asms;
7085           n_ready -= n_asms;
7086         }
7087       else if (n_ready > 0)
7088         return 1;
7089     }
7090
7091   if (ia64_final_schedule)
7092     {
7093       int deleted = 0;
7094       int nr_need_stop = 0;
7095
7096       for (insnp = ready; insnp < e_ready; insnp++)
7097         if (safe_group_barrier_needed (*insnp))
7098           nr_need_stop++;
7099
7100       if (reorder_type == 1 && n_ready == nr_need_stop)
7101         return 0;
7102       if (reorder_type == 0)
7103         return 1;
7104       insnp = e_ready;
7105       /* Move down everything that needs a stop bit, preserving
7106          relative order.  */
7107       while (insnp-- > ready + deleted)
7108         while (insnp >= ready + deleted)
7109           {
7110             rtx insn = *insnp;
7111             if (! safe_group_barrier_needed (insn))
7112               break;
7113             memmove (ready + 1, ready, (insnp - ready) * sizeof (rtx));
7114             *ready = insn;
7115             deleted++;
7116           }
7117       n_ready -= deleted;
7118       ready += deleted;
7119     }
7120
7121   current_cycle = clock_var;
7122   if (reload_completed && mem_ops_in_group[clock_var % 4] >= ia64_max_memory_insns)
7123     {
7124       int moved = 0;
7125
7126       insnp = e_ready;
7127       /* Move down loads/stores, preserving relative order.  */
7128       while (insnp-- > ready + moved)
7129         while (insnp >= ready + moved)
7130           {
7131             rtx insn = *insnp;
7132             if (! is_load_p (insn))
7133               break;
7134             memmove (ready + 1, ready, (insnp - ready) * sizeof (rtx));
7135             *ready = insn;
7136             moved++;
7137           }
7138       n_ready -= moved;
7139       ready += moved;
7140     }
7141
7142   return 1;
7143 }
7144
7145 /* We are about to being issuing insns for this clock cycle.  Override
7146    the default sort algorithm to better slot instructions.  */
7147
7148 static int
7149 ia64_sched_reorder (FILE *dump, int sched_verbose, rtx *ready, int *pn_ready,
7150                     int clock_var)
7151 {
7152   return ia64_dfa_sched_reorder (dump, sched_verbose, ready,
7153                                  pn_ready, clock_var, 0);
7154 }
7155
7156 /* Like ia64_sched_reorder, but called after issuing each insn.
7157    Override the default sort algorithm to better slot instructions.  */
7158
7159 static int
7160 ia64_sched_reorder2 (FILE *dump ATTRIBUTE_UNUSED,
7161                      int sched_verbose ATTRIBUTE_UNUSED, rtx *ready,
7162                      int *pn_ready, int clock_var)
7163 {
7164   return ia64_dfa_sched_reorder (dump, sched_verbose, ready, pn_ready,
7165                                  clock_var, 1);
7166 }
7167
7168 /* We are about to issue INSN.  Return the number of insns left on the
7169    ready queue that can be issued this cycle.  */
7170
7171 static int
7172 ia64_variable_issue (FILE *dump ATTRIBUTE_UNUSED,
7173                      int sched_verbose ATTRIBUTE_UNUSED,
7174                      rtx insn ATTRIBUTE_UNUSED,
7175                      int can_issue_more ATTRIBUTE_UNUSED)
7176 {
7177   if (sched_deps_info->generate_spec_deps && !sel_sched_p ())
7178     /* Modulo scheduling does not extend h_i_d when emitting
7179        new instructions.  Don't use h_i_d, if we don't have to.  */
7180     {
7181       if (DONE_SPEC (insn) & BEGIN_DATA)
7182         pending_data_specs++;
7183       if (CHECK_SPEC (insn) & BEGIN_DATA)
7184         pending_data_specs--;
7185     }
7186
7187   if (DEBUG_INSN_P (insn))
7188     return 1;
7189
7190   last_scheduled_insn = insn;
7191   memcpy (prev_cycle_state, curr_state, dfa_state_size);
7192   if (reload_completed)
7193     {
7194       int needed = group_barrier_needed (insn);
7195       
7196       gcc_assert (!needed);
7197       if (GET_CODE (insn) == CALL_INSN)
7198         init_insn_group_barriers ();
7199       stops_p [INSN_UID (insn)] = stop_before_p;
7200       stop_before_p = 0;
7201
7202       record_memory_reference (insn);
7203     }
7204   return 1;
7205 }
7206
7207 /* We are choosing insn from the ready queue.  Return nonzero if INSN
7208    can be chosen.  */
7209
7210 static int
7211 ia64_first_cycle_multipass_dfa_lookahead_guard (rtx insn)
7212 {
7213   gcc_assert (insn && INSN_P (insn));
7214   return ((!reload_completed
7215            || !safe_group_barrier_needed (insn))
7216           && ia64_first_cycle_multipass_dfa_lookahead_guard_spec (insn)
7217           && (!mflag_sched_mem_insns_hard_limit
7218               || !is_load_p (insn)
7219               || mem_ops_in_group[current_cycle % 4] < ia64_max_memory_insns));
7220 }
7221
7222 /* We are choosing insn from the ready queue.  Return nonzero if INSN
7223    can be chosen.  */
7224
7225 static bool
7226 ia64_first_cycle_multipass_dfa_lookahead_guard_spec (const_rtx insn)
7227 {
7228   gcc_assert (insn  && INSN_P (insn));
7229   /* Size of ALAT is 32.  As far as we perform conservative data speculation,
7230      we keep ALAT half-empty.  */
7231   return (pending_data_specs < 16
7232           || !(TODO_SPEC (insn) & BEGIN_DATA));
7233 }
7234
7235 /* The following variable value is pseudo-insn used by the DFA insn
7236    scheduler to change the DFA state when the simulated clock is
7237    increased.  */
7238
7239 static rtx dfa_pre_cycle_insn;
7240
7241 /* Returns 1 when a meaningful insn was scheduled between the last group
7242    barrier and LAST.  */
7243 static int
7244 scheduled_good_insn (rtx last)
7245 {
7246   if (last && recog_memoized (last) >= 0)
7247     return 1;
7248
7249   for ( ;
7250        last != NULL && !NOTE_INSN_BASIC_BLOCK_P (last)
7251        && !stops_p[INSN_UID (last)];
7252        last = PREV_INSN (last))
7253     /* We could hit a NOTE_INSN_DELETED here which is actually outside
7254        the ebb we're scheduling.  */
7255     if (INSN_P (last) && recog_memoized (last) >= 0)
7256       return 1;
7257
7258   return 0;
7259 }
7260
7261 /* We are about to being issuing INSN.  Return nonzero if we cannot
7262    issue it on given cycle CLOCK and return zero if we should not sort
7263    the ready queue on the next clock start.  */
7264
7265 static int
7266 ia64_dfa_new_cycle (FILE *dump, int verbose, rtx insn, int last_clock,
7267                     int clock, int *sort_p)
7268 {
7269   gcc_assert (insn && INSN_P (insn));
7270
7271   if (DEBUG_INSN_P (insn))
7272     return 0;
7273
7274   /* When a group barrier is needed for insn, last_scheduled_insn
7275      should be set.  */
7276   gcc_assert (!(reload_completed && safe_group_barrier_needed (insn))
7277               || last_scheduled_insn);
7278
7279   if ((reload_completed
7280        && (safe_group_barrier_needed (insn)
7281            || (mflag_sched_stop_bits_after_every_cycle
7282                && last_clock != clock
7283                && last_scheduled_insn
7284                && scheduled_good_insn (last_scheduled_insn))))
7285       || (last_scheduled_insn
7286           && (GET_CODE (last_scheduled_insn) == CALL_INSN
7287               || GET_CODE (PATTERN (last_scheduled_insn)) == ASM_INPUT
7288               || asm_noperands (PATTERN (last_scheduled_insn)) >= 0)))
7289     {
7290       init_insn_group_barriers ();
7291
7292       if (verbose && dump)
7293         fprintf (dump, "//    Stop should be before %d%s\n", INSN_UID (insn),
7294                  last_clock == clock ? " + cycle advance" : "");
7295
7296       stop_before_p = 1;
7297       current_cycle = clock;
7298       mem_ops_in_group[current_cycle % 4] = 0;
7299
7300       if (last_clock == clock)
7301         {
7302           state_transition (curr_state, dfa_stop_insn);
7303           if (TARGET_EARLY_STOP_BITS)
7304             *sort_p = (last_scheduled_insn == NULL_RTX
7305                        || GET_CODE (last_scheduled_insn) != CALL_INSN);
7306           else
7307             *sort_p = 0;
7308           return 1;
7309         }
7310
7311       if (last_scheduled_insn)
7312         {
7313           if (GET_CODE (PATTERN (last_scheduled_insn)) == ASM_INPUT
7314               || asm_noperands (PATTERN (last_scheduled_insn)) >= 0)
7315             state_reset (curr_state);
7316           else
7317             {
7318               memcpy (curr_state, prev_cycle_state, dfa_state_size);
7319               state_transition (curr_state, dfa_stop_insn);
7320               state_transition (curr_state, dfa_pre_cycle_insn);
7321               state_transition (curr_state, NULL);
7322             }
7323         }
7324     }
7325   return 0;
7326 }
7327
7328 /* Implement targetm.sched.h_i_d_extended hook.
7329    Extend internal data structures.  */
7330 static void
7331 ia64_h_i_d_extended (void)
7332 {
7333   if (stops_p != NULL) 
7334     {
7335       int new_clocks_length = get_max_uid () * 3 / 2;
7336       stops_p = (char *) xrecalloc (stops_p, new_clocks_length, clocks_length, 1);
7337       clocks_length = new_clocks_length;
7338     }
7339 }
7340 \f
7341
7342 /* This structure describes the data used by the backend to guide scheduling.
7343    When the current scheduling point is switched, this data should be saved
7344    and restored later, if the scheduler returns to this point.  */
7345 struct _ia64_sched_context
7346 {
7347   state_t prev_cycle_state;
7348   rtx last_scheduled_insn;
7349   struct reg_write_state rws_sum[NUM_REGS];
7350   struct reg_write_state rws_insn[NUM_REGS];
7351   int first_instruction;
7352   int pending_data_specs;
7353   int current_cycle;
7354   char mem_ops_in_group[4];
7355 };
7356 typedef struct _ia64_sched_context *ia64_sched_context_t;
7357
7358 /* Allocates a scheduling context.  */
7359 static void *
7360 ia64_alloc_sched_context (void)
7361 {
7362   return xmalloc (sizeof (struct _ia64_sched_context));
7363 }
7364
7365 /* Initializes the _SC context with clean data, if CLEAN_P, and from
7366    the global context otherwise.  */
7367 static void
7368 ia64_init_sched_context (void *_sc, bool clean_p)
7369 {
7370   ia64_sched_context_t sc = (ia64_sched_context_t) _sc;
7371
7372   sc->prev_cycle_state = xmalloc (dfa_state_size);
7373   if (clean_p)
7374     {
7375       state_reset (sc->prev_cycle_state);
7376       sc->last_scheduled_insn = NULL_RTX;
7377       memset (sc->rws_sum, 0, sizeof (rws_sum));
7378       memset (sc->rws_insn, 0, sizeof (rws_insn));
7379       sc->first_instruction = 1;
7380       sc->pending_data_specs = 0;
7381       sc->current_cycle = 0;
7382       memset (sc->mem_ops_in_group, 0, sizeof (mem_ops_in_group));
7383     }
7384   else
7385     {
7386       memcpy (sc->prev_cycle_state, prev_cycle_state, dfa_state_size);
7387       sc->last_scheduled_insn = last_scheduled_insn;
7388       memcpy (sc->rws_sum, rws_sum, sizeof (rws_sum));
7389       memcpy (sc->rws_insn, rws_insn, sizeof (rws_insn));
7390       sc->first_instruction = first_instruction;
7391       sc->pending_data_specs = pending_data_specs;
7392       sc->current_cycle = current_cycle;
7393       memcpy (sc->mem_ops_in_group, mem_ops_in_group, sizeof (mem_ops_in_group));
7394     }
7395 }
7396
7397 /* Sets the global scheduling context to the one pointed to by _SC.  */
7398 static void
7399 ia64_set_sched_context (void *_sc)
7400 {
7401   ia64_sched_context_t sc = (ia64_sched_context_t) _sc;
7402
7403   gcc_assert (sc != NULL);
7404
7405   memcpy (prev_cycle_state, sc->prev_cycle_state, dfa_state_size);
7406   last_scheduled_insn = sc->last_scheduled_insn;
7407   memcpy (rws_sum, sc->rws_sum, sizeof (rws_sum));
7408   memcpy (rws_insn, sc->rws_insn, sizeof (rws_insn));
7409   first_instruction = sc->first_instruction;
7410   pending_data_specs = sc->pending_data_specs;
7411   current_cycle = sc->current_cycle;
7412   memcpy (mem_ops_in_group, sc->mem_ops_in_group, sizeof (mem_ops_in_group));
7413 }
7414
7415 /* Clears the data in the _SC scheduling context.  */
7416 static void
7417 ia64_clear_sched_context (void *_sc)
7418 {
7419   ia64_sched_context_t sc = (ia64_sched_context_t) _sc;
7420   
7421   free (sc->prev_cycle_state);
7422   sc->prev_cycle_state = NULL;
7423 }
7424
7425 /* Frees the _SC scheduling context.  */
7426 static void
7427 ia64_free_sched_context (void *_sc)
7428 {
7429   gcc_assert (_sc != NULL);
7430
7431   free (_sc);
7432 }
7433
7434 typedef rtx (* gen_func_t) (rtx, rtx);
7435
7436 /* Return a function that will generate a load of mode MODE_NO
7437    with speculation types TS.  */
7438 static gen_func_t
7439 get_spec_load_gen_function (ds_t ts, int mode_no)
7440 {
7441   static gen_func_t gen_ld_[] = {
7442     gen_movbi,
7443     gen_movqi_internal,
7444     gen_movhi_internal,
7445     gen_movsi_internal,
7446     gen_movdi_internal,
7447     gen_movsf_internal,
7448     gen_movdf_internal,
7449     gen_movxf_internal,
7450     gen_movti_internal,
7451     gen_zero_extendqidi2,
7452     gen_zero_extendhidi2,
7453     gen_zero_extendsidi2,
7454   };
7455
7456   static gen_func_t gen_ld_a[] = {
7457     gen_movbi_advanced,
7458     gen_movqi_advanced,
7459     gen_movhi_advanced,
7460     gen_movsi_advanced,
7461     gen_movdi_advanced,
7462     gen_movsf_advanced,
7463     gen_movdf_advanced,
7464     gen_movxf_advanced,
7465     gen_movti_advanced,
7466     gen_zero_extendqidi2_advanced,
7467     gen_zero_extendhidi2_advanced,
7468     gen_zero_extendsidi2_advanced,
7469   };
7470   static gen_func_t gen_ld_s[] = {
7471     gen_movbi_speculative,
7472     gen_movqi_speculative,
7473     gen_movhi_speculative,
7474     gen_movsi_speculative,
7475     gen_movdi_speculative,
7476     gen_movsf_speculative,
7477     gen_movdf_speculative,
7478     gen_movxf_speculative,
7479     gen_movti_speculative,
7480     gen_zero_extendqidi2_speculative,
7481     gen_zero_extendhidi2_speculative,
7482     gen_zero_extendsidi2_speculative,
7483   };
7484   static gen_func_t gen_ld_sa[] = {
7485     gen_movbi_speculative_advanced,
7486     gen_movqi_speculative_advanced,
7487     gen_movhi_speculative_advanced,
7488     gen_movsi_speculative_advanced,
7489     gen_movdi_speculative_advanced,
7490     gen_movsf_speculative_advanced,
7491     gen_movdf_speculative_advanced,
7492     gen_movxf_speculative_advanced,
7493     gen_movti_speculative_advanced,
7494     gen_zero_extendqidi2_speculative_advanced,
7495     gen_zero_extendhidi2_speculative_advanced,
7496     gen_zero_extendsidi2_speculative_advanced,
7497   };
7498   static gen_func_t gen_ld_s_a[] = {
7499     gen_movbi_speculative_a,
7500     gen_movqi_speculative_a,
7501     gen_movhi_speculative_a,
7502     gen_movsi_speculative_a,
7503     gen_movdi_speculative_a,
7504     gen_movsf_speculative_a,
7505     gen_movdf_speculative_a,
7506     gen_movxf_speculative_a,
7507     gen_movti_speculative_a,
7508     gen_zero_extendqidi2_speculative_a,
7509     gen_zero_extendhidi2_speculative_a,
7510     gen_zero_extendsidi2_speculative_a,
7511   };
7512
7513   gen_func_t *gen_ld;
7514
7515   if (ts & BEGIN_DATA)
7516     {
7517       if (ts & BEGIN_CONTROL)
7518         gen_ld = gen_ld_sa;
7519       else
7520         gen_ld = gen_ld_a;
7521     }
7522   else if (ts & BEGIN_CONTROL)
7523     {
7524       if ((spec_info->flags & SEL_SCHED_SPEC_DONT_CHECK_CONTROL)
7525           || ia64_needs_block_p (ts))
7526         gen_ld = gen_ld_s;
7527       else
7528         gen_ld = gen_ld_s_a;
7529     }
7530   else if (ts == 0)
7531     gen_ld = gen_ld_;
7532   else
7533     gcc_unreachable ();
7534
7535   return gen_ld[mode_no];
7536 }
7537
7538 /* Constants that help mapping 'enum machine_mode' to int.  */
7539 enum SPEC_MODES
7540   {
7541     SPEC_MODE_INVALID = -1,
7542     SPEC_MODE_FIRST = 0,
7543     SPEC_MODE_FOR_EXTEND_FIRST = 1,
7544     SPEC_MODE_FOR_EXTEND_LAST = 3,
7545     SPEC_MODE_LAST = 8
7546   };
7547
7548 enum
7549   {
7550     /* Offset to reach ZERO_EXTEND patterns.  */
7551     SPEC_GEN_EXTEND_OFFSET = SPEC_MODE_LAST - SPEC_MODE_FOR_EXTEND_FIRST + 1
7552   };
7553
7554 /* Return index of the MODE.  */
7555 static int
7556 ia64_mode_to_int (enum machine_mode mode)
7557 {
7558   switch (mode)
7559     {
7560     case BImode: return 0; /* SPEC_MODE_FIRST  */
7561     case QImode: return 1; /* SPEC_MODE_FOR_EXTEND_FIRST  */
7562     case HImode: return 2;
7563     case SImode: return 3; /* SPEC_MODE_FOR_EXTEND_LAST  */
7564     case DImode: return 4;
7565     case SFmode: return 5;
7566     case DFmode: return 6;
7567     case XFmode: return 7;
7568     case TImode:
7569       /* ??? This mode needs testing.  Bypasses for ldfp8 instruction are not
7570          mentioned in itanium[12].md.  Predicate fp_register_operand also
7571          needs to be defined.  Bottom line: better disable for now.  */
7572       return SPEC_MODE_INVALID;
7573     default:     return SPEC_MODE_INVALID;
7574     }
7575 }
7576
7577 /* Provide information about speculation capabilities.  */
7578 static void
7579 ia64_set_sched_flags (spec_info_t spec_info)
7580 {
7581   unsigned int *flags = &(current_sched_info->flags);
7582
7583   if (*flags & SCHED_RGN
7584       || *flags & SCHED_EBB
7585       || *flags & SEL_SCHED)
7586     {
7587       int mask = 0;
7588
7589       if ((mflag_sched_br_data_spec && !reload_completed && optimize > 0)
7590           || (mflag_sched_ar_data_spec && reload_completed))
7591         {
7592           mask |= BEGIN_DATA;
7593
7594           if (!sel_sched_p ()
7595               && ((mflag_sched_br_in_data_spec && !reload_completed)
7596                   || (mflag_sched_ar_in_data_spec && reload_completed)))
7597             mask |= BE_IN_DATA;
7598         }
7599       
7600       if (mflag_sched_control_spec
7601           && (!sel_sched_p ()
7602               || reload_completed))
7603         {
7604           mask |= BEGIN_CONTROL;
7605           
7606           if (!sel_sched_p () && mflag_sched_in_control_spec)
7607             mask |= BE_IN_CONTROL;
7608         }
7609
7610       spec_info->mask = mask;
7611
7612       if (mask)
7613         {
7614           *flags |= USE_DEPS_LIST | DO_SPECULATION;
7615
7616           if (mask & BE_IN_SPEC)
7617             *flags |= NEW_BBS;
7618           
7619           spec_info->flags = 0;
7620       
7621           if ((mask & DATA_SPEC) && mflag_sched_prefer_non_data_spec_insns)
7622             spec_info->flags |= PREFER_NON_DATA_SPEC;
7623
7624           if (mask & CONTROL_SPEC)
7625             {
7626               if (mflag_sched_prefer_non_control_spec_insns)
7627                 spec_info->flags |= PREFER_NON_CONTROL_SPEC;
7628
7629               if (sel_sched_p () && mflag_sel_sched_dont_check_control_spec)
7630                 spec_info->flags |= SEL_SCHED_SPEC_DONT_CHECK_CONTROL;
7631             }
7632
7633           if (sched_verbose >= 1)
7634             spec_info->dump = sched_dump;
7635           else
7636             spec_info->dump = 0;
7637           
7638           if (mflag_sched_count_spec_in_critical_path)
7639             spec_info->flags |= COUNT_SPEC_IN_CRITICAL_PATH;
7640         }
7641     }
7642   else
7643     spec_info->mask = 0;
7644 }
7645
7646 /* If INSN is an appropriate load return its mode.
7647    Return -1 otherwise.  */
7648 static int
7649 get_mode_no_for_insn (rtx insn)
7650 {
7651   rtx reg, mem, mode_rtx;
7652   int mode_no;
7653   bool extend_p;
7654
7655   extract_insn_cached (insn);
7656
7657   /* We use WHICH_ALTERNATIVE only after reload.  This will
7658      guarantee that reload won't touch a speculative insn.  */
7659
7660   if (recog_data.n_operands != 2)
7661     return -1;
7662
7663   reg = recog_data.operand[0];
7664   mem = recog_data.operand[1];
7665
7666   /* We should use MEM's mode since REG's mode in presence of
7667      ZERO_EXTEND will always be DImode.  */
7668   if (get_attr_speculable1 (insn) == SPECULABLE1_YES)
7669     /* Process non-speculative ld.  */
7670     {
7671       if (!reload_completed)
7672         {
7673           /* Do not speculate into regs like ar.lc.  */
7674           if (!REG_P (reg) || AR_REGNO_P (REGNO (reg)))
7675             return -1;
7676
7677           if (!MEM_P (mem))
7678             return -1;
7679
7680           {
7681             rtx mem_reg = XEXP (mem, 0);
7682
7683             if (!REG_P (mem_reg))
7684               return -1;
7685           }
7686
7687           mode_rtx = mem;
7688         }
7689       else if (get_attr_speculable2 (insn) == SPECULABLE2_YES)
7690         {
7691           gcc_assert (REG_P (reg) && MEM_P (mem));
7692           mode_rtx = mem;
7693         }
7694       else
7695         return -1;
7696     }
7697   else if (get_attr_data_speculative (insn) == DATA_SPECULATIVE_YES
7698            || get_attr_control_speculative (insn) == CONTROL_SPECULATIVE_YES
7699            || get_attr_check_load (insn) == CHECK_LOAD_YES)
7700     /* Process speculative ld or ld.c.  */
7701     {
7702       gcc_assert (REG_P (reg) && MEM_P (mem));
7703       mode_rtx = mem;
7704     }
7705   else
7706     {
7707       enum attr_itanium_class attr_class = get_attr_itanium_class (insn);
7708
7709       if (attr_class == ITANIUM_CLASS_CHK_A
7710           || attr_class == ITANIUM_CLASS_CHK_S_I
7711           || attr_class == ITANIUM_CLASS_CHK_S_F)
7712         /* Process chk.  */
7713         mode_rtx = reg;
7714       else
7715         return -1;
7716     }
7717
7718   mode_no = ia64_mode_to_int (GET_MODE (mode_rtx));
7719
7720   if (mode_no == SPEC_MODE_INVALID)
7721     return -1;
7722
7723   extend_p = (GET_MODE (reg) != GET_MODE (mode_rtx));
7724
7725   if (extend_p)
7726     {
7727       if (!(SPEC_MODE_FOR_EXTEND_FIRST <= mode_no
7728             && mode_no <= SPEC_MODE_FOR_EXTEND_LAST))
7729         return -1;
7730
7731       mode_no += SPEC_GEN_EXTEND_OFFSET;
7732     }
7733
7734   return mode_no;
7735 }
7736
7737 /* If X is an unspec part of a speculative load, return its code.
7738    Return -1 otherwise.  */
7739 static int
7740 get_spec_unspec_code (const_rtx x)
7741 {
7742   if (GET_CODE (x) != UNSPEC)
7743     return -1;
7744
7745   {
7746     int code;
7747
7748     code = XINT (x, 1);
7749
7750     switch (code)
7751       {
7752       case UNSPEC_LDA:
7753       case UNSPEC_LDS:
7754       case UNSPEC_LDS_A:
7755       case UNSPEC_LDSA:
7756         return code;
7757
7758       default:
7759         return -1;
7760       }
7761   }
7762 }
7763
7764 /* Implement skip_rtx_p hook.  */
7765 static bool
7766 ia64_skip_rtx_p (const_rtx x)
7767 {
7768   return get_spec_unspec_code (x) != -1;
7769 }
7770
7771 /* If INSN is a speculative load, return its UNSPEC code.
7772    Return -1 otherwise.  */
7773 static int
7774 get_insn_spec_code (const_rtx insn)
7775 {
7776   rtx pat, reg, mem;
7777
7778   pat = PATTERN (insn);
7779
7780   if (GET_CODE (pat) == COND_EXEC)
7781     pat = COND_EXEC_CODE (pat);
7782
7783   if (GET_CODE (pat) != SET)
7784     return -1;
7785
7786   reg = SET_DEST (pat);
7787   if (!REG_P (reg))
7788     return -1;
7789
7790   mem = SET_SRC (pat);
7791   if (GET_CODE (mem) == ZERO_EXTEND)
7792     mem = XEXP (mem, 0);
7793
7794   return get_spec_unspec_code (mem);
7795 }
7796
7797 /* If INSN is a speculative load, return a ds with the speculation types.
7798    Otherwise [if INSN is a normal instruction] return 0.  */
7799 static ds_t
7800 ia64_get_insn_spec_ds (rtx insn)
7801 {
7802   int code = get_insn_spec_code (insn);
7803
7804   switch (code)
7805     {
7806     case UNSPEC_LDA:
7807       return BEGIN_DATA;
7808
7809     case UNSPEC_LDS:
7810     case UNSPEC_LDS_A:
7811       return BEGIN_CONTROL;
7812
7813     case UNSPEC_LDSA:
7814       return BEGIN_DATA | BEGIN_CONTROL;
7815
7816     default:
7817       return 0;
7818     }
7819 }
7820
7821 /* If INSN is a speculative load return a ds with the speculation types that
7822    will be checked.
7823    Otherwise [if INSN is a normal instruction] return 0.  */
7824 static ds_t
7825 ia64_get_insn_checked_ds (rtx insn)
7826 {
7827   int code = get_insn_spec_code (insn);
7828
7829   switch (code)
7830     {
7831     case UNSPEC_LDA:
7832       return BEGIN_DATA | BEGIN_CONTROL;
7833
7834     case UNSPEC_LDS:
7835       return BEGIN_CONTROL;
7836
7837     case UNSPEC_LDS_A:
7838     case UNSPEC_LDSA:
7839       return BEGIN_DATA | BEGIN_CONTROL;
7840
7841     default:
7842       return 0;
7843     }
7844 }
7845
7846 /* If GEN_P is true, calculate the index of needed speculation check and return
7847    speculative pattern for INSN with speculative mode TS, machine mode
7848    MODE_NO and with ZERO_EXTEND (if EXTEND_P is true).
7849    If GEN_P is false, just calculate the index of needed speculation check.  */
7850 static rtx
7851 ia64_gen_spec_load (rtx insn, ds_t ts, int mode_no)
7852 {
7853   rtx pat, new_pat;
7854   gen_func_t gen_load;
7855
7856   gen_load = get_spec_load_gen_function (ts, mode_no);
7857
7858   new_pat = gen_load (copy_rtx (recog_data.operand[0]),
7859                       copy_rtx (recog_data.operand[1]));
7860
7861   pat = PATTERN (insn);
7862   if (GET_CODE (pat) == COND_EXEC)
7863     new_pat = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (COND_EXEC_TEST (pat)),
7864                                  new_pat);
7865
7866   return new_pat;
7867 }
7868
7869 static bool
7870 insn_can_be_in_speculative_p (rtx insn ATTRIBUTE_UNUSED,
7871                               ds_t ds ATTRIBUTE_UNUSED)
7872 {
7873   return false;
7874 }
7875
7876 /* Implement targetm.sched.speculate_insn hook.
7877    Check if the INSN can be TS speculative.
7878    If 'no' - return -1.
7879    If 'yes' - generate speculative pattern in the NEW_PAT and return 1.
7880    If current pattern of the INSN already provides TS speculation,
7881    return 0.  */
7882 static int
7883 ia64_speculate_insn (rtx insn, ds_t ts, rtx *new_pat)
7884 {  
7885   int mode_no;
7886   int res;
7887   
7888   gcc_assert (!(ts & ~SPECULATIVE));
7889
7890   if (ia64_spec_check_p (insn))
7891     return -1;
7892
7893   if ((ts & BE_IN_SPEC)
7894       && !insn_can_be_in_speculative_p (insn, ts))
7895     return -1;
7896
7897   mode_no = get_mode_no_for_insn (insn);
7898
7899   if (mode_no != SPEC_MODE_INVALID)
7900     {
7901       if (ia64_get_insn_spec_ds (insn) == ds_get_speculation_types (ts))
7902         res = 0;
7903       else
7904         {
7905           res = 1;
7906           *new_pat = ia64_gen_spec_load (insn, ts, mode_no);
7907         }
7908     }
7909   else
7910     res = -1;
7911
7912   return res;
7913 }
7914
7915 /* Return a function that will generate a check for speculation TS with mode
7916    MODE_NO.
7917    If simple check is needed, pass true for SIMPLE_CHECK_P.
7918    If clearing check is needed, pass true for CLEARING_CHECK_P.  */
7919 static gen_func_t
7920 get_spec_check_gen_function (ds_t ts, int mode_no,
7921                              bool simple_check_p, bool clearing_check_p)
7922 {
7923   static gen_func_t gen_ld_c_clr[] = {
7924     gen_movbi_clr,
7925     gen_movqi_clr,
7926     gen_movhi_clr,
7927     gen_movsi_clr,
7928     gen_movdi_clr,
7929     gen_movsf_clr,
7930     gen_movdf_clr,
7931     gen_movxf_clr,
7932     gen_movti_clr,
7933     gen_zero_extendqidi2_clr,
7934     gen_zero_extendhidi2_clr,
7935     gen_zero_extendsidi2_clr,
7936   };
7937   static gen_func_t gen_ld_c_nc[] = {
7938     gen_movbi_nc,
7939     gen_movqi_nc,
7940     gen_movhi_nc,
7941     gen_movsi_nc,
7942     gen_movdi_nc,
7943     gen_movsf_nc,
7944     gen_movdf_nc,
7945     gen_movxf_nc,
7946     gen_movti_nc,
7947     gen_zero_extendqidi2_nc,
7948     gen_zero_extendhidi2_nc,
7949     gen_zero_extendsidi2_nc,
7950   };
7951   static gen_func_t gen_chk_a_clr[] = {
7952     gen_advanced_load_check_clr_bi,
7953     gen_advanced_load_check_clr_qi,
7954     gen_advanced_load_check_clr_hi,
7955     gen_advanced_load_check_clr_si,
7956     gen_advanced_load_check_clr_di,
7957     gen_advanced_load_check_clr_sf,
7958     gen_advanced_load_check_clr_df,
7959     gen_advanced_load_check_clr_xf,
7960     gen_advanced_load_check_clr_ti,
7961     gen_advanced_load_check_clr_di,
7962     gen_advanced_load_check_clr_di,
7963     gen_advanced_load_check_clr_di,
7964   };
7965   static gen_func_t gen_chk_a_nc[] = {
7966     gen_advanced_load_check_nc_bi,
7967     gen_advanced_load_check_nc_qi,
7968     gen_advanced_load_check_nc_hi,
7969     gen_advanced_load_check_nc_si,
7970     gen_advanced_load_check_nc_di,
7971     gen_advanced_load_check_nc_sf,
7972     gen_advanced_load_check_nc_df,
7973     gen_advanced_load_check_nc_xf,
7974     gen_advanced_load_check_nc_ti,
7975     gen_advanced_load_check_nc_di,
7976     gen_advanced_load_check_nc_di,
7977     gen_advanced_load_check_nc_di,
7978   };
7979   static gen_func_t gen_chk_s[] = {
7980     gen_speculation_check_bi,
7981     gen_speculation_check_qi,
7982     gen_speculation_check_hi,
7983     gen_speculation_check_si,
7984     gen_speculation_check_di,
7985     gen_speculation_check_sf,
7986     gen_speculation_check_df,
7987     gen_speculation_check_xf,
7988     gen_speculation_check_ti,
7989     gen_speculation_check_di,
7990     gen_speculation_check_di,
7991     gen_speculation_check_di,
7992   };
7993
7994   gen_func_t *gen_check;
7995
7996   if (ts & BEGIN_DATA)
7997     {
7998       /* We don't need recovery because even if this is ld.sa
7999          ALAT entry will be allocated only if NAT bit is set to zero.
8000          So it is enough to use ld.c here.  */
8001
8002       if (simple_check_p)
8003         {
8004           gcc_assert (mflag_sched_spec_ldc);
8005
8006           if (clearing_check_p)
8007             gen_check = gen_ld_c_clr;
8008           else
8009             gen_check = gen_ld_c_nc;
8010         }
8011       else
8012         {
8013           if (clearing_check_p)
8014             gen_check = gen_chk_a_clr;
8015           else
8016             gen_check = gen_chk_a_nc;
8017         }
8018     }
8019   else if (ts & BEGIN_CONTROL)
8020     {
8021       if (simple_check_p)
8022         /* We might want to use ld.sa -> ld.c instead of
8023            ld.s -> chk.s.  */
8024         {
8025           gcc_assert (!ia64_needs_block_p (ts));
8026
8027           if (clearing_check_p)
8028             gen_check = gen_ld_c_clr;
8029           else
8030             gen_check = gen_ld_c_nc;
8031         }
8032       else
8033         {
8034           gen_check = gen_chk_s;
8035         }
8036     }
8037   else
8038     gcc_unreachable ();
8039
8040   gcc_assert (mode_no >= 0);
8041   return gen_check[mode_no];
8042 }
8043
8044 /* Return nonzero, if INSN needs branchy recovery check.  */
8045 static bool
8046 ia64_needs_block_p (ds_t ts)
8047 {
8048   if (ts & BEGIN_DATA)
8049     return !mflag_sched_spec_ldc;
8050
8051   gcc_assert ((ts & BEGIN_CONTROL) != 0);
8052
8053   return !(mflag_sched_spec_control_ldc && mflag_sched_spec_ldc);
8054 }
8055
8056 /* Generate (or regenerate, if (MUTATE_P)) recovery check for INSN.
8057    If (LABEL != 0 || MUTATE_P), generate branchy recovery check.
8058    Otherwise, generate a simple check.  */
8059 static rtx
8060 ia64_gen_spec_check (rtx insn, rtx label, ds_t ds)
8061 {
8062   rtx op1, pat, check_pat;
8063   gen_func_t gen_check;
8064   int mode_no;
8065
8066   mode_no = get_mode_no_for_insn (insn);
8067   gcc_assert (mode_no >= 0);
8068
8069   if (label)
8070     op1 = label;
8071   else
8072     {
8073       gcc_assert (!ia64_needs_block_p (ds));
8074       op1 = copy_rtx (recog_data.operand[1]);
8075     }
8076       
8077   gen_check = get_spec_check_gen_function (ds, mode_no, label == NULL_RTX,
8078                                            true);
8079
8080   check_pat = gen_check (copy_rtx (recog_data.operand[0]), op1);
8081     
8082   pat = PATTERN (insn);
8083   if (GET_CODE (pat) == COND_EXEC)
8084     check_pat = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (COND_EXEC_TEST (pat)),
8085                                    check_pat);
8086
8087   return check_pat;
8088 }
8089
8090 /* Return nonzero, if X is branchy recovery check.  */
8091 static int
8092 ia64_spec_check_p (rtx x)
8093 {
8094   x = PATTERN (x);
8095   if (GET_CODE (x) == COND_EXEC)
8096     x = COND_EXEC_CODE (x);
8097   if (GET_CODE (x) == SET)
8098     return ia64_spec_check_src_p (SET_SRC (x));
8099   return 0;
8100 }
8101
8102 /* Return nonzero, if SRC belongs to recovery check.  */
8103 static int
8104 ia64_spec_check_src_p (rtx src)
8105 {
8106   if (GET_CODE (src) == IF_THEN_ELSE)
8107     {
8108       rtx t;
8109
8110       t = XEXP (src, 0);
8111       if (GET_CODE (t) == NE)
8112         {
8113           t = XEXP (t, 0);          
8114
8115           if (GET_CODE (t) == UNSPEC)
8116             {
8117               int code;
8118               
8119               code = XINT (t, 1);
8120              
8121               if (code == UNSPEC_LDCCLR
8122                   || code == UNSPEC_LDCNC
8123                   || code == UNSPEC_CHKACLR
8124                   || code == UNSPEC_CHKANC
8125                   || code == UNSPEC_CHKS)
8126                 {
8127                   gcc_assert (code != 0);
8128                   return code;
8129                 }
8130             }
8131         }
8132     }
8133   return 0;
8134 }
8135 \f
8136
8137 /* The following page contains abstract data `bundle states' which are
8138    used for bundling insns (inserting nops and template generation).  */
8139
8140 /* The following describes state of insn bundling.  */
8141
8142 struct bundle_state
8143 {
8144   /* Unique bundle state number to identify them in the debugging
8145      output  */
8146   int unique_num;
8147   rtx insn;     /* corresponding insn, NULL for the 1st and the last state  */
8148   /* number nops before and after the insn  */
8149   short before_nops_num, after_nops_num;
8150   int insn_num; /* insn number (0 - for initial state, 1 - for the 1st
8151                    insn */
8152   int cost;     /* cost of the state in cycles */
8153   int accumulated_insns_num; /* number of all previous insns including
8154                                 nops.  L is considered as 2 insns */
8155   int branch_deviation; /* deviation of previous branches from 3rd slots  */
8156   int middle_bundle_stops; /* number of stop bits in the middle of bundles */
8157   struct bundle_state *next;  /* next state with the same insn_num  */
8158   struct bundle_state *originator; /* originator (previous insn state)  */
8159   /* All bundle states are in the following chain.  */
8160   struct bundle_state *allocated_states_chain;
8161   /* The DFA State after issuing the insn and the nops.  */
8162   state_t dfa_state;
8163 };
8164
8165 /* The following is map insn number to the corresponding bundle state.  */
8166
8167 static struct bundle_state **index_to_bundle_states;
8168
8169 /* The unique number of next bundle state.  */
8170
8171 static int bundle_states_num;
8172
8173 /* All allocated bundle states are in the following chain.  */
8174
8175 static struct bundle_state *allocated_bundle_states_chain;
8176
8177 /* All allocated but not used bundle states are in the following
8178    chain.  */
8179
8180 static struct bundle_state *free_bundle_state_chain;
8181
8182
8183 /* The following function returns a free bundle state.  */
8184
8185 static struct bundle_state *
8186 get_free_bundle_state (void)
8187 {
8188   struct bundle_state *result;
8189
8190   if (free_bundle_state_chain != NULL)
8191     {
8192       result = free_bundle_state_chain;
8193       free_bundle_state_chain = result->next;
8194     }
8195   else
8196     {
8197       result = XNEW (struct bundle_state);
8198       result->dfa_state = xmalloc (dfa_state_size);
8199       result->allocated_states_chain = allocated_bundle_states_chain;
8200       allocated_bundle_states_chain = result;
8201     }
8202   result->unique_num = bundle_states_num++;
8203   return result;
8204
8205 }
8206
8207 /* The following function frees given bundle state.  */
8208
8209 static void
8210 free_bundle_state (struct bundle_state *state)
8211 {
8212   state->next = free_bundle_state_chain;
8213   free_bundle_state_chain = state;
8214 }
8215
8216 /* Start work with abstract data `bundle states'.  */
8217
8218 static void
8219 initiate_bundle_states (void)
8220 {
8221   bundle_states_num = 0;
8222   free_bundle_state_chain = NULL;
8223   allocated_bundle_states_chain = NULL;
8224 }
8225
8226 /* Finish work with abstract data `bundle states'.  */
8227
8228 static void
8229 finish_bundle_states (void)
8230 {
8231   struct bundle_state *curr_state, *next_state;
8232
8233   for (curr_state = allocated_bundle_states_chain;
8234        curr_state != NULL;
8235        curr_state = next_state)
8236     {
8237       next_state = curr_state->allocated_states_chain;
8238       free (curr_state->dfa_state);
8239       free (curr_state);
8240     }
8241 }
8242
8243 /* Hash table of the bundle states.  The key is dfa_state and insn_num
8244    of the bundle states.  */
8245
8246 static htab_t bundle_state_table;
8247
8248 /* The function returns hash of BUNDLE_STATE.  */
8249
8250 static unsigned
8251 bundle_state_hash (const void *bundle_state)
8252 {
8253   const struct bundle_state *const state
8254     = (const struct bundle_state *) bundle_state;
8255   unsigned result, i;
8256
8257   for (result = i = 0; i < dfa_state_size; i++)
8258     result += (((unsigned char *) state->dfa_state) [i]
8259                << ((i % CHAR_BIT) * 3 + CHAR_BIT));
8260   return result + state->insn_num;
8261 }
8262
8263 /* The function returns nonzero if the bundle state keys are equal.  */
8264
8265 static int
8266 bundle_state_eq_p (const void *bundle_state_1, const void *bundle_state_2)
8267 {
8268   const struct bundle_state *const state1
8269     = (const struct bundle_state *) bundle_state_1;
8270   const struct bundle_state *const state2
8271     = (const struct bundle_state *) bundle_state_2;
8272
8273   return (state1->insn_num == state2->insn_num
8274           && memcmp (state1->dfa_state, state2->dfa_state,
8275                      dfa_state_size) == 0);
8276 }
8277
8278 /* The function inserts the BUNDLE_STATE into the hash table.  The
8279    function returns nonzero if the bundle has been inserted into the
8280    table.  The table contains the best bundle state with given key.  */
8281
8282 static int
8283 insert_bundle_state (struct bundle_state *bundle_state)
8284 {
8285   void **entry_ptr;
8286
8287   entry_ptr = htab_find_slot (bundle_state_table, bundle_state, INSERT);
8288   if (*entry_ptr == NULL)
8289     {
8290       bundle_state->next = index_to_bundle_states [bundle_state->insn_num];
8291       index_to_bundle_states [bundle_state->insn_num] = bundle_state;
8292       *entry_ptr = (void *) bundle_state;
8293       return TRUE;
8294     }
8295   else if (bundle_state->cost < ((struct bundle_state *) *entry_ptr)->cost
8296            || (bundle_state->cost == ((struct bundle_state *) *entry_ptr)->cost
8297                && (((struct bundle_state *)*entry_ptr)->accumulated_insns_num
8298                    > bundle_state->accumulated_insns_num
8299                    || (((struct bundle_state *)
8300                         *entry_ptr)->accumulated_insns_num
8301                        == bundle_state->accumulated_insns_num
8302                        && (((struct bundle_state *)
8303                             *entry_ptr)->branch_deviation
8304                            > bundle_state->branch_deviation
8305                            || (((struct bundle_state *)
8306                                 *entry_ptr)->branch_deviation
8307                                == bundle_state->branch_deviation
8308                                && ((struct bundle_state *)
8309                                    *entry_ptr)->middle_bundle_stops
8310                                > bundle_state->middle_bundle_stops))))))
8311
8312     {
8313       struct bundle_state temp;
8314
8315       temp = *(struct bundle_state *) *entry_ptr;
8316       *(struct bundle_state *) *entry_ptr = *bundle_state;
8317       ((struct bundle_state *) *entry_ptr)->next = temp.next;
8318       *bundle_state = temp;
8319     }
8320   return FALSE;
8321 }
8322
8323 /* Start work with the hash table.  */
8324
8325 static void
8326 initiate_bundle_state_table (void)
8327 {
8328   bundle_state_table = htab_create (50, bundle_state_hash, bundle_state_eq_p,
8329                                     (htab_del) 0);
8330 }
8331
8332 /* Finish work with the hash table.  */
8333
8334 static void
8335 finish_bundle_state_table (void)
8336 {
8337   htab_delete (bundle_state_table);
8338 }
8339
8340 \f
8341
8342 /* The following variable is a insn `nop' used to check bundle states
8343    with different number of inserted nops.  */
8344
8345 static rtx ia64_nop;
8346
8347 /* The following function tries to issue NOPS_NUM nops for the current
8348    state without advancing processor cycle.  If it failed, the
8349    function returns FALSE and frees the current state.  */
8350
8351 static int
8352 try_issue_nops (struct bundle_state *curr_state, int nops_num)
8353 {
8354   int i;
8355
8356   for (i = 0; i < nops_num; i++)
8357     if (state_transition (curr_state->dfa_state, ia64_nop) >= 0)
8358       {
8359         free_bundle_state (curr_state);
8360         return FALSE;
8361       }
8362   return TRUE;
8363 }
8364
8365 /* The following function tries to issue INSN for the current
8366    state without advancing processor cycle.  If it failed, the
8367    function returns FALSE and frees the current state.  */
8368
8369 static int
8370 try_issue_insn (struct bundle_state *curr_state, rtx insn)
8371 {
8372   if (insn && state_transition (curr_state->dfa_state, insn) >= 0)
8373     {
8374       free_bundle_state (curr_state);
8375       return FALSE;
8376     }
8377   return TRUE;
8378 }
8379
8380 /* The following function tries to issue BEFORE_NOPS_NUM nops and INSN
8381    starting with ORIGINATOR without advancing processor cycle.  If
8382    TRY_BUNDLE_END_P is TRUE, the function also/only (if
8383    ONLY_BUNDLE_END_P is TRUE) tries to issue nops to fill all bundle.
8384    If it was successful, the function creates new bundle state and
8385    insert into the hash table and into `index_to_bundle_states'.  */
8386
8387 static void
8388 issue_nops_and_insn (struct bundle_state *originator, int before_nops_num,
8389                      rtx insn, int try_bundle_end_p, int only_bundle_end_p)
8390 {
8391   struct bundle_state *curr_state;
8392
8393   curr_state = get_free_bundle_state ();
8394   memcpy (curr_state->dfa_state, originator->dfa_state, dfa_state_size);
8395   curr_state->insn = insn;
8396   curr_state->insn_num = originator->insn_num + 1;
8397   curr_state->cost = originator->cost;
8398   curr_state->originator = originator;
8399   curr_state->before_nops_num = before_nops_num;
8400   curr_state->after_nops_num = 0;
8401   curr_state->accumulated_insns_num
8402     = originator->accumulated_insns_num + before_nops_num;
8403   curr_state->branch_deviation = originator->branch_deviation;
8404   curr_state->middle_bundle_stops = originator->middle_bundle_stops;
8405   gcc_assert (insn);
8406   if (INSN_CODE (insn) == CODE_FOR_insn_group_barrier)
8407     {
8408       gcc_assert (GET_MODE (insn) != TImode);
8409       if (!try_issue_nops (curr_state, before_nops_num))
8410         return;
8411       if (!try_issue_insn (curr_state, insn))
8412         return;
8413       memcpy (temp_dfa_state, curr_state->dfa_state, dfa_state_size);
8414       if (curr_state->accumulated_insns_num % 3 != 0)
8415         curr_state->middle_bundle_stops++;
8416       if (state_transition (temp_dfa_state, dfa_pre_cycle_insn) >= 0
8417           && curr_state->accumulated_insns_num % 3 != 0)
8418         {
8419           free_bundle_state (curr_state);
8420           return;
8421         }
8422     }
8423   else if (GET_MODE (insn) != TImode)
8424     {
8425       if (!try_issue_nops (curr_state, before_nops_num))
8426         return;
8427       if (!try_issue_insn (curr_state, insn))
8428         return;
8429       curr_state->accumulated_insns_num++;
8430       gcc_assert (GET_CODE (PATTERN (insn)) != ASM_INPUT
8431                   && asm_noperands (PATTERN (insn)) < 0);
8432
8433       if (ia64_safe_type (insn) == TYPE_L)
8434         curr_state->accumulated_insns_num++;
8435     }
8436   else
8437     {
8438       /* If this is an insn that must be first in a group, then don't allow
8439          nops to be emitted before it.  Currently, alloc is the only such
8440          supported instruction.  */
8441       /* ??? The bundling automatons should handle this for us, but they do
8442          not yet have support for the first_insn attribute.  */
8443       if (before_nops_num > 0 && get_attr_first_insn (insn) == FIRST_INSN_YES)
8444         {
8445           free_bundle_state (curr_state);
8446           return;
8447         }
8448
8449       state_transition (curr_state->dfa_state, dfa_pre_cycle_insn);
8450       state_transition (curr_state->dfa_state, NULL);
8451       curr_state->cost++;
8452       if (!try_issue_nops (curr_state, before_nops_num))
8453         return;
8454       if (!try_issue_insn (curr_state, insn))
8455         return;
8456       curr_state->accumulated_insns_num++;
8457       if (GET_CODE (PATTERN (insn)) == ASM_INPUT
8458           || asm_noperands (PATTERN (insn)) >= 0)
8459         {
8460           /* Finish bundle containing asm insn.  */
8461           curr_state->after_nops_num
8462             = 3 - curr_state->accumulated_insns_num % 3;
8463           curr_state->accumulated_insns_num
8464             += 3 - curr_state->accumulated_insns_num % 3;
8465         }
8466       else if (ia64_safe_type (insn) == TYPE_L)
8467         curr_state->accumulated_insns_num++;
8468     }
8469   if (ia64_safe_type (insn) == TYPE_B)
8470     curr_state->branch_deviation
8471       += 2 - (curr_state->accumulated_insns_num - 1) % 3;
8472   if (try_bundle_end_p && curr_state->accumulated_insns_num % 3 != 0)
8473     {
8474       if (!only_bundle_end_p && insert_bundle_state (curr_state))
8475         {
8476           state_t dfa_state;
8477           struct bundle_state *curr_state1;
8478           struct bundle_state *allocated_states_chain;
8479
8480           curr_state1 = get_free_bundle_state ();
8481           dfa_state = curr_state1->dfa_state;
8482           allocated_states_chain = curr_state1->allocated_states_chain;
8483           *curr_state1 = *curr_state;
8484           curr_state1->dfa_state = dfa_state;
8485           curr_state1->allocated_states_chain = allocated_states_chain;
8486           memcpy (curr_state1->dfa_state, curr_state->dfa_state,
8487                   dfa_state_size);
8488           curr_state = curr_state1;
8489         }
8490       if (!try_issue_nops (curr_state,
8491                            3 - curr_state->accumulated_insns_num % 3))
8492         return;
8493       curr_state->after_nops_num
8494         = 3 - curr_state->accumulated_insns_num % 3;
8495       curr_state->accumulated_insns_num
8496         += 3 - curr_state->accumulated_insns_num % 3;
8497     }
8498   if (!insert_bundle_state (curr_state))
8499     free_bundle_state (curr_state);
8500   return;
8501 }
8502
8503 /* The following function returns position in the two window bundle
8504    for given STATE.  */
8505
8506 static int
8507 get_max_pos (state_t state)
8508 {
8509   if (cpu_unit_reservation_p (state, pos_6))
8510     return 6;
8511   else if (cpu_unit_reservation_p (state, pos_5))
8512     return 5;
8513   else if (cpu_unit_reservation_p (state, pos_4))
8514     return 4;
8515   else if (cpu_unit_reservation_p (state, pos_3))
8516     return 3;
8517   else if (cpu_unit_reservation_p (state, pos_2))
8518     return 2;
8519   else if (cpu_unit_reservation_p (state, pos_1))
8520     return 1;
8521   else
8522     return 0;
8523 }
8524
8525 /* The function returns code of a possible template for given position
8526    and state.  The function should be called only with 2 values of
8527    position equal to 3 or 6.  We avoid generating F NOPs by putting
8528    templates containing F insns at the end of the template search
8529    because undocumented anomaly in McKinley derived cores which can
8530    cause stalls if an F-unit insn (including a NOP) is issued within a
8531    six-cycle window after reading certain application registers (such
8532    as ar.bsp).  Furthermore, power-considerations also argue against
8533    the use of F-unit instructions unless they're really needed.  */
8534
8535 static int
8536 get_template (state_t state, int pos)
8537 {
8538   switch (pos)
8539     {
8540     case 3:
8541       if (cpu_unit_reservation_p (state, _0mmi_))
8542         return 1;
8543       else if (cpu_unit_reservation_p (state, _0mii_))
8544         return 0;
8545       else if (cpu_unit_reservation_p (state, _0mmb_))
8546         return 7;
8547       else if (cpu_unit_reservation_p (state, _0mib_))
8548         return 6;
8549       else if (cpu_unit_reservation_p (state, _0mbb_))
8550         return 5;
8551       else if (cpu_unit_reservation_p (state, _0bbb_))
8552         return 4;
8553       else if (cpu_unit_reservation_p (state, _0mmf_))
8554         return 3;
8555       else if (cpu_unit_reservation_p (state, _0mfi_))
8556         return 2;
8557       else if (cpu_unit_reservation_p (state, _0mfb_))
8558         return 8;
8559       else if (cpu_unit_reservation_p (state, _0mlx_))
8560         return 9;
8561       else
8562         gcc_unreachable ();
8563     case 6:
8564       if (cpu_unit_reservation_p (state, _1mmi_))
8565         return 1;
8566       else if (cpu_unit_reservation_p (state, _1mii_))
8567         return 0;
8568       else if (cpu_unit_reservation_p (state, _1mmb_))
8569         return 7;
8570       else if (cpu_unit_reservation_p (state, _1mib_))
8571         return 6;
8572       else if (cpu_unit_reservation_p (state, _1mbb_))
8573         return 5;
8574       else if (cpu_unit_reservation_p (state, _1bbb_))
8575         return 4;
8576       else if (_1mmf_ >= 0 && cpu_unit_reservation_p (state, _1mmf_))
8577         return 3;
8578       else if (cpu_unit_reservation_p (state, _1mfi_))
8579         return 2;
8580       else if (cpu_unit_reservation_p (state, _1mfb_))
8581         return 8;
8582       else if (cpu_unit_reservation_p (state, _1mlx_))
8583         return 9;
8584       else
8585         gcc_unreachable ();
8586     default:
8587       gcc_unreachable ();
8588     }
8589 }
8590
8591 /* True when INSN is important for bundling.  */
8592 static bool
8593 important_for_bundling_p (rtx insn)
8594 {
8595   return (INSN_P (insn)
8596           && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
8597           && GET_CODE (PATTERN (insn)) != USE
8598           && GET_CODE (PATTERN (insn)) != CLOBBER);
8599 }
8600
8601 /* The following function returns an insn important for insn bundling
8602    followed by INSN and before TAIL.  */
8603
8604 static rtx
8605 get_next_important_insn (rtx insn, rtx tail)
8606 {
8607   for (; insn && insn != tail; insn = NEXT_INSN (insn))
8608     if (important_for_bundling_p (insn))
8609       return insn;
8610   return NULL_RTX;
8611 }
8612
8613 /* Add a bundle selector TEMPLATE0 before INSN.  */
8614
8615 static void
8616 ia64_add_bundle_selector_before (int template0, rtx insn)
8617 {
8618   rtx b = gen_bundle_selector (GEN_INT (template0));
8619
8620   ia64_emit_insn_before (b, insn);
8621 #if NR_BUNDLES == 10
8622   if ((template0 == 4 || template0 == 5)
8623       && ia64_except_unwind_info () == UI_TARGET)
8624     {
8625       int i;
8626       rtx note = NULL_RTX;
8627
8628       /* In .mbb and .bbb bundles, check if CALL_INSN isn't in the
8629          first or second slot.  If it is and has REG_EH_NOTE set, copy it
8630          to following nops, as br.call sets rp to the address of following
8631          bundle and therefore an EH region end must be on a bundle
8632          boundary.  */
8633       insn = PREV_INSN (insn);
8634       for (i = 0; i < 3; i++)
8635         {
8636           do
8637             insn = next_active_insn (insn);
8638           while (GET_CODE (insn) == INSN
8639                  && get_attr_empty (insn) == EMPTY_YES);
8640           if (GET_CODE (insn) == CALL_INSN)
8641             note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
8642           else if (note)
8643             {
8644               int code;
8645
8646               gcc_assert ((code = recog_memoized (insn)) == CODE_FOR_nop
8647                           || code == CODE_FOR_nop_b);
8648               if (find_reg_note (insn, REG_EH_REGION, NULL_RTX))
8649                 note = NULL_RTX;
8650               else
8651                 add_reg_note (insn, REG_EH_REGION, XEXP (note, 0));
8652             }
8653         }
8654     }
8655 #endif
8656 }
8657
8658 /* The following function does insn bundling.  Bundling means
8659    inserting templates and nop insns to fit insn groups into permitted
8660    templates.  Instruction scheduling uses NDFA (non-deterministic
8661    finite automata) encoding informations about the templates and the
8662    inserted nops.  Nondeterminism of the automata permits follows
8663    all possible insn sequences very fast.
8664
8665    Unfortunately it is not possible to get information about inserting
8666    nop insns and used templates from the automata states.  The
8667    automata only says that we can issue an insn possibly inserting
8668    some nops before it and using some template.  Therefore insn
8669    bundling in this function is implemented by using DFA
8670    (deterministic finite automata).  We follow all possible insn
8671    sequences by inserting 0-2 nops (that is what the NDFA describe for
8672    insn scheduling) before/after each insn being bundled.  We know the
8673    start of simulated processor cycle from insn scheduling (insn
8674    starting a new cycle has TImode).
8675
8676    Simple implementation of insn bundling would create enormous
8677    number of possible insn sequences satisfying information about new
8678    cycle ticks taken from the insn scheduling.  To make the algorithm
8679    practical we use dynamic programming.  Each decision (about
8680    inserting nops and implicitly about previous decisions) is described
8681    by structure bundle_state (see above).  If we generate the same
8682    bundle state (key is automaton state after issuing the insns and
8683    nops for it), we reuse already generated one.  As consequence we
8684    reject some decisions which cannot improve the solution and
8685    reduce memory for the algorithm.
8686
8687    When we reach the end of EBB (extended basic block), we choose the
8688    best sequence and then, moving back in EBB, insert templates for
8689    the best alternative.  The templates are taken from querying
8690    automaton state for each insn in chosen bundle states.
8691
8692    So the algorithm makes two (forward and backward) passes through
8693    EBB.  */
8694
8695 static void
8696 bundling (FILE *dump, int verbose, rtx prev_head_insn, rtx tail)
8697 {
8698   struct bundle_state *curr_state, *next_state, *best_state;
8699   rtx insn, next_insn;
8700   int insn_num;
8701   int i, bundle_end_p, only_bundle_end_p, asm_p;
8702   int pos = 0, max_pos, template0, template1;
8703   rtx b;
8704   rtx nop;
8705   enum attr_type type;
8706
8707   insn_num = 0;
8708   /* Count insns in the EBB.  */
8709   for (insn = NEXT_INSN (prev_head_insn);
8710        insn && insn != tail;
8711        insn = NEXT_INSN (insn))
8712     if (INSN_P (insn))
8713       insn_num++;
8714   if (insn_num == 0)
8715     return;
8716   bundling_p = 1;
8717   dfa_clean_insn_cache ();
8718   initiate_bundle_state_table ();
8719   index_to_bundle_states = XNEWVEC (struct bundle_state *, insn_num + 2);
8720   /* First (forward) pass -- generation of bundle states.  */
8721   curr_state = get_free_bundle_state ();
8722   curr_state->insn = NULL;
8723   curr_state->before_nops_num = 0;
8724   curr_state->after_nops_num = 0;
8725   curr_state->insn_num = 0;
8726   curr_state->cost = 0;
8727   curr_state->accumulated_insns_num = 0;
8728   curr_state->branch_deviation = 0;
8729   curr_state->middle_bundle_stops = 0;
8730   curr_state->next = NULL;
8731   curr_state->originator = NULL;
8732   state_reset (curr_state->dfa_state);
8733   index_to_bundle_states [0] = curr_state;
8734   insn_num = 0;
8735   /* Shift cycle mark if it is put on insn which could be ignored.  */
8736   for (insn = NEXT_INSN (prev_head_insn);
8737        insn != tail;
8738        insn = NEXT_INSN (insn))
8739     if (INSN_P (insn)
8740         && (ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IGNORE
8741             || GET_CODE (PATTERN (insn)) == USE
8742             || GET_CODE (PATTERN (insn)) == CLOBBER)
8743         && GET_MODE (insn) == TImode)
8744       {
8745         PUT_MODE (insn, VOIDmode);
8746         for (next_insn = NEXT_INSN (insn);
8747              next_insn != tail;
8748              next_insn = NEXT_INSN (next_insn))
8749           if (INSN_P (next_insn)
8750               && ia64_safe_itanium_class (next_insn) != ITANIUM_CLASS_IGNORE
8751               && GET_CODE (PATTERN (next_insn)) != USE
8752               && GET_CODE (PATTERN (next_insn)) != CLOBBER
8753               && INSN_CODE (next_insn) != CODE_FOR_insn_group_barrier)
8754             {
8755               PUT_MODE (next_insn, TImode);
8756               break;
8757             }
8758       }
8759   /* Forward pass: generation of bundle states.  */
8760   for (insn = get_next_important_insn (NEXT_INSN (prev_head_insn), tail);
8761        insn != NULL_RTX;
8762        insn = next_insn)
8763     {
8764       gcc_assert (INSN_P (insn)
8765                   && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
8766                   && GET_CODE (PATTERN (insn)) != USE
8767                   && GET_CODE (PATTERN (insn)) != CLOBBER);
8768       type = ia64_safe_type (insn);
8769       next_insn = get_next_important_insn (NEXT_INSN (insn), tail);
8770       insn_num++;
8771       index_to_bundle_states [insn_num] = NULL;
8772       for (curr_state = index_to_bundle_states [insn_num - 1];
8773            curr_state != NULL;
8774            curr_state = next_state)
8775         {
8776           pos = curr_state->accumulated_insns_num % 3;
8777           next_state = curr_state->next;
8778           /* We must fill up the current bundle in order to start a
8779              subsequent asm insn in a new bundle.  Asm insn is always
8780              placed in a separate bundle.  */
8781           only_bundle_end_p
8782             = (next_insn != NULL_RTX
8783                && INSN_CODE (insn) == CODE_FOR_insn_group_barrier
8784                && ia64_safe_type (next_insn) == TYPE_UNKNOWN);
8785           /* We may fill up the current bundle if it is the cycle end
8786              without a group barrier.  */
8787           bundle_end_p
8788             = (only_bundle_end_p || next_insn == NULL_RTX
8789                || (GET_MODE (next_insn) == TImode
8790                    && INSN_CODE (insn) != CODE_FOR_insn_group_barrier));
8791           if (type == TYPE_F || type == TYPE_B || type == TYPE_L
8792               || type == TYPE_S)
8793             issue_nops_and_insn (curr_state, 2, insn, bundle_end_p,
8794                                  only_bundle_end_p);
8795           issue_nops_and_insn (curr_state, 1, insn, bundle_end_p,
8796                                only_bundle_end_p);
8797           issue_nops_and_insn (curr_state, 0, insn, bundle_end_p,
8798                                only_bundle_end_p);
8799         }
8800       gcc_assert (index_to_bundle_states [insn_num]);
8801       for (curr_state = index_to_bundle_states [insn_num];
8802            curr_state != NULL;
8803            curr_state = curr_state->next)
8804         if (verbose >= 2 && dump)
8805           {
8806             /* This structure is taken from generated code of the
8807                pipeline hazard recognizer (see file insn-attrtab.c).
8808                Please don't forget to change the structure if a new
8809                automaton is added to .md file.  */
8810             struct DFA_chip
8811             {
8812               unsigned short one_automaton_state;
8813               unsigned short oneb_automaton_state;
8814               unsigned short two_automaton_state;
8815               unsigned short twob_automaton_state;
8816             };
8817
8818             fprintf
8819               (dump,
8820                "//    Bundle state %d (orig %d, cost %d, nops %d/%d, insns %d, branch %d, mid.stops %d state %d) for %d\n",
8821                curr_state->unique_num,
8822                (curr_state->originator == NULL
8823                 ? -1 : curr_state->originator->unique_num),
8824                curr_state->cost,
8825                curr_state->before_nops_num, curr_state->after_nops_num,
8826                curr_state->accumulated_insns_num, curr_state->branch_deviation,
8827                curr_state->middle_bundle_stops,
8828                ((struct DFA_chip *) curr_state->dfa_state)->twob_automaton_state,
8829                INSN_UID (insn));
8830           }
8831     }
8832   
8833   /* We should find a solution because the 2nd insn scheduling has
8834      found one.  */
8835   gcc_assert (index_to_bundle_states [insn_num]);
8836   /* Find a state corresponding to the best insn sequence.  */
8837   best_state = NULL;
8838   for (curr_state = index_to_bundle_states [insn_num];
8839        curr_state != NULL;
8840        curr_state = curr_state->next)
8841     /* We are just looking at the states with fully filled up last
8842        bundle.  The first we prefer insn sequences with minimal cost
8843        then with minimal inserted nops and finally with branch insns
8844        placed in the 3rd slots.  */
8845     if (curr_state->accumulated_insns_num % 3 == 0
8846         && (best_state == NULL || best_state->cost > curr_state->cost
8847             || (best_state->cost == curr_state->cost
8848                 && (curr_state->accumulated_insns_num
8849                     < best_state->accumulated_insns_num
8850                     || (curr_state->accumulated_insns_num
8851                         == best_state->accumulated_insns_num
8852                         && (curr_state->branch_deviation
8853                             < best_state->branch_deviation
8854                             || (curr_state->branch_deviation
8855                                 == best_state->branch_deviation
8856                                 && curr_state->middle_bundle_stops
8857                                 < best_state->middle_bundle_stops)))))))
8858       best_state = curr_state;
8859   /* Second (backward) pass: adding nops and templates.  */
8860   gcc_assert (best_state);
8861   insn_num = best_state->before_nops_num;
8862   template0 = template1 = -1;
8863   for (curr_state = best_state;
8864        curr_state->originator != NULL;
8865        curr_state = curr_state->originator)
8866     {
8867       insn = curr_state->insn;
8868       asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
8869                || asm_noperands (PATTERN (insn)) >= 0);
8870       insn_num++;
8871       if (verbose >= 2 && dump)
8872         {
8873           struct DFA_chip
8874           {
8875             unsigned short one_automaton_state;
8876             unsigned short oneb_automaton_state;
8877             unsigned short two_automaton_state;
8878             unsigned short twob_automaton_state;
8879           };
8880
8881           fprintf
8882             (dump,
8883              "//    Best %d (orig %d, cost %d, nops %d/%d, insns %d, branch %d, mid.stops %d, state %d) for %d\n",
8884              curr_state->unique_num,
8885              (curr_state->originator == NULL
8886               ? -1 : curr_state->originator->unique_num),
8887              curr_state->cost,
8888              curr_state->before_nops_num, curr_state->after_nops_num,
8889              curr_state->accumulated_insns_num, curr_state->branch_deviation,
8890              curr_state->middle_bundle_stops,
8891              ((struct DFA_chip *) curr_state->dfa_state)->twob_automaton_state,
8892              INSN_UID (insn));
8893         }
8894       /* Find the position in the current bundle window.  The window can
8895          contain at most two bundles.  Two bundle window means that
8896          the processor will make two bundle rotation.  */
8897       max_pos = get_max_pos (curr_state->dfa_state);
8898       if (max_pos == 6
8899           /* The following (negative template number) means that the
8900              processor did one bundle rotation.  */
8901           || (max_pos == 3 && template0 < 0))
8902         {
8903           /* We are at the end of the window -- find template(s) for
8904              its bundle(s).  */
8905           pos = max_pos;
8906           if (max_pos == 3)
8907             template0 = get_template (curr_state->dfa_state, 3);
8908           else
8909             {
8910               template1 = get_template (curr_state->dfa_state, 3);
8911               template0 = get_template (curr_state->dfa_state, 6);
8912             }
8913         }
8914       if (max_pos > 3 && template1 < 0)
8915         /* It may happen when we have the stop inside a bundle.  */
8916         {
8917           gcc_assert (pos <= 3);
8918           template1 = get_template (curr_state->dfa_state, 3);
8919           pos += 3;
8920         }
8921       if (!asm_p)
8922         /* Emit nops after the current insn.  */
8923         for (i = 0; i < curr_state->after_nops_num; i++)
8924           {
8925             nop = gen_nop ();
8926             emit_insn_after (nop, insn);
8927             pos--;
8928             gcc_assert (pos >= 0);
8929             if (pos % 3 == 0)
8930               {
8931                 /* We are at the start of a bundle: emit the template
8932                    (it should be defined).  */
8933                 gcc_assert (template0 >= 0);
8934                 ia64_add_bundle_selector_before (template0, nop);
8935                 /* If we have two bundle window, we make one bundle
8936                    rotation.  Otherwise template0 will be undefined
8937                    (negative value).  */
8938                 template0 = template1;
8939                 template1 = -1;
8940               }
8941           }
8942       /* Move the position backward in the window.  Group barrier has
8943          no slot.  Asm insn takes all bundle.  */
8944       if (INSN_CODE (insn) != CODE_FOR_insn_group_barrier
8945           && GET_CODE (PATTERN (insn)) != ASM_INPUT
8946           && asm_noperands (PATTERN (insn)) < 0)
8947         pos--;
8948       /* Long insn takes 2 slots.  */
8949       if (ia64_safe_type (insn) == TYPE_L)
8950         pos--;
8951       gcc_assert (pos >= 0);
8952       if (pos % 3 == 0
8953           && INSN_CODE (insn) != CODE_FOR_insn_group_barrier
8954           && GET_CODE (PATTERN (insn)) != ASM_INPUT
8955           && asm_noperands (PATTERN (insn)) < 0)
8956         {
8957           /* The current insn is at the bundle start: emit the
8958              template.  */
8959           gcc_assert (template0 >= 0);
8960           ia64_add_bundle_selector_before (template0, insn);
8961           b = PREV_INSN (insn);
8962           insn = b;
8963           /* See comment above in analogous place for emitting nops
8964              after the insn.  */
8965           template0 = template1;
8966           template1 = -1;
8967         }
8968       /* Emit nops after the current insn.  */
8969       for (i = 0; i < curr_state->before_nops_num; i++)
8970         {
8971           nop = gen_nop ();
8972           ia64_emit_insn_before (nop, insn);
8973           nop = PREV_INSN (insn);
8974           insn = nop;
8975           pos--;
8976           gcc_assert (pos >= 0);
8977           if (pos % 3 == 0)
8978             {
8979               /* See comment above in analogous place for emitting nops
8980                  after the insn.  */
8981               gcc_assert (template0 >= 0);
8982               ia64_add_bundle_selector_before (template0, insn);
8983               b = PREV_INSN (insn);
8984               insn = b;
8985               template0 = template1;
8986               template1 = -1;
8987             }
8988         }
8989     }
8990
8991 #ifdef ENABLE_CHECKING
8992   {
8993     /* Assert right calculation of middle_bundle_stops.  */
8994     int num = best_state->middle_bundle_stops;
8995     bool start_bundle = true, end_bundle = false;
8996
8997     for (insn = NEXT_INSN (prev_head_insn);
8998          insn && insn != tail;
8999          insn = NEXT_INSN (insn))
9000       {
9001         if (!INSN_P (insn))
9002           continue;
9003         if (recog_memoized (insn) == CODE_FOR_bundle_selector)
9004           start_bundle = true;
9005         else
9006           {
9007             rtx next_insn;
9008
9009             for (next_insn = NEXT_INSN (insn);
9010                  next_insn && next_insn != tail;
9011                  next_insn = NEXT_INSN (next_insn))
9012               if (INSN_P (next_insn)
9013                   && (ia64_safe_itanium_class (next_insn)
9014                       != ITANIUM_CLASS_IGNORE
9015                       || recog_memoized (next_insn)
9016                       == CODE_FOR_bundle_selector)
9017                   && GET_CODE (PATTERN (next_insn)) != USE
9018                   && GET_CODE (PATTERN (next_insn)) != CLOBBER)
9019                 break;
9020
9021             end_bundle = next_insn == NULL_RTX
9022              || next_insn == tail
9023              || (INSN_P (next_insn)
9024                  && recog_memoized (next_insn)
9025                  == CODE_FOR_bundle_selector);
9026             if (recog_memoized (insn) == CODE_FOR_insn_group_barrier
9027                 && !start_bundle && !end_bundle
9028                 && next_insn
9029                 && GET_CODE (PATTERN (next_insn)) != ASM_INPUT
9030                 && asm_noperands (PATTERN (next_insn)) < 0)
9031               num--;
9032
9033             start_bundle = false;
9034           }
9035       }
9036
9037     gcc_assert (num == 0);
9038   }
9039 #endif
9040
9041   free (index_to_bundle_states);
9042   finish_bundle_state_table ();
9043   bundling_p = 0;
9044   dfa_clean_insn_cache ();
9045 }
9046
9047 /* The following function is called at the end of scheduling BB or
9048    EBB.  After reload, it inserts stop bits and does insn bundling.  */
9049
9050 static void
9051 ia64_sched_finish (FILE *dump, int sched_verbose)
9052 {
9053   if (sched_verbose)
9054     fprintf (dump, "// Finishing schedule.\n");
9055   if (!reload_completed)
9056     return;
9057   if (reload_completed)
9058     {
9059       final_emit_insn_group_barriers (dump);
9060       bundling (dump, sched_verbose, current_sched_info->prev_head,
9061                 current_sched_info->next_tail);
9062       if (sched_verbose && dump)
9063         fprintf (dump, "//    finishing %d-%d\n",
9064                  INSN_UID (NEXT_INSN (current_sched_info->prev_head)),
9065                  INSN_UID (PREV_INSN (current_sched_info->next_tail)));
9066
9067       return;
9068     }
9069 }
9070
9071 /* The following function inserts stop bits in scheduled BB or EBB.  */
9072
9073 static void
9074 final_emit_insn_group_barriers (FILE *dump ATTRIBUTE_UNUSED)
9075 {
9076   rtx insn;
9077   int need_barrier_p = 0;
9078   int seen_good_insn = 0;
9079
9080   init_insn_group_barriers ();
9081
9082   for (insn = NEXT_INSN (current_sched_info->prev_head);
9083        insn != current_sched_info->next_tail;
9084        insn = NEXT_INSN (insn))
9085     {
9086       if (GET_CODE (insn) == BARRIER)
9087         {
9088           rtx last = prev_active_insn (insn);
9089
9090           if (! last)
9091             continue;
9092           if (GET_CODE (last) == JUMP_INSN
9093               && GET_CODE (PATTERN (last)) == ADDR_DIFF_VEC)
9094             last = prev_active_insn (last);
9095           if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
9096             emit_insn_after (gen_insn_group_barrier (GEN_INT (3)), last);
9097
9098           init_insn_group_barriers ();
9099           seen_good_insn = 0;
9100           need_barrier_p = 0;
9101         }
9102       else if (NONDEBUG_INSN_P (insn))
9103         {
9104           if (recog_memoized (insn) == CODE_FOR_insn_group_barrier)
9105             {
9106               init_insn_group_barriers ();
9107               seen_good_insn = 0;
9108               need_barrier_p = 0;
9109             }
9110           else if (need_barrier_p || group_barrier_needed (insn)
9111                    || (mflag_sched_stop_bits_after_every_cycle
9112                        && GET_MODE (insn) == TImode
9113                        && seen_good_insn))
9114             {
9115               if (TARGET_EARLY_STOP_BITS)
9116                 {
9117                   rtx last;
9118
9119                   for (last = insn;
9120                        last != current_sched_info->prev_head;
9121                        last = PREV_INSN (last))
9122                     if (INSN_P (last) && GET_MODE (last) == TImode
9123                         && stops_p [INSN_UID (last)])
9124                       break;
9125                   if (last == current_sched_info->prev_head)
9126                     last = insn;
9127                   last = prev_active_insn (last);
9128                   if (last
9129                       && recog_memoized (last) != CODE_FOR_insn_group_barrier)
9130                     emit_insn_after (gen_insn_group_barrier (GEN_INT (3)),
9131                                      last);
9132                   init_insn_group_barriers ();
9133                   for (last = NEXT_INSN (last);
9134                        last != insn;
9135                        last = NEXT_INSN (last))
9136                     if (INSN_P (last))
9137                       {
9138                         group_barrier_needed (last);
9139                         if (recog_memoized (last) >= 0
9140                             && important_for_bundling_p (last))
9141                           seen_good_insn = 1;
9142                       }
9143                 }
9144               else
9145                 {
9146                   emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
9147                                     insn);
9148                   init_insn_group_barriers ();
9149                   seen_good_insn = 0;
9150                 }
9151               group_barrier_needed (insn);
9152               if (recog_memoized (insn) >= 0
9153                   && important_for_bundling_p (insn))
9154                 seen_good_insn = 1;
9155             }
9156           else if (recog_memoized (insn) >= 0
9157                    && important_for_bundling_p (insn))
9158             seen_good_insn = 1;
9159           need_barrier_p = (GET_CODE (insn) == CALL_INSN
9160                             || GET_CODE (PATTERN (insn)) == ASM_INPUT
9161                             || asm_noperands (PATTERN (insn)) >= 0);
9162         }
9163     }
9164 }
9165
9166 \f
9167
9168 /* If the following function returns TRUE, we will use the DFA
9169    insn scheduler.  */
9170
9171 static int
9172 ia64_first_cycle_multipass_dfa_lookahead (void)
9173 {
9174   return (reload_completed ? 6 : 4);
9175 }
9176
9177 /* The following function initiates variable `dfa_pre_cycle_insn'.  */
9178
9179 static void
9180 ia64_init_dfa_pre_cycle_insn (void)
9181 {
9182   if (temp_dfa_state == NULL)
9183     {
9184       dfa_state_size = state_size ();
9185       temp_dfa_state = xmalloc (dfa_state_size);
9186       prev_cycle_state = xmalloc (dfa_state_size);
9187     }
9188   dfa_pre_cycle_insn = make_insn_raw (gen_pre_cycle ());
9189   PREV_INSN (dfa_pre_cycle_insn) = NEXT_INSN (dfa_pre_cycle_insn) = NULL_RTX;
9190   recog_memoized (dfa_pre_cycle_insn);
9191   dfa_stop_insn = make_insn_raw (gen_insn_group_barrier (GEN_INT (3)));
9192   PREV_INSN (dfa_stop_insn) = NEXT_INSN (dfa_stop_insn) = NULL_RTX;
9193   recog_memoized (dfa_stop_insn);
9194 }
9195
9196 /* The following function returns the pseudo insn DFA_PRE_CYCLE_INSN
9197    used by the DFA insn scheduler.  */
9198
9199 static rtx
9200 ia64_dfa_pre_cycle_insn (void)
9201 {
9202   return dfa_pre_cycle_insn;
9203 }
9204
9205 /* The following function returns TRUE if PRODUCER (of type ilog or
9206    ld) produces address for CONSUMER (of type st or stf). */
9207
9208 int
9209 ia64_st_address_bypass_p (rtx producer, rtx consumer)
9210 {
9211   rtx dest, reg, mem;
9212
9213   gcc_assert (producer && consumer);
9214   dest = ia64_single_set (producer);
9215   gcc_assert (dest);
9216   reg = SET_DEST (dest);
9217   gcc_assert (reg);
9218   if (GET_CODE (reg) == SUBREG)
9219     reg = SUBREG_REG (reg);
9220   gcc_assert (GET_CODE (reg) == REG);
9221   
9222   dest = ia64_single_set (consumer);
9223   gcc_assert (dest);
9224   mem = SET_DEST (dest);
9225   gcc_assert (mem && GET_CODE (mem) == MEM);
9226   return reg_mentioned_p (reg, mem);
9227 }
9228
9229 /* The following function returns TRUE if PRODUCER (of type ilog or
9230    ld) produces address for CONSUMER (of type ld or fld). */
9231
9232 int
9233 ia64_ld_address_bypass_p (rtx producer, rtx consumer)
9234 {
9235   rtx dest, src, reg, mem;
9236
9237   gcc_assert (producer && consumer);
9238   dest = ia64_single_set (producer);
9239   gcc_assert (dest);
9240   reg = SET_DEST (dest);
9241   gcc_assert (reg);
9242   if (GET_CODE (reg) == SUBREG)
9243     reg = SUBREG_REG (reg);
9244   gcc_assert (GET_CODE (reg) == REG);
9245   
9246   src = ia64_single_set (consumer);
9247   gcc_assert (src);
9248   mem = SET_SRC (src);
9249   gcc_assert (mem);
9250  
9251   if (GET_CODE (mem) == UNSPEC && XVECLEN (mem, 0) > 0)
9252     mem = XVECEXP (mem, 0, 0);
9253   else if (GET_CODE (mem) == IF_THEN_ELSE)
9254     /* ??? Is this bypass necessary for ld.c?  */
9255     {
9256       gcc_assert (XINT (XEXP (XEXP (mem, 0), 0), 1) == UNSPEC_LDCCLR);
9257       mem = XEXP (mem, 1);
9258     }
9259      
9260   while (GET_CODE (mem) == SUBREG || GET_CODE (mem) == ZERO_EXTEND)
9261     mem = XEXP (mem, 0);
9262
9263   if (GET_CODE (mem) == UNSPEC)
9264     {
9265       int c = XINT (mem, 1);
9266
9267       gcc_assert (c == UNSPEC_LDA || c == UNSPEC_LDS || c == UNSPEC_LDS_A
9268                   || c == UNSPEC_LDSA);
9269       mem = XVECEXP (mem, 0, 0);
9270     }
9271
9272   /* Note that LO_SUM is used for GOT loads.  */
9273   gcc_assert (GET_CODE (mem) == LO_SUM || GET_CODE (mem) == MEM);
9274
9275   return reg_mentioned_p (reg, mem);
9276 }
9277
9278 /* The following function returns TRUE if INSN produces address for a
9279    load/store insn.  We will place such insns into M slot because it
9280    decreases its latency time.  */
9281
9282 int
9283 ia64_produce_address_p (rtx insn)
9284 {
9285   return insn->call;
9286 }
9287
9288 \f
9289 /* Emit pseudo-ops for the assembler to describe predicate relations.
9290    At present this assumes that we only consider predicate pairs to
9291    be mutex, and that the assembler can deduce proper values from
9292    straight-line code.  */
9293
9294 static void
9295 emit_predicate_relation_info (void)
9296 {
9297   basic_block bb;
9298
9299   FOR_EACH_BB_REVERSE (bb)
9300     {
9301       int r;
9302       rtx head = BB_HEAD (bb);
9303
9304       /* We only need such notes at code labels.  */
9305       if (GET_CODE (head) != CODE_LABEL)
9306         continue;
9307       if (NOTE_INSN_BASIC_BLOCK_P (NEXT_INSN (head)))
9308         head = NEXT_INSN (head);
9309
9310       /* Skip p0, which may be thought to be live due to (reg:DI p0)
9311          grabbing the entire block of predicate registers.  */
9312       for (r = PR_REG (2); r < PR_REG (64); r += 2)
9313         if (REGNO_REG_SET_P (df_get_live_in (bb), r))
9314           {
9315             rtx p = gen_rtx_REG (BImode, r);
9316             rtx n = emit_insn_after (gen_pred_rel_mutex (p), head);
9317             if (head == BB_END (bb))
9318               BB_END (bb) = n;
9319             head = n;
9320           }
9321     }
9322
9323   /* Look for conditional calls that do not return, and protect predicate
9324      relations around them.  Otherwise the assembler will assume the call
9325      returns, and complain about uses of call-clobbered predicates after
9326      the call.  */
9327   FOR_EACH_BB_REVERSE (bb)
9328     {
9329       rtx insn = BB_HEAD (bb);
9330
9331       while (1)
9332         {
9333           if (GET_CODE (insn) == CALL_INSN
9334               && GET_CODE (PATTERN (insn)) == COND_EXEC
9335               && find_reg_note (insn, REG_NORETURN, NULL_RTX))
9336             {
9337               rtx b = emit_insn_before (gen_safe_across_calls_all (), insn);
9338               rtx a = emit_insn_after (gen_safe_across_calls_normal (), insn);
9339               if (BB_HEAD (bb) == insn)
9340                 BB_HEAD (bb) = b;
9341               if (BB_END (bb) == insn)
9342                 BB_END (bb) = a;
9343             }
9344
9345           if (insn == BB_END (bb))
9346             break;
9347           insn = NEXT_INSN (insn);
9348         }
9349     }
9350 }
9351
9352 /* Perform machine dependent operations on the rtl chain INSNS.  */
9353
9354 static void
9355 ia64_reorg (void)
9356 {
9357   /* We are freeing block_for_insn in the toplev to keep compatibility
9358      with old MDEP_REORGS that are not CFG based.  Recompute it now.  */
9359   compute_bb_for_insn ();
9360
9361   /* If optimizing, we'll have split before scheduling.  */
9362   if (optimize == 0)
9363     split_all_insns ();
9364
9365   if (optimize && ia64_flag_schedule_insns2
9366       && dbg_cnt (ia64_sched2))
9367     {
9368       timevar_push (TV_SCHED2);
9369       ia64_final_schedule = 1;
9370
9371       initiate_bundle_states ();
9372       ia64_nop = make_insn_raw (gen_nop ());
9373       PREV_INSN (ia64_nop) = NEXT_INSN (ia64_nop) = NULL_RTX;
9374       recog_memoized (ia64_nop);
9375       clocks_length = get_max_uid () + 1;
9376       stops_p = XCNEWVEC (char, clocks_length);
9377
9378       if (ia64_tune == PROCESSOR_ITANIUM2)
9379         {
9380           pos_1 = get_cpu_unit_code ("2_1");
9381           pos_2 = get_cpu_unit_code ("2_2");
9382           pos_3 = get_cpu_unit_code ("2_3");
9383           pos_4 = get_cpu_unit_code ("2_4");
9384           pos_5 = get_cpu_unit_code ("2_5");
9385           pos_6 = get_cpu_unit_code ("2_6");
9386           _0mii_ = get_cpu_unit_code ("2b_0mii.");
9387           _0mmi_ = get_cpu_unit_code ("2b_0mmi.");
9388           _0mfi_ = get_cpu_unit_code ("2b_0mfi.");
9389           _0mmf_ = get_cpu_unit_code ("2b_0mmf.");
9390           _0bbb_ = get_cpu_unit_code ("2b_0bbb.");
9391           _0mbb_ = get_cpu_unit_code ("2b_0mbb.");
9392           _0mib_ = get_cpu_unit_code ("2b_0mib.");
9393           _0mmb_ = get_cpu_unit_code ("2b_0mmb.");
9394           _0mfb_ = get_cpu_unit_code ("2b_0mfb.");
9395           _0mlx_ = get_cpu_unit_code ("2b_0mlx.");
9396           _1mii_ = get_cpu_unit_code ("2b_1mii.");
9397           _1mmi_ = get_cpu_unit_code ("2b_1mmi.");
9398           _1mfi_ = get_cpu_unit_code ("2b_1mfi.");
9399           _1mmf_ = get_cpu_unit_code ("2b_1mmf.");
9400           _1bbb_ = get_cpu_unit_code ("2b_1bbb.");
9401           _1mbb_ = get_cpu_unit_code ("2b_1mbb.");
9402           _1mib_ = get_cpu_unit_code ("2b_1mib.");
9403           _1mmb_ = get_cpu_unit_code ("2b_1mmb.");
9404           _1mfb_ = get_cpu_unit_code ("2b_1mfb.");
9405           _1mlx_ = get_cpu_unit_code ("2b_1mlx.");
9406         }
9407       else
9408         {
9409           pos_1 = get_cpu_unit_code ("1_1");
9410           pos_2 = get_cpu_unit_code ("1_2");
9411           pos_3 = get_cpu_unit_code ("1_3");
9412           pos_4 = get_cpu_unit_code ("1_4");
9413           pos_5 = get_cpu_unit_code ("1_5");
9414           pos_6 = get_cpu_unit_code ("1_6");
9415           _0mii_ = get_cpu_unit_code ("1b_0mii.");
9416           _0mmi_ = get_cpu_unit_code ("1b_0mmi.");
9417           _0mfi_ = get_cpu_unit_code ("1b_0mfi.");
9418           _0mmf_ = get_cpu_unit_code ("1b_0mmf.");
9419           _0bbb_ = get_cpu_unit_code ("1b_0bbb.");
9420           _0mbb_ = get_cpu_unit_code ("1b_0mbb.");
9421           _0mib_ = get_cpu_unit_code ("1b_0mib.");
9422           _0mmb_ = get_cpu_unit_code ("1b_0mmb.");
9423           _0mfb_ = get_cpu_unit_code ("1b_0mfb.");
9424           _0mlx_ = get_cpu_unit_code ("1b_0mlx.");
9425           _1mii_ = get_cpu_unit_code ("1b_1mii.");
9426           _1mmi_ = get_cpu_unit_code ("1b_1mmi.");
9427           _1mfi_ = get_cpu_unit_code ("1b_1mfi.");
9428           _1mmf_ = get_cpu_unit_code ("1b_1mmf.");
9429           _1bbb_ = get_cpu_unit_code ("1b_1bbb.");
9430           _1mbb_ = get_cpu_unit_code ("1b_1mbb.");
9431           _1mib_ = get_cpu_unit_code ("1b_1mib.");
9432           _1mmb_ = get_cpu_unit_code ("1b_1mmb.");
9433           _1mfb_ = get_cpu_unit_code ("1b_1mfb.");
9434           _1mlx_ = get_cpu_unit_code ("1b_1mlx.");
9435         }
9436
9437       if (flag_selective_scheduling2
9438           && !maybe_skip_selective_scheduling ())
9439         run_selective_scheduling ();
9440       else
9441         schedule_ebbs ();
9442
9443       /* Redo alignment computation, as it might gone wrong.  */
9444       compute_alignments ();
9445
9446       /* We cannot reuse this one because it has been corrupted by the
9447          evil glat.  */
9448       finish_bundle_states ();
9449       free (stops_p);
9450       stops_p = NULL;
9451       emit_insn_group_barriers (dump_file);
9452
9453       ia64_final_schedule = 0;
9454       timevar_pop (TV_SCHED2);
9455     }
9456   else
9457     emit_all_insn_group_barriers (dump_file);
9458
9459   df_analyze ();
9460  
9461   /* A call must not be the last instruction in a function, so that the
9462      return address is still within the function, so that unwinding works
9463      properly.  Note that IA-64 differs from dwarf2 on this point.  */
9464   if (ia64_except_unwind_info () == UI_TARGET)
9465     {
9466       rtx insn;
9467       int saw_stop = 0;
9468
9469       insn = get_last_insn ();
9470       if (! INSN_P (insn))
9471         insn = prev_active_insn (insn);
9472       if (insn)
9473         {
9474           /* Skip over insns that expand to nothing.  */
9475           while (GET_CODE (insn) == INSN
9476                  && get_attr_empty (insn) == EMPTY_YES)
9477             {
9478               if (GET_CODE (PATTERN (insn)) == UNSPEC_VOLATILE
9479                   && XINT (PATTERN (insn), 1) == UNSPECV_INSN_GROUP_BARRIER)
9480                 saw_stop = 1;
9481               insn = prev_active_insn (insn);
9482             }
9483           if (GET_CODE (insn) == CALL_INSN)
9484             {
9485               if (! saw_stop)
9486                 emit_insn (gen_insn_group_barrier (GEN_INT (3)));
9487               emit_insn (gen_break_f ());
9488               emit_insn (gen_insn_group_barrier (GEN_INT (3)));
9489             }
9490         }
9491     }
9492
9493   emit_predicate_relation_info ();
9494
9495   if (ia64_flag_var_tracking)
9496     {
9497       timevar_push (TV_VAR_TRACKING);
9498       variable_tracking_main ();
9499       timevar_pop (TV_VAR_TRACKING);
9500     }
9501   df_finish_pass (false);
9502 }
9503 \f
9504 /* Return true if REGNO is used by the epilogue.  */
9505
9506 int
9507 ia64_epilogue_uses (int regno)
9508 {
9509   switch (regno)
9510     {
9511     case R_GR (1):
9512       /* With a call to a function in another module, we will write a new
9513          value to "gp".  After returning from such a call, we need to make
9514          sure the function restores the original gp-value, even if the
9515          function itself does not use the gp anymore.  */
9516       return !(TARGET_AUTO_PIC || TARGET_NO_PIC);
9517
9518     case IN_REG (0): case IN_REG (1): case IN_REG (2): case IN_REG (3):
9519     case IN_REG (4): case IN_REG (5): case IN_REG (6): case IN_REG (7):
9520       /* For functions defined with the syscall_linkage attribute, all
9521          input registers are marked as live at all function exits.  This
9522          prevents the register allocator from using the input registers,
9523          which in turn makes it possible to restart a system call after
9524          an interrupt without having to save/restore the input registers.
9525          This also prevents kernel data from leaking to application code.  */
9526       return lookup_attribute ("syscall_linkage",
9527            TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))) != NULL;
9528
9529     case R_BR (0):
9530       /* Conditional return patterns can't represent the use of `b0' as
9531          the return address, so we force the value live this way.  */
9532       return 1;
9533
9534     case AR_PFS_REGNUM:
9535       /* Likewise for ar.pfs, which is used by br.ret.  */
9536       return 1;
9537
9538     default:
9539       return 0;
9540     }
9541 }
9542
9543 /* Return true if REGNO is used by the frame unwinder.  */
9544
9545 int
9546 ia64_eh_uses (int regno)
9547 {
9548   unsigned int r;
9549
9550   if (! reload_completed)
9551     return 0;
9552
9553   if (regno == 0)
9554     return 0;
9555
9556   for (r = reg_save_b0; r <= reg_save_ar_lc; r++)
9557     if (regno == current_frame_info.r[r]
9558        || regno == emitted_frame_related_regs[r])
9559       return 1;
9560
9561   return 0;
9562 }
9563 \f
9564 /* Return true if this goes in small data/bss.  */
9565
9566 /* ??? We could also support own long data here.  Generating movl/add/ld8
9567    instead of addl,ld8/ld8.  This makes the code bigger, but should make the
9568    code faster because there is one less load.  This also includes incomplete
9569    types which can't go in sdata/sbss.  */
9570
9571 static bool
9572 ia64_in_small_data_p (const_tree exp)
9573 {
9574   if (TARGET_NO_SDATA)
9575     return false;
9576
9577   /* We want to merge strings, so we never consider them small data.  */
9578   if (TREE_CODE (exp) == STRING_CST)
9579     return false;
9580
9581   /* Functions are never small data.  */
9582   if (TREE_CODE (exp) == FUNCTION_DECL)
9583     return false;
9584
9585   if (TREE_CODE (exp) == VAR_DECL && DECL_SECTION_NAME (exp))
9586     {
9587       const char *section = TREE_STRING_POINTER (DECL_SECTION_NAME (exp));
9588
9589       if (strcmp (section, ".sdata") == 0
9590           || strncmp (section, ".sdata.", 7) == 0
9591           || strncmp (section, ".gnu.linkonce.s.", 16) == 0
9592           || strcmp (section, ".sbss") == 0
9593           || strncmp (section, ".sbss.", 6) == 0
9594           || strncmp (section, ".gnu.linkonce.sb.", 17) == 0)
9595         return true;
9596     }
9597   else
9598     {
9599       HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (exp));
9600
9601       /* If this is an incomplete type with size 0, then we can't put it
9602          in sdata because it might be too big when completed.  */
9603       if (size > 0 && size <= ia64_section_threshold)
9604         return true;
9605     }
9606
9607   return false;
9608 }
9609 \f
9610 /* Output assembly directives for prologue regions.  */
9611
9612 /* The current basic block number.  */
9613
9614 static bool last_block;
9615
9616 /* True if we need a copy_state command at the start of the next block.  */
9617
9618 static bool need_copy_state;
9619
9620 #ifndef MAX_ARTIFICIAL_LABEL_BYTES
9621 # define MAX_ARTIFICIAL_LABEL_BYTES 30
9622 #endif
9623
9624 /* Emit a debugging label after a call-frame-related insn.  We'd
9625    rather output the label right away, but we'd have to output it
9626    after, not before, the instruction, and the instruction has not
9627    been output yet.  So we emit the label after the insn, delete it to
9628    avoid introducing basic blocks, and mark it as preserved, such that
9629    it is still output, given that it is referenced in debug info.  */
9630
9631 static const char *
9632 ia64_emit_deleted_label_after_insn (rtx insn)
9633 {
9634   char label[MAX_ARTIFICIAL_LABEL_BYTES];
9635   rtx lb = gen_label_rtx ();
9636   rtx label_insn = emit_label_after (lb, insn);
9637
9638   LABEL_PRESERVE_P (lb) = 1;
9639
9640   delete_insn (label_insn);
9641
9642   ASM_GENERATE_INTERNAL_LABEL (label, "L", CODE_LABEL_NUMBER (label_insn));
9643
9644   return xstrdup (label);
9645 }
9646
9647 /* Define the CFA after INSN with the steady-state definition.  */
9648
9649 static void
9650 ia64_dwarf2out_def_steady_cfa (rtx insn, bool frame)
9651 {
9652   rtx fp = frame_pointer_needed
9653     ? hard_frame_pointer_rtx
9654     : stack_pointer_rtx;
9655   const char *label = ia64_emit_deleted_label_after_insn (insn);
9656
9657   if (!frame)
9658     return;
9659
9660   dwarf2out_def_cfa
9661     (label, REGNO (fp),
9662      ia64_initial_elimination_offset
9663      (REGNO (arg_pointer_rtx), REGNO (fp))
9664      + ARG_POINTER_CFA_OFFSET (current_function_decl));
9665 }
9666
9667 /* All we need to do here is avoid a crash in the generic dwarf2
9668    processing.  The real CFA definition is set up above.  */
9669
9670 static void
9671 ia64_dwarf_handle_frame_unspec (const char * ARG_UNUSED (label),
9672                                 rtx ARG_UNUSED (pattern),
9673                                 int index)
9674 {
9675   gcc_assert (index == UNSPECV_ALLOC);
9676 }
9677
9678 /* The generic dwarf2 frame debug info generator does not define a
9679    separate region for the very end of the epilogue, so refrain from
9680    doing so in the IA64-specific code as well.  */
9681
9682 #define IA64_CHANGE_CFA_IN_EPILOGUE 0
9683
9684 /* The function emits unwind directives for the start of an epilogue.  */
9685
9686 static void
9687 process_epilogue (FILE *asm_out_file, rtx insn, bool unwind, bool frame)
9688 {
9689   /* If this isn't the last block of the function, then we need to label the
9690      current state, and copy it back in at the start of the next block.  */
9691
9692   if (!last_block)
9693     {
9694       if (unwind)
9695         fprintf (asm_out_file, "\t.label_state %d\n",
9696                  ++cfun->machine->state_num);
9697       need_copy_state = true;
9698     }
9699
9700   if (unwind)
9701     fprintf (asm_out_file, "\t.restore sp\n");
9702   if (IA64_CHANGE_CFA_IN_EPILOGUE && frame)
9703     dwarf2out_def_cfa (ia64_emit_deleted_label_after_insn (insn),
9704                        STACK_POINTER_REGNUM, INCOMING_FRAME_SP_OFFSET);
9705 }
9706
9707 /* This function processes a SET pattern for REG_CFA_ADJUST_CFA.  */
9708
9709 static void
9710 process_cfa_adjust_cfa (FILE *asm_out_file, rtx pat, rtx insn,
9711                         bool unwind, bool frame)
9712 {
9713   rtx dest = SET_DEST (pat);
9714   rtx src = SET_SRC (pat);
9715
9716   if (dest == stack_pointer_rtx)
9717     {
9718       if (GET_CODE (src) == PLUS)
9719         {
9720           rtx op0 = XEXP (src, 0);
9721           rtx op1 = XEXP (src, 1);
9722           
9723           gcc_assert (op0 == dest && GET_CODE (op1) == CONST_INT);
9724           
9725           if (INTVAL (op1) < 0)
9726             {
9727               gcc_assert (!frame_pointer_needed);
9728               if (unwind)
9729                 fprintf (asm_out_file,
9730                          "\t.fframe "HOST_WIDE_INT_PRINT_DEC"\n",
9731                          -INTVAL (op1));
9732               ia64_dwarf2out_def_steady_cfa (insn, frame);
9733             }
9734           else
9735             process_epilogue (asm_out_file, insn, unwind, frame);
9736         }
9737       else
9738         {
9739           gcc_assert (src == hard_frame_pointer_rtx);
9740           process_epilogue (asm_out_file, insn, unwind, frame);
9741         }
9742     }
9743   else if (dest == hard_frame_pointer_rtx)
9744     {
9745       gcc_assert (src == stack_pointer_rtx);
9746       gcc_assert (frame_pointer_needed);
9747
9748       if (unwind)
9749         fprintf (asm_out_file, "\t.vframe r%d\n",
9750                  ia64_dbx_register_number (REGNO (dest)));
9751       ia64_dwarf2out_def_steady_cfa (insn, frame);
9752     }
9753   else
9754     gcc_unreachable ();
9755 }
9756
9757 /* This function processes a SET pattern for REG_CFA_REGISTER.  */
9758
9759 static void
9760 process_cfa_register (FILE *asm_out_file, rtx pat, bool unwind)
9761 {
9762   rtx dest = SET_DEST (pat);
9763   rtx src = SET_SRC (pat);
9764
9765   int dest_regno = REGNO (dest);
9766   int src_regno = REGNO (src);
9767
9768   switch (src_regno)
9769     {
9770     case BR_REG (0):
9771       /* Saving return address pointer.  */
9772       gcc_assert (dest_regno == current_frame_info.r[reg_save_b0]);
9773       if (unwind)
9774         fprintf (asm_out_file, "\t.save rp, r%d\n",
9775                  ia64_dbx_register_number (dest_regno));
9776       break;
9777
9778     case PR_REG (0):
9779       gcc_assert (dest_regno == current_frame_info.r[reg_save_pr]);
9780       if (unwind)
9781         fprintf (asm_out_file, "\t.save pr, r%d\n",
9782                  ia64_dbx_register_number (dest_regno));
9783       break;
9784
9785     case AR_UNAT_REGNUM:
9786       gcc_assert (dest_regno == current_frame_info.r[reg_save_ar_unat]);
9787       if (unwind)
9788         fprintf (asm_out_file, "\t.save ar.unat, r%d\n",
9789                  ia64_dbx_register_number (dest_regno));
9790       break;
9791
9792     case AR_LC_REGNUM:
9793       gcc_assert (dest_regno == current_frame_info.r[reg_save_ar_lc]);
9794       if (unwind)
9795         fprintf (asm_out_file, "\t.save ar.lc, r%d\n",
9796                  ia64_dbx_register_number (dest_regno));
9797       break;
9798
9799     default:
9800       /* Everything else should indicate being stored to memory.  */
9801       gcc_unreachable ();
9802     }
9803 }
9804
9805 /* This function processes a SET pattern for REG_CFA_OFFSET.  */
9806
9807 static void
9808 process_cfa_offset (FILE *asm_out_file, rtx pat, bool unwind)
9809 {
9810   rtx dest = SET_DEST (pat);
9811   rtx src = SET_SRC (pat);
9812   int src_regno = REGNO (src);
9813   const char *saveop;
9814   HOST_WIDE_INT off;
9815   rtx base;
9816
9817   gcc_assert (MEM_P (dest));
9818   if (GET_CODE (XEXP (dest, 0)) == REG)
9819     {
9820       base = XEXP (dest, 0);
9821       off = 0;
9822     }
9823   else
9824     {
9825       gcc_assert (GET_CODE (XEXP (dest, 0)) == PLUS
9826                   && GET_CODE (XEXP (XEXP (dest, 0), 1)) == CONST_INT);
9827       base = XEXP (XEXP (dest, 0), 0);
9828       off = INTVAL (XEXP (XEXP (dest, 0), 1));
9829     }
9830
9831   if (base == hard_frame_pointer_rtx)
9832     {
9833       saveop = ".savepsp";
9834       off = - off;
9835     }
9836   else
9837     {
9838       gcc_assert (base == stack_pointer_rtx);
9839       saveop = ".savesp";
9840     }
9841
9842   src_regno = REGNO (src);
9843   switch (src_regno)
9844     {
9845     case BR_REG (0):
9846       gcc_assert (!current_frame_info.r[reg_save_b0]);
9847       if (unwind)
9848         fprintf (asm_out_file, "\t%s rp, " HOST_WIDE_INT_PRINT_DEC "\n",
9849                  saveop, off);
9850       break;
9851
9852     case PR_REG (0):
9853       gcc_assert (!current_frame_info.r[reg_save_pr]);
9854       if (unwind)
9855         fprintf (asm_out_file, "\t%s pr, " HOST_WIDE_INT_PRINT_DEC "\n",
9856                  saveop, off);
9857       break;
9858
9859     case AR_LC_REGNUM:
9860       gcc_assert (!current_frame_info.r[reg_save_ar_lc]);
9861       if (unwind)
9862         fprintf (asm_out_file, "\t%s ar.lc, " HOST_WIDE_INT_PRINT_DEC "\n",
9863                  saveop, off);
9864       break;
9865
9866     case AR_PFS_REGNUM:
9867       gcc_assert (!current_frame_info.r[reg_save_ar_pfs]);
9868       if (unwind)
9869         fprintf (asm_out_file, "\t%s ar.pfs, " HOST_WIDE_INT_PRINT_DEC "\n",
9870                  saveop, off);
9871       break;
9872
9873     case AR_UNAT_REGNUM:
9874       gcc_assert (!current_frame_info.r[reg_save_ar_unat]);
9875       if (unwind)
9876         fprintf (asm_out_file, "\t%s ar.unat, " HOST_WIDE_INT_PRINT_DEC "\n",
9877                  saveop, off);
9878       break;
9879
9880     case GR_REG (4):
9881     case GR_REG (5):
9882     case GR_REG (6):
9883     case GR_REG (7):
9884       if (unwind)
9885         fprintf (asm_out_file, "\t.save.g 0x%x\n",
9886                  1 << (src_regno - GR_REG (4)));
9887       break;
9888
9889     case BR_REG (1):
9890     case BR_REG (2):
9891     case BR_REG (3):
9892     case BR_REG (4):
9893     case BR_REG (5):
9894       if (unwind)
9895         fprintf (asm_out_file, "\t.save.b 0x%x\n",
9896                  1 << (src_regno - BR_REG (1)));
9897       break;
9898
9899     case FR_REG (2):
9900     case FR_REG (3):
9901     case FR_REG (4):
9902     case FR_REG (5):
9903       if (unwind)
9904         fprintf (asm_out_file, "\t.save.f 0x%x\n",
9905                  1 << (src_regno - FR_REG (2)));
9906       break;
9907
9908     case FR_REG (16): case FR_REG (17): case FR_REG (18): case FR_REG (19):
9909     case FR_REG (20): case FR_REG (21): case FR_REG (22): case FR_REG (23):
9910     case FR_REG (24): case FR_REG (25): case FR_REG (26): case FR_REG (27):
9911     case FR_REG (28): case FR_REG (29): case FR_REG (30): case FR_REG (31):
9912       if (unwind)
9913         fprintf (asm_out_file, "\t.save.gf 0x0, 0x%x\n",
9914                  1 << (src_regno - FR_REG (12)));
9915       break;
9916
9917     default:
9918       /* ??? For some reason we mark other general registers, even those
9919          we can't represent in the unwind info.  Ignore them.  */
9920       break;
9921     }
9922 }
9923
9924 /* This function looks at a single insn and emits any directives
9925    required to unwind this insn.  */
9926
9927 static void
9928 ia64_asm_unwind_emit (FILE *asm_out_file, rtx insn)
9929 {
9930   bool unwind = ia64_except_unwind_info () == UI_TARGET;
9931   bool frame = dwarf2out_do_frame ();
9932   rtx note, pat;
9933   bool handled_one;
9934
9935   if (!unwind && !frame)
9936     return;
9937
9938   if (NOTE_INSN_BASIC_BLOCK_P (insn))
9939     {
9940       last_block = NOTE_BASIC_BLOCK (insn)->next_bb == EXIT_BLOCK_PTR;
9941
9942       /* Restore unwind state from immediately before the epilogue.  */
9943       if (need_copy_state)
9944         {
9945           if (unwind)
9946             {
9947               fprintf (asm_out_file, "\t.body\n");
9948               fprintf (asm_out_file, "\t.copy_state %d\n",
9949                        cfun->machine->state_num);
9950             }
9951           if (IA64_CHANGE_CFA_IN_EPILOGUE)
9952             ia64_dwarf2out_def_steady_cfa (insn, frame);
9953           need_copy_state = false;
9954         }
9955     }
9956
9957   if (GET_CODE (insn) == NOTE || ! RTX_FRAME_RELATED_P (insn))
9958     return;
9959
9960   /* Look for the ALLOC insn.  */
9961   if (INSN_CODE (insn) == CODE_FOR_alloc)
9962     {
9963       rtx dest = SET_DEST (XVECEXP (PATTERN (insn), 0, 0));
9964       int dest_regno = REGNO (dest);
9965
9966       /* If this is the final destination for ar.pfs, then this must
9967          be the alloc in the prologue.  */
9968       if (dest_regno == current_frame_info.r[reg_save_ar_pfs])
9969         {
9970           if (unwind)
9971             fprintf (asm_out_file, "\t.save ar.pfs, r%d\n",
9972                      ia64_dbx_register_number (dest_regno));
9973         }
9974       else
9975         {
9976           /* This must be an alloc before a sibcall.  We must drop the
9977              old frame info.  The easiest way to drop the old frame
9978              info is to ensure we had a ".restore sp" directive
9979              followed by a new prologue.  If the procedure doesn't
9980              have a memory-stack frame, we'll issue a dummy ".restore
9981              sp" now.  */
9982           if (current_frame_info.total_size == 0 && !frame_pointer_needed)
9983             /* if haven't done process_epilogue() yet, do it now */
9984             process_epilogue (asm_out_file, insn, unwind, frame);
9985           if (unwind)
9986             fprintf (asm_out_file, "\t.prologue\n");
9987         }
9988       return;
9989     }
9990
9991   handled_one = false;
9992   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
9993     switch (REG_NOTE_KIND (note))
9994       {
9995       case REG_CFA_ADJUST_CFA:
9996         pat = XEXP (note, 0);
9997         if (pat == NULL)
9998           pat = PATTERN (insn);
9999         process_cfa_adjust_cfa (asm_out_file, pat, insn, unwind, frame);
10000         handled_one = true;
10001         break;
10002
10003       case REG_CFA_OFFSET:
10004         pat = XEXP (note, 0);
10005         if (pat == NULL)
10006           pat = PATTERN (insn);
10007         process_cfa_offset (asm_out_file, pat, unwind);
10008         handled_one = true;
10009         break;
10010
10011       case REG_CFA_REGISTER:
10012         pat = XEXP (note, 0);
10013         if (pat == NULL)
10014           pat = PATTERN (insn);
10015         process_cfa_register (asm_out_file, pat, unwind);
10016         handled_one = true;
10017         break;
10018
10019       case REG_FRAME_RELATED_EXPR:
10020       case REG_CFA_DEF_CFA:
10021       case REG_CFA_EXPRESSION:
10022       case REG_CFA_RESTORE:
10023       case REG_CFA_SET_VDRAP:
10024         /* Not used in the ia64 port.  */
10025         gcc_unreachable ();
10026
10027       default:
10028         /* Not a frame-related note.  */
10029         break;
10030       }
10031
10032   /* All REG_FRAME_RELATED_P insns, besides ALLOC, are marked with the
10033      explicit action to take.  No guessing required.  */
10034   gcc_assert (handled_one);
10035 }
10036
10037 /* Implement TARGET_ASM_EMIT_EXCEPT_PERSONALITY.  */
10038
10039 static void
10040 ia64_asm_emit_except_personality (rtx personality)
10041 {
10042   fputs ("\t.personality\t", asm_out_file);
10043   output_addr_const (asm_out_file, personality);
10044   fputc ('\n', asm_out_file);
10045 }
10046
10047 /* Implement TARGET_ASM_INITIALIZE_SECTIONS.  */
10048
10049 static void
10050 ia64_asm_init_sections (void)
10051 {
10052   exception_section = get_unnamed_section (0, output_section_asm_op,
10053                                            "\t.handlerdata");
10054 }
10055
10056 /* Implement TARGET_DEBUG_UNWIND_INFO.  */
10057
10058 static enum unwind_info_type
10059 ia64_debug_unwind_info (void)
10060 {
10061   return UI_TARGET;
10062 }
10063
10064 /* Implement TARGET_EXCEPT_UNWIND_INFO.  */
10065
10066 static enum unwind_info_type
10067 ia64_except_unwind_info (void)
10068 {
10069   /* Honor the --enable-sjlj-exceptions configure switch.  */
10070 #ifdef CONFIG_UNWIND_EXCEPTIONS
10071   if (CONFIG_UNWIND_EXCEPTIONS)
10072     return UI_SJLJ;
10073 #endif
10074
10075   /* For simplicity elsewhere in this file, indicate that all unwind
10076      info is disabled if we're not emitting unwind tables.  */
10077   if (!flag_exceptions && !flag_unwind_tables)
10078     return UI_NONE;
10079
10080   return UI_TARGET;
10081 }
10082 \f
10083 enum ia64_builtins
10084 {
10085   IA64_BUILTIN_BSP,
10086   IA64_BUILTIN_COPYSIGNQ,
10087   IA64_BUILTIN_FABSQ,
10088   IA64_BUILTIN_FLUSHRS,
10089   IA64_BUILTIN_INFQ,
10090   IA64_BUILTIN_HUGE_VALQ,
10091   IA64_BUILTIN_max
10092 };
10093
10094 static GTY(()) tree ia64_builtins[(int) IA64_BUILTIN_max];
10095
10096 void
10097 ia64_init_builtins (void)
10098 {
10099   tree fpreg_type;
10100   tree float80_type;
10101   tree decl;
10102
10103   /* The __fpreg type.  */
10104   fpreg_type = make_node (REAL_TYPE);
10105   TYPE_PRECISION (fpreg_type) = 82;
10106   layout_type (fpreg_type);
10107   (*lang_hooks.types.register_builtin_type) (fpreg_type, "__fpreg");
10108
10109   /* The __float80 type.  */
10110   float80_type = make_node (REAL_TYPE);
10111   TYPE_PRECISION (float80_type) = 80;
10112   layout_type (float80_type);
10113   (*lang_hooks.types.register_builtin_type) (float80_type, "__float80");
10114
10115   /* The __float128 type.  */
10116   if (!TARGET_HPUX)
10117     {
10118       tree ftype;
10119       tree float128_type = make_node (REAL_TYPE);
10120
10121       TYPE_PRECISION (float128_type) = 128;
10122       layout_type (float128_type);
10123       (*lang_hooks.types.register_builtin_type) (float128_type, "__float128");
10124
10125       /* TFmode support builtins.  */
10126       ftype = build_function_type (float128_type, void_list_node);
10127       decl = add_builtin_function ("__builtin_infq", ftype,
10128                                    IA64_BUILTIN_INFQ, BUILT_IN_MD,
10129                                    NULL, NULL_TREE);
10130       ia64_builtins[IA64_BUILTIN_INFQ] = decl;
10131
10132       decl = add_builtin_function ("__builtin_huge_valq", ftype,
10133                                    IA64_BUILTIN_HUGE_VALQ, BUILT_IN_MD,
10134                                    NULL, NULL_TREE);
10135       ia64_builtins[IA64_BUILTIN_HUGE_VALQ] = decl;
10136
10137       ftype = build_function_type_list (float128_type,
10138                                         float128_type,
10139                                         NULL_TREE);
10140       decl = add_builtin_function ("__builtin_fabsq", ftype,
10141                                    IA64_BUILTIN_FABSQ, BUILT_IN_MD,
10142                                    "__fabstf2", NULL_TREE);
10143       TREE_READONLY (decl) = 1;
10144       ia64_builtins[IA64_BUILTIN_FABSQ] = decl;
10145
10146       ftype = build_function_type_list (float128_type,
10147                                         float128_type,
10148                                         float128_type,
10149                                         NULL_TREE);
10150       decl = add_builtin_function ("__builtin_copysignq", ftype,
10151                                    IA64_BUILTIN_COPYSIGNQ, BUILT_IN_MD,
10152                                    "__copysigntf3", NULL_TREE);
10153       TREE_READONLY (decl) = 1;
10154       ia64_builtins[IA64_BUILTIN_COPYSIGNQ] = decl;
10155     }
10156   else
10157     /* Under HPUX, this is a synonym for "long double".  */
10158     (*lang_hooks.types.register_builtin_type) (long_double_type_node,
10159                                                "__float128");
10160
10161   /* Fwrite on VMS is non-standard.  */
10162   if (TARGET_ABI_OPEN_VMS)
10163     {
10164       implicit_built_in_decls[(int) BUILT_IN_FWRITE] = NULL_TREE;
10165       implicit_built_in_decls[(int) BUILT_IN_FWRITE_UNLOCKED] = NULL_TREE;
10166     }
10167
10168 #define def_builtin(name, type, code)                                   \
10169   add_builtin_function ((name), (type), (code), BUILT_IN_MD,    \
10170                        NULL, NULL_TREE)
10171
10172   decl = def_builtin ("__builtin_ia64_bsp",
10173                build_function_type (ptr_type_node, void_list_node),
10174                IA64_BUILTIN_BSP);
10175   ia64_builtins[IA64_BUILTIN_BSP] = decl;
10176
10177   decl = def_builtin ("__builtin_ia64_flushrs",
10178                build_function_type (void_type_node, void_list_node),
10179                IA64_BUILTIN_FLUSHRS);
10180   ia64_builtins[IA64_BUILTIN_FLUSHRS] = decl;
10181
10182 #undef def_builtin
10183
10184   if (TARGET_HPUX)
10185     {
10186       if (built_in_decls [BUILT_IN_FINITE])
10187         set_user_assembler_name (built_in_decls [BUILT_IN_FINITE],
10188           "_Isfinite");
10189       if (built_in_decls [BUILT_IN_FINITEF])
10190         set_user_assembler_name (built_in_decls [BUILT_IN_FINITEF],
10191           "_Isfinitef");
10192       if (built_in_decls [BUILT_IN_FINITEL])
10193         set_user_assembler_name (built_in_decls [BUILT_IN_FINITEL],
10194           "_Isfinitef128");
10195     }
10196 }
10197
10198 rtx
10199 ia64_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
10200                      enum machine_mode mode ATTRIBUTE_UNUSED,
10201                      int ignore ATTRIBUTE_UNUSED)
10202 {
10203   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
10204   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
10205
10206   switch (fcode)
10207     {
10208     case IA64_BUILTIN_BSP:
10209       if (! target || ! register_operand (target, DImode))
10210         target = gen_reg_rtx (DImode);
10211       emit_insn (gen_bsp_value (target));
10212 #ifdef POINTERS_EXTEND_UNSIGNED
10213       target = convert_memory_address (ptr_mode, target);
10214 #endif
10215       return target;
10216
10217     case IA64_BUILTIN_FLUSHRS:
10218       emit_insn (gen_flushrs ());
10219       return const0_rtx;
10220
10221     case IA64_BUILTIN_INFQ:
10222     case IA64_BUILTIN_HUGE_VALQ:
10223       {
10224         REAL_VALUE_TYPE inf;
10225         rtx tmp;
10226
10227         real_inf (&inf);
10228         tmp = CONST_DOUBLE_FROM_REAL_VALUE (inf, mode);
10229
10230         tmp = validize_mem (force_const_mem (mode, tmp));
10231
10232         if (target == 0)
10233           target = gen_reg_rtx (mode);
10234
10235         emit_move_insn (target, tmp);
10236         return target;
10237       }
10238
10239     case IA64_BUILTIN_FABSQ:
10240     case IA64_BUILTIN_COPYSIGNQ:
10241       return expand_call (exp, target, ignore);
10242
10243     default:
10244       gcc_unreachable ();
10245     }
10246
10247   return NULL_RTX;
10248 }
10249
10250 /* Return the ia64 builtin for CODE.  */
10251
10252 static tree
10253 ia64_builtin_decl (unsigned code, bool initialize_p ATTRIBUTE_UNUSED)
10254 {
10255   if (code >= IA64_BUILTIN_max)
10256     return error_mark_node;
10257
10258   return ia64_builtins[code];
10259 }
10260
10261 /* For the HP-UX IA64 aggregate parameters are passed stored in the
10262    most significant bits of the stack slot.  */
10263
10264 enum direction
10265 ia64_hpux_function_arg_padding (enum machine_mode mode, const_tree type)
10266 {
10267    /* Exception to normal case for structures/unions/etc.  */
10268
10269    if (type && AGGREGATE_TYPE_P (type)
10270        && int_size_in_bytes (type) < UNITS_PER_WORD)
10271      return upward;
10272
10273    /* Fall back to the default.  */
10274    return DEFAULT_FUNCTION_ARG_PADDING (mode, type);
10275 }
10276
10277 /* Emit text to declare externally defined variables and functions, because
10278    the Intel assembler does not support undefined externals.  */
10279
10280 void
10281 ia64_asm_output_external (FILE *file, tree decl, const char *name)
10282 {
10283   /* We output the name if and only if TREE_SYMBOL_REFERENCED is
10284      set in order to avoid putting out names that are never really
10285      used. */
10286   if (TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
10287     {
10288       /* maybe_assemble_visibility will return 1 if the assembler
10289          visibility directive is output.  */
10290       int need_visibility = ((*targetm.binds_local_p) (decl)
10291                              && maybe_assemble_visibility (decl));
10292
10293 #ifdef DO_CRTL_NAMES
10294       DO_CRTL_NAMES;
10295 #endif
10296
10297       /* GNU as does not need anything here, but the HP linker does
10298          need something for external functions.  */
10299       if ((TARGET_HPUX_LD || !TARGET_GNU_AS)
10300           && TREE_CODE (decl) == FUNCTION_DECL)
10301           (*targetm.asm_out.globalize_decl_name) (file, decl);
10302       else if (need_visibility && !TARGET_GNU_AS)
10303         (*targetm.asm_out.globalize_label) (file, name);
10304     }
10305 }
10306
10307 /* Set SImode div/mod functions, init_integral_libfuncs only initializes
10308    modes of word_mode and larger.  Rename the TFmode libfuncs using the
10309    HPUX conventions. __divtf3 is used for XFmode. We need to keep it for
10310    backward compatibility. */
10311
10312 static void
10313 ia64_init_libfuncs (void)
10314 {
10315   set_optab_libfunc (sdiv_optab, SImode, "__divsi3");
10316   set_optab_libfunc (udiv_optab, SImode, "__udivsi3");
10317   set_optab_libfunc (smod_optab, SImode, "__modsi3");
10318   set_optab_libfunc (umod_optab, SImode, "__umodsi3");
10319
10320   set_optab_libfunc (add_optab, TFmode, "_U_Qfadd");
10321   set_optab_libfunc (sub_optab, TFmode, "_U_Qfsub");
10322   set_optab_libfunc (smul_optab, TFmode, "_U_Qfmpy");
10323   set_optab_libfunc (sdiv_optab, TFmode, "_U_Qfdiv");
10324   set_optab_libfunc (neg_optab, TFmode, "_U_Qfneg");
10325
10326   set_conv_libfunc (sext_optab, TFmode, SFmode, "_U_Qfcnvff_sgl_to_quad");
10327   set_conv_libfunc (sext_optab, TFmode, DFmode, "_U_Qfcnvff_dbl_to_quad");
10328   set_conv_libfunc (sext_optab, TFmode, XFmode, "_U_Qfcnvff_f80_to_quad");
10329   set_conv_libfunc (trunc_optab, SFmode, TFmode, "_U_Qfcnvff_quad_to_sgl");
10330   set_conv_libfunc (trunc_optab, DFmode, TFmode, "_U_Qfcnvff_quad_to_dbl");
10331   set_conv_libfunc (trunc_optab, XFmode, TFmode, "_U_Qfcnvff_quad_to_f80");
10332
10333   set_conv_libfunc (sfix_optab, SImode, TFmode, "_U_Qfcnvfxt_quad_to_sgl");
10334   set_conv_libfunc (sfix_optab, DImode, TFmode, "_U_Qfcnvfxt_quad_to_dbl");
10335   set_conv_libfunc (sfix_optab, TImode, TFmode, "_U_Qfcnvfxt_quad_to_quad");
10336   set_conv_libfunc (ufix_optab, SImode, TFmode, "_U_Qfcnvfxut_quad_to_sgl");
10337   set_conv_libfunc (ufix_optab, DImode, TFmode, "_U_Qfcnvfxut_quad_to_dbl");
10338
10339   set_conv_libfunc (sfloat_optab, TFmode, SImode, "_U_Qfcnvxf_sgl_to_quad");
10340   set_conv_libfunc (sfloat_optab, TFmode, DImode, "_U_Qfcnvxf_dbl_to_quad");
10341   set_conv_libfunc (sfloat_optab, TFmode, TImode, "_U_Qfcnvxf_quad_to_quad");
10342   /* HP-UX 11.23 libc does not have a function for unsigned
10343      SImode-to-TFmode conversion.  */
10344   set_conv_libfunc (ufloat_optab, TFmode, DImode, "_U_Qfcnvxuf_dbl_to_quad");
10345 }
10346
10347 /* Rename all the TFmode libfuncs using the HPUX conventions.  */
10348
10349 static void
10350 ia64_hpux_init_libfuncs (void)
10351 {
10352   ia64_init_libfuncs ();
10353
10354   /* The HP SI millicode division and mod functions expect DI arguments.
10355      By turning them off completely we avoid using both libgcc and the
10356      non-standard millicode routines and use the HP DI millicode routines
10357      instead.  */
10358
10359   set_optab_libfunc (sdiv_optab, SImode, 0);
10360   set_optab_libfunc (udiv_optab, SImode, 0);
10361   set_optab_libfunc (smod_optab, SImode, 0);
10362   set_optab_libfunc (umod_optab, SImode, 0);
10363
10364   set_optab_libfunc (sdiv_optab, DImode, "__milli_divI");
10365   set_optab_libfunc (udiv_optab, DImode, "__milli_divU");
10366   set_optab_libfunc (smod_optab, DImode, "__milli_remI");
10367   set_optab_libfunc (umod_optab, DImode, "__milli_remU");
10368
10369   /* HP-UX libc has TF min/max/abs routines in it.  */
10370   set_optab_libfunc (smin_optab, TFmode, "_U_Qfmin");
10371   set_optab_libfunc (smax_optab, TFmode, "_U_Qfmax");
10372   set_optab_libfunc (abs_optab, TFmode, "_U_Qfabs");
10373
10374   /* ia64_expand_compare uses this.  */
10375   cmptf_libfunc = init_one_libfunc ("_U_Qfcmp");
10376
10377   /* These should never be used.  */
10378   set_optab_libfunc (eq_optab, TFmode, 0);
10379   set_optab_libfunc (ne_optab, TFmode, 0);
10380   set_optab_libfunc (gt_optab, TFmode, 0);
10381   set_optab_libfunc (ge_optab, TFmode, 0);
10382   set_optab_libfunc (lt_optab, TFmode, 0);
10383   set_optab_libfunc (le_optab, TFmode, 0);
10384 }
10385
10386 /* Rename the division and modulus functions in VMS.  */
10387
10388 static void
10389 ia64_vms_init_libfuncs (void)
10390 {
10391   set_optab_libfunc (sdiv_optab, SImode, "OTS$DIV_I");
10392   set_optab_libfunc (sdiv_optab, DImode, "OTS$DIV_L");
10393   set_optab_libfunc (udiv_optab, SImode, "OTS$DIV_UI");
10394   set_optab_libfunc (udiv_optab, DImode, "OTS$DIV_UL");
10395   set_optab_libfunc (smod_optab, SImode, "OTS$REM_I");
10396   set_optab_libfunc (smod_optab, DImode, "OTS$REM_L");
10397   set_optab_libfunc (umod_optab, SImode, "OTS$REM_UI");
10398   set_optab_libfunc (umod_optab, DImode, "OTS$REM_UL");
10399   abort_libfunc = init_one_libfunc ("decc$abort");
10400   memcmp_libfunc = init_one_libfunc ("decc$memcmp");
10401 #ifdef MEM_LIBFUNCS_INIT
10402   MEM_LIBFUNCS_INIT;
10403 #endif
10404 }
10405
10406 /* Rename the TFmode libfuncs available from soft-fp in glibc using
10407    the HPUX conventions.  */
10408
10409 static void
10410 ia64_sysv4_init_libfuncs (void)
10411 {
10412   ia64_init_libfuncs ();
10413
10414   /* These functions are not part of the HPUX TFmode interface.  We
10415      use them instead of _U_Qfcmp, which doesn't work the way we
10416      expect.  */
10417   set_optab_libfunc (eq_optab, TFmode, "_U_Qfeq");
10418   set_optab_libfunc (ne_optab, TFmode, "_U_Qfne");
10419   set_optab_libfunc (gt_optab, TFmode, "_U_Qfgt");
10420   set_optab_libfunc (ge_optab, TFmode, "_U_Qfge");
10421   set_optab_libfunc (lt_optab, TFmode, "_U_Qflt");
10422   set_optab_libfunc (le_optab, TFmode, "_U_Qfle");
10423
10424   /* We leave out _U_Qfmin, _U_Qfmax and _U_Qfabs since soft-fp in
10425      glibc doesn't have them.  */
10426 }
10427
10428 /* Use soft-fp.  */
10429
10430 static void
10431 ia64_soft_fp_init_libfuncs (void)
10432 {
10433 }
10434
10435 static bool
10436 ia64_vms_valid_pointer_mode (enum machine_mode mode)
10437 {
10438   return (mode == SImode || mode == DImode);
10439 }
10440 \f
10441 /* For HPUX, it is illegal to have relocations in shared segments.  */
10442
10443 static int
10444 ia64_hpux_reloc_rw_mask (void)
10445 {
10446   return 3;
10447 }
10448
10449 /* For others, relax this so that relocations to local data goes in
10450    read-only segments, but we still cannot allow global relocations
10451    in read-only segments.  */
10452
10453 static int
10454 ia64_reloc_rw_mask (void)
10455 {
10456   return flag_pic ? 3 : 2;
10457 }
10458
10459 /* Return the section to use for X.  The only special thing we do here
10460    is to honor small data.  */
10461
10462 static section *
10463 ia64_select_rtx_section (enum machine_mode mode, rtx x,
10464                          unsigned HOST_WIDE_INT align)
10465 {
10466   if (GET_MODE_SIZE (mode) > 0
10467       && GET_MODE_SIZE (mode) <= ia64_section_threshold
10468       && !TARGET_NO_SDATA)
10469     return sdata_section;
10470   else
10471     return default_elf_select_rtx_section (mode, x, align);
10472 }
10473
10474 static unsigned int
10475 ia64_section_type_flags (tree decl, const char *name, int reloc)
10476 {
10477   unsigned int flags = 0;
10478
10479   if (strcmp (name, ".sdata") == 0
10480       || strncmp (name, ".sdata.", 7) == 0
10481       || strncmp (name, ".gnu.linkonce.s.", 16) == 0
10482       || strncmp (name, ".sdata2.", 8) == 0
10483       || strncmp (name, ".gnu.linkonce.s2.", 17) == 0
10484       || strcmp (name, ".sbss") == 0
10485       || strncmp (name, ".sbss.", 6) == 0
10486       || strncmp (name, ".gnu.linkonce.sb.", 17) == 0)
10487     flags = SECTION_SMALL;
10488
10489 #if TARGET_ABI_OPEN_VMS
10490   if (decl && DECL_ATTRIBUTES (decl)
10491       && lookup_attribute ("common_object", DECL_ATTRIBUTES (decl)))
10492     flags |= SECTION_VMS_OVERLAY;
10493 #endif
10494
10495   flags |= default_section_type_flags (decl, name, reloc);
10496   return flags;
10497 }
10498
10499 /* Returns true if FNTYPE (a FUNCTION_TYPE or a METHOD_TYPE) returns a
10500    structure type and that the address of that type should be passed
10501    in out0, rather than in r8.  */
10502
10503 static bool
10504 ia64_struct_retval_addr_is_first_parm_p (tree fntype)
10505 {
10506   tree ret_type = TREE_TYPE (fntype);
10507
10508   /* The Itanium C++ ABI requires that out0, rather than r8, be used
10509      as the structure return address parameter, if the return value
10510      type has a non-trivial copy constructor or destructor.  It is not
10511      clear if this same convention should be used for other
10512      programming languages.  Until G++ 3.4, we incorrectly used r8 for
10513      these return values.  */
10514   return (abi_version_at_least (2)
10515           && ret_type
10516           && TYPE_MODE (ret_type) == BLKmode 
10517           && TREE_ADDRESSABLE (ret_type)
10518           && strcmp (lang_hooks.name, "GNU C++") == 0);
10519 }
10520
10521 /* Output the assembler code for a thunk function.  THUNK_DECL is the
10522    declaration for the thunk function itself, FUNCTION is the decl for
10523    the target function.  DELTA is an immediate constant offset to be
10524    added to THIS.  If VCALL_OFFSET is nonzero, the word at
10525    *(*this + vcall_offset) should be added to THIS.  */
10526
10527 static void
10528 ia64_output_mi_thunk (FILE *file, tree thunk ATTRIBUTE_UNUSED,
10529                       HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
10530                       tree function)
10531 {
10532   rtx this_rtx, insn, funexp;
10533   unsigned int this_parmno;
10534   unsigned int this_regno;
10535   rtx delta_rtx;
10536
10537   reload_completed = 1;
10538   epilogue_completed = 1;
10539
10540   /* Set things up as ia64_expand_prologue might.  */
10541   last_scratch_gr_reg = 15;
10542
10543   memset (&current_frame_info, 0, sizeof (current_frame_info));
10544   current_frame_info.spill_cfa_off = -16;
10545   current_frame_info.n_input_regs = 1;
10546   current_frame_info.need_regstk = (TARGET_REG_NAMES != 0);
10547
10548   /* Mark the end of the (empty) prologue.  */
10549   emit_note (NOTE_INSN_PROLOGUE_END);
10550
10551   /* Figure out whether "this" will be the first parameter (the
10552      typical case) or the second parameter (as happens when the
10553      virtual function returns certain class objects).  */
10554   this_parmno
10555     = (ia64_struct_retval_addr_is_first_parm_p (TREE_TYPE (thunk))
10556        ? 1 : 0);
10557   this_regno = IN_REG (this_parmno);
10558   if (!TARGET_REG_NAMES)
10559     reg_names[this_regno] = ia64_reg_numbers[this_parmno];
10560
10561   this_rtx = gen_rtx_REG (Pmode, this_regno);
10562
10563   /* Apply the constant offset, if required.  */
10564   delta_rtx = GEN_INT (delta);
10565   if (TARGET_ILP32)
10566     {
10567       rtx tmp = gen_rtx_REG (ptr_mode, this_regno);
10568       REG_POINTER (tmp) = 1;
10569       if (delta && satisfies_constraint_I (delta_rtx))
10570         {
10571           emit_insn (gen_ptr_extend_plus_imm (this_rtx, tmp, delta_rtx));
10572           delta = 0;
10573         }
10574       else
10575         emit_insn (gen_ptr_extend (this_rtx, tmp));
10576     }
10577   if (delta)
10578     {
10579       if (!satisfies_constraint_I (delta_rtx))
10580         {
10581           rtx tmp = gen_rtx_REG (Pmode, 2);
10582           emit_move_insn (tmp, delta_rtx);
10583           delta_rtx = tmp;
10584         }
10585       emit_insn (gen_adddi3 (this_rtx, this_rtx, delta_rtx));
10586     }
10587
10588   /* Apply the offset from the vtable, if required.  */
10589   if (vcall_offset)
10590     {
10591       rtx vcall_offset_rtx = GEN_INT (vcall_offset);
10592       rtx tmp = gen_rtx_REG (Pmode, 2);
10593
10594       if (TARGET_ILP32)
10595         {
10596           rtx t = gen_rtx_REG (ptr_mode, 2);
10597           REG_POINTER (t) = 1;
10598           emit_move_insn (t, gen_rtx_MEM (ptr_mode, this_rtx));
10599           if (satisfies_constraint_I (vcall_offset_rtx))
10600             {
10601               emit_insn (gen_ptr_extend_plus_imm (tmp, t, vcall_offset_rtx));
10602               vcall_offset = 0;
10603             }
10604           else
10605             emit_insn (gen_ptr_extend (tmp, t));
10606         }
10607       else
10608         emit_move_insn (tmp, gen_rtx_MEM (Pmode, this_rtx));
10609
10610       if (vcall_offset)
10611         {
10612           if (!satisfies_constraint_J (vcall_offset_rtx))
10613             {
10614               rtx tmp2 = gen_rtx_REG (Pmode, next_scratch_gr_reg ());
10615               emit_move_insn (tmp2, vcall_offset_rtx);
10616               vcall_offset_rtx = tmp2;
10617             }
10618           emit_insn (gen_adddi3 (tmp, tmp, vcall_offset_rtx));
10619         }
10620
10621       if (TARGET_ILP32)
10622         emit_insn (gen_zero_extendsidi2 (tmp, gen_rtx_MEM (ptr_mode, tmp)));
10623       else
10624         emit_move_insn (tmp, gen_rtx_MEM (Pmode, tmp));
10625
10626       emit_insn (gen_adddi3 (this_rtx, this_rtx, tmp));
10627     }
10628
10629   /* Generate a tail call to the target function.  */
10630   if (! TREE_USED (function))
10631     {
10632       assemble_external (function);
10633       TREE_USED (function) = 1;
10634     }
10635   funexp = XEXP (DECL_RTL (function), 0);
10636   funexp = gen_rtx_MEM (FUNCTION_MODE, funexp);
10637   ia64_expand_call (NULL_RTX, funexp, NULL_RTX, 1);
10638   insn = get_last_insn ();
10639   SIBLING_CALL_P (insn) = 1;
10640
10641   /* Code generation for calls relies on splitting.  */
10642   reload_completed = 1;
10643   epilogue_completed = 1;
10644   try_split (PATTERN (insn), insn, 0);
10645
10646   emit_barrier ();
10647
10648   /* Run just enough of rest_of_compilation to get the insns emitted.
10649      There's not really enough bulk here to make other passes such as
10650      instruction scheduling worth while.  Note that use_thunk calls
10651      assemble_start_function and assemble_end_function.  */
10652
10653   insn_locators_alloc ();
10654   emit_all_insn_group_barriers (NULL);
10655   insn = get_insns ();
10656   shorten_branches (insn);
10657   final_start_function (insn, file, 1);
10658   final (insn, file, 1);
10659   final_end_function ();
10660
10661   reload_completed = 0;
10662   epilogue_completed = 0;
10663 }
10664
10665 /* Worker function for TARGET_STRUCT_VALUE_RTX.  */
10666
10667 static rtx
10668 ia64_struct_value_rtx (tree fntype,
10669                        int incoming ATTRIBUTE_UNUSED)
10670 {
10671   if (TARGET_ABI_OPEN_VMS ||
10672       (fntype && ia64_struct_retval_addr_is_first_parm_p (fntype)))
10673     return NULL_RTX;
10674   return gen_rtx_REG (Pmode, GR_REG (8));
10675 }
10676
10677 static bool
10678 ia64_scalar_mode_supported_p (enum machine_mode mode)
10679 {
10680   switch (mode)
10681     {
10682     case QImode:
10683     case HImode:
10684     case SImode:
10685     case DImode:
10686     case TImode:
10687       return true;
10688
10689     case SFmode:
10690     case DFmode:
10691     case XFmode:
10692     case RFmode:
10693       return true;
10694
10695     case TFmode:
10696       return true;
10697
10698     default:
10699       return false;
10700     }
10701 }
10702
10703 static bool
10704 ia64_vector_mode_supported_p (enum machine_mode mode)
10705 {
10706   switch (mode)
10707     {
10708     case V8QImode:
10709     case V4HImode:
10710     case V2SImode:
10711       return true;
10712
10713     case V2SFmode:
10714       return true;
10715
10716     default:
10717       return false;
10718     }
10719 }
10720
10721 /* Implement the FUNCTION_PROFILER macro.  */
10722
10723 void
10724 ia64_output_function_profiler (FILE *file, int labelno)
10725 {
10726   bool indirect_call;
10727
10728   /* If the function needs a static chain and the static chain
10729      register is r15, we use an indirect call so as to bypass
10730      the PLT stub in case the executable is dynamically linked,
10731      because the stub clobbers r15 as per 5.3.6 of the psABI.
10732      We don't need to do that in non canonical PIC mode.  */
10733
10734   if (cfun->static_chain_decl && !TARGET_NO_PIC && !TARGET_AUTO_PIC)
10735     {
10736       gcc_assert (STATIC_CHAIN_REGNUM == 15);
10737       indirect_call = true;
10738     }
10739   else
10740     indirect_call = false;
10741
10742   if (TARGET_GNU_AS)
10743     fputs ("\t.prologue 4, r40\n", file);
10744   else
10745     fputs ("\t.prologue\n\t.save ar.pfs, r40\n", file);
10746   fputs ("\talloc out0 = ar.pfs, 8, 0, 4, 0\n", file);
10747
10748   if (NO_PROFILE_COUNTERS)
10749     fputs ("\tmov out3 = r0\n", file);
10750   else
10751     {
10752       char buf[20];
10753       ASM_GENERATE_INTERNAL_LABEL (buf, "LP", labelno);
10754
10755       if (TARGET_AUTO_PIC)
10756         fputs ("\tmovl out3 = @gprel(", file);
10757       else
10758         fputs ("\taddl out3 = @ltoff(", file);
10759       assemble_name (file, buf);
10760       if (TARGET_AUTO_PIC)
10761         fputs (")\n", file);
10762       else
10763         fputs ("), r1\n", file);
10764     }
10765
10766   if (indirect_call)
10767     fputs ("\taddl r14 = @ltoff(@fptr(_mcount)), r1\n", file);
10768   fputs ("\t;;\n", file);
10769
10770   fputs ("\t.save rp, r42\n", file);
10771   fputs ("\tmov out2 = b0\n", file);
10772   if (indirect_call)
10773     fputs ("\tld8 r14 = [r14]\n\t;;\n", file);
10774   fputs ("\t.body\n", file);
10775   fputs ("\tmov out1 = r1\n", file);
10776   if (indirect_call)
10777     {
10778       fputs ("\tld8 r16 = [r14], 8\n\t;;\n", file);
10779       fputs ("\tmov b6 = r16\n", file);
10780       fputs ("\tld8 r1 = [r14]\n", file);
10781       fputs ("\tbr.call.sptk.many b0 = b6\n\t;;\n", file);
10782     }
10783   else
10784     fputs ("\tbr.call.sptk.many b0 = _mcount\n\t;;\n", file);
10785 }
10786
10787 static GTY(()) rtx mcount_func_rtx;
10788 static rtx
10789 gen_mcount_func_rtx (void)
10790 {
10791   if (!mcount_func_rtx)
10792     mcount_func_rtx = init_one_libfunc ("_mcount");
10793   return mcount_func_rtx;
10794 }
10795
10796 void
10797 ia64_profile_hook (int labelno)
10798 {
10799   rtx label, ip;
10800
10801   if (NO_PROFILE_COUNTERS)
10802     label = const0_rtx;
10803   else
10804     {
10805       char buf[30];
10806       const char *label_name;
10807       ASM_GENERATE_INTERNAL_LABEL (buf, "LP", labelno);
10808       label_name = (*targetm.strip_name_encoding) (ggc_strdup (buf));
10809       label = gen_rtx_SYMBOL_REF (Pmode, label_name);
10810       SYMBOL_REF_FLAGS (label) = SYMBOL_FLAG_LOCAL;
10811     }
10812   ip = gen_reg_rtx (Pmode);
10813   emit_insn (gen_ip_value (ip));
10814   emit_library_call (gen_mcount_func_rtx (), LCT_NORMAL,
10815                      VOIDmode, 3,
10816                      gen_rtx_REG (Pmode, BR_REG (0)), Pmode,
10817                      ip, Pmode,
10818                      label, Pmode);
10819 }
10820
10821 /* Return the mangling of TYPE if it is an extended fundamental type.  */
10822
10823 static const char *
10824 ia64_mangle_type (const_tree type)
10825 {
10826   type = TYPE_MAIN_VARIANT (type);
10827
10828   if (TREE_CODE (type) != VOID_TYPE && TREE_CODE (type) != BOOLEAN_TYPE
10829       && TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
10830     return NULL;
10831
10832   /* On HP-UX, "long double" is mangled as "e" so __float128 is
10833      mangled as "e".  */
10834   if (!TARGET_HPUX && TYPE_MODE (type) == TFmode)
10835     return "g";
10836   /* On HP-UX, "e" is not available as a mangling of __float80 so use
10837      an extended mangling.  Elsewhere, "e" is available since long
10838      double is 80 bits.  */
10839   if (TYPE_MODE (type) == XFmode)
10840     return TARGET_HPUX ? "u9__float80" : "e";
10841   if (TYPE_MODE (type) == RFmode)
10842     return "u7__fpreg";
10843   return NULL;
10844 }
10845
10846 /* Return the diagnostic message string if conversion from FROMTYPE to
10847    TOTYPE is not allowed, NULL otherwise.  */
10848 static const char *
10849 ia64_invalid_conversion (const_tree fromtype, const_tree totype)
10850 {
10851   /* Reject nontrivial conversion to or from __fpreg.  */
10852   if (TYPE_MODE (fromtype) == RFmode
10853       && TYPE_MODE (totype) != RFmode
10854       && TYPE_MODE (totype) != VOIDmode)
10855     return N_("invalid conversion from %<__fpreg%>");
10856   if (TYPE_MODE (totype) == RFmode
10857       && TYPE_MODE (fromtype) != RFmode)
10858     return N_("invalid conversion to %<__fpreg%>");
10859   return NULL;
10860 }
10861
10862 /* Return the diagnostic message string if the unary operation OP is
10863    not permitted on TYPE, NULL otherwise.  */
10864 static const char *
10865 ia64_invalid_unary_op (int op, const_tree type)
10866 {
10867   /* Reject operations on __fpreg other than unary + or &.  */
10868   if (TYPE_MODE (type) == RFmode
10869       && op != CONVERT_EXPR
10870       && op != ADDR_EXPR)
10871     return N_("invalid operation on %<__fpreg%>");
10872   return NULL;
10873 }
10874
10875 /* Return the diagnostic message string if the binary operation OP is
10876    not permitted on TYPE1 and TYPE2, NULL otherwise.  */
10877 static const char *
10878 ia64_invalid_binary_op (int op ATTRIBUTE_UNUSED, const_tree type1, const_tree type2)
10879 {
10880   /* Reject operations on __fpreg.  */
10881   if (TYPE_MODE (type1) == RFmode || TYPE_MODE (type2) == RFmode)
10882     return N_("invalid operation on %<__fpreg%>");
10883   return NULL;
10884 }
10885
10886 /* Implement TARGET_OPTION_DEFAULT_PARAMS.  */
10887 static void
10888 ia64_option_default_params (void)
10889 {
10890   /* Let the scheduler form additional regions.  */
10891   set_default_param_value (PARAM_MAX_SCHED_EXTEND_REGIONS_ITERS, 2);
10892
10893   /* Set the default values for cache-related parameters.  */
10894   set_default_param_value (PARAM_SIMULTANEOUS_PREFETCHES, 6);
10895   set_default_param_value (PARAM_L1_CACHE_LINE_SIZE, 32);
10896
10897   set_default_param_value (PARAM_SCHED_MEM_TRUE_DEP_COST, 4);
10898 }
10899
10900 /* HP-UX version_id attribute.
10901    For object foo, if the version_id is set to 1234 put out an alias
10902    of '.alias foo "foo{1234}"  We can't use "foo{1234}" in anything
10903    other than an alias statement because it is an illegal symbol name.  */
10904
10905 static tree
10906 ia64_handle_version_id_attribute (tree *node ATTRIBUTE_UNUSED,
10907                                  tree name ATTRIBUTE_UNUSED,
10908                                  tree args,
10909                                  int flags ATTRIBUTE_UNUSED,
10910                                  bool *no_add_attrs)
10911 {
10912   tree arg = TREE_VALUE (args);
10913
10914   if (TREE_CODE (arg) != STRING_CST)
10915     {
10916       error("version attribute is not a string");
10917       *no_add_attrs = true;
10918       return NULL_TREE;
10919     }
10920   return NULL_TREE;
10921 }
10922
10923 /* Target hook for c_mode_for_suffix.  */
10924
10925 static enum machine_mode
10926 ia64_c_mode_for_suffix (char suffix)
10927 {
10928   if (suffix == 'q')
10929     return TFmode;
10930   if (suffix == 'w')
10931     return XFmode;
10932
10933   return VOIDmode;
10934 }
10935
10936 static enum machine_mode
10937 ia64_promote_function_mode (const_tree type,
10938                             enum machine_mode mode,
10939                             int *punsignedp,
10940                             const_tree funtype,
10941                             int for_return)
10942 {
10943   /* Special processing required for OpenVMS ...  */
10944
10945   if (!TARGET_ABI_OPEN_VMS)
10946     return default_promote_function_mode(type, mode, punsignedp, funtype,
10947                                          for_return);
10948
10949   /* HP OpenVMS Calling Standard dated June, 2004, that describes
10950      HP OpenVMS I64 Version 8.2EFT,
10951      chapter 4 "OpenVMS I64 Conventions"
10952      section 4.7 "Procedure Linkage"
10953      subsection 4.7.5.2, "Normal Register Parameters"
10954
10955      "Unsigned integral (except unsigned 32-bit), set, and VAX floating-point
10956      values passed in registers are zero-filled; signed integral values as
10957      well as unsigned 32-bit integral values are sign-extended to 64 bits.
10958      For all other types passed in the general registers, unused bits are
10959      undefined."  */
10960
10961   if (!AGGREGATE_TYPE_P (type)
10962       && GET_MODE_CLASS (mode) == MODE_INT
10963       && GET_MODE_SIZE (mode) < UNITS_PER_WORD)
10964     {
10965       if (mode == SImode)
10966         *punsignedp = 0;
10967       return DImode;
10968     }
10969   else
10970     return promote_mode (type, mode, punsignedp);
10971 }
10972    
10973 static GTY(()) rtx ia64_dconst_0_5_rtx;
10974
10975 rtx
10976 ia64_dconst_0_5 (void)
10977 {
10978   if (! ia64_dconst_0_5_rtx)
10979     {
10980       REAL_VALUE_TYPE rv;
10981       real_from_string (&rv, "0.5");
10982       ia64_dconst_0_5_rtx = const_double_from_real_value (rv, DFmode);
10983     }
10984   return ia64_dconst_0_5_rtx;
10985 }
10986
10987 static GTY(()) rtx ia64_dconst_0_375_rtx;
10988
10989 rtx
10990 ia64_dconst_0_375 (void)
10991 {
10992   if (! ia64_dconst_0_375_rtx)
10993     {
10994       REAL_VALUE_TYPE rv;
10995       real_from_string (&rv, "0.375");
10996       ia64_dconst_0_375_rtx = const_double_from_real_value (rv, DFmode);
10997     }
10998   return ia64_dconst_0_375_rtx;
10999 }
11000
11001 static enum machine_mode
11002 ia64_get_reg_raw_mode (int regno)
11003 {
11004   if (FR_REGNO_P (regno))
11005     return XFmode;
11006   return default_get_reg_raw_mode(regno);
11007 }
11008
11009 #include "gt-ia64.h"