OSDN Git Service

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