OSDN Git Service

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