OSDN Git Service

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