OSDN Git Service

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