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