OSDN Git Service

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