OSDN Git Service

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